Updated to Drupal 8.6.4, which is PHP 7.3 friendly. Also updated HTMLaw library....
[yaffs-website] / web / core / modules / locale / locale.module
1 <?php
2
3 /**
4  * @file
5  * Enables the translation of the user interface to languages other than English.
6  *
7  * When enabled, multiple languages can be added. The site interface can be
8  * displayed in different languages, and nodes can have languages assigned. The
9  * setup of languages and translations is completely web based. Gettext portable
10  * object files are supported.
11  */
12
13 use Drupal\Component\Serialization\Json;
14 use Drupal\Component\Utility\Html;
15 use Drupal\Component\Utility\UrlHelper;
16 use Drupal\Component\Utility\Xss;
17 use Drupal\Core\Url;
18 use Drupal\Core\Asset\AttachedAssetsInterface;
19 use Drupal\Core\Form\FormStateInterface;
20 use Drupal\Core\Routing\RouteMatchInterface;
21 use Drupal\Core\Language\LanguageInterface;
22 use Drupal\language\ConfigurableLanguageInterface;
23 use Drupal\Component\Utility\Crypt;
24 use Drupal\locale\Locale;
25 use Drupal\locale\LocaleEvent;
26 use Drupal\locale\LocaleEvents;
27
28 /**
29  * Regular expression pattern used to localize JavaScript strings.
30  */
31 const LOCALE_JS_STRING = '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+';
32
33 /**
34  * Regular expression pattern used to match simple JS object literal.
35  *
36  * This pattern matches a basic JS object, but will fail on an object with
37  * nested objects. Used in JS file parsing for string arg processing.
38  */
39 const LOCALE_JS_OBJECT = '\{.*?\}';
40
41 /**
42  * Regular expression to match an object containing a key 'context'.
43  *
44  * Pattern to match a JS object containing a 'context key' with a string value,
45  * which is captured. Will fail if there are nested objects.
46  */
47 define('LOCALE_JS_OBJECT_CONTEXT', '
48   \{              # match object literal start
49   .*?             # match anything, non-greedy
50   (?:             # match a form of "context"
51     \'context\'
52     |
53     "context"
54     |
55     context
56   )
57   \s*:\s*         # match key-value separator ":"
58   (' . LOCALE_JS_STRING . ')  # match context string
59   .*?             # match anything, non-greedy
60   \}              # match end of object literal
61 ');
62
63 /**
64  * Flag for locally not customized interface translation.
65  *
66  * Such translations are imported from .po files downloaded from
67  * localize.drupal.org for example.
68  */
69 const LOCALE_NOT_CUSTOMIZED = 0;
70
71 /**
72  * Flag for locally customized interface translation.
73  *
74  * Such translations are edited from their imported originals on the user
75  * interface or are imported as customized.
76  */
77 const LOCALE_CUSTOMIZED = 1;
78
79 /**
80  * Translation update mode: Use local files only.
81  *
82  * When checking for available translation updates, only local files will be
83  * used. Any remote translation file will be ignored. Also custom modules and
84  * themes which have set a "server pattern" to use a remote translation server
85  * will be ignored.
86  */
87 const LOCALE_TRANSLATION_USE_SOURCE_LOCAL = 'local';
88
89 /**
90  * Translation update mode: Use both remote and local files.
91  *
92  * When checking for available translation updates, both local and remote files
93  * will be checked.
94  */
95 const LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL = 'remote_and_local';
96
97 /**
98  * Default location of gettext file on the translation server.
99  *
100  * @see locale_translation_default_translation_server().
101  */
102 const LOCALE_TRANSLATION_DEFAULT_SERVER_PATTERN = 'https://ftp.drupal.org/files/translations/%core/%project/%project-%version.%language.po';
103
104 /**
105  * The number of seconds that the translations status entry should be considered.
106  */
107 const LOCALE_TRANSLATION_STATUS_TTL = 600;
108
109 /**
110  * UI option for override of existing translations. Override any translation.
111  */
112 const LOCALE_TRANSLATION_OVERWRITE_ALL = 'all';
113
114 /**
115  * UI option for override of existing translations. Only override non-customized
116  * translations.
117  */
118 const LOCALE_TRANSLATION_OVERWRITE_NON_CUSTOMIZED = 'non_customized';
119
120 /**
121  * UI option for override of existing translations. Don't override existing
122  * translations.
123  */
124 const LOCALE_TRANSLATION_OVERWRITE_NONE = 'none';
125
126 /**
127  * Translation source is a remote file.
128  */
129 const LOCALE_TRANSLATION_REMOTE = 'remote';
130
131 /**
132  * Translation source is a local file.
133  */
134 const LOCALE_TRANSLATION_LOCAL = 'local';
135
136 /**
137  * Translation source is the current translation.
138  */
139 const LOCALE_TRANSLATION_CURRENT = 'current';
140
141 /**
142  * Implements hook_help().
143  */
144 function locale_help($route_name, RouteMatchInterface $route_match) {
145   switch ($route_name) {
146     case 'help.page.locale':
147       $output = '';
148       $output .= '<h3>' . t('About') . '</h3>';
149       $output .= '<p>' . t('The Interface Translation module allows you to translate interface text (<em>strings</em>) into different languages, and to switch between them for the display of interface text. It uses the functionality provided by the <a href=":language">Language module</a>. For more information, see the <a href=":doc-url">online documentation for the Interface Translation module</a>.', [':doc-url' => 'https://www.drupal.org/documentation/modules/locale/', ':language' => \Drupal::url('help.page', ['name' => 'language'])]) . '</p>';
150       $output .= '<h3>' . t('Uses') . '</h3>';
151       $output .= '<dl>';
152       $output .= '<dt>' . t('Importing translation files') . '</dt>';
153       $output .= '<dd>' . t('Translation files with translated interface text are imported automatically when languages are added on the <a href=":languages">Languages</a> page, or when modules or themes are enabled. On the <a href=":locale-settings">Interface translation settings</a> page, the <em>Translation source</em> can be restricted to local files only, or to include the <a href=":server">Drupal translation server</a>. Although modules and themes may not be fully translated in all languages, new translations become available frequently. You can specify whether and how often to check for translation file updates and whether to overwrite existing translations on the <a href=":locale-settings">Interface translation settings</a> page. You can also manually import a translation file on the <a href=":import">Interface translation import</a> page.', [':import' => \Drupal::url('locale.translate_import'), ':locale-settings' => \Drupal::url('locale.settings'), ':languages' => \Drupal::url('entity.configurable_language.collection'), ':server' => 'https://localize.drupal.org']) . '</dd>';
154       $output .= '<dt>' . t('Checking the translation status') . '</dt>';
155       $output .= '<dd>' . t('You can check how much of the interface on your site is translated into which language on the <a href=":languages">Languages</a> page. On the <a href=":translation-updates">Available translation updates</a> page, you can check whether interface translation updates are available on the <a href=":server">Drupal translation server</a>.', [':languages' => \Drupal::url('entity.configurable_language.collection'), ':translation-updates' => \Drupal::url('locale.translate_status'), ':server' => 'https://localize.drupal.org']) . '<dd>';
156       $output .= '<dt>' . t('Translating individual strings') . '</dt>';
157       $output .= '<dd>' . t('You can translate individual strings directly on the <a href=":translate">User interface translation</a> page, or download the currently-used translation file for a specific language on the <a href=":export">Interface translation export</a> page. Once you have edited the translation file, you can then import it again on the <a href=":import">Interface translation import</a> page.', [':translate' => \Drupal::url('locale.translate_page'), ':export' => \Drupal::url('locale.translate_export'), ':import' => \Drupal::url('locale.translate_import')]) . '</dd>';
158       $output .= '<dt>' . t('Overriding default English strings') . '</dt>';
159       $output .= '<dd>' . t('If translation is enabled for English, you can <em>override</em> the default English interface text strings in your site with other English text strings on the <a href=":translate">User interface translation</a> page. Translation is off by default for English, but you can turn it on by visiting the <em>Edit language</em> page for <em>English</em> from the <a href=":languages">Languages</a> page.', [':translate' => \Drupal::url('locale.translate_page'), ':languages' => \Drupal::url('entity.configurable_language.collection')]) . '</dd>';
160       $output .= '</dl>';
161       return $output;
162
163     case 'entity.configurable_language.collection':
164       return '<p>' . t('Interface translations are automatically imported when a language is added, or when new modules or themes are enabled. The report <a href=":update">Available translation updates</a> shows the status. Interface text can be customized in the <a href=":translate">user interface translation</a> page.', [':update' => \Drupal::url('locale.translate_status'), ':translate' => \Drupal::url('locale.translate_page')]) . '</p>';
165
166     case 'locale.translate_page':
167       $output = '<p>' . t('This page allows a translator to search for specific translated and untranslated strings, and is used when creating or editing translations. (Note: Because translation tasks involve many strings, it may be more convenient to <a title="User interface translation export" href=":export">export</a> strings for offline editing in a desktop Gettext translation editor.) Searches may be limited to strings in a specific language.', [':export' => \Drupal::url('locale.translate_export')]) . '</p>';
168       return $output;
169
170     case 'locale.translate_import':
171       $output = '<p>' . t('Translation files are automatically downloaded and imported when <a title="Languages" href=":language">languages</a> are added, or when modules or themes are enabled.', [':language' => \Drupal::url('entity.configurable_language.collection')]) . '</p>';
172       $output .= '<p>' . t('This page allows translators to manually import translated strings contained in a Gettext Portable Object (.po) file. Manual import may be used for customized translations or for the translation of custom modules and themes. To customize translations you can download a translation file from the <a href=":url">Drupal translation server</a> or <a title="User interface translation export" href=":export">export</a> translations from the site, customize the translations using a Gettext translation editor, and import the result using this page.', [':url' => 'https://localize.drupal.org', ':export' => \Drupal::url('locale.translate_export')]) . '</p>';
173       $output .= '<p>' . t('Note that importing large .po files may take several minutes.') . '</p>';
174       return $output;
175
176     case 'locale.translate_export':
177       return '<p>' . t('This page exports the translated strings used by your site. An export file may be in Gettext Portable Object (<em>.po</em>) form, which includes both the original string and the translation (used to share translations with others), or in Gettext Portable Object Template (<em>.pot</em>) form, which includes the original strings only (used to create new translations with a Gettext translation editor).') . '</p>';
178   }
179 }
180
181 /**
182  * Implements hook_theme().
183  */
184 function locale_theme() {
185   return [
186     'locale_translation_last_check' => [
187       'variables' => ['last' => NULL],
188       'file' => 'locale.pages.inc',
189     ],
190     'locale_translation_update_info' => [
191       'variables' => ['updates' => [], 'not_found' => []],
192       'file' => 'locale.pages.inc',
193     ],
194   ];
195 }
196
197 /**
198  * Implements hook_ENTITY_TYPE_insert() for 'configurable_language'.
199  */
200 function locale_configurable_language_insert(ConfigurableLanguageInterface $language) {
201   // @todo move these two cache clears out. See
202   //   https://www.drupal.org/node/1293252.
203   // Changing the language settings impacts the interface: clear render cache.
204   \Drupal::cache('render')->deleteAll();
205   // Force JavaScript translation file re-creation for the new language.
206   _locale_invalidate_js($language->id());
207 }
208
209 /**
210  * Implements hook_ENTITY_TYPE_update() for 'configurable_language'.
211  */
212 function locale_configurable_language_update(ConfigurableLanguageInterface $language) {
213   // @todo move these two cache clears out. See
214   //   https://www.drupal.org/node/1293252.
215   // Changing the language settings impacts the interface: clear render cache.
216   \Drupal::cache('render')->deleteAll();
217   // Force JavaScript translation file re-creation for the modified language.
218   _locale_invalidate_js($language->id());
219 }
220
221 /**
222  * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
223  */
224 function locale_configurable_language_delete(ConfigurableLanguageInterface $language) {
225   // Remove translations.
226   \Drupal::service('locale.storage')->deleteTranslations(['language' => $language->id()]);
227
228   // Remove interface translation files.
229   module_load_include('inc', 'locale', 'locale.bulk');
230   locale_translate_delete_translation_files([], [$language->id()]);
231
232   // Remove translated configuration objects.
233   Locale::config()->deleteLanguageTranslations($language->id());
234
235   // Changing the language settings impacts the interface:
236   _locale_invalidate_js($language->id());
237   \Drupal::cache('render')->deleteAll();
238
239   // Clear locale translation caches.
240   locale_translation_status_delete_languages([$language->id()]);
241   \Drupal::cache()->delete('locale:' . $language->id());
242 }
243
244 /**
245  * Returns list of translatable languages.
246  *
247  * @return array
248  *   Array of installed languages keyed by language name. English is omitted
249  *   unless it is marked as translatable.
250  */
251 function locale_translatable_language_list() {
252   $languages = \Drupal::languageManager()->getLanguages();
253   if (!locale_is_translatable('en')) {
254     unset($languages['en']);
255   }
256   return $languages;
257 }
258
259 /**
260  * Returns plural form index for a specific number.
261  *
262  * The index is computed from the formula of this language.
263  *
264  * @param int $count
265  *   Number to return plural for.
266  * @param string|null $langcode
267  *   (optional) Language code to translate to a language other than what is used
268  *   to display the page, or NULL for current language. Defaults to NULL.
269  *
270  * @return int
271  *   The numeric index of the plural variant to use for this $langcode and
272  *   $count combination or -1 if the language was not found or does not have a
273  *   plural formula.
274  */
275 function locale_get_plural($count, $langcode = NULL) {
276   $language_interface = \Drupal::languageManager()->getCurrentLanguage();
277
278   // Used to store precomputed plural indexes corresponding to numbers
279   // individually for each language.
280   $plural_indexes = &drupal_static(__FUNCTION__ . ':plurals', []);
281
282   $langcode = $langcode ? $langcode : $language_interface->getId();
283
284   if (!isset($plural_indexes[$langcode][$count])) {
285     // Retrieve and statically cache the plural formulas for all languages.
286     $plural_formulas = \Drupal::service('locale.plural.formula')->getFormula($langcode);
287
288     // If there is a plural formula for the language, evaluate it for the given
289     // $count and statically cache the result for the combination of language
290     // and count, since the result will always be identical.
291     if (!empty($plural_formulas)) {
292       // Plural formulas are stored as an array for 0-199. 100 is the highest
293       // modulo used but storing 0-99 is not enough because below 100 we often
294       // find exceptions (1, 2, etc).
295       $index = $count > 199 ? 100 + ($count % 100) : $count;
296       $plural_indexes[$langcode][$count] = isset($plural_formulas[$index]) ? $plural_formulas[$index] : $plural_formulas['default'];
297     }
298     // In case there is no plural formula for English (no imported translation
299     // for English), use a default formula.
300     elseif ($langcode == 'en') {
301       $plural_indexes[$langcode][$count] = (int) ($count != 1);
302     }
303     // Otherwise, return -1 (unknown).
304     else {
305       $plural_indexes[$langcode][$count] = -1;
306     }
307   }
308   return $plural_indexes[$langcode][$count];
309 }
310
311 /**
312  * Implements hook_modules_installed().
313  */
314 function locale_modules_installed($modules) {
315   locale_system_set_config_langcodes();
316
317   $components['module'] = $modules;
318   locale_system_update($components);
319 }
320
321 /**
322  * Implements hook_module_preuninstall().
323  */
324 function locale_module_preuninstall($module) {
325   $components['module'] = [$module];
326   locale_system_remove($components);
327 }
328
329 /**
330  * Implements hook_themes_installed().
331  */
332 function locale_themes_installed($themes) {
333   locale_system_set_config_langcodes();
334
335   $components['theme'] = $themes;
336   locale_system_update($components);
337 }
338
339 /**
340  * Implements hook_themes_uninstalled().
341  */
342 function locale_themes_uninstalled($themes) {
343   $components['theme'] = $themes;
344   locale_system_remove($components);
345 }
346
347 /**
348  * Implements hook_cron().
349  *
350  * @see \Drupal\locale\Plugin\QueueWorker\LocaleTranslation
351  */
352 function locale_cron() {
353   // Update translations only when an update frequency was set by the admin
354   // and a translatable language was set.
355   // Update tasks are added to the queue here but processed by Drupal's cron.
356   if ($frequency = \Drupal::config('locale.settings')->get('translation.update_interval_days') && locale_translatable_language_list()) {
357     module_load_include('translation.inc', 'locale');
358     locale_cron_fill_queue();
359   }
360 }
361
362 /**
363  * Updates default configuration when new modules or themes are installed.
364  */
365 function locale_system_set_config_langcodes() {
366   // Need to rewrite some default configuration language codes if the default
367   // site language is not English.
368   $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
369   if ($default_langcode != 'en') {
370     // Update active configuration copies of all prior shipped configuration if
371     // they are still English. It is not enough to change configuration shipped
372     // with the components just installed, because installing a component such
373     // as views or tour module may bring in default configuration from prior
374     // components.
375     $names = Locale::config()->getComponentNames();
376     foreach ($names as $name) {
377       $config = \Drupal::configFactory()->reset($name)->getEditable($name);
378       // Should only update if still exists in active configuration. If locale
379       // module is enabled later, then some configuration may not exist anymore.
380       if (!$config->isNew()) {
381         $langcode = $config->get('langcode');
382         if (empty($langcode) || $langcode == 'en') {
383           $config->set('langcode', $default_langcode)->save();
384         }
385       }
386     }
387   }
388 }
389
390 /**
391  * Imports translations when new modules or themes are installed.
392  *
393  * This function will start a batch to import translations for the added
394  * components.
395  *
396  * @param array $components
397  *   An array of arrays of component (theme and/or module) names to import
398  *   translations for, indexed by type.
399  */
400 function locale_system_update(array $components) {
401   $components += ['module' => [], 'theme' => []];
402   $list = array_merge($components['module'], $components['theme']);
403
404   // Skip running the translation imports if in the installer,
405   // because it would break out of the installer flow. We have
406   // built-in support for translation imports in the installer.
407   if (!drupal_installation_attempted() && locale_translatable_language_list()) {
408     if (\Drupal::config('locale.settings')->get('translation.import_enabled')) {
409       module_load_include('compare.inc', 'locale');
410
411       // Update the list of translatable projects and start the import batch.
412       // Only when new projects are added the update batch will be triggered.
413       // Not each enabled module will introduce a new project. E.g. sub modules.
414       $projects = array_keys(locale_translation_build_projects());
415       if ($list = array_intersect($list, $projects)) {
416         module_load_include('fetch.inc', 'locale');
417         // Get translation status of the projects, download and update
418         // translations.
419         $options = _locale_translation_default_update_options();
420         $batch = locale_translation_batch_update_build($list, [], $options);
421         batch_set($batch);
422       }
423     }
424
425     // Construct a batch to update configuration for all components. Installing
426     // this component may have installed configuration from any number of other
427     // components. Do this even if import is not enabled because parsing new
428     // configuration may expose new source strings.
429     \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
430     if ($batch = locale_config_batch_update_components([])) {
431       batch_set($batch);
432     }
433   }
434 }
435
436 /**
437  * Delete translation history of modules and themes.
438  *
439  * Only the translation history is removed, not the source strings or
440  * translations. This is not possible because strings are shared between
441  * modules and we have no record of which string is used by which module.
442  *
443  * @param array $components
444  *   An array of arrays of component (theme and/or module) names to import
445  *   translations for, indexed by type.
446  */
447 function locale_system_remove($components) {
448   $components += ['module' => [], 'theme' => []];
449   $list = array_merge($components['module'], $components['theme']);
450   if ($language_list = locale_translatable_language_list()) {
451     module_load_include('compare.inc', 'locale');
452     \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
453
454     // Only when projects are removed, the translation files and records will be
455     // deleted. Not each disabled module will remove a project, e.g., sub
456     // modules.
457     $projects = array_keys(locale_translation_get_projects());
458     if ($list = array_intersect($list, $projects)) {
459       locale_translation_file_history_delete($list);
460
461       // Remove translation files.
462       locale_translate_delete_translation_files($list, []);
463
464       // Remove translatable projects.
465       // Follow-up issue https://www.drupal.org/node/1842362 to replace the
466       // {locale_project} table. Then change this to a function call.
467       \Drupal::service('locale.project')->deleteMultiple($list);
468
469       // Clear the translation status.
470       locale_translation_status_delete_projects($list);
471     }
472
473   }
474 }
475
476 /**
477  * Implements hook_cache_flush().
478  */
479 function locale_cache_flush() {
480   \Drupal::state()->delete('system.javascript_parsed');
481 }
482
483 /**
484  * Implements hook_js_alter().
485  */
486 function locale_js_alter(&$javascript, AttachedAssetsInterface $assets) {
487   // @todo Remove this in https://www.drupal.org/node/2421323.
488   $files = [];
489   foreach ($javascript as $item) {
490     if (isset($item['type']) && $item['type'] == 'file') {
491       // Ignore the JS translation placeholder file.
492       if ($item['data'] === 'core/modules/locale/locale.translation.js') {
493         continue;
494       }
495       $files[] = $item['data'];
496     }
497   }
498
499   // Replace the placeholder file with the actual JS translation file.
500   $placeholder_file = 'core/modules/locale/locale.translation.js';
501   if (isset($javascript[$placeholder_file])) {
502     if ($translation_file = locale_js_translate($files)) {
503       $js_translation_asset = &$javascript[$placeholder_file];
504       $js_translation_asset['data'] = $translation_file;
505       // @todo Remove this when https://www.drupal.org/node/1945262 lands.
506       // Decrease the weight so that the translation file is loaded first.
507       $js_translation_asset['weight'] = $javascript['core/misc/drupal.js']['weight'] - 0.001;
508     }
509     else {
510       // If no translation file exists, then remove the placeholder JS asset.
511       unset($javascript[$placeholder_file]);
512     }
513   }
514 }
515
516 /**
517  * Returns a list of translation files given a list of JavaScript files.
518  *
519  * This function checks all JavaScript files passed and invokes parsing if they
520  * have not yet been parsed for Drupal.t() and Drupal.formatPlural() calls.
521  * Also refreshes the JavaScript translation files if necessary, and returns
522  * the filepath to the translation file (if any).
523  *
524  * @param array $files
525  *   An array of local file paths.
526  *
527  * @return string|null
528  *   The filepath to the translation file or NULL if no translation is
529  *   applicable.
530  */
531 function locale_js_translate(array $files = []) {
532   $language_interface = \Drupal::languageManager()->getCurrentLanguage();
533
534   $dir = 'public://' . \Drupal::config('locale.settings')->get('javascript.directory');
535   $parsed = \Drupal::state()->get('system.javascript_parsed') ?: [];
536   $new_files = FALSE;
537
538   foreach ($files as $filepath) {
539     if (!in_array($filepath, $parsed)) {
540       // Don't parse our own translations files.
541       if (substr($filepath, 0, strlen($dir)) != $dir) {
542         _locale_parse_js_file($filepath);
543         $parsed[] = $filepath;
544         $new_files = TRUE;
545       }
546     }
547   }
548
549   // If there are any new source files we parsed, invalidate existing
550   // JavaScript translation files for all languages, adding the refresh
551   // flags into the existing array.
552   if ($new_files) {
553     $parsed += _locale_invalidate_js();
554   }
555
556   // If necessary, rebuild the translation file for the current language.
557   if (!empty($parsed['refresh:' . $language_interface->getId()])) {
558     // Don't clear the refresh flag on failure, so that another try will
559     // be performed later.
560     if (_locale_rebuild_js()) {
561       unset($parsed['refresh:' . $language_interface->getId()]);
562     }
563     // Store any changes after refresh was attempted.
564     \Drupal::state()->set('system.javascript_parsed', $parsed);
565   }
566   // If no refresh was attempted, but we have new source files, we need
567   // to store them too. This occurs if current page is in English.
568   elseif ($new_files) {
569     \Drupal::state()->set('system.javascript_parsed', $parsed);
570   }
571
572   // Add the translation JavaScript file to the page.
573   $locale_javascripts = \Drupal::state()->get('locale.translation.javascript') ?: [];
574   $translation_file = NULL;
575   if (!empty($files) && !empty($locale_javascripts[$language_interface->getId()])) {
576     // Add the translation JavaScript file to the page.
577     $translation_file = $dir . '/' . $language_interface->getId() . '_' . $locale_javascripts[$language_interface->getId()] . '.js';
578   }
579   return $translation_file;
580 }
581
582 /**
583  * Implements hook_library_info_alter().
584  *
585  * Provides the language support for the jQuery UI Date Picker.
586  */
587 function locale_library_info_alter(array &$libraries, $module) {
588   if ($module === 'core' && isset($libraries['jquery.ui.datepicker'])) {
589     $libraries['jquery.ui.datepicker']['dependencies'][] = 'locale/drupal.locale.datepicker';
590     $libraries['jquery.ui.datepicker']['drupalSettings']['jquery']['ui']['datepicker'] = [
591       'isRTL' => NULL,
592       'firstDay' => NULL,
593     ];
594   }
595
596   // When the locale module is enabled, we update the core/drupal library to
597   // have a dependency on the locale/translations library, which provides
598   // window.drupalTranslations, containing the translations for all strings in
599   // JavaScript assets in the current language.
600   // @see locale_js_alter()
601   if ($module === 'core' && isset($libraries['drupal'])) {
602     $libraries['drupal']['dependencies'][] = 'locale/translations';
603   }
604 }
605
606 /**
607  * Implements hook_js_settings_alter().
608  *
609  * Generates the values for the altered core/jquery.ui.datepicker library.
610  */
611 function locale_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
612   if (isset($settings['jquery']['ui']['datepicker'])) {
613     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
614     $settings['jquery']['ui']['datepicker']['isRTL'] = $language_interface->getDirection() == LanguageInterface::DIRECTION_RTL;
615     $settings['jquery']['ui']['datepicker']['firstDay'] = \Drupal::config('system.date')->get('first_day');
616   }
617 }
618
619 /**
620  * Implements hook_form_FORM_ID_alter() for language_admin_overview_form().
621  */
622 function locale_form_language_admin_overview_form_alter(&$form, FormStateInterface $form_state) {
623   $languages = $form['languages']['#languages'];
624
625   $total_strings = \Drupal::service('locale.storage')->countStrings();
626   $stats = array_fill_keys(array_keys($languages), []);
627
628   // If we have source strings, count translations and calculate progress.
629   if (!empty($total_strings)) {
630     $translations = \Drupal::service('locale.storage')->countTranslations();
631     foreach ($translations as $langcode => $translated) {
632       $stats[$langcode]['translated'] = $translated;
633       if ($translated > 0) {
634         $stats[$langcode]['ratio'] = round($translated / $total_strings * 100, 2);
635       }
636     }
637   }
638
639   array_splice($form['languages']['#header'], -1, 0, ['translation-interface' => t('Interface translation')]);
640
641   foreach ($languages as $langcode => $language) {
642     $stats[$langcode] += [
643       'translated' => 0,
644       'ratio' => 0,
645     ];
646     if (!$language->isLocked() && locale_is_translatable($langcode)) {
647       $form['languages'][$langcode]['locale_statistics'] = [
648         '#markup' => \Drupal::l(
649           t('@translated/@total (@ratio%)', [
650             '@translated' => $stats[$langcode]['translated'],
651             '@total' => $total_strings,
652             '@ratio' => $stats[$langcode]['ratio'],
653           ]),
654           new Url('locale.translate_page', [], ['query' => ['langcode' => $langcode]])
655         ),
656       ];
657     }
658     else {
659       $form['languages'][$langcode]['locale_statistics'] = [
660         '#markup' => t('not applicable'),
661       ];
662     }
663     // #type = link doesn't work with #weight on table.
664     // reset and set it back after locale_statistics to get it at the right end.
665     $operations = $form['languages'][$langcode]['operations'];
666     unset($form['languages'][$langcode]['operations']);
667     $form['languages'][$langcode]['operations'] = $operations;
668   }
669 }
670
671 /**
672  * Implements hook_form_FORM_ID_alter() for language_admin_add_form().
673  */
674 function locale_form_language_admin_add_form_alter(&$form, FormStateInterface $form_state) {
675   $form['predefined_submit']['#submit'][] = 'locale_form_language_admin_add_form_alter_submit';
676   $form['custom_language']['submit']['#submit'][] = 'locale_form_language_admin_add_form_alter_submit';
677 }
678
679 /**
680  * Form submission handler for language_admin_add_form().
681  *
682  * Set a batch for a newly-added language.
683  */
684 function locale_form_language_admin_add_form_alter_submit($form, FormStateInterface $form_state) {
685   \Drupal::moduleHandler()->loadInclude('locale', 'fetch.inc');
686   $options = _locale_translation_default_update_options();
687
688   if ($form_state->isValueEmpty('predefined_langcode') || $form_state->getValue('predefined_langcode') == 'custom') {
689     $langcode = $form_state->getValue('langcode');
690   }
691   else {
692     $langcode = $form_state->getValue('predefined_langcode');
693   }
694
695   if (\Drupal::config('locale.settings')->get('translation.import_enabled')) {
696     // Download and import translations for the newly added language.
697     $batch = locale_translation_batch_update_build([], [$langcode], $options);
698     batch_set($batch);
699   }
700
701   // Create or update all configuration translations for this language. If we
702   // are adding English then we need to run this even if import is not enabled,
703   // because then we extract English sources from shipped configuration.
704   if (\Drupal::config('locale.settings')->get('translation.import_enabled') || $langcode == 'en') {
705     \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
706     if ($batch = locale_config_batch_update_components($options, [$langcode])) {
707       batch_set($batch);
708     }
709   }
710 }
711
712 /**
713  * Implements hook_form_FORM_ID_alter() for language_admin_edit_form().
714  */
715 function locale_form_language_admin_edit_form_alter(&$form, FormStateInterface $form_state) {
716   if ($form['langcode']['#type'] == 'value' && $form['langcode']['#value'] == 'en') {
717     $form['locale_translate_english'] = [
718       '#title' => t('Enable interface translation to English'),
719       '#type' => 'checkbox',
720       '#default_value' => \Drupal::configFactory()->getEditable('locale.settings')->get('translate_english'),
721     ];
722     $form['actions']['submit']['#submit'][] = 'locale_form_language_admin_edit_form_alter_submit';
723   }
724 }
725
726 /**
727  * Form submission handler for language_admin_edit_form().
728  */
729 function locale_form_language_admin_edit_form_alter_submit($form, FormStateInterface $form_state) {
730   \Drupal::configFactory()->getEditable('locale.settings')->set('translate_english', intval($form_state->getValue('locale_translate_english')))->save();
731 }
732
733 /**
734  * Checks whether $langcode is a language supported as a locale target.
735  *
736  * @param string $langcode
737  *   The language code.
738  *
739  * @return bool
740  *   Whether $langcode can be translated to in locale.
741  */
742 function locale_is_translatable($langcode) {
743   return $langcode != 'en' || \Drupal::config('locale.settings')->get('translate_english');
744 }
745
746 /**
747  * Implements hook_form_FORM_ID_alter() for system_file_system_settings().
748  *
749  * Add interface translation directory setting to directories configuration.
750  */
751 function locale_form_system_file_system_settings_alter(&$form, FormStateInterface $form_state) {
752   $form['translation_path'] = [
753     '#type' => 'textfield',
754     '#title' => t('Interface translations directory'),
755     '#default_value' => \Drupal::configFactory()->getEditable('locale.settings')->get('translation.path'),
756     '#maxlength' => 255,
757     '#description' => t('A local file system path where interface translation files will be stored.'),
758     '#required' => TRUE,
759     '#after_build' => ['system_check_directory'],
760     '#weight' => 10,
761   ];
762   if ($form['file_default_scheme']) {
763     $form['file_default_scheme']['#weight'] = 20;
764   }
765   $form['#submit'][] = 'locale_system_file_system_settings_submit';
766 }
767
768 /**
769  * Submit handler for the file system settings form.
770  *
771  * Clears the translation status when the Interface translations directory
772  * changes. Without a translations directory local po files in the directory
773  * should be ignored. The old translation status is no longer valid.
774  */
775 function locale_system_file_system_settings_submit(&$form, FormStateInterface $form_state) {
776   if ($form['translation_path']['#default_value'] != $form_state->getValue('translation_path')) {
777     locale_translation_clear_status();
778   }
779
780   \Drupal::configFactory()->getEditable('locale.settings')
781     ->set('translation.path', $form_state->getValue('translation_path'))
782     ->save();
783 }
784
785 /**
786  * Implements hook_preprocess_HOOK() for node templates.
787  */
788 function locale_preprocess_node(&$variables) {
789   /* @var $node \Drupal\node\NodeInterface */
790   $node = $variables['node'];
791   if ($node->language()->getId() != LanguageInterface::LANGCODE_NOT_SPECIFIED) {
792     $interface_language = \Drupal::languageManager()->getCurrentLanguage();
793
794     $node_language = $node->language();
795     if ($node_language->getId() != $interface_language->getId()) {
796       // If the node language was different from the page language, we should
797       // add markup to identify the language. Otherwise the page language is
798       // inherited.
799       $variables['attributes']['lang'] = $node_language->getId();
800       if ($node_language->getDirection() != $interface_language->getDirection()) {
801         // If text direction is different form the page's text direction, add
802         // direction information as well.
803         $variables['attributes']['dir'] = $node_language->getDirection();
804       }
805     }
806   }
807 }
808
809 /**
810  * Gets current translation status from the {locale_file} table.
811  *
812  * @return array
813  *   Array of translation file objects.
814  */
815 function locale_translation_get_file_history() {
816   $history = &drupal_static(__FUNCTION__, []);
817
818   if (empty($history)) {
819     // Get file history from the database.
820     $result = db_query('SELECT project, langcode, filename, version, uri, timestamp, last_checked FROM {locale_file}');
821     foreach ($result as $file) {
822       $file->type = $file->timestamp ? LOCALE_TRANSLATION_CURRENT : '';
823       $history[$file->project][$file->langcode] = $file;
824     }
825   }
826   return $history;
827 }
828
829 /**
830  * Updates the {locale_file} table.
831  *
832  * @param object $file
833  *   Object representing the file just imported.
834  *
835  * @return int
836  *   FALSE on failure. Otherwise SAVED_NEW or SAVED_UPDATED.
837  */
838 function locale_translation_update_file_history($file) {
839   $status = db_merge('locale_file')
840     ->key([
841       'project' => $file->project,
842       'langcode' => $file->langcode,
843     ])
844     ->fields([
845       'version' => $file->version,
846       'timestamp' => $file->timestamp,
847       'last_checked' => $file->last_checked,
848     ])
849     ->execute();
850   // The file history has changed, flush the static cache now.
851   // @todo Can we make this more fine grained?
852   drupal_static_reset('locale_translation_get_file_history');
853   return $status;
854 }
855
856 /**
857  * Deletes the history of downloaded translations.
858  *
859  * @param array $projects
860  *   Project name(s) to be deleted from the file history. If both project(s) and
861  *   language code(s) are specified the conditions will be ANDed.
862  * @param array $langcodes
863  *   Language code(s) to be deleted from the file history.
864  */
865 function locale_translation_file_history_delete($projects = [], $langcodes = []) {
866   $query = db_delete('locale_file');
867   if (!empty($projects)) {
868     $query->condition('project', $projects, 'IN');
869   }
870   if (!empty($langcodes)) {
871     $query->condition('langcode', $langcodes, 'IN');
872   }
873   $query->execute();
874 }
875
876 /**
877  * Gets the current translation status.
878  *
879  * @todo What is 'translation status'?
880  */
881 function locale_translation_get_status($projects = NULL, $langcodes = NULL) {
882   $result = [];
883   $status = \Drupal::keyValue('locale.translation_status')->getAll();
884   module_load_include('translation.inc', 'locale');
885   $projects = $projects ? $projects : array_keys(locale_translation_get_projects());
886   $langcodes = $langcodes ? $langcodes : array_keys(locale_translatable_language_list());
887
888   // Get the translation status of each project-language combination. If no
889   // status was stored, a new translation source is created.
890   foreach ($projects as $project) {
891     foreach ($langcodes as $langcode) {
892       if (isset($status[$project][$langcode])) {
893         $result[$project][$langcode] = $status[$project][$langcode];
894       }
895       else {
896         $sources = locale_translation_build_sources([$project], [$langcode]);
897         if (isset($sources[$project][$langcode])) {
898           $result[$project][$langcode] = $sources[$project][$langcode];
899         }
900       }
901     }
902   }
903   return $result;
904 }
905
906 /**
907  * Saves the status of translation sources in static cache.
908  *
909  * @param string $project
910  *   Machine readable project name.
911  * @param string $langcode
912  *   Language code.
913  * @param string $type
914  *   Type of data to be stored.
915  * @param object $data
916  *   File object also containing timestamp when the translation is last updated.
917  */
918 function locale_translation_status_save($project, $langcode, $type, $data) {
919   // Load the translation status or build it if not already available.
920   module_load_include('translation.inc', 'locale');
921   $status = locale_translation_get_status();
922   if (empty($status)) {
923     $projects = locale_translation_get_projects([$project]);
924     if (isset($projects[$project])) {
925       $status[$project][$langcode] = locale_translation_source_build($projects[$project], $langcode);
926     }
927   }
928
929   // Merge the new status data with the existing status.
930   if (isset($status[$project][$langcode])) {
931     switch ($type) {
932       case LOCALE_TRANSLATION_REMOTE:
933       case LOCALE_TRANSLATION_LOCAL:
934         // Add the source data to the status array.
935         $status[$project][$langcode]->files[$type] = $data;
936
937         // Check if this translation is the most recent one. Set timestamp and
938         // data type of the most recent translation source.
939         if (isset($data->timestamp) && $data->timestamp) {
940           if ($data->timestamp > $status[$project][$langcode]->timestamp) {
941             $status[$project][$langcode]->timestamp = $data->timestamp;
942             $status[$project][$langcode]->last_checked = REQUEST_TIME;
943             $status[$project][$langcode]->type = $type;
944           }
945         }
946         break;
947
948       case LOCALE_TRANSLATION_CURRENT:
949         $data->last_checked = REQUEST_TIME;
950         $status[$project][$langcode]->timestamp = $data->timestamp;
951         $status[$project][$langcode]->last_checked = $data->last_checked;
952         $status[$project][$langcode]->type = $type;
953         locale_translation_update_file_history($data);
954         break;
955     }
956
957     \Drupal::keyValue('locale.translation_status')->set($project, $status[$project]);
958     \Drupal::state()->set('locale.translation_last_checked', REQUEST_TIME);
959   }
960 }
961
962 /**
963  * Delete language entries from the status cache.
964  *
965  * @param array $langcodes
966  *   Language code(s) to be deleted from the cache.
967  */
968 function locale_translation_status_delete_languages($langcodes) {
969   if ($status = locale_translation_get_status()) {
970     foreach ($status as $project => $languages) {
971       foreach ($languages as $langcode => $source) {
972         if (in_array($langcode, $langcodes)) {
973           unset($status[$project][$langcode]);
974         }
975       }
976       \Drupal::keyValue('locale.translation_status')->set($project, $status[$project]);
977     }
978   }
979 }
980
981 /**
982  * Delete project entries from the status cache.
983  *
984  * @param array $projects
985  *   Project name(s) to be deleted from the cache.
986  */
987 function locale_translation_status_delete_projects($projects) {
988   \Drupal::keyValue('locale.translation_status')->deleteMultiple($projects);
989 }
990
991 /**
992  * Clear the translation status cache.
993  */
994 function locale_translation_clear_status() {
995   \Drupal::keyValue('locale.translation_status')->deleteAll();
996   \Drupal::state()->delete('locale.translation_last_checked');
997 }
998
999 /**
1000  * Checks whether remote translation sources are used.
1001  *
1002  * @return bool
1003  *   Returns TRUE if remote translations sources should be taken into account
1004  *   when checking or importing translation files, FALSE otherwise.
1005  */
1006 function locale_translation_use_remote_source() {
1007   return \Drupal::config('locale.settings')->get('translation.use_source') == LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL;
1008 }
1009
1010 /**
1011  * Check that a string is safe to be added or imported as a translation.
1012  *
1013  * This test can be used to detect possibly bad translation strings. It should
1014  * not have any false positives. But it is only a test, not a transformation,
1015  * as it destroys valid HTML. We cannot reliably filter translation strings
1016  * on import because some strings are irreversibly corrupted. For example,
1017  * a &amp; in the translation would get encoded to &amp;amp; by
1018  * \Drupal\Component\Utility\Xss::filter() before being put in the database,
1019  * and thus would be displayed incorrectly.
1020  *
1021  * The allowed tag list is like \Drupal\Component\Utility\Xss::filterAdmin(),
1022  * but omitting div and img as not needed for translation and likely to cause
1023  * layout issues (div) or a possible attack vector (img).
1024  */
1025 function locale_string_is_safe($string) {
1026   // Some strings have tokens in them. For tokens in the first part of href or
1027   // src HTML attributes, \Drupal\Component\Utility\Xss::filter() removes part
1028   // of the token, the part before the first colon.
1029   // \Drupal\Component\Utility\Xss::filter() assumes it could be an attempt to
1030   // inject javascript. When \Drupal\Component\Utility\Xss::filter() removes
1031   // part of tokens, it causes the string to not be translatable when it should
1032   // be translatable.
1033   // @see \Drupal\Tests\locale\Kernel\LocaleStringIsSafeTest::testLocaleStringIsSafe()
1034   //
1035   // We can recognize tokens since they are wrapped with brackets and are only
1036   // composed of alphanumeric characters, colon, underscore, and dashes. We can
1037   // be sure these strings are safe to strip out before the string is checked in
1038   // \Drupal\Component\Utility\Xss::filter() because no dangerous javascript
1039   // will match that pattern.
1040   //
1041   // Strings with tokens should not be assumed to be dangerous because even if
1042   // we evaluate them to be safe here, later replacing the token inside the
1043   // string will automatically mark it as unsafe as it is not the same string
1044   // anymore.
1045   //
1046   // @todo Do not strip out the token. Fix
1047   //   \Drupal\Component\Utility\Xss::filter() to not incorrectly alter the
1048   //   string. https://www.drupal.org/node/2372127
1049   $string = preg_replace('/\[[a-z0-9_-]+(:[a-z0-9_-]+)+\]/i', '', $string);
1050
1051   return Html::decodeEntities($string) == Html::decodeEntities(Xss::filter($string, ['a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'ol', 'p', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var']));
1052 }
1053
1054 /**
1055  * Refresh related information after string translations have been updated.
1056  *
1057  * The information that will be refreshed includes:
1058  * - JavaScript translations.
1059  * - Locale cache.
1060  * - Render cache.
1061  *
1062  * @param array $langcodes
1063  *   Language codes for updated translations.
1064  * @param array $lids
1065  *   (optional) List of string identifiers that have been updated / created.
1066  *   If not provided, all caches for the affected languages are cleared.
1067  */
1068 function _locale_refresh_translations($langcodes, $lids = []) {
1069   if (!empty($langcodes)) {
1070     // Update javascript translations if any of the strings has a javascript
1071     // location, or if no string ids were provided, update all languages.
1072     if (empty($lids) || ($strings = \Drupal::service('locale.storage')->getStrings(['lid' => $lids, 'type' => 'javascript']))) {
1073       array_map('_locale_invalidate_js', $langcodes);
1074     }
1075   }
1076
1077   // Throw locale.save_translation event.
1078   \Drupal::service('event_dispatcher')->dispatch(LocaleEvents::SAVE_TRANSLATION, new LocaleEvent($langcodes, $lids));
1079 }
1080
1081 /**
1082  * Refreshes configuration after string translations have been updated.
1083  *
1084  * @param array $langcodes
1085  *   Language codes for updated translations.
1086  * @param array $lids
1087  *   List of string identifiers that have been updated / created.
1088  */
1089 function _locale_refresh_configuration(array $langcodes, array $lids) {
1090   if ($lids && $langcodes && $names = Locale::config()->getStringNames($lids)) {
1091     Locale::config()->updateConfigTranslations($names, $langcodes);
1092   }
1093 }
1094
1095 /**
1096  * Removes the quotes and string concatenations from the string.
1097  *
1098  * @param string $string
1099  *   Single or double quoted strings, optionally concatenated by plus (+) sign.
1100  *
1101  * @return string
1102  *   String with leading and trailing quotes removed.
1103  */
1104 function _locale_strip_quotes($string) {
1105   return implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($string, 1, -1)));
1106 }
1107
1108 /**
1109  * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
1110  * Drupal.formatPlural() and inserts them into the database.
1111  *
1112  * @param string $filepath
1113  *   File name to parse.
1114  *
1115  * @throws Exception
1116  *   If a non-local file is attempted to be parsed.
1117  */
1118 function _locale_parse_js_file($filepath) {
1119   // The file path might contain a query string, so make sure we only use the
1120   // actual file.
1121   $parsed_url = UrlHelper::parse($filepath);
1122   $filepath = $parsed_url['path'];
1123
1124   // If there is still a protocol component in the path, reject that.
1125   if (strpos($filepath, ':')) {
1126     throw new Exception('Only local files should be passed to _locale_parse_js_file().');
1127   }
1128
1129   // Load the JavaScript file.
1130   $file = file_get_contents($filepath);
1131
1132   // Match all calls to Drupal.t() in an array.
1133   // Note: \s also matches newlines with the 's' modifier.
1134   preg_match_all('~
1135     [^\w]Drupal\s*\.\s*t\s*                       # match "Drupal.t" with whitespace
1136     \(\s*                                         # match "(" argument list start
1137     (' . LOCALE_JS_STRING . ')\s*                 # capture string argument
1138     (?:,\s*' . LOCALE_JS_OBJECT . '\s*            # optionally capture str args
1139       (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*) # optionally capture context
1140     ?)?                                           # close optional args
1141     [,\)]                                         # match ")" or "," to finish
1142     ~sx', $file, $t_matches);
1143
1144   // Match all Drupal.formatPlural() calls in another array.
1145   preg_match_all('~
1146     [^\w]Drupal\s*\.\s*formatPlural\s*  # match "Drupal.formatPlural" with whitespace
1147     \(                                  # match "(" argument list start
1148     \s*.+?\s*,\s*                       # match count argument
1149     (' . LOCALE_JS_STRING . ')\s*,\s*   # match singular string argument
1150     (                             # capture plural string argument
1151       (?:                         # non-capturing group to repeat string pieces
1152         (?:
1153           \'                      # match start of single-quoted string
1154           (?:\\\\\'|[^\'])*       # match any character except unescaped single-quote
1155           @count                  # match "@count"
1156           (?:\\\\\'|[^\'])*       # match any character except unescaped single-quote
1157           \'                      # match end of single-quoted string
1158           |
1159           "                       # match start of double-quoted string
1160           (?:\\\\"|[^"])*         # match any character except unescaped double-quote
1161           @count                  # match "@count"
1162           (?:\\\\"|[^"])*         # match any character except unescaped double-quote
1163           "                       # match end of double-quoted string
1164         )
1165         (?:\s*\+\s*)?             # match "+" with possible whitespace, for str concat
1166       )+                          # match multiple because we supports concatenating strs
1167     )\s*                          # end capturing of plural string argument
1168     (?:,\s*' . LOCALE_JS_OBJECT . '\s*          # optionally capture string args
1169       (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*)?  # optionally capture context
1170     )?
1171     [,\)]
1172     ~sx', $file, $plural_matches);
1173
1174   $matches = [];
1175
1176   // Add strings from Drupal.t().
1177   foreach ($t_matches[1] as $key => $string) {
1178     $matches[] = [
1179       'source'  => _locale_strip_quotes($string),
1180       'context' => _locale_strip_quotes($t_matches[2][$key]),
1181     ];
1182   }
1183
1184   // Add string from Drupal.formatPlural().
1185   foreach ($plural_matches[1] as $key => $string) {
1186     $matches[] = [
1187       'source'  => _locale_strip_quotes($string) . LOCALE_PLURAL_DELIMITER . _locale_strip_quotes($plural_matches[2][$key]),
1188       'context' => _locale_strip_quotes($plural_matches[3][$key]),
1189     ];
1190   }
1191
1192   // Loop through all matches and process them.
1193   foreach ($matches as $match) {
1194     $source = \Drupal::service('locale.storage')->findString($match);
1195
1196     if (!$source) {
1197       // We don't have the source string yet, thus we insert it into the
1198       // database.
1199       $source = \Drupal::service('locale.storage')->createString($match);
1200     }
1201
1202     // Besides adding the location this will tag it for current version.
1203     $source->addLocation('javascript', $filepath);
1204     $source->save();
1205   }
1206 }
1207
1208 /**
1209  * Force the JavaScript translation file(s) to be refreshed.
1210  *
1211  * This function sets a refresh flag for a specified language, or all
1212  * languages except English, if none specified. JavaScript translation
1213  * files are rebuilt (with locale_update_js_files()) the next time a
1214  * request is served in that language.
1215  *
1216  * @param string|null $langcode
1217  *   (optional) The language code for which the file needs to be refreshed, or
1218  *   NULL to refresh all languages. Defaults to NULL.
1219  *
1220  * @return array
1221  *   New content of the 'system.javascript_parsed' variable.
1222  */
1223 function _locale_invalidate_js($langcode = NULL) {
1224   $parsed = \Drupal::state()->get('system.javascript_parsed') ?: [];
1225
1226   if (empty($langcode)) {
1227     // Invalidate all languages.
1228     $languages = locale_translatable_language_list();
1229     foreach ($languages as $lcode => $data) {
1230       $parsed['refresh:' . $lcode] = 'waiting';
1231     }
1232   }
1233   else {
1234     // Invalidate single language.
1235     $parsed['refresh:' . $langcode] = 'waiting';
1236   }
1237
1238   \Drupal::state()->set('system.javascript_parsed', $parsed);
1239   return $parsed;
1240 }
1241
1242 /**
1243  * (Re-)Creates the JavaScript translation file for a language.
1244  *
1245  * @param string|null $langcode
1246  *   (optional) The language that the translation file should be (re)created
1247  *   for, or NULL for the current language. Defaults to NULL.
1248  *
1249  * @return bool
1250  *   TRUE if translation file exists, FALSE otherwise.
1251  */
1252 function _locale_rebuild_js($langcode = NULL) {
1253   $config = \Drupal::config('locale.settings');
1254   if (!isset($langcode)) {
1255     $language = \Drupal::languageManager()->getCurrentLanguage();
1256   }
1257   else {
1258     // Get information about the locale.
1259     $languages = \Drupal::languageManager()->getLanguages();
1260     $language = $languages[$langcode];
1261   }
1262
1263   // Construct the array for JavaScript translations.
1264   // Only add strings with a translation to the translations array.
1265   $conditions = [
1266     'type' => 'javascript',
1267     'language' => $language->getId(),
1268     'translated' => TRUE,
1269   ];
1270   $translations = [];
1271   foreach (\Drupal::service('locale.storage')->getTranslations($conditions) as $data) {
1272     $translations[$data->context][$data->source] = $data->translation;
1273   }
1274
1275   // Construct the JavaScript file, if there are translations.
1276   $data_hash = NULL;
1277   $data = $status = '';
1278   if (!empty($translations)) {
1279     $data = [
1280       'strings' => $translations,
1281     ];
1282
1283     $locale_plurals = \Drupal::service('locale.plural.formula')->getFormula($language->getId());
1284     if ($locale_plurals) {
1285       $data['pluralFormula'] = $locale_plurals;
1286     }
1287
1288     $data = 'window.drupalTranslations = ' . Json::encode($data) . ';';
1289     $data_hash = Crypt::hashBase64($data);
1290   }
1291
1292   // Construct the filepath where JS translation files are stored.
1293   // There is (on purpose) no front end to edit that variable.
1294   $dir = 'public://' . $config->get('javascript.directory');
1295
1296   // Delete old file, if we have no translations anymore, or a different file to
1297   // be saved.
1298   $locale_javascripts = \Drupal::state()->get('locale.translation.javascript') ?: [];
1299   $changed_hash = !isset($locale_javascripts[$language->getId()]) || ($locale_javascripts[$language->getId()] != $data_hash);
1300   if (!empty($locale_javascripts[$language->getId()]) && (!$data || $changed_hash)) {
1301     file_unmanaged_delete($dir . '/' . $language->getId() . '_' . $locale_javascripts[$language->getId()] . '.js');
1302     $locale_javascripts[$language->getId()] = '';
1303     $status = 'deleted';
1304   }
1305
1306   // Only create a new file if the content has changed or the original file got
1307   // lost.
1308   $dest = $dir . '/' . $language->getId() . '_' . $data_hash . '.js';
1309   if ($data && ($changed_hash || !file_exists($dest))) {
1310     // Ensure that the directory exists and is writable, if possible.
1311     file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
1312
1313     // Save the file.
1314     if (file_unmanaged_save_data($data, $dest)) {
1315       $locale_javascripts[$language->getId()] = $data_hash;
1316       // If we deleted a previous version of the file and we replace it with a
1317       // new one we have an update.
1318       if ($status == 'deleted') {
1319         $status = 'updated';
1320       }
1321       // If the file did not exist previously and the data has changed we have
1322       // a fresh creation.
1323       elseif ($changed_hash) {
1324         $status = 'created';
1325       }
1326       // If the data hash is unchanged the translation was lost and has to be
1327       // rebuilt.
1328       else {
1329         $status = 'rebuilt';
1330       }
1331     }
1332     else {
1333       $locale_javascripts[$language->getId()] = '';
1334       $status = 'error';
1335     }
1336   }
1337
1338   // Save the new JavaScript hash (or an empty value if the file just got
1339   // deleted). Act only if some operation was executed that changed the hash
1340   // code.
1341   if ($status && $changed_hash) {
1342     \Drupal::state()->set('locale.translation.javascript', $locale_javascripts);
1343   }
1344
1345   // Log the operation and return success flag.
1346   $logger = \Drupal::logger('locale');
1347   switch ($status) {
1348     case 'updated':
1349       $logger->notice('Updated JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
1350       return TRUE;
1351
1352     case 'rebuilt':
1353       $logger->warning('JavaScript translation file %file.js was lost.', ['%file' => $locale_javascripts[$language->getId()]]);
1354       // Proceed to the 'created' case as the JavaScript translation file has
1355       // been created again.
1356
1357     case 'created':
1358       $logger->notice('Created JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
1359       return TRUE;
1360
1361     case 'deleted':
1362       $logger->notice('Removed JavaScript translation file for the language %language because no translations currently exist for that language.', ['%language' => $language->getName()]);
1363       return TRUE;
1364
1365     case 'error':
1366       $logger->error('An error occurred during creation of the JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
1367       return FALSE;
1368
1369     default:
1370       // No operation needed.
1371       return TRUE;
1372   }
1373 }
1374
1375 /**
1376  * Form element callback: After build changes to the language update table.
1377  *
1378  * Adds labels to the languages and removes checkboxes from languages from which
1379  * translation files could not be found.
1380  */
1381 function locale_translation_language_table($form_element) {
1382   // Remove checkboxes of languages without updates.
1383   if ($form_element['#not_found']) {
1384     foreach ($form_element['#not_found'] as $langcode) {
1385       $form_element[$langcode] = [];
1386     }
1387   }
1388   return $form_element;
1389 }