25e004db7be80fbe0846a26542a09eede55b4ce1
[Packages/TYPO3.CMS.git] / typo3 / sysext / form / Classes / Service / TranslationService.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Form\Service;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use TYPO3\CMS\Core\Localization\LanguageService;
19 use TYPO3\CMS\Core\Localization\Locales;
20 use TYPO3\CMS\Core\Localization\LocalizationFactory;
21 use TYPO3\CMS\Core\SingletonInterface;
22 use TYPO3\CMS\Core\Utility\ArrayUtility;
23 use TYPO3\CMS\Core\Utility\Exception\MissingArrayPathException;
24 use TYPO3\CMS\Core\Utility\GeneralUtility;
25 use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
26 use TYPO3\CMS\Extbase\Object\ObjectManager;
27 use TYPO3\CMS\Form\Domain\Model\FormElements\FormElementInterface;
28 use TYPO3\CMS\Form\Domain\Model\Renderable\RootRenderableInterface;
29 use TYPO3\CMS\Form\Domain\Runtime\FormRuntime;
30 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
31
32 /**
33 * Advanced translations
34 * This class is subjected to change.
35 * **Do NOT subclass**
36 *
37 * Scope: frontend / backend
38 * @internal
39 */
40 class TranslationService implements SingletonInterface
41 {
42
43 /**
44 * Local Language content
45 *
46 * @var array
47 */
48 protected $LOCAL_LANG = [];
49
50 /**
51 * Contains those LL keys, which have been set to (empty) in TypoScript.
52 * This is necessary, as we cannot distinguish between a nonexisting
53 * translation and a label that has been cleared by TS.
54 * In both cases ['key'][0]['target'] is "".
55 *
56 * @var array
57 */
58 protected $LOCAL_LANG_UNSET = [];
59
60 /**
61 * Key of the language to use
62 *
63 * @var string
64 */
65 protected $languageKey = null;
66
67 /**
68 * Pointer to alternative fall-back language to use
69 *
70 * @var array
71 */
72 protected $alternativeLanguageKeys = [];
73
74 /**
75 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
76 */
77 protected $configurationManager = null;
78
79 /**
80 * Return TranslationService as singleton
81 *
82 * @return TranslationService
83 * @internal
84 */
85 public static function getInstance()
86 {
87 return GeneralUtility::makeInstance(ObjectManager::class)->get(self::class);
88 }
89
90 /**
91 * Returns the localized label of the LOCAL_LANG key, $key.
92 *
93 * @param mixed $key The key from the LOCAL_LANG array for which to return the value.
94 * @param array $arguments the arguments of the extension, being passed over to vsprintf
95 * @param string $locallangPathAndFilename
96 * @param string $language
97 * @param mixed $defaultValue
98 * @return mixed The value from LOCAL_LANG or $defaultValue if no translation was found.
99 * @internal
100 */
101 public function translate(
102 $key,
103 array $arguments = null,
104 string $locallangPathAndFilename = null,
105 string $language = null,
106 $defaultValue = ''
107 ) {
108 $value = null;
109 $key = (string)$key;
110
111 if ($locallangPathAndFilename) {
112 $key = $locallangPathAndFilename . ':' . $key;
113 }
114
115 $keyParts = explode(':', $key);
116 if (GeneralUtility::isFirstPartOfStr($key, 'LLL:')) {
117 $locallangPathAndFilename = $keyParts[1] . ':' . $keyParts[2];
118 $key = $keyParts[3];
119 } elseif (GeneralUtility::isFirstPartOfStr($key, 'EXT:')) {
120 $locallangPathAndFilename = $keyParts[0] . ':' . $keyParts[1];
121 $key = $keyParts[2];
122 } else {
123 if (count($keyParts) === 2) {
124 $locallangPathAndFilename = $keyParts[0];
125 $key = $keyParts[1];
126 }
127 }
128
129 if ($language) {
130 $this->languageKey = $language;
131 }
132
133 $this->initializeLocalization($locallangPathAndFilename);
134
135 // The "from" charset of csConv() is only set for strings from TypoScript via _LOCAL_LANG
136 if (!empty($this->LOCAL_LANG[$this->languageKey][$key][0]['target'])
137 || isset($this->LOCAL_LANG_UNSET[$this->languageKey][$key])
138 ) {
139 // Local language translation for key exists
140 $value = $this->LOCAL_LANG[$this->languageKey][$key][0]['target'];
141 } elseif (!empty($this->alternativeLanguageKeys)) {
142 $languages = array_reverse($this->alternativeLanguageKeys);
143 foreach ($languages as $language) {
144 if (!empty($this->LOCAL_LANG[$language][$key][0]['target'])
145 || isset($this->LOCAL_LANG_UNSET[$language][$key])
146 ) {
147 // Alternative language translation for key exists
148 $value = $this->LOCAL_LANG[$language][$key][0]['target'];
149 break;
150 }
151 }
152 }
153
154 if ($value === null && (!empty($this->LOCAL_LANG['default'][$key][0]['target'])
155 || isset($this->LOCAL_LANG_UNSET['default'][$key]))
156 ) {
157 // Default language translation for key exists
158 // No charset conversion because default is English and thereby ASCII
159 $value = $this->LOCAL_LANG['default'][$key][0]['target'];
160 }
161
162 if (is_array($arguments) && !empty($arguments) && $value !== null) {
163 $value = vsprintf($value, $arguments);
164 } else {
165 if (empty($value)) {
166 $value = $defaultValue;
167 }
168 }
169
170 return $value;
171 }
172
173 /**
174 * Recursively translate values.
175 *
176 * @param array $array
177 * @param array|string|null $translationFile
178 * @return array the modified array
179 * @internal
180 */
181 public function translateValuesRecursive(array $array, $translationFile = null): array
182 {
183 $result = $array;
184 foreach ($result as $key => $value) {
185 if (is_array($value)) {
186 $result[$key] = $this->translateValuesRecursive($value, $translationFile);
187 } else {
188 $translationFiles = null;
189 if (is_string($translationFile)) {
190 $translationFiles = [$translationFile];
191 } elseif (is_array($translationFile)) {
192 $translationFiles = $this->sortArrayWithIntegerKeysDescending($translationFile);
193 }
194
195 if ($translationFiles) {
196 foreach ($translationFiles as $_translationFile) {
197 $translatedValue = $this->translate($value, null, $_translationFile, null);
198 if (!empty($translatedValue)) {
199 $result[$key] = $translatedValue;
200 break;
201 }
202 }
203 } else {
204 $result[$key] = $this->translate($value, null, $translationFile, null, $value);
205 }
206 }
207 }
208 return $result;
209 }
210
211 /**
212 * @param FormRuntime $formRuntime
213 * @param string $finisherIdentifier
214 * @param string $optionKey
215 * @param string $optionValue
216 * @param array $renderingOptions
217 * @return string
218 * @throws \InvalidArgumentException
219 * @api
220 */
221 public function translateFinisherOption(
222 FormRuntime $formRuntime,
223 string $finisherIdentifier,
224 string $optionKey,
225 string $optionValue,
226 array $renderingOptions = []
227 ): string {
228 if (empty($finisherIdentifier)) {
229 throw new \InvalidArgumentException('The argument "finisherIdentifier" is empty', 1476216059);
230 }
231 if (empty($optionKey)) {
232 throw new \InvalidArgumentException('The argument "optionKey" is empty', 1476216060);
233 }
234
235 $finisherIdentifier = preg_replace('/Finisher$/', '', $finisherIdentifier);
236 $translationFile = $renderingOptions['translationFile'] ?? null;
237 if (empty($translationFile)) {
238 $translationFile = $formRuntime->getRenderingOptions()['translation']['translationFile'];
239 }
240
241 if (is_string($translationFile)) {
242 $translationFiles = [$translationFile];
243 } else {
244 $translationFiles = $this->sortArrayWithIntegerKeysDescending($translationFile);
245 }
246
247 if (isset($renderingOptions['translatePropertyValueIfEmpty'])) {
248 $translatePropertyValueIfEmpty = (bool)$renderingOptions['translatePropertyValueIfEmpty'];
249 } else {
250 $translatePropertyValueIfEmpty = true;
251 }
252
253 if (empty($optionValue) && !$translatePropertyValueIfEmpty) {
254 return $optionValue;
255 }
256
257 $language = null;
258 if (isset($renderingOptions['language'])) {
259 $language = $renderingOptions['language'];
260 }
261
262 try {
263 $arguments = ArrayUtility::getValueByPath($renderingOptions['arguments'] ?? [], $optionKey, '.');
264 } catch (MissingArrayPathException $e) {
265 $arguments = [];
266 }
267
268 $translationKeyChain = [];
269 foreach ($translationFiles as $translationFile) {
270 $translationKeyChain[] = sprintf('%s:%s.finisher.%s.%s', $translationFile, $formRuntime->getIdentifier(), $finisherIdentifier, $optionKey);
271 $translationKeyChain[] = sprintf('%s:finisher.%s.%s', $translationFile, $finisherIdentifier, $optionKey);
272 }
273
274 $translatedValue = $this->processTranslationChain($translationKeyChain, $language, $arguments);
275 $translatedValue = empty($translatedValue) ? $optionValue : $translatedValue;
276
277 return $translatedValue;
278 }
279
280 /**
281 * @param RootRenderableInterface $element
282 * @param array $propertyParts
283 * @param FormRuntime $formRuntime
284 * @return string|array
285 * @throws \InvalidArgumentException
286 * @internal
287 */
288 public function translateFormElementValue(
289 RootRenderableInterface $element,
290 array $propertyParts,
291 FormRuntime $formRuntime
292 ) {
293 if (empty($propertyParts)) {
294 throw new \InvalidArgumentException('The argument "propertyParts" is empty', 1476216007);
295 }
296
297 $propertyType = 'properties';
298 $property = implode('.', $propertyParts);
299 $renderingOptions = $element->getRenderingOptions();
300
301 if ($property === 'label') {
302 $defaultValue = $element->getLabel();
303 } else {
304 if ($element instanceof FormElementInterface) {
305 try {
306 $defaultValue = ArrayUtility::getValueByPath($element->getProperties(), $propertyParts, '.');
307 } catch (MissingArrayPathException $exception) {
308 $defaultValue = null;
309 }
310 } else {
311 $propertyType = 'renderingOptions';
312 try {
313 $defaultValue = ArrayUtility::getValueByPath($renderingOptions, $propertyParts, '.');
314 } catch (MissingArrayPathException $exception) {
315 $defaultValue = null;
316 }
317 }
318 }
319
320 if (isset($renderingOptions['translation']['translatePropertyValueIfEmpty'])) {
321 $translatePropertyValueIfEmpty = $renderingOptions['translation']['translatePropertyValueIfEmpty'];
322 } else {
323 $translatePropertyValueIfEmpty = true;
324 }
325
326 if (empty($defaultValue) && !$translatePropertyValueIfEmpty) {
327 return $defaultValue;
328 }
329
330 $defaultValue = empty($defaultValue) ? '' : $defaultValue;
331 $translationFile = $renderingOptions['translation']['translationFile'] ?? null;
332 if (empty($translationFile)) {
333 $translationFile = $formRuntime->getRenderingOptions()['translation']['translationFile'];
334 }
335
336 if (is_string($translationFile)) {
337 $translationFiles = [$translationFile];
338 } else {
339 $translationFiles = $this->sortArrayWithIntegerKeysDescending($translationFile);
340 }
341
342 $language = null;
343 if (isset($renderingOptions['translation']['language'])) {
344 $language = $renderingOptions['translation']['language'];
345 }
346
347 try {
348 $arguments = ArrayUtility::getValueByPath($renderingOptions['translation']['arguments'] ?? [], $propertyParts, '.');
349 } catch (MissingArrayPathException $e) {
350 $arguments = [];
351 }
352
353 if ($property === 'options' && is_array($defaultValue)) {
354 foreach ($defaultValue as $optionValue => &$optionLabel) {
355 $translationKeyChain = [];
356 foreach ($translationFiles as $translationFile) {
357 $translationKeyChain[] = sprintf('%s:%s.element.%s.%s.%s.%s', $translationFile, $formRuntime->getIdentifier(), $element->getIdentifier(), $propertyType, $property, $optionValue);
358 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s.%s', $translationFile, $element->getIdentifier(), $propertyType, $property, $optionValue);
359 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s.%s', $translationFile, $element->getType(), $propertyType, $property, $optionValue);
360 }
361
362 $translatedValue = $this->processTranslationChain($translationKeyChain, $language, $arguments);
363 $optionLabel = empty($translatedValue) ? $optionLabel : $translatedValue;
364 }
365 $translatedValue = $defaultValue;
366 } elseif ($property === 'fluidAdditionalAttributes' && is_array($defaultValue)) {
367 foreach ($defaultValue as $propertyName => &$propertyValue) {
368 $translationKeyChain = [];
369 foreach ($translationFiles as $translationFile) {
370 $translationKeyChain[] = sprintf('%s:%s.element.%s.%s.%s', $translationFile, $formRuntime->getIdentifier(), $element->getIdentifier(), $propertyType, $propertyName);
371 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s', $translationFile, $element->getIdentifier(), $propertyType, $propertyName);
372 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s', $translationFile, $element->getType(), $propertyType, $propertyName);
373 }
374
375 $translatedValue = $this->processTranslationChain($translationKeyChain, $language, $arguments);
376 $propertyValue = empty($translatedValue) ? $propertyValue : $translatedValue;
377 }
378 $translatedValue = $defaultValue;
379 } else {
380 $translationKeyChain = [];
381 foreach ($translationFiles as $translationFile) {
382 $translationKeyChain[] = sprintf('%s:%s.element.%s.%s.%s', $translationFile, $formRuntime->getIdentifier(), $element->getIdentifier(), $propertyType, $property);
383 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s', $translationFile, $element->getIdentifier(), $propertyType, $property);
384 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s', $translationFile, $element->getType(), $propertyType, $property);
385 }
386
387 $translatedValue = $this->processTranslationChain($translationKeyChain, $language, $arguments);
388 $translatedValue = empty($translatedValue) ? $defaultValue : $translatedValue;
389 }
390
391 return $translatedValue;
392 }
393
394 /**
395 * @param RootRenderableInterface $element
396 * @param int $code
397 * @param string $defaultValue
398 * @param array $arguments
399 * @param FormRuntime $formRuntime
400 * @return string
401 * @throws \InvalidArgumentException
402 * @internal
403 */
404 public function translateFormElementError(
405 RootRenderableInterface $element,
406 int $code,
407 array $arguments,
408 string $defaultValue = '',
409 FormRuntime $formRuntime
410 ): string {
411 if (empty($code)) {
412 throw new \InvalidArgumentException('The argument "code" is empty', 1489272978);
413 }
414
415 $validationErrors = $element->getProperties()['validationErrorMessages'];
416 if (is_array($validationErrors)) {
417 foreach ($validationErrors as $validationError) {
418 if ((int)$validationError['code'] === $code) {
419 return sprintf($validationError['message'], $arguments);
420 }
421 }
422 }
423
424 $renderingOptions = $element->getRenderingOptions();
425 $translationFile = $renderingOptions['translation']['translationFile'];
426 if (empty($translationFile)) {
427 $translationFile = $formRuntime->getRenderingOptions()['translation']['translationFile'];
428 }
429
430 if (is_string($translationFile)) {
431 $translationFiles = [$translationFile];
432 } else {
433 $translationFiles = $this->sortArrayWithIntegerKeysDescending($translationFile);
434 }
435
436 $language = null;
437 if (isset($renderingOptions['language'])) {
438 $language = $renderingOptions['language'];
439 }
440
441 $translationKeyChain = [];
442 foreach ($translationFiles as $translationFile) {
443 $translationKeyChain[] = sprintf('%s:%s.validation.error.%s.%s', $translationFile, $formRuntime->getIdentifier(), $element->getIdentifier(), $code);
444 $translationKeyChain[] = sprintf('%s:%s.validation.error.%s', $translationFile, $formRuntime->getIdentifier(), $code);
445 $translationKeyChain[] = sprintf('%s:validation.error.%s.%s', $translationFile, $element->getIdentifier(), $code);
446 $translationKeyChain[] = sprintf('%s:validation.error.%s', $translationFile, $code);
447 }
448
449 $translatedValue = $this->processTranslationChain($translationKeyChain, $language, $arguments);
450 $translatedValue = empty($translatedValue) ? $defaultValue : $translatedValue;
451 return $translatedValue;
452 }
453
454 /**
455 * @param string $languageKey
456 * @internal
457 */
458 public function setLanguage(string $languageKey)
459 {
460 $this->languageKey = $languageKey;
461 }
462
463 /**
464 * @return string
465 * @internal
466 */
467 public function getLanguage(): string
468 {
469 return $this->languageKey;
470 }
471
472 /**
473 * @param array $translationKeyChain
474 * @param string $language
475 * @param array $arguments
476 * @return string|null
477 */
478 protected function processTranslationChain(
479 array $translationKeyChain,
480 string $language = null,
481 array $arguments = null
482 ) {
483 $translatedValue = null;
484 foreach ($translationKeyChain as $translationKey) {
485 $translatedValue = $this->translate($translationKey, $arguments, null, $language);
486 if (!empty($translatedValue)) {
487 break;
488 }
489 }
490 return $translatedValue;
491 }
492
493 /**
494 * @param string $locallangPathAndFilename
495 */
496 protected function initializeLocalization(string $locallangPathAndFilename)
497 {
498 if (empty($this->languageKey)) {
499 $this->setLanguageKeys();
500 }
501
502 if (!empty($locallangPathAndFilename)) {
503 /** @var $languageFactory LocalizationFactory */
504 $languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
505 $this->LOCAL_LANG = $languageFactory->getParsedData($locallangPathAndFilename, $this->languageKey);
506
507 foreach ($this->alternativeLanguageKeys as $language) {
508 $tempLL = $languageFactory->getParsedData($locallangPathAndFilename, $language);
509 if ($this->languageKey !== 'default' && isset($tempLL[$language])) {
510 $this->LOCAL_LANG[$language] = $tempLL[$language];
511 }
512 }
513 }
514 $this->loadTypoScriptLabels();
515 }
516
517 /**
518 * Sets the currently active language/language_alt keys.
519 * Default values are "default" for language key and "" for language_alt key.
520 */
521 protected function setLanguageKeys()
522 {
523 $this->languageKey = 'default';
524
525 $this->alternativeLanguageKeys = [];
526 if (TYPO3_MODE === 'FE') {
527 if (isset($this->getTypoScriptFrontendController()->config['config']['language'])) {
528 $this->languageKey = $this->getTypoScriptFrontendController()->config['config']['language'];
529 if (isset($this->getTypoScriptFrontendController()->config['config']['language_alt'])) {
530 $this->alternativeLanguageKeys[] = $this->getTypoScriptFrontendController()->config['config']['language_alt'];
531 } else {
532 /** @var $locales \TYPO3\CMS\Core\Localization\Locales */
533 $locales = GeneralUtility::makeInstance(Locales::class);
534 if (in_array($this->languageKey, $locales->getLocales(), true)) {
535 foreach ($locales->getLocaleDependencies($this->languageKey) as $language) {
536 $this->alternativeLanguageKeys[] = $language;
537 }
538 }
539 }
540 }
541 } elseif (!empty($GLOBALS['BE_USER']->uc['lang'])) {
542 $this->languageKey = $GLOBALS['BE_USER']->uc['lang'];
543 } elseif (!empty($this->getLanguageService()->lang)) {
544 $this->languageKey = $this->getLanguageService()->lang;
545 }
546 }
547
548 /**
549 * Overwrites labels that are set via TypoScript.
550 * TS locallang labels have to be configured like:
551 * plugin.tx_form._LOCAL_LANG.languageKey.key = value
552 */
553 protected function loadTypoScriptLabels()
554 {
555 $frameworkConfiguration = $this->getConfigurationManager()
556 ->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, 'form');
557
558 if (!is_array($frameworkConfiguration['_LOCAL_LANG'])) {
559 return;
560 }
561 $this->LOCAL_LANG_UNSET = [];
562 foreach ($frameworkConfiguration['_LOCAL_LANG'] as $languageKey => $labels) {
563 if (!(is_array($labels) && isset($this->LOCAL_LANG[$languageKey]))) {
564 continue;
565 }
566 foreach ($labels as $labelKey => $labelValue) {
567 if (is_string($labelValue)) {
568 $this->LOCAL_LANG[$languageKey][$labelKey][0]['target'] = $labelValue;
569 if ($labelValue === '') {
570 $this->LOCAL_LANG_UNSET[$languageKey][$labelKey] = '';
571 }
572 } elseif (is_array($labelValue)) {
573 $labelValue = $this->flattenTypoScriptLabelArray($labelValue, $labelKey);
574 foreach ($labelValue as $key => $value) {
575 $this->LOCAL_LANG[$languageKey][$key][0]['target'] = $value;
576 if ($value === '') {
577 $this->LOCAL_LANG_UNSET[$languageKey][$key] = '';
578 }
579 }
580 }
581 }
582 }
583 }
584
585 /**
586 * Flatten TypoScript label array; converting a hierarchical array into a flat
587 * array with the keys separated by dots.
588 *
589 * Example Input: array('k1' => array('subkey1' => 'val1'))
590 * Example Output: array('k1.subkey1' => 'val1')
591 *
592 * @param array $labelValues Hierarchical array of labels
593 * @param string $parentKey the name of the parent key in the recursion; is only needed for recursion.
594 * @return array flattened array of labels.
595 */
596 protected function flattenTypoScriptLabelArray(array $labelValues, string $parentKey = ''): array
597 {
598 $result = [];
599 foreach ($labelValues as $key => $labelValue) {
600 if (!empty($parentKey)) {
601 $key = $parentKey . '.' . $key;
602 }
603 if (is_array($labelValue)) {
604 $labelValue = $this->flattenTypoScriptLabelArray($labelValue, $key);
605 $result = array_merge($result, $labelValue);
606 } else {
607 $result[$key] = $labelValue;
608 }
609 }
610 return $result;
611 }
612
613 /**
614 * If the array contains numerical keys only, sort it in descending order
615 *
616 * @param array $array
617 * @return array
618 */
619 protected function sortArrayWithIntegerKeysDescending(array $array)
620 {
621 if (count(array_filter(array_keys($array), 'is_string')) === 0) {
622 krsort($array);
623 }
624 return $array;
625 }
626
627 /**
628 * Returns instance of the configuration manager
629 *
630 * @return ConfigurationManagerInterface
631 */
632 protected function getConfigurationManager(): ConfigurationManagerInterface
633 {
634 if ($this->configurationManager !== null) {
635 return $this->configurationManager;
636 }
637
638 $this->configurationManager = GeneralUtility::makeInstance(ObjectManager::class)
639 ->get(ConfigurationManagerInterface::class);
640 return $this->configurationManager;
641 }
642
643 /**
644 * @return LanguageService
645 */
646 protected function getLanguageService(): LanguageService
647 {
648 return $GLOBALS['LANG'];
649 }
650
651 /**
652 * @return TypoScriptFrontendController
653 */
654 protected function getTypoScriptFrontendController(): TypoScriptFrontendController
655 {
656 return $GLOBALS['TSFE'];
657 }
658 }