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