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