locale.module 56 KB

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