locale.module 56 KB

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