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