[BUGFIX] EXT:form - let the CountValidator provide its arguments
[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 string $property
276 * @param FormRuntime $formRuntime
277 * @return string|array
278 * @throws \InvalidArgumentException
279 * @internal
280 */
281 public function translateFormElementValue(
282 RootRenderableInterface $element,
283 string $property,
284 FormRuntime $formRuntime
285 ) {
286 if (empty($property)) {
287 throw new \InvalidArgumentException('The argument "property" is empty', 1476216007);
288 }
289
290 $propertyType = 'properties';
291 $renderingOptions = $element->getRenderingOptions();
292
293 if ($property === 'label') {
294 $defaultValue = $element->getLabel();
295 } else {
296 if ($element instanceof FormElementInterface) {
297 try {
298 $defaultValue = ArrayUtility::getValueByPath($element->getProperties(), $property, '.');
299 } catch (\RuntimeException $exception) {
300 $defaultValue = null;
301 }
302 } else {
303 $propertyType = 'renderingOptions';
304 try {
305 $defaultValue = ArrayUtility::getValueByPath($renderingOptions, $property, '.');
306 } catch (\RuntimeException $exception) {
307 $defaultValue = null;
308 }
309 }
310 }
311
312 if (isset($renderingOptions['translation']['translatePropertyValueIfEmpty'])) {
313 $translatePropertyValueIfEmpty = $renderingOptions['translation']['translatePropertyValueIfEmpty'];
314 } else {
315 $translatePropertyValueIfEmpty = true;
316 }
317
318 if (empty($defaultValue) && !$translatePropertyValueIfEmpty) {
319 return $defaultValue;
320 }
321
322 $defaultValue = empty($defaultValue) ? '' : $defaultValue;
323 $translationFile = $renderingOptions['translation']['translationFile'];
324 if (empty($translationFile)) {
325 $translationFile = $formRuntime->getRenderingOptions()['translation']['translationFile'];
326 }
327
328 if (is_string($translationFile)) {
329 $translationFiles = [$translationFile];
330 } else {
331 $translationFiles = $this->sortArrayWithIntegerKeysDescending($translationFile);
332 }
333
334 $language = null;
335 if (isset($renderingOptions['translation']['language'])) {
336 $language = $renderingOptions['translation']['language'];
337 }
338
339 if ($property === 'options' && is_array($defaultValue)) {
340 foreach ($defaultValue as $optionValue => &$optionLabel) {
341 $translationKeyChain = [];
342 foreach ($translationFiles as $translationFile) {
343 $translationKeyChain[] = sprintf('%s:%s.element.%s.%s.%s.%s', $translationFile, $formRuntime->getIdentifier(), $element->getIdentifier(), $propertyType, $property, $optionValue);
344 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s.%s', $translationFile, $element->getIdentifier(), $propertyType, $property, $optionValue);
345 }
346
347 $translatedValue = $this->processTranslationChain($translationKeyChain, $language);
348 $optionLabel = (empty($translatedValue)) ? $optionLabel : $translatedValue;
349 }
350 $translatedValue = $defaultValue;
351 } elseif ($property === 'fluidAdditionalAttributes' && is_array($defaultValue)) {
352 foreach ($defaultValue as $propertyName => &$propertyValue) {
353 $translationKeyChain = [];
354 foreach ($translationFiles as $translationFile) {
355 $translationKeyChain[] = sprintf('%s:%s.element.%s.%s.%s', $translationFile, $formRuntime->getIdentifier(), $element->getIdentifier(), $propertyType, $propertyName);
356 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s', $translationFile, $element->getIdentifier(), $propertyType, $propertyName);
357 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s', $translationFile, $element->getType(), $propertyType, $propertyName);
358 }
359
360 $translatedValue = $this->processTranslationChain($translationKeyChain, $language);
361 $propertyValue = (empty($translatedValue)) ? $propertyValue : $translatedValue;
362 }
363 $translatedValue = $defaultValue;
364 } else {
365 $translationKeyChain = [];
366 foreach ($translationFiles as $translationFile) {
367 $translationKeyChain[] = sprintf('%s:%s.element.%s.%s.%s', $translationFile, $formRuntime->getIdentifier(), $element->getIdentifier(), $propertyType, $property);
368 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s', $translationFile, $element->getIdentifier(), $propertyType, $property);
369 $translationKeyChain[] = sprintf('%s:element.%s.%s.%s', $translationFile, $element->getType(), $propertyType, $property);
370 }
371
372 $translatedValue = $this->processTranslationChain($translationKeyChain, $language);
373 $translatedValue = (empty($translatedValue)) ? $defaultValue : $translatedValue;
374 }
375
376 return $translatedValue;
377 }
378
379 /**
380 * @param RootRenderableInterface $element
381 * @param int $code
382 * @param string $defaultValue
383 * @param array $arguments
384 * @param FormRuntime $formRuntime
385 * @return string
386 * @throws \InvalidArgumentException
387 * @internal
388 */
389 public function translateFormElementError(
390 RootRenderableInterface $element,
391 int $code,
392 array $arguments,
393 string $defaultValue = '',
394 FormRuntime $formRuntime
395 ): string {
396 if (empty($code)) {
397 throw new \InvalidArgumentException('The argument "code" is empty', 1489272978);
398 }
399
400 $validationErrors = $element->getProperties()['validationErrorMessages'];
401 if (is_array($validationErrors)) {
402 foreach ($validationErrors as $validationError) {
403 if ((int)$validationError['code'] === $code) {
404 return sprintf($validationError['message'], $arguments);
405 }
406 }
407 }
408
409 $renderingOptions = $element->getRenderingOptions();
410 $translationFile = $renderingOptions['translation']['translationFile'];
411 if (empty($translationFile)) {
412 $translationFile = $formRuntime->getRenderingOptions()['translation']['translationFile'];
413 }
414
415 if (is_string($translationFile)) {
416 $translationFiles = [$translationFile];
417 } else {
418 $translationFiles = $this->sortArrayWithIntegerKeysDescending($translationFile);
419 }
420
421 $language = null;
422 if (isset($renderingOptions['language'])) {
423 $language = $renderingOptions['language'];
424 }
425
426 $translationKeyChain = [];
427 foreach ($translationFiles as $translationFile) {
428 $translationKeyChain[] = sprintf('%s:%s.validation.error.%s.%s', $translationFile, $formRuntime->getIdentifier(), $element->getIdentifier(), $code);
429 $translationKeyChain[] = sprintf('%s:%s.validation.error.%s', $translationFile, $formRuntime->getIdentifier(), $code);
430 $translationKeyChain[] = sprintf('%s:validation.error.%s', $translationFile, $code);
431 }
432
433 $translatedValue = $this->processTranslationChain($translationKeyChain, $language, $arguments);
434 $translatedValue = (empty($translatedValue)) ? $defaultValue : $translatedValue;
435 return $translatedValue;
436 }
437
438 /**
439 * @param string $languageKey
440 * @internal
441 */
442 public function setLanguage(string $languageKey)
443 {
444 $this->languageKey = $languageKey;
445 }
446
447 /**
448 * @return string
449 * @internal
450 */
451 public function getLanguage(): string
452 {
453 return $this->languageKey;
454 }
455
456 /**
457 * @param array $translationKeyChain
458 * @param string $language
459 * @param array $arguments
460 * @return string|null
461 */
462 protected function processTranslationChain(
463 array $translationKeyChain,
464 string $language = null,
465 array $arguments = null
466 ) {
467 $translatedValue = null;
468 foreach ($translationKeyChain as $translationKey) {
469 $translatedValue = $this->translate($translationKey, $arguments, null, $language);
470 if (!empty($translatedValue)) {
471 break;
472 }
473 }
474 return $translatedValue;
475 }
476
477 /**
478 * @param string $locallangPathAndFilename
479 */
480 protected function initializeLocalization(string $locallangPathAndFilename)
481 {
482 if (empty($this->languageKey)) {
483 $this->setLanguageKeys();
484 }
485
486 if (!empty($locallangPathAndFilename)) {
487 /** @var $languageFactory LocalizationFactory */
488 $languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
489 $this->LOCAL_LANG = $languageFactory->getParsedData($locallangPathAndFilename, $this->languageKey);
490
491 foreach ($this->alternativeLanguageKeys as $language) {
492 $tempLL = $languageFactory->getParsedData($locallangPathAndFilename, $language);
493 if ($this->languageKey !== 'default' && isset($tempLL[$language])) {
494 $this->LOCAL_LANG[$language] = $tempLL[$language];
495 }
496 }
497 }
498 $this->loadTypoScriptLabels();
499 }
500
501 /**
502 * Sets the currently active language/language_alt keys.
503 * Default values are "default" for language key and "" for language_alt key.
504 */
505 protected function setLanguageKeys()
506 {
507 $this->languageKey = 'default';
508
509 $this->alternativeLanguageKeys = [];
510 if (TYPO3_MODE === 'FE') {
511 if (isset($this->getTypoScriptFrontendController()->config['config']['language'])) {
512 $this->languageKey = $this->getTypoScriptFrontendController()->config['config']['language'];
513 if (isset($this->getTypoScriptFrontendController()->config['config']['language_alt'])) {
514 $this->alternativeLanguageKeys[] = $this->getTypoScriptFrontendController()->config['config']['language_alt'];
515 } else {
516 /** @var $locales \TYPO3\CMS\Core\Localization\Locales */
517 $locales = GeneralUtility::makeInstance(Locales::class);
518 if (in_array($this->languageKey, $locales->getLocales(), true)) {
519 foreach ($locales->getLocaleDependencies($this->languageKey) as $language) {
520 $this->alternativeLanguageKeys[] = $language;
521 }
522 }
523 }
524 }
525 } elseif (!empty($GLOBALS['BE_USER']->uc['lang'])) {
526 $this->languageKey = $GLOBALS['BE_USER']->uc['lang'];
527 } elseif (!empty($this->getLanguageService()->lang)) {
528 $this->languageKey = $this->getLanguageService()->lang;
529 }
530 }
531
532 /**
533 * Overwrites labels that are set via TypoScript.
534 * TS locallang labels have to be configured like:
535 * plugin.tx_form._LOCAL_LANG.languageKey.key = value
536 */
537 protected function loadTypoScriptLabels()
538 {
539 $frameworkConfiguration = $this->getConfigurationManager()
540 ->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, 'form');
541
542 if (!is_array($frameworkConfiguration['_LOCAL_LANG'])) {
543 return;
544 }
545 $this->LOCAL_LANG_UNSET = [];
546 foreach ($frameworkConfiguration['_LOCAL_LANG'] as $languageKey => $labels) {
547 if (!(is_array($labels) && isset($this->LOCAL_LANG[$languageKey]))) {
548 continue;
549 }
550 foreach ($labels as $labelKey => $labelValue) {
551 if (is_string($labelValue)) {
552 $this->LOCAL_LANG[$languageKey][$labelKey][0]['target'] = $labelValue;
553 if ($labelValue === '') {
554 $this->LOCAL_LANG_UNSET[$languageKey][$labelKey] = '';
555 }
556 } elseif (is_array($labelValue)) {
557 $labelValue = $this->flattenTypoScriptLabelArray($labelValue, $labelKey);
558 foreach ($labelValue as $key => $value) {
559 $this->LOCAL_LANG[$languageKey][$key][0]['target'] = $value;
560 if ($value === '') {
561 $this->LOCAL_LANG_UNSET[$languageKey][$key] = '';
562 }
563 }
564 }
565 }
566 }
567 }
568
569 /**
570 * Flatten TypoScript label array; converting a hierarchical array into a flat
571 * array with the keys separated by dots.
572 *
573 * Example Input: array('k1' => array('subkey1' => 'val1'))
574 * Example Output: array('k1.subkey1' => 'val1')
575 *
576 * @param array $labelValues Hierarchical array of labels
577 * @param string $parentKey the name of the parent key in the recursion; is only needed for recursion.
578 * @return array flattened array of labels.
579 */
580 protected function flattenTypoScriptLabelArray(array $labelValues, string $parentKey = ''): array
581 {
582 $result = [];
583 foreach ($labelValues as $key => $labelValue) {
584 if (!empty($parentKey)) {
585 $key = $parentKey . '.' . $key;
586 }
587 if (is_array($labelValue)) {
588 $labelValue = $this->flattenTypoScriptLabelArray($labelValue, $key);
589 $result = array_merge($result, $labelValue);
590 } else {
591 $result[$key] = $labelValue;
592 }
593 }
594 return $result;
595 }
596
597 /**
598 * If the array contains numerical keys only, sort it in descending order
599 *
600 * @param array $array
601 * @return array
602 */
603 protected function sortArrayWithIntegerKeysDescending(array $array)
604 {
605 if (count(array_filter(array_keys($array), 'is_string')) === 0) {
606 krsort($array);
607 }
608 return $array;
609 }
610
611 /**
612 * Returns instance of the configuration manager
613 *
614 * @return ConfigurationManagerInterface
615 */
616 protected function getConfigurationManager(): ConfigurationManagerInterface
617 {
618 if ($this->configurationManager !== null) {
619 return $this->configurationManager;
620 }
621
622 $this->configurationManager = GeneralUtility::makeInstance(ObjectManager::class)
623 ->get(ConfigurationManagerInterface::class);
624 return $this->configurationManager;
625 }
626
627 /**
628 * @return LanguageService
629 */
630 protected function getLanguageService(): LanguageService
631 {
632 return $GLOBALS['LANG'];
633 }
634
635 /**
636 * @return TypoScriptFrontendController
637 */
638 protected function getTypoScriptFrontendController(): TypoScriptFrontendController
639 {
640 return $GLOBALS['TSFE'];
641 }
642 }