5 * Enables the translation of the user interface to languages other than English.
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.
13 use Drupal\Component\Serialization\Json;
14 use Drupal\Component\Utility\Html;
15 use Drupal\Component\Utility\UrlHelper;
16 use Drupal\Component\Utility\Xss;
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;
29 * Regular expression pattern used to localize JavaScript strings.
31 const LOCALE_JS_STRING = '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+';
34 * Regular expression pattern used to match simple JS object literal.
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.
39 const LOCALE_JS_OBJECT = '\{.*?\}';
42 * Regular expression to match an object containing a key 'context'.
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.
47 define('LOCALE_JS_OBJECT_CONTEXT', '
48 \{ # match object literal start
49 .*? # match anything, non-greedy
50 (?: # match a form of "context"
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
64 * Flag for locally not customized interface translation.
66 * Such translations are imported from .po files downloaded from
67 * localize.drupal.org for example.
69 const LOCALE_NOT_CUSTOMIZED = 0;
72 * Flag for locally customized interface translation.
74 * Such translations are edited from their imported originals on the user
75 * interface or are imported as customized.
77 const LOCALE_CUSTOMIZED = 1;
80 * Translation update mode: Use local files only.
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
87 const LOCALE_TRANSLATION_USE_SOURCE_LOCAL = 'local';
90 * Translation update mode: Use both remote and local files.
92 * When checking for available translation updates, both local and remote files
95 const LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL = 'remote_and_local';
98 * Default location of gettext file on the translation server.
100 * @see locale_translation_default_translation_server().
102 const LOCALE_TRANSLATION_DEFAULT_SERVER_PATTERN = 'http://ftp.drupal.org/files/translations/%core/%project/%project-%version.%language.po';
105 * The number of seconds that the translations status entry should be considered.
107 const LOCALE_TRANSLATION_STATUS_TTL = 600;
110 * UI option for override of existing translations. Override any translation.
112 const LOCALE_TRANSLATION_OVERWRITE_ALL = 'all';
115 * UI option for override of existing translations. Only override non-customized
118 const LOCALE_TRANSLATION_OVERWRITE_NON_CUSTOMIZED = 'non_customized';
121 * UI option for override of existing translations. Don't override existing
124 const LOCALE_TRANSLATION_OVERWRITE_NONE = 'none';
127 * Translation source is a remote file.
129 const LOCALE_TRANSLATION_REMOTE = 'remote';
132 * Translation source is a local file.
134 const LOCALE_TRANSLATION_LOCAL = 'local';
137 * Translation source is the current translation.
139 const LOCALE_TRANSLATION_CURRENT = 'current';
142 * Implements hook_help().
144 function locale_help($route_name, RouteMatchInterface $route_match) {
145 switch ($route_name) {
146 case 'help.page.locale':
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>';
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>';
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>';
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>';
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>';
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>';
182 * Implements hook_theme().
184 function locale_theme() {
186 'locale_translation_last_check' => [
187 'variables' => ['last' => NULL],
188 'file' => 'locale.pages.inc',
190 'locale_translation_update_info' => [
191 'variables' => ['updates' => [], 'not_found' => []],
192 'file' => 'locale.pages.inc',
198 * Implements hook_ENTITY_TYPE_insert() for 'configurable_language'.
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());
210 * Implements hook_ENTITY_TYPE_update() for 'configurable_language'.
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());
222 * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
224 function locale_configurable_language_delete(ConfigurableLanguageInterface $language) {
225 // Remove translations.
226 \Drupal::service('locale.storage')->deleteTranslations(['language' => $language->id()]);
228 // Remove interface translation files.
229 module_load_include('inc', 'locale', 'locale.bulk');
230 locale_translate_delete_translation_files([], [$language->id()]);
232 // Remove translated configuration objects.
233 Locale::config()->deleteLanguageTranslations($language->id());
235 // Changing the language settings impacts the interface:
236 _locale_invalidate_js($language->id());
237 \Drupal::cache('render')->deleteAll();
239 // Clear locale translation caches.
240 locale_translation_status_delete_languages([$language->id()]);
241 \Drupal::cache()->delete('locale:' . $language->id());
245 * Returns list of translatable languages.
248 * Array of installed languages keyed by language name. English is omitted
249 * unless it is marked as translatable.
251 function locale_translatable_language_list() {
252 $languages = \Drupal::languageManager()->getLanguages();
253 if (!locale_is_translatable('en')) {
254 unset($languages['en']);
260 * Returns plural form index for a specific number.
262 * The index is computed from the formula of this language.
265 * Number to return plural for.
267 * Optional language code to translate to a language other than
268 * what is used to display the page.
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
275 function locale_get_plural($count, $langcode = NULL) {
276 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
278 // Used to store precomputed plural indexes corresponding to numbers
279 // individually for each language.
280 $plural_indexes = &drupal_static(__FUNCTION__ . ':plurals', []);
282 $langcode = $langcode ? $langcode : $language_interface->getId();
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);
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'];
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);
303 // Otherwise, return -1 (unknown).
305 $plural_indexes[$langcode][$count] = -1;
308 return $plural_indexes[$langcode][$count];
313 * Implements hook_modules_installed().
315 function locale_modules_installed($modules) {
316 locale_system_set_config_langcodes();
318 $components['module'] = $modules;
319 locale_system_update($components);
323 * Implements hook_module_preuninstall().
325 function locale_module_preuninstall($module) {
326 $components['module'] = [$module];
327 locale_system_remove($components);
331 * Implements hook_themes_installed().
333 function locale_themes_installed($themes) {
334 locale_system_set_config_langcodes();
336 $components['theme'] = $themes;
337 locale_system_update($components);
341 * Implements hook_themes_uninstalled().
343 function locale_themes_uninstalled($themes) {
344 $components['theme'] = $themes;
345 locale_system_remove($components);
349 * Implements hook_cron().
351 * @see \Drupal\locale\Plugin\QueueWorker\LocaleTranslation
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();
364 * Updates default configuration when new modules or themes are installed.
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
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();
392 * Imports translations when new modules or themes are installed.
394 * This function will start a batch to import translations for the added
397 * @param array $components
398 * An array of arrays of component (theme and/or module) names to import
399 * translations for, indexed by type.
401 function locale_system_update(array $components) {
402 $components += ['module' => [], 'theme' => []];
403 $list = array_merge($components['module'], $components['theme']);
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');
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
420 $options = _locale_translation_default_update_options();
421 $batch = locale_translation_batch_update_build($list, [], $options);
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([])) {
438 * Delete translation history of modules and themes.
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.
444 * @param array $components
445 * An array of arrays of component (theme and/or module) names to import
446 * translations for, indexed by type.
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');
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
458 $projects = array_keys(locale_translation_get_projects());
459 if ($list = array_intersect($list, $projects)) {
460 locale_translation_file_history_delete($list);
462 // Remove translation files.
463 locale_translate_delete_translation_files($list, []);
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);
470 // Clear the translation status.
471 locale_translation_status_delete_projects($list);
478 * Implements hook_cache_flush().
480 function locale_cache_flush() {
481 \Drupal::state()->delete('system.javascript_parsed');
485 * Implements hook_js_alter().
487 function locale_js_alter(&$javascript, AttachedAssetsInterface $assets) {
488 // @todo Remove this in https://www.drupal.org/node/2421323.
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') {
496 $files[] = $item['data'];
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;
511 // If no translation file exists, then remove the placeholder JS asset.
512 unset($javascript[$placeholder_file]);
518 * Returns a list of translation files given a list of JavaScript files.
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).
525 * @param array $files
526 * An array of local file paths.
528 * @return string|null
529 * The filepath to the translation file or NULL if no translation is
532 function locale_js_translate(array $files = []) {
533 $language_interface = \Drupal::languageManager()->getCurrentLanguage();
535 $dir = 'public://' . \Drupal::config('locale.settings')->get('javascript.directory');
536 $parsed = \Drupal::state()->get('system.javascript_parsed') ?: [];
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;
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.
554 $parsed += _locale_invalidate_js();
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()]);
564 // Store any changes after refresh was attempted.
565 \Drupal::state()->set('system.javascript_parsed', $parsed);
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);
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';
580 return $translation_file;
584 * Implements hook_library_info_alter().
586 * Provides the language support for the jQuery UI Date Picker.
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'] = [
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';
608 * Implements hook_js_settings_alter().
610 * Generates the values for the altered core/jquery.ui.datepicker library.
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');
621 * Implements hook_form_FORM_ID_alter() for language_admin_overview_form().
623 function locale_form_language_admin_overview_form_alter(&$form, FormStateInterface $form_state) {
624 $languages = $form['languages']['#languages'];
626 $total_strings = \Drupal::service('locale.storage')->countStrings();
627 $stats = array_fill_keys(array_keys($languages), []);
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);
640 array_splice($form['languages']['#header'], -1, 0, ['translation-interface' => t('Interface translation')]);
642 foreach ($languages as $langcode => $language) {
643 $stats[$langcode] += [
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'],
655 new Url('locale.translate_page', [], ['query' => ['langcode' => $langcode]])
660 $form['languages'][$langcode]['locale_statistics'] = [
661 '#markup' => t('not applicable'),
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;
673 * Implements hook_form_FORM_ID_alter() for language_admin_add_form().
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';
681 * Form submission handler for language_admin_add_form().
683 * Set a batch for a newly-added language.
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();
689 if ($form_state->isValueEmpty('predefined_langcode') || $form_state->getValue('predefined_langcode') == 'custom') {
690 $langcode = $form_state->getValue('langcode');
693 $langcode = $form_state->getValue('predefined_langcode');
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);
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])) {
714 * Implements hook_form_FORM_ID_alter() for language_admin_edit_form().
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'),
723 $form['actions']['submit']['#submit'][] = 'locale_form_language_admin_edit_form_alter_submit';
728 * Form submission handler for language_admin_edit_form().
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();
735 * Checks whether $langcode is a language supported as a locale target.
737 * @param string $langcode
741 * Whether $langcode can be translated to in locale.
743 function locale_is_translatable($langcode) {
744 return $langcode != 'en' || \Drupal::config('locale.settings')->get('translate_english');
748 * Implements hook_form_FORM_ID_alter() for system_file_system_settings().
750 * Add interface translation directory setting to directories configuration.
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'),
758 '#description' => t('A local file system path where interface translation files will be stored.'),
760 '#after_build' => ['system_check_directory'],
763 if ($form['file_default_scheme']) {
764 $form['file_default_scheme']['#weight'] = 20;
766 $form['#submit'][] = 'locale_system_file_system_settings_submit';
770 * Submit handler for the file system settings form.
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.
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();
781 \Drupal::configFactory()->getEditable('locale.settings')
782 ->set('translation.path', $form_state->getValue('translation_path'))
787 * Implements hook_preprocess_HOOK() for node templates.
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();
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
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();
811 * Gets current translation status from the {locale_file} table.
814 * Array of translation file objects.
816 function locale_translation_get_file_history() {
817 $history = &drupal_static(__FUNCTION__, []);
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;
831 * Updates the {locale_file} table.
833 * @param object $file
834 * Object representing the file just imported.
837 * FALSE on failure. Otherwise SAVED_NEW or SAVED_UPDATED.
839 function locale_translation_update_file_history($file) {
840 $status = db_merge('locale_file')
842 'project' => $file->project,
843 'langcode' => $file->langcode,
846 'version' => $file->version,
847 'timestamp' => $file->timestamp,
848 'last_checked' => $file->last_checked,
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');
858 * Deletes the history of downloaded translations.
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.
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');
871 if (!empty($langcodes)) {
872 $query->condition('langcode', $langcodes, 'IN');
878 * Gets the current translation status.
880 * @todo What is 'translation status'?
882 function locale_translation_get_status($projects = NULL, $langcodes = NULL) {
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());
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];
897 $sources = locale_translation_build_sources([$project], [$langcode]);
898 if (isset($sources[$project][$langcode])) {
899 $result[$project][$langcode] = $sources[$project][$langcode];
908 * Saves the status of translation sources in static cache.
910 * @param string $project
911 * Machine readable project name.
912 * @param string $langcode
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.
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);
930 // Merge the new status data with the existing status.
931 if (isset($status[$project][$langcode])) {
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;
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;
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);
958 \Drupal::keyValue('locale.translation_status')->set($project, $status[$project]);
959 \Drupal::state()->set('locale.translation_last_checked', REQUEST_TIME);
964 * Delete language entries from the status cache.
966 * @param array $langcodes
967 * Language code(s) to be deleted from the cache.
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]);
977 \Drupal::keyValue('locale.translation_status')->set($project, $status[$project]);
983 * Delete project entries from the status cache.
985 * @param array $projects
986 * Project name(s) to be deleted from the cache.
988 function locale_translation_status_delete_projects($projects) {
989 \Drupal::keyValue('locale.translation_status')->deleteMultiple($projects);
993 * Clear the translation status cache.
995 function locale_translation_clear_status() {
996 \Drupal::keyValue('locale.translation_status')->deleteAll();
997 \Drupal::state()->delete('locale.translation_last_checked');
1001 * Checks whether remote translation sources are used.
1004 * Returns TRUE if remote translations sources should be taken into account
1005 * when checking or importing translation files, FALSE otherwise.
1007 function locale_translation_use_remote_source() {
1008 return \Drupal::config('locale.settings')->get('translation.use_source') == LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL;
1012 * Check that a string is safe to be added or imported as a translation.
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 & in the translation would get encoded to &amp; by
1019 * \Drupal\Component\Utility\Xss::filter() before being put in the database,
1020 * and thus would be displayed incorrectly.
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).
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
1034 // @see \Drupal\Tests\locale\Kernel\LocaleStringIsSafeTest::testLocaleStringIsSafe()
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.
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
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);
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']));
1056 * Refresh related information after string translations have been updated.
1058 * The information that will be refreshed includes:
1059 * - JavaScript translations.
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.
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);
1078 // Throw locale.save_translation event.
1079 \Drupal::service('event_dispatcher')->dispatch(LocaleEvents::SAVE_TRANSLATION, new LocaleEvent($langcodes, $lids));
1083 * Refreshes configuration after string translations have been updated.
1085 * @param array $langcodes
1086 * Language codes for updated translations.
1087 * @param array $lids
1088 * List of string identifiers that have been updated / created.
1090 function _locale_refresh_configuration(array $langcodes, array $lids) {
1091 if ($lids && $langcodes && $names = Locale::config()->getStringNames($lids)) {
1092 Locale::config()->updateConfigTranslations($names, $langcodes);
1097 * Removes the quotes and string concatenations from the string.
1099 * @param string $string
1100 * Single or double quoted strings, optionally concatenated by plus (+) sign.
1103 * String with leading and trailing quotes removed.
1105 function _locale_strip_quotes($string) {
1106 return implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($string, 1, -1)));
1110 * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
1111 * Drupal.formatPlural() and inserts them into the database.
1113 * @param string $filepath
1114 * File name to parse.
1117 * Array of string objects to update indexed by context and source.
1120 * If a non-local file is attempted to be parsed.
1122 function _locale_parse_js_file($filepath) {
1123 // The file path might contain a query string, so make sure we only use the
1125 $parsed_url = UrlHelper::parse($filepath);
1126 $filepath = $parsed_url['path'];
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().');
1133 // Load the JavaScript file.
1134 $file = file_get_contents($filepath);
1136 // Match all calls to Drupal.t() in an array.
1137 // Note: \s also matches newlines with the 's' modifier.
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);
1148 // Match all Drupal.formatPlural() calls in another array.
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
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
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
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
1176 ~sx', $file, $plural_matches);
1180 // Add strings from Drupal.t().
1181 foreach ($t_matches[1] as $key => $string) {
1183 'source' => _locale_strip_quotes($string),
1184 'context' => _locale_strip_quotes($t_matches[2][$key]),
1188 // Add string from Drupal.formatPlural().
1189 foreach ($plural_matches[1] as $key => $string) {
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]),
1196 // Loop through all matches and process them.
1197 foreach ($matches as $match) {
1198 $source = \Drupal::service('locale.storage')->findString($match);
1201 // We don't have the source string yet, thus we insert it into the
1203 $source = \Drupal::service('locale.storage')->createString($match);
1206 // Besides adding the location this will tag it for current version.
1207 $source->addLocation('javascript', $filepath);
1213 * Force the JavaScript translation file(s) to be refreshed.
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.
1221 * The language code for which the file needs to be refreshed.
1224 * New content of the 'system.javascript_parsed' variable.
1226 function _locale_invalidate_js($langcode = NULL) {
1227 $parsed = \Drupal::state()->get('system.javascript_parsed') ?: [];
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';
1237 // Invalidate single language.
1238 $parsed['refresh:' . $langcode] = 'waiting';
1241 \Drupal::state()->set('system.javascript_parsed', $parsed);
1246 * (Re-)Creates the JavaScript translation file for a language.
1249 * The language, the translation file should be (re)created for.
1252 * TRUE if translation file exists, FALSE otherwise.
1254 function _locale_rebuild_js($langcode = NULL) {
1255 $config = \Drupal::config('locale.settings');
1256 if (!isset($langcode)) {
1257 $language = \Drupal::languageManager()->getCurrentLanguage();
1260 // Get information about the locale.
1261 $languages = \Drupal::languageManager()->getLanguages();
1262 $language = $languages[$langcode];
1265 // Construct the array for JavaScript translations.
1266 // Only add strings with a translation to the translations array.
1268 'type' => 'javascript',
1269 'language' => $language->getId(),
1270 'translated' => TRUE,
1273 foreach (\Drupal::service('locale.storage')->getTranslations($conditions) as $data) {
1274 $translations[$data->context][$data->source] = $data->translation;
1277 // Construct the JavaScript file, if there are translations.
1279 $data = $status = '';
1280 if (!empty($translations)) {
1282 'strings' => $translations,
1285 $locale_plurals = \Drupal::service('locale.plural.formula')->getFormula($language->getId());
1286 if ($locale_plurals) {
1287 $data['pluralFormula'] = $locale_plurals;
1290 $data = 'window.drupalTranslations = ' . Json::encode($data) . ';';
1291 $data_hash = Crypt::hashBase64($data);
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');
1298 // Delete old file, if we have no translations anymore, or a different file to
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';
1308 // Only create a new file if the content has changed or the original file got
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);
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';
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';
1328 // If the data hash is unchanged the translation was lost and has to be
1331 $status = 'rebuilt';
1335 $locale_javascripts[$language->getId()] = '';
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
1343 if ($status && $changed_hash) {
1344 \Drupal::state()->set('locale.translation.javascript', $locale_javascripts);
1347 // Log the operation and return success flag.
1348 $logger = \Drupal::logger('locale');
1351 $logger->notice('Updated JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
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.
1360 $logger->notice('Created JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
1364 $logger->notice('Removed JavaScript translation file for the language %language because no translations currently exist for that language.', ['%language' => $language->getName()]);
1368 $logger->error('An error occurred during creation of the JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
1372 // No operation needed.
1377 * Form element callback: After build changes to the language update table.
1379 * Adds labels to the languages and removes checkboxes from languages from which
1380 * translation files could not be found.
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] = [];
1389 return $form_element;