locale.module 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  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 = 'http://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 $count
  233. * Number to return plural for.
  234. * @param $langcode
  235. * Optional language code to translate to a language other than
  236. * what is used to display the page.
  237. *
  238. * @return
  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. * @return array
  1010. * Array of string objects to update indexed by context and source.
  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 start of single-quoted string
  1047. (?:\\\\\'|[^\'])* # match any character except unescaped single-quote
  1048. @count # match "@count"
  1049. (?:\\\\\'|[^\'])* # match any character except unescaped single-quote
  1050. \' # match end of single-quoted string
  1051. |
  1052. " # match start of double-quoted string
  1053. (?:\\\\"|[^"])* # match any character except unescaped double-quote
  1054. @count # match "@count"
  1055. (?:\\\\"|[^"])* # match any character except unescaped double-quote
  1056. " # match end of double-quoted string
  1057. )
  1058. (?:\s*\+\s*)? # match "+" with possible whitespace, for str concat
  1059. )+ # match multiple because we supports concatenating strs
  1060. )\s* # end capturing of plural string argument
  1061. (?:,\s*' . LOCALE_JS_OBJECT . '\s* # optionally capture string args
  1062. (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*)? # optionally capture context
  1063. )?
  1064. [,\)]
  1065. ~sx', $file, $plural_matches);
  1066. $matches = [];
  1067. // Add strings from Drupal.t().
  1068. foreach ($t_matches[1] as $key => $string) {
  1069. $matches[] = [
  1070. 'source' => _locale_strip_quotes($string),
  1071. 'context' => _locale_strip_quotes($t_matches[2][$key]),
  1072. ];
  1073. }
  1074. // Add string from Drupal.formatPlural().
  1075. foreach ($plural_matches[1] as $key => $string) {
  1076. $matches[] = [
  1077. 'source' => _locale_strip_quotes($string) . LOCALE_PLURAL_DELIMITER . _locale_strip_quotes($plural_matches[2][$key]),
  1078. 'context' => _locale_strip_quotes($plural_matches[3][$key]),
  1079. ];
  1080. }
  1081. // Loop through all matches and process them.
  1082. foreach ($matches as $match) {
  1083. $source = \Drupal::service('locale.storage')->findString($match);
  1084. if (!$source) {
  1085. // We don't have the source string yet, thus we insert it into the
  1086. // database.
  1087. $source = \Drupal::service('locale.storage')->createString($match);
  1088. }
  1089. // Besides adding the location this will tag it for current version.
  1090. $source->addLocation('javascript', $filepath);
  1091. $source->save();
  1092. }
  1093. }
  1094. /**
  1095. * Force the JavaScript translation file(s) to be refreshed.
  1096. *
  1097. * This function sets a refresh flag for a specified language, or all
  1098. * languages except English, if none specified. JavaScript translation
  1099. * files are rebuilt (with locale_update_js_files()) the next time a
  1100. * request is served in that language.
  1101. *
  1102. * @param $langcode
  1103. * The language code for which the file needs to be refreshed.
  1104. *
  1105. * @return
  1106. * New content of the 'system.javascript_parsed' variable.
  1107. */
  1108. function _locale_invalidate_js($langcode = NULL) {
  1109. $parsed = \Drupal::state()->get('system.javascript_parsed') ?: [];
  1110. if (empty($langcode)) {
  1111. // Invalidate all languages.
  1112. $languages = locale_translatable_language_list();
  1113. foreach ($languages as $lcode => $data) {
  1114. $parsed['refresh:' . $lcode] = 'waiting';
  1115. }
  1116. }
  1117. else {
  1118. // Invalidate single language.
  1119. $parsed['refresh:' . $langcode] = 'waiting';
  1120. }
  1121. \Drupal::state()->set('system.javascript_parsed', $parsed);
  1122. return $parsed;
  1123. }
  1124. /**
  1125. * (Re-)Creates the JavaScript translation file for a language.
  1126. *
  1127. * @param $langcode
  1128. * The language, the translation file should be (re)created for.
  1129. *
  1130. * @return bool
  1131. * TRUE if translation file exists, FALSE otherwise.
  1132. */
  1133. function _locale_rebuild_js($langcode = NULL) {
  1134. $config = \Drupal::config('locale.settings');
  1135. if (!isset($langcode)) {
  1136. $language = \Drupal::languageManager()->getCurrentLanguage();
  1137. }
  1138. else {
  1139. // Get information about the locale.
  1140. $languages = \Drupal::languageManager()->getLanguages();
  1141. $language = $languages[$langcode];
  1142. }
  1143. // Construct the array for JavaScript translations.
  1144. // Only add strings with a translation to the translations array.
  1145. $conditions = [
  1146. 'type' => 'javascript',
  1147. 'language' => $language->getId(),
  1148. 'translated' => TRUE,
  1149. ];
  1150. $translations = [];
  1151. foreach (\Drupal::service('locale.storage')->getTranslations($conditions) as $data) {
  1152. $translations[$data->context][$data->source] = $data->translation;
  1153. }
  1154. // Construct the JavaScript file, if there are translations.
  1155. $data_hash = NULL;
  1156. $data = $status = '';
  1157. if (!empty($translations)) {
  1158. $data = [
  1159. 'strings' => $translations,
  1160. ];
  1161. $locale_plurals = \Drupal::service('locale.plural.formula')->getFormula($language->getId());
  1162. if ($locale_plurals) {
  1163. $data['pluralFormula'] = $locale_plurals;
  1164. }
  1165. $data = 'window.drupalTranslations = ' . Json::encode($data) . ';';
  1166. $data_hash = Crypt::hashBase64($data);
  1167. }
  1168. // Construct the filepath where JS translation files are stored.
  1169. // There is (on purpose) no front end to edit that variable.
  1170. $dir = 'public://' . $config->get('javascript.directory');
  1171. // Delete old file, if we have no translations anymore, or a different file to
  1172. // be saved.
  1173. $locale_javascripts = \Drupal::state()->get('locale.translation.javascript') ?: [];
  1174. $changed_hash = !isset($locale_javascripts[$language->getId()]) || ($locale_javascripts[$language->getId()] != $data_hash);
  1175. if (!empty($locale_javascripts[$language->getId()]) && (!$data || $changed_hash)) {
  1176. file_unmanaged_delete($dir . '/' . $language->getId() . '_' . $locale_javascripts[$language->getId()] . '.js');
  1177. $locale_javascripts[$language->getId()] = '';
  1178. $status = 'deleted';
  1179. }
  1180. // Only create a new file if the content has changed or the original file got
  1181. // lost.
  1182. $dest = $dir . '/' . $language->getId() . '_' . $data_hash . '.js';
  1183. if ($data && ($changed_hash || !file_exists($dest))) {
  1184. // Ensure that the directory exists and is writable, if possible.
  1185. file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
  1186. // Save the file.
  1187. if (file_unmanaged_save_data($data, $dest)) {
  1188. $locale_javascripts[$language->getId()] = $data_hash;
  1189. // If we deleted a previous version of the file and we replace it with a
  1190. // new one we have an update.
  1191. if ($status == 'deleted') {
  1192. $status = 'updated';
  1193. }
  1194. // If the file did not exist previously and the data has changed we have
  1195. // a fresh creation.
  1196. elseif ($changed_hash) {
  1197. $status = 'created';
  1198. }
  1199. // If the data hash is unchanged the translation was lost and has to be
  1200. // rebuilt.
  1201. else {
  1202. $status = 'rebuilt';
  1203. }
  1204. }
  1205. else {
  1206. $locale_javascripts[$language->getId()] = '';
  1207. $status = 'error';
  1208. }
  1209. }
  1210. // Save the new JavaScript hash (or an empty value if the file just got
  1211. // deleted). Act only if some operation was executed that changed the hash
  1212. // code.
  1213. if ($status && $changed_hash) {
  1214. \Drupal::state()->set('locale.translation.javascript', $locale_javascripts);
  1215. }
  1216. // Log the operation and return success flag.
  1217. $logger = \Drupal::logger('locale');
  1218. switch ($status) {
  1219. case 'updated':
  1220. $logger->notice('Updated JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
  1221. return TRUE;
  1222. case 'rebuilt':
  1223. $logger->warning('JavaScript translation file %file.js was lost.', ['%file' => $locale_javascripts[$language->getId()]]);
  1224. // Proceed to the 'created' case as the JavaScript translation file has
  1225. // been created again.
  1226. case 'created':
  1227. $logger->notice('Created JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
  1228. return TRUE;
  1229. case 'deleted':
  1230. $logger->notice('Removed JavaScript translation file for the language %language because no translations currently exist for that language.', ['%language' => $language->getName()]);
  1231. return TRUE;
  1232. case 'error':
  1233. $logger->error('An error occurred during creation of the JavaScript translation file for the language %language.', ['%language' => $language->getName()]);
  1234. return FALSE;
  1235. default:
  1236. // No operation needed.
  1237. return TRUE;
  1238. }
  1239. }
  1240. /**
  1241. * Form element callback: After build changes to the language update table.
  1242. *
  1243. * Adds labels to the languages and removes checkboxes from languages from which
  1244. * translation files could not be found.
  1245. */
  1246. function locale_translation_language_table($form_element) {
  1247. // Remove checkboxes of languages without updates.
  1248. if ($form_element['#not_found']) {
  1249. foreach ($form_element['#not_found'] as $langcode) {
  1250. $form_element[$langcode] = [];
  1251. }
  1252. }
  1253. return $form_element;
  1254. }