Upgraded drupal core with security updates
[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 = 'http://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 $count
265  *   Number to return plural for.
266  * @param $langcode
267  *   Optional language code to translate to a language other than
268  *   what is used to display the page.
269  *
270  * @return
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 /**
313  * Implements hook_modules_installed().
314  */
315 function locale_modules_installed($modules) {
316   locale_system_set_config_langcodes();
317
318   $components['module'] = $modules;
319   locale_system_update($components);
320 }
321
322 /**
323  * Implements hook_module_preuninstall().
324  */
325 function locale_module_preuninstall($module) {
326   $components['module'] = [$module];
327   locale_system_remove($components);
328 }
329
330 /**
331  * Implements hook_themes_installed().
332  */
333 function locale_themes_installed($themes) {
334   locale_system_set_config_langcodes();
335
336   $components['theme'] = $themes;
337   locale_system_update($components);
338 }
339
340 /**
341  * Implements hook_themes_uninstalled().
342  */
343 function locale_themes_uninstalled($themes) {
344   $components['theme'] = $themes;
345   locale_system_remove($components);
346 }
347
348 /**
349  * Implements hook_cron().
350  *
351  * @see \Drupal\locale\Plugin\QueueWorker\LocaleTranslation
352  */
353 function locale_cron() {
354   // Update translations only when an update frequency was set by the admin
355   // and a translatable language was set.
356   // Update tasks are added to the queue here but processed by Drupal's cron.
357   if ($frequency = \Drupal::config('locale.settings')->get('translation.update_interval_days') && locale_translatable_language_list()) {
358     module_load_include('translation.inc', 'locale');
359     locale_cron_fill_queue();
360   }
361 }
362
363 /**
364  * Updates default configuration when new modules or themes are installed.
365  */
366 function locale_system_set_config_langcodes() {
367   // Need to rewrite some default configuration language codes if the default
368   // site language is not English.
369   $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
370   if ($default_langcode != 'en') {
371     // Update active configuration copies of all prior shipped configuration if
372     // they are still English. It is not enough to change configuration shipped
373     // with the components just installed, because installing a component such
374     // as views or tour module may bring in default configuration from prior
375     // components.
376     $names = Locale::config()->getComponentNames();
377     foreach ($names as $name) {
378       $config = \Drupal::configFactory()->reset($name)->getEditable($name);
379       // Should only update if still exists in active configuration. If locale
380       // module is enabled later, then some configuration may not exist anymore.
381       if (!$config->isNew()) {
382         $langcode = $config->get('langcode');
383         if (empty($langcode) || $langcode == 'en') {
384           $config->set('langcode', $default_langcode)->save();
385         }
386       }
387     }
388   }
389 }
390
391 /**
392  * Imports translations when new modules or themes are installed.
393  *
394  * This function will start a batch to import translations for the added
395  * components.
396  *
397  * @param array $components
398  *   An array of arrays of component (theme and/or module) names to import
399  *   translations for, indexed by type.
400  */
401 function locale_system_update(array $components) {
402   $components += ['module' => [], 'theme' => []];
403   $list = array_merge($components['module'], $components['theme']);
404
405   // Skip running the translation imports if in the installer,
406   // because it would break out of the installer flow. We have
407   // built-in support for translation imports in the installer.
408   if (!drupal_installation_attempted() && locale_translatable_language_list()) {
409     if (\Drupal::config('locale.settings')->get('translation.import_enabled')) {
410       module_load_include('compare.inc', 'locale');
411
412       // Update the list of translatable projects and start the import batch.
413       // Only when new projects are added the update batch will be triggered.
414       // Not each enabled module will introduce a new project. E.g. sub modules.
415       $projects = array_keys(locale_translation_build_projects());
416       if ($list = array_intersect($list, $projects)) {
417         module_load_include('fetch.inc', 'locale');
418         // Get translation status of the projects, download and update
419         // translations.
420         $options = _locale_translation_default_update_options();
421         $batch = locale_translation_batch_update_build($list, [], $options);
422         batch_set($batch);
423       }
424     }
425
426     // Construct a batch to update configuration for all components. Installing
427     // this component may have installed configuration from any number of other
428     // components. Do this even if import is not enabled because parsing new
429     // configuration may expose new source strings.
430     \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
431     if ($batch = locale_config_batch_update_components([])) {
432       batch_set($batch);
433     }
434   }
435 }
436
437 /**
438  * Delete translation history of modules and themes.
439  *
440  * Only the translation history is removed, not the source strings or
441  * translations. This is not possible because strings are shared between
442  * modules and we have no record of which string is used by which module.
443  *
444  * @param array $components
445  *   An array of arrays of component (theme and/or module) names to import
446  *   translations for, indexed by type.
447  */
448 function locale_system_remove($components) {
449   $components += ['module' => [], 'theme' => []];
450   $list = array_merge($components['module'], $components['theme']);
451   if ($language_list = locale_translatable_language_list()) {
452     module_load_include('compare.inc', 'locale');
453     \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
454
455     // Only when projects are removed, the translation files and records will be
456     // deleted. Not each disabled module will remove a project, e.g., sub
457     // modules.
458     $projects = array_keys(locale_translation_get_projects());
459     if ($list = array_intersect($list, $projects)) {
460       locale_translation_file_history_delete($list);
461
462       // Remove translation files.
463       locale_translate_delete_translation_files($list, []);
464
465       // Remove translatable projects.
466       // Follow-up issue https://www.drupal.org/node/1842362 to replace the
467       // {locale_project} table. Then change this to a function call.
468       \Drupal::service('locale.project')->deleteMultiple($list);
469
470       // Clear the translation status.
471       locale_translation_status_delete_projects($list);
472     }
473
474   }
475 }
476
477 /**
478  * Implements hook_cache_flush().
479  */
480 function locale_cache_flush() {
481   \Drupal::state()->delete('system.javascript_parsed');
482 }
483
484 /**
485  * Implements hook_js_alter().
486  */
487 function locale_js_alter(&$javascript, AttachedAssetsInterface $assets) {
488   // @todo Remove this in https://www.drupal.org/node/2421323.
489   $files = [];
490   foreach ($javascript as $item) {
491     if (isset($item['type']) && $item['type'] == 'file') {
492       // Ignore the JS translation placeholder file.
493       if ($item['data'] === 'core/modules/locale/locale.translation.js') {
494         continue;
495       }
496       $files[] = $item['data'];
497     }
498   }
499
500   // Replace the placeholder file with the actual JS translation file.
501   $placeholder_file = 'core/modules/locale/locale.translation.js';
502   if (isset($javascript[$placeholder_file])) {
503     if ($translation_file = locale_js_translate($files)) {
504       $js_translation_asset = &$javascript[$placeholder_file];
505       $js_translation_asset['data'] = $translation_file;
506       // @todo Remove this when https://www.drupal.org/node/1945262 lands.
507       // Decrease the weight so that the translation file is loaded first.
508       $js_translation_asset['weight'] = $javascript['core/misc/drupal.js']['weight'] - 0.001;
509     }
510     else {
511       // If no translation file exists, then remove the placeholder JS asset.
512       unset($javascript[$placeholder_file]);
513     }
514   }
515 }
516
517 /**
518  * Returns a list of translation files given a list of JavaScript files.
519  *
520  * This function checks all JavaScript files passed and invokes parsing if they
521  * have not yet been parsed for Drupal.t() and Drupal.formatPlural() calls.
522  * Also refreshes the JavaScript translation files if necessary, and returns
523  * the filepath to the translation file (if any).
524  *
525  * @param array $files
526  *   An array of local file paths.
527  *
528  * @return string|null
529  *   The filepath to the translation file or NULL if no translation is
530  *   applicable.
531  */
532 function locale_js_translate(array $files = []) {
533   $language_interface = \Drupal::languageManager()->getCurrentLanguage();
534
535   $dir = 'public://' . \Drupal::config('locale.settings')->get('javascript.directory');
536   $parsed = \Drupal::state()->get('system.javascript_parsed') ?: [];
537   $new_files = FALSE;
538
539   foreach ($files as $filepath) {
540     if (!in_array($filepath, $parsed)) {
541       // Don't parse our own translations files.
542       if (substr($filepath, 0, strlen($dir)) != $dir) {
543         _locale_parse_js_file($filepath);
544         $parsed[] = $filepath;
545         $new_files = TRUE;
546       }
547     }
548   }
549
550   // If there are any new source files we parsed, invalidate existing
551   // JavaScript translation files for all languages, adding the refresh
552   // flags into the existing array.
553   if ($new_files) {
554     $parsed += _locale_invalidate_js();
555   }
556
557   // If necessary, rebuild the translation file for the current language.
558   if (!empty($parsed['refresh:' . $language_interface->getId()])) {
559     // Don't clear the refresh flag on failure, so that another try will
560     // be performed later.
561     if (_locale_rebuild_js()) {
562       unset($parsed['refresh:' . $language_interface->getId()]);
563     }
564     // Store any changes after refresh was attempted.
565     \Drupal::state()->set('system.javascript_parsed', $parsed);
566   }
567   // If no refresh was attempted, but we have new source files, we need
568   // to store them too. This occurs if current page is in English.
569   elseif ($new_files) {
570     \Drupal::state()->set('system.javascript_parsed', $parsed);
571   }
572
573   // Add the translation JavaScript file to the page.
574   $locale_javascripts = \Drupal::state()->get('locale.translation.javascript') ?: [];
575   $translation_file = NULL;
576   if (!empty($files) && !empty($locale_javascripts[$language_interface->getId()])) {
577     // Add the translation JavaScript file to the page.
578     $translation_file = $dir . '/' . $language_interface->getId() . '_' . $locale_javascripts[$language_interface->getId()] . '.js';
579   }
580   return $translation_file;
581 }
582
583 /**
584  * Implements hook_library_info_alter().
585  *
586  * Provides the language support for the jQuery UI Date Picker.
587  */
588 function locale_library_info_alter(array &$libraries, $module) {
589   if ($module === 'core' && isset($libraries['jquery.ui.datepicker'])) {
590     $libraries['jquery.ui.datepicker']['dependencies'][] = 'locale/drupal.locale.datepicker';
591     $libraries['jquery.ui.datepicker']['drupalSettings']['jquery']['ui']['datepicker'] = [
592       'isRTL' => NULL,
593       'firstDay' => NULL,
594     ];
595   }
596
597   // When the locale module is enabled, we update the core/drupal library to
598   // have a dependency on the locale/translations library, which provides
599   // window.drupalTranslations, containing the translations for all strings in
600   // JavaScript assets in the current language.
601   // @see locale_js_alter()
602   if ($module === 'core' && isset($libraries['drupal'])) {
603     $libraries['drupal']['dependencies'][] = 'locale/translations';
604   }
605 }
606
607 /**
608  * Implements hook_js_settings_alter().
609  *
610  * Generates the values for the altered core/jquery.ui.datepicker library.
611  */
612 function locale_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
613   if (isset($settings['jquery']['ui']['datepicker'])) {
614     $language_interface = \Drupal::languageManager()->getCurrentLanguage();
615     $settings['jquery']['ui']['datepicker']['isRTL'] = $language_interface->getDirection() == LanguageInterface::DIRECTION_RTL;
616     $settings['jquery']['ui']['datepicker']['firstDay'] = \Drupal::config('system.date')->get('first_day');
617   }
618 }
619
620 /**
621  * Implements hook_form_FORM_ID_alter() for language_admin_overview_form().
622  */
623 function locale_form_language_admin_overview_form_alter(&$form, FormStateInterface $form_state) {
624   $languages = $form['languages']['#languages'];
625
626   $total_strings = \Drupal::service('locale.storage')->countStrings();
627   $stats = array_fill_keys(array_keys($languages), []);
628
629   // If we have source strings, count translations and calculate progress.
630   if (!empty($total_strings)) {
631     $translations = \Drupal::service('locale.storage')->countTranslations();
632     foreach ($translations as $langcode => $translated) {
633       $stats[$langcode]['translated'] = $translated;
634       if ($translated > 0) {
635         $stats[$langcode]['ratio'] = round($translated / $total_strings * 100, 2);
636       }
637     }
638   }
639
640   array_splice($form['languages']['#header'], -1, 0, ['translation-interface' => t('Interface translation')]);
641
642   foreach ($languages as $langcode => $language) {
643     $stats[$langcode] += [
644       'translated' => 0,
645       'ratio' => 0,
646     ];
647     if (!$language->isLocked() && locale_is_translatable($langcode)) {
648       $form['languages'][$langcode]['locale_statistics'] = [
649         '#markup' => \Drupal::l(
650           t('@translated/@total (@ratio%)', [
651             '@translated' => $stats[$langcode]['translated'],
652             '@total' => $total_strings,
653             '@ratio' => $stats[$langcode]['ratio'],
654           ]),
655           new Url('locale.translate_page', [], ['query' => ['langcode' => $langcode]])
656         ),
657       ];
658     }
659     else {
660       $form['languages'][$langcode]['locale_statistics'] = [
661         '#markup' => t('not applicable'),
662       ];
663     }
664     // #type = link doesn't work with #weight on table.
665     // reset and set it back after locale_statistics to get it at the right end.
666     $operations = $form['languages'][$langcode]['operations'];
667     unset($form['languages'][$langcode]['operations']);
668     $form['languages'][$langcode]['operations'] = $operations;
669   }
670 }
671
672 /**
673  * Implements hook_form_FORM_ID_alter() for language_admin_add_form().
674  */
675 function locale_form_language_admin_add_form_alter(&$form, FormStateInterface $form_state) {
676   $form['predefined_submit']['#submit'][] = 'locale_form_language_admin_add_form_alter_submit';
677   $form['custom_language']['submit']['#submit'][] = 'locale_form_language_admin_add_form_alter_submit';
678 }
679
680 /**
681  * Form submission handler for language_admin_add_form().
682  *
683  * Set a batch for a newly-added language.
684  */
685 function locale_form_language_admin_add_form_alter_submit($form, FormStateInterface $form_state) {
686   \Drupal::moduleHandler()->loadInclude('locale', 'fetch.inc');
687   $options = _locale_translation_default_update_options();
688
689   if ($form_state->isValueEmpty('predefined_langcode') || $form_state->getValue('predefined_langcode') == 'custom') {
690     $langcode = $form_state->getValue('langcode');
691   }
692   else {
693     $langcode = $form_state->getValue('predefined_langcode');
694   }
695
696   if (\Drupal::config('locale.settings')->get('translation.import_enabled')) {
697     // Download and import translations for the newly added language.
698     $batch = locale_translation_batch_update_build([], [$langcode], $options);
699     batch_set($batch);
700   }
701
702   // Create or update all configuration translations for this language. If we
703   // are adding English then we need to run this even if import is not enabled,
704   // because then we extract English sources from shipped configuration.
705   if (\Drupal::config('locale.settings')->get('translation.import_enabled') || $langcode == 'en') {
706     \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
707     if ($batch = locale_config_batch_update_components($options, [$langcode])) {
708       batch_set($batch);
709     }
710   }
711 }
712
713 /**
714  * Implements hook_form_FORM_ID_alter() for language_admin_edit_form().
715  */
716 function locale_form_language_admin_edit_form_alter(&$form, FormStateInterface $form_state) {
717   if ($form['langcode']['#type'] == 'value' && $form['langcode']['#value'] == 'en') {
718     $form['locale_translate_english'] = [
719       '#title' => t('Enable interface translation to English'),
720       '#type' => 'checkbox',
721       '#default_value' => \Drupal::configFactory()->getEditable('locale.settings')->get('translate_english'),
722     ];
723     $form['actions']['submit']['#submit'][] = 'locale_form_language_admin_edit_form_alter_submit';
724   }
725 }
726
727 /**
728  * Form submission handler for language_admin_edit_form().
729  */
730 function locale_form_language_admin_edit_form_alter_submit($form, FormStateInterface $form_state) {
731   \Drupal::configFactory()->getEditable('locale.settings')->set('translate_english', intval($form_state->getValue('locale_translate_english')))->save();
732 }
733
734 /**
735  * Checks whether $langcode is a language supported as a locale target.
736  *
737  * @param string $langcode
738  *   The language code.
739  *
740  * @return bool
741  *   Whether $langcode can be translated to in locale.
742  */
743 function locale_is_translatable($langcode) {
744   return $langcode != 'en' || \Drupal::config('locale.settings')->get('translate_english');
745 }
746
747 /**
748  * Implements hook_form_FORM_ID_alter() for system_file_system_settings().
749  *
750  * Add interface translation directory setting to directories configuration.
751  */
752 function locale_form_system_file_system_settings_alter(&$form, FormStateInterface $form_state) {
753   $form['translation_path'] = [
754     '#type' => 'textfield',
755     '#title' => t('Interface translations directory'),
756     '#default_value' => \Drupal::configFactory()->getEditable('locale.settings')->get('translation.path'),
757     '#maxlength' => 255,
758     '#description' => t('A local file system path where interface translation files will be stored.'),
759     '#required' => TRUE,
760     '#after_build' => ['system_check_directory'],
761     '#weight' => 10,
762   ];
763   if ($form['file_default_scheme']) {
764     $form['file_default_scheme']['#weight'] = 20;
765   }
766   $form['#submit'][] = 'locale_system_file_system_settings_submit';
767 }
768
769 /**
770  * Submit handler for the file system settings form.
771  *
772  * Clears the translation status when the Interface translations directory
773  * changes. Without a translations directory local po files in the directory
774  * should be ignored. The old translation status is no longer valid.
775  */
776 function locale_system_file_system_settings_submit(&$form, FormStateInterface $form_state) {
777   if ($form['translation_path']['#default_value'] != $form_state->getValue('translation_path')) {
778     locale_translation_clear_status();
779   }
780
781   \Drupal::configFactory()->getEditable('locale.settings')
782     ->set('translation.path', $form_state->getValue('translation_path'))
783     ->save();
784 }
785
786 /**
787  * Implements hook_preprocess_HOOK() for node templates.
788  */
789 function locale_preprocess_node(&$variables) {
790   /* @var $node \Drupal\node\NodeInterface */
791   $node = $variables['node'];
792   if ($node->language()->getId() != LanguageInterface::LANGCODE_NOT_SPECIFIED) {
793     $interface_language = \Drupal::languageManager()->getCurrentLanguage();
794
795     $node_language = $node->language();
796     if ($node_language->getId() != $interface_language->getId()) {
797       // If the node language was different from the page language, we should
798       // add markup to identify the language. Otherwise the page language is
799       // inherited.
800       $variables['attributes']['lang'] = $node_language->getId();
801       if ($node_language->getDirection() != $interface_language->getDirection()) {
802         // If text direction is different form the page's text direction, add
803         // direction information as well.
804         $variables['attributes']['dir'] = $node_language->getDirection();
805       }
806     }
807   }
808 }
809
810 /**
811  * Gets current translation status from the {locale_file} table.
812  *
813  * @return array
814  *   Array of translation file objects.
815  */
816 function locale_translation_get_file_history() {
817   $history = &drupal_static(__FUNCTION__, []);
818
819   if (empty($history)) {
820     // Get file history from the database.
821     $result = db_query('SELECT project, langcode, filename, version, uri, timestamp, last_checked FROM {locale_file}');
822     foreach ($result as $file) {
823       $file->type = $file->timestamp ? LOCALE_TRANSLATION_CURRENT : '';
824       $history[$file->project][$file->langcode] = $file;
825     }
826   }
827   return $history;
828 }
829
830 /**
831  * Updates the {locale_file} table.
832  *
833  * @param object $file
834  *   Object representing the file just imported.
835  *
836  * @return int
837  *   FALSE on failure. Otherwise SAVED_NEW or SAVED_UPDATED.
838  */
839 function locale_translation_update_file_history($file) {
840   $status = db_merge('locale_file')
841     ->key([
842       'project' => $file->project,
843       'langcode' => $file->langcode,
844     ])
845     ->fields([
846       'version' => $file->version,
847       'timestamp' => $file->timestamp,
848       'last_checked' => $file->last_checked,
849     ])
850     ->execute();
851   // The file history has changed, flush the static cache now.
852   // @todo Can we make this more fine grained?
853   drupal_static_reset('locale_translation_get_file_history');
854   return $status;
855 }
856
857 /**
858  * Deletes the history of downloaded translations.
859  *
860  * @param array $projects
861  *   Project name(s) to be deleted from the file history. If both project(s) and
862  *   language code(s) are specified the conditions will be ANDed.
863  * @param array $langcodes
864  *   Language code(s) to be deleted from the file history.
865  */
866 function locale_translation_file_history_delete($projects = [], $langcodes = []) {
867   $query = db_delete('locale_file');
868   if (!empty($projects)) {
869     $query->condition('project', $projects, 'IN');
870   }
871   if (!empty($langcodes)) {
872     $query->condition('langcode', $langcodes, 'IN');
873   }
874   $query->execute();
875 }
876
877 /**
878  * Gets the current translation status.
879  *
880  * @todo What is 'translation status'?
881  */
882 function locale_translation_get_status($projects = NULL, $langcodes = NULL) {
883   $result = [];
884   $status = \Drupal::keyValue('locale.translation_status')->getAll();
885   module_load_include('translation.inc', 'locale');
886   $projects = $projects ? $projects : array_keys(locale_translation_get_projects());
887   $langcodes = $langcodes ? $langcodes : array_keys(locale_translatable_language_list());
888
889   // Get the translation status of each project-language combination. If no
890   // status was stored, a new translation source is created.
891   foreach ($projects as $project) {
892     foreach ($langcodes as $langcode) {
893       if (isset($status[$project][$langcode])) {
894         $result[$project][$langcode] = $status[$project][$langcode];
895       }
896       else {
897         $sources = locale_translation_build_sources([$project], [$langcode]);
898         if (isset($sources[$project][$langcode])) {
899           $result[$project][$langcode] = $sources[$project][$langcode];
900         }
901       }
902     }
903   }
904   return $result;
905 }
906
907 /**
908  * Saves the status of translation sources in static cache.
909  *
910  * @param string $project
911  *   Machine readable project name.
912  * @param string $langcode
913  *   Language code.
914  * @param string $type
915  *   Type of data to be stored.
916  * @param object $data
917  *   File object also containing timestamp when the translation is last updated.
918  */
919 function locale_translation_status_save($project, $langcode, $type, $data) {
920   // Load the translation status or build it if not already available.
921   module_load_include('translation.inc', 'locale');
922   $status = locale_translation_get_status();
923   if (empty($status)) {
924     $projects = locale_translation_get_projects([$project]);
925     if (isset($projects[$project])) {
926       $status[$project][$langcode] = locale_translation_source_build($projects[$project], $langcode);
927     }
928   }
929
930   // Merge the new status data with the existing status.
931   if (isset($status[$project][$langcode])) {
932     switch ($type) {
933       case LOCALE_TRANSLATION_REMOTE:
934       case LOCALE_TRANSLATION_LOCAL:
935         // Add the source data to the status array.
936         $status[$project][$langcode]->files[$type] = $data;
937
938         // Check if this translation is the most recent one. Set timestamp and
939         // data type of the most recent translation source.
940         if (isset($data->timestamp) && $data->timestamp) {
941           if ($data->timestamp > $status[$project][$langcode]->timestamp) {
942             $status[$project][$langcode]->timestamp = $data->timestamp;
943             $status[$project][$langcode]->last_checked = REQUEST_TIME;
944             $status[$project][$langcode]->type = $type;
945           }
946         }
947         break;
948
949       case LOCALE_TRANSLATION_CURRENT:
950         $data->last_checked = REQUEST_TIME;
951         $status[$project][$langcode]->timestamp = $data->timestamp;
952         $status[$project][$langcode]->last_checked = $data->last_checked;
953         $status[$project][$langcode]->type = $type;
954         locale_translation_update_file_history($data);
955         break;
956     }
957
958     \Drupal::keyValue('locale.translation_status')->set($project, $status[$project]);
959     \Drupal::state()->set('locale.translation_last_checked', REQUEST_TIME);
960   }
961 }
962
963 /**
964  * Delete language entries from the status cache.
965  *
966  * @param array $langcodes
967  *   Language code(s) to be deleted from the cache.
968  */
969 function locale_translation_status_delete_languages($langcodes) {
970   if ($status = locale_translation_get_status()) {
971     foreach ($status as $project => $languages) {
972       foreach ($languages as $langcode => $source) {
973         if (in_array($langcode, $langcodes)) {
974           unset($status[$project][$langcode]);
975         }
976       }
977       \Drupal::keyValue('locale.translation_status')->set($project, $status[$project]);
978     }
979   }
980 }
981
982 /**
983  * Delete project entries from the status cache.
984  *
985  * @param array $projects
986  *   Project name(s) to be deleted from the cache.
987  */
988 function locale_translation_status_delete_projects($projects) {
989   \Drupal::keyValue('locale.translation_status')->deleteMultiple($projects);
990 }
991
992 /**
993  * Clear the translation status cache.
994  */
995 function locale_translation_clear_status() {
996   \Drupal::keyValue('locale.translation_status')->deleteAll();
997   \Drupal::state()->delete('locale.translation_last_checked');
998 }
999
1000 /**
1001  * Checks whether remote translation sources are used.
1002  *
1003  * @return bool
1004  *   Returns TRUE if remote translations sources should be taken into account
1005  *   when checking or importing translation files, FALSE otherwise.
1006  */
1007 function locale_translation_use_remote_source() {
1008   return \Drupal::config('locale.settings')->get('translation.use_source') == LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL;
1009 }
1010
1011 /**
1012  * Check that a string is safe to be added or imported as a translation.
1013  *
1014  * This test can be used to detect possibly bad translation strings. It should
1015  * not have any false positives. But it is only a test, not a transformation,
1016  * as it destroys valid HTML. We cannot reliably filter translation strings
1017  * on import because some strings are irreversibly corrupted. For example,
1018  * a &amp; in the translation would get encoded to &amp;amp; by
1019  * \Drupal\Component\Utility\Xss::filter() before being put in the database,
1020  * and thus would be displayed incorrectly.
1021  *
1022  * The allowed tag list is like \Drupal\Component\Utility\Xss::filterAdmin(),
1023  * but omitting div and img as not needed for translation and likely to cause
1024  * layout issues (div) or a possible attack vector (img).
1025  */
1026 function locale_string_is_safe($string) {
1027   // Some strings have tokens in them. For tokens in the first part of href or
1028   // src HTML attributes, \Drupal\Component\Utility\Xss::filter() removes part
1029   // of the token, the part before the first colon.
1030   // \Drupal\Component\Utility\Xss::filter() assumes it could be an attempt to
1031   // inject javascript. When \Drupal\Component\Utility\Xss::filter() removes
1032   // part of tokens, it causes the string to not be translatable when it should
1033   // be translatable.
1034   // @see \Drupal\Tests\locale\Kernel\LocaleStringIsSafeTest::testLocaleStringIsSafe()
1035   //
1036   // We can recognize tokens since they are wrapped with brackets and are only
1037   // composed of alphanumeric characters, colon, underscore, and dashes. We can
1038   // be sure these strings are safe to strip out before the string is checked in
1039   // \Drupal\Component\Utility\Xss::filter() because no dangerous javascript
1040   // will match that pattern.
1041   //
1042   // Strings with tokens should not be assumed to be dangerous because even if
1043   // we evaluate them to be safe here, later replacing the token inside the
1044   // string will automatically mark it as unsafe as it is not the same string
1045   // anymore.
1046   //
1047   // @todo Do not strip out the token. Fix
1048   //   \Drupal\Component\Utility\Xss::filter() to not incorrectly alter the
1049   //   string. https://www.drupal.org/node/2372127
1050   $string = preg_replace('/\[[a-z0-9_-]+(:[a-z0-9_-]+)+\]/i', '', $string);
1051
1052   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']));
1053 }
1054
1055 /**
1056  * Refresh related information after string translations have been updated.
1057  *
1058  * The information that will be refreshed includes:
1059  * - JavaScript translations.
1060  * - Locale cache.
1061  * - Render cache.
1062  *
1063  * @param array $langcodes
1064  *   Language codes for updated translations.
1065  * @param array $lids
1066  *   (optional) List of string identifiers that have been updated / created.
1067  *   If not provided, all caches for the affected languages are cleared.
1068  */
1069 function _locale_refresh_translations($langcodes, $lids = []) {
1070   if (!empty($langcodes)) {
1071     // Update javascript translations if any of the strings has a javascript
1072     // location, or if no string ids were provided, update all languages.
1073     if (empty($lids) || ($strings = \Drupal::service('locale.storage')->getStrings(['lid' => $lids, 'type' => 'javascript']))) {
1074       array_map('_locale_invalidate_js', $langcodes);
1075     }
1076   }
1077
1078   // Throw locale.save_translation event.
1079   \Drupal::service('event_dispatcher')->dispatch(LocaleEvents::SAVE_TRANSLATION, new LocaleEvent($langcodes, $lids));
1080 }
1081
1082 /**
1083  * Refreshes configuration after string translations have been updated.
1084  *
1085  * @param array $langcodes
1086  *   Language codes for updated translations.
1087  * @param array $lids
1088  *   List of string identifiers that have been updated / created.
1089  */
1090 function _locale_refresh_configuration(array $langcodes, array $lids) {
1091   if ($lids && $langcodes && $names = Locale::config()->getStringNames($lids)) {
1092     Locale::config()->updateConfigTranslations($names, $langcodes);
1093   }
1094 }
1095
1096 /**
1097  * Removes the quotes and string concatenations from the string.
1098  *
1099  * @param string $string
1100  *   Single or double quoted strings, optionally concatenated by plus (+) sign.
1101  *
1102  * @return string
1103  *   String with leading and trailing quotes removed.
1104  */
1105 function _locale_strip_quotes($string) {
1106   return implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($string, 1, -1)));
1107 }
1108
1109 /**
1110  * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
1111  * Drupal.formatPlural() and inserts them into the database.
1112  *
1113  * @param string $filepath
1114  *   File name to parse.
1115  *
1116  * @return array
1117  *   Array of string objects to update indexed by context and source.
1118  *
1119  * @throws Exception
1120  *   If a non-local file is attempted to be parsed.
1121  */
1122 function _locale_parse_js_file($filepath) {
1123   // The file path might contain a query string, so make sure we only use the
1124   // actual file.
1125   $parsed_url = UrlHelper::parse($filepath);
1126   $filepath = $parsed_url['path'];
1127
1128   // If there is still a protocol component in the path, reject that.
1129   if (strpos($filepath, ':')) {
1130     throw new Exception('Only local files should be passed to _locale_parse_js_file().');
1131   }
1132
1133   // Load the JavaScript file.
1134   $file = file_get_contents($filepath);
1135
1136   // Match all calls to Drupal.t() in an array.
1137   // Note: \s also matches newlines with the 's' modifier.
1138   preg_match_all('~
1139     [^\w]Drupal\s*\.\s*t\s*                       # match "Drupal.t" with whitespace
1140     \(\s*                                         # match "(" argument list start
1141     (' . LOCALE_JS_STRING . ')\s*                 # capture string argument
1142     (?:,\s*' . LOCALE_JS_OBJECT . '\s*            # optionally capture str args
1143       (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*) # optionally capture context
1144     ?)?                                           # close optional args
1145     [,\)]                                         # match ")" or "," to finish
1146     ~sx', $file, $t_matches);
1147
1148   // Match all Drupal.formatPlural() calls in another array.
1149   preg_match_all('~
1150     [^\w]Drupal\s*\.\s*formatPlural\s*  # match "Drupal.formatPlural" with whitespace
1151     \(                                  # match "(" argument list start
1152     \s*.+?\s*,\s*                       # match count argument
1153     (' . LOCALE_JS_STRING . ')\s*,\s*   # match singular string argument
1154     (                             # capture plural string argument
1155       (?:                         # non-capturing group to repeat string pieces
1156         (?:
1157           \'                      # match start of single-quoted string
1158           (?:\\\\\'|[^\'])*       # match any character except unescaped single-quote
1159           @count                  # match "@count"
1160           (?:\\\\\'|[^\'])*       # match any character except unescaped single-quote
1161           \'                      # match end of single-quoted string
1162           |
1163           "                       # match start of double-quoted string
1164           (?:\\\\"|[^"])*         # match any character except unescaped double-quote
1165           @count                  # match "@count"
1166           (?:\\\\"|[^"])*         # match any character except unescaped double-quote
1167           "                       # match end of double-quoted string
1168         )
1169         (?:\s*\+\s*)?             # match "+" with possible whitespace, for str concat
1170       )+                          # match multiple because we supports concatenating strs
1171     )\s*                          # end capturing of plural string argument
1172     (?:,\s*' . LOCALE_JS_OBJECT . '\s*          # optionally capture string args
1173       (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*)?  # optionally capture context
1174     )?
1175     [,\)]
1176     ~sx', $file, $plural_matches);
1177
1178   $matches = [];
1179
1180   // Add strings from Drupal.t().
1181   foreach ($t_matches[1] as $key => $string) {
1182     $matches[] = [
1183       'source'  => _locale_strip_quotes($string),
1184       'context' => _locale_strip_quotes($t_matches[2][$key]),
1185     ];
1186   }
1187
1188   // Add string from Drupal.formatPlural().
1189   foreach ($plural_matches[1] as $key => $string) {
1190     $matches[] = [
1191       'source'  => _locale_strip_quotes($string) . LOCALE_PLURAL_DELIMITER . _locale_strip_quotes($plural_matches[2][$key]),
1192       'context' => _locale_strip_quotes($plural_matches[3][$key]),
1193     ];
1194   }
1195
1196   // Loop through all matches and process them.
1197   foreach ($matches as $match) {
1198     $source = \Drupal::service('locale.storage')->findString($match);
1199
1200     if (!$source) {
1201       // We don't have the source string yet, thus we insert it into the
1202       // database.
1203       $source = \Drupal::service('locale.storage')->createString($match);
1204     }
1205
1206     // Besides adding the location this will tag it for current version.
1207     $source->addLocation('javascript', $filepath);
1208     $source->save();
1209   }
1210 }
1211
1212 /**
1213  * Force the JavaScript translation file(s) to be refreshed.
1214  *
1215  * This function sets a refresh flag for a specified language, or all
1216  * languages except English, if none specified. JavaScript translation
1217  * files are rebuilt (with locale_update_js_files()) the next time a
1218  * request is served in that language.
1219  *
1220  * @param $langcode
1221  *   The language code for which the file needs to be refreshed.
1222  *
1223  * @return
1224  *   New content of the 'system.javascript_parsed' variable.
1225  */
1226 function _locale_invalidate_js($langcode = NULL) {
1227   $parsed = \Drupal::state()->get('system.javascript_parsed') ?: [];
1228
1229   if (empty($langcode)) {
1230     // Invalidate all languages.
1231     $languages = locale_translatable_language_list();
1232     foreach ($languages as $lcode => $data) {
1233       $parsed['refresh:' . $lcode] = 'waiting';
1234     }
1235   }
1236   else {
1237     // Invalidate single language.
1238     $parsed['refresh:' . $langcode] = 'waiting';
1239   }
1240
1241   \Drupal::state()->set('system.javascript_parsed', $parsed);
1242   return $parsed;
1243 }
1244
1245 /**
1246  * (Re-)Creates the JavaScript translation file for a language.
1247  *
1248  * @param $langcode
1249  *   The language, the translation file should be (re)created for.
1250  *
1251  * @return bool
1252  *   TRUE if translation file exists, FALSE otherwise.
1253  */
1254 function _locale_rebuild_js($langcode = NULL) {
1255   $config = \Drupal::config('locale.settings');
1256   if (!isset($langcode)) {
1257     $language = \Drupal::languageManager()->getCurrentLanguage();
1258   }
1259   else {
1260     // Get information about the locale.
1261     $languages = \Drupal::languageManager()->getLanguages();
1262     $language = $languages[$langcode];
1263   }
1264
1265   // Construct the array for JavaScript translations.
1266   // Only add strings with a translation to the translations array.
1267   $conditions = [
1268     'type' => 'javascript',
1269     'language' => $language->getId(),
1270     'translated' => TRUE,
1271   ];
1272   $translations = [];
1273   foreach (\Drupal::service('locale.storage')->getTranslations($conditions) as $data) {
1274     $translations[$data->context][$data->source] = $data->translation;
1275   }
1276
1277   // Construct the JavaScript file, if there are translations.
1278   $data_hash = NULL;
1279   $data = $status = '';
1280   if (!empty($translations)) {
1281     $data = [
1282       'strings' => $translations,
1283     ];
1284
1285     $locale_plurals = \Drupal::service('locale.plural.formula')->getFormula($language->getId());
1286     if ($locale_plurals) {
1287       $data['pluralFormula'] = $locale_plurals;
1288     }
1289
1290     $data = 'window.drupalTranslations = ' . Json::encode($data) . ';';
1291     $data_hash = Crypt::hashBase64($data);
1292   }
1293
1294   // Construct the filepath where JS translation files are stored.
1295   // There is (on purpose) no front end to edit that variable.
1296   $dir = 'public://' . $config->get('javascript.directory');
1297
1298   // Delete old file, if we have no translations anymore, or a different file to
1299   // be saved.
1300   $locale_javascripts = \Drupal::state()->get('locale.translation.javascript') ?: [];
1301   $changed_hash = !isset($locale_javascripts[$language->getId()]) || ($locale_javascripts[$language->getId()] != $data_hash);
1302   if (!empty($locale_javascripts[$language->getId()]) && (!$data || $changed_hash)) {
1303     file_unmanaged_delete($dir . '/' . $language->getId() . '_' . $locale_javascripts[$language->getId()] . '.js');
1304     $locale_javascripts[$language->getId()] = '';
1305     $status = 'deleted';
1306   }
1307
1308   // Only create a new file if the content has changed or the original file got
1309   // lost.
1310   $dest = $dir . '/' . $language->getId() . '_' . $data_hash . '.js';
1311   if ($data && ($changed_hash || !file_exists($dest))) {
1312     // Ensure that the directory exists and is writable, if possible.
1313     file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
1314
1315     // Save the file.
1316     if (file_unmanaged_save_data($data, $dest)) {
1317       $locale_javascripts[$language->getId()] = $data_hash;
1318       // If we deleted a previous version of the file and we replace it with a
1319       // new one we have an update.
1320       if ($status == 'deleted') {
1321         $status = 'updated';
1322       }
1323       // If the file did not exist previously and the data has changed we have
1324       // a fresh creation.
1325       elseif ($changed_hash) {
1326         $status = 'created';
1327       }
1328       // If the data hash is unchanged the translation was lost and has to be
1329       // rebuilt.
1330       else {
1331         $status = 'rebuilt';
1332       }
1333     }
1334     else {
1335       $locale_javascripts[$language->getId()] = '';
1336       $status = 'error';
1337     }
1338   }
1339
1340   // Save the new JavaScript hash (or an empty value if the file just got
1341   // deleted). Act only if some operation was executed that changed the hash
1342   // code.
1343   if ($status && $changed_hash) {
1344     \Drupal::state()->set('locale.translation.javascript', $locale_javascripts);
1345   }
1346
1347   // Log the operation and return success flag.
1348   $logger = \Drupal::logger('locale');
1349   switch ($status) {
1350     case 'updated':
1351       $logger->notice('Updated JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
1352       return TRUE;
1353
1354     case 'rebuilt':
1355       $logger->warning('JavaScript translation file %file.js was lost.', ['%file' => $locale_javascripts[$language->getId()]]);
1356       // Proceed to the 'created' case as the JavaScript translation file has
1357       // been created again.
1358
1359     case 'created':
1360       $logger->notice('Created JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
1361       return TRUE;
1362
1363     case 'deleted':
1364       $logger->notice('Removed JavaScript translation file for the language %language because no translations currently exist for that language.', ['%language' => $language->getName()]);
1365       return TRUE;
1366
1367     case 'error':
1368       $logger->error('An error occurred during creation of the JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
1369       return FALSE;
1370
1371     default:
1372       // No operation needed.
1373       return TRUE;
1374   }
1375 }
1376 /**
1377  * Form element callback: After build changes to the language update table.
1378  *
1379  * Adds labels to the languages and removes checkboxes from languages from which
1380  * translation files could not be found.
1381  */
1382 function locale_translation_language_table($form_element) {
1383   // Remove checkboxes of languages without updates.
1384   if ($form_element['#not_found']) {
1385     foreach ($form_element['#not_found'] as $langcode) {
1386       $form_element[$langcode] = [];
1387     }
1388   }
1389   return $form_element;
1390 }