annotate core/modules/locale/locale.module @ 0:c75dbcec494b

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