[TASK] EXT:form - allow validation translation for a field in all forms
[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\GeneralUtility;
24 use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
25 use TYPO3\CMS\Extbase\Object\ObjectManager;
26 use TYPO3\CMS\Form\Domain\Model\FormElements\FormElementInterface;
27 use TYPO3\CMS\Form\Domain\Model\Renderable\RootRenderableInterface;
28 use TYPO3\CMS\Form\Domain\Runtime\FormRuntime;
29 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
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.%s', $translationFile, $element->getIdentifier(), $code);
431 $translationKeyChain[] = sprintf('%s:validation.error.%s', $translationFile, $code);
432 }
433
434 $translatedValue = $this->processTranslationChain($translationKeyChain, $language, $arguments);
435 $translatedValue = (empty($translatedValue)) ? $defaultValue : $translatedValue;
436 return $translatedValue;
437 }
438
439 /**
440 * @param string $languageKey
441 * @internal
442 */
443 public function setLanguage(string $languageKey)
444 {
445 $this->languageKey = $languageKey;
446 }
447
448 /**
449 * @return string
450 * @internal
451 */
452 public function getLanguage(): string
453 {
454 return $this->languageKey;
455 }
456
457 /**
458 * @param array $translationKeyChain
459 * @param string $language
460 * @param array $arguments
461 * @return string|null
462 */
463 protected function processTranslationChain(
464 array $translationKeyChain,
465 string $language = null,
466 array $arguments = null
467 ) {
468 $translatedValue = null;
469 foreach ($translationKeyChain as $translationKey) {
470 $translatedValue = $this->translate($translationKey, $arguments, null, $language);
471 if (!empty($translatedValue)) {
472 break;
473 }
474 }
475 return $translatedValue;
476 }
477
478 /**
479 * @param string $locallangPathAndFilename
480 */
481 protected function initializeLocalization(string $locallangPathAndFilename)
482 {
483 if (empty($this->languageKey)) {
484 $this->setLanguageKeys();
485 }
486
487 if (!empty($locallangPathAndFilename)) {
488 /** @var $languageFactory LocalizationFactory */
489 $languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
490 $this->LOCAL_LANG = $languageFactory->getParsedData($locallangPathAndFilename, $this->languageKey);
491
492 foreach ($this->alternativeLanguageKeys as $language) {
493 $tempLL = $languageFactory->getParsedData($locallangPathAndFilename, $language);
494 if ($this->languageKey !== 'default' && isset($tempLL[$language])) {
495 $this->LOCAL_LANG[$language] = $tempLL[$language];
496 }
497 }
498 }
499 $this->loadTypoScriptLabels();
500 }
501
502 /**
503 * Sets the currently active language/language_alt keys.
504 * Default values are "default" for language key and "" for language_alt key.
505 */
506 protected function setLanguageKeys()
507 {
508 $this->languageKey = 'default';
509
510 $this->alternativeLanguageKeys = [];
511 if (TYPO3_MODE === 'FE') {
512 if (isset($this->getTypoScriptFrontendController()->config['config']['language'])) {
513 $this->languageKey = $this->getTypoScriptFrontendController()->config['config']['language'];
514 if (isset($this->getTypoScriptFrontendController()->config['config']['language_alt'])) {
515 $this->alternativeLanguageKeys[] = $this->getTypoScriptFrontendController()->config['config']['language_alt'];
516 } else {
517 /** @var $locales \TYPO3\CMS\Core\Localization\Locales */
518 $locales = GeneralUtility::makeInstance(Locales::class);
519 if (in_array($this->languageKey, $locales->getLocales(), true)) {
520 foreach ($locales->getLocaleDependencies($this->languageKey) as $language) {
521 $this->alternativeLanguageKeys[] = $language;
522 }
523 }
524 }
525 }
526 } elseif (!empty($GLOBALS['BE_USER']->uc['lang'])) {
527 $this->languageKey = $GLOBALS['BE_USER']->uc['lang'];
528 } elseif (!empty($this->getLanguageService()->lang)) {
529 $this->languageKey = $this->getLanguageService()->lang;
530 }
531 }
532
533 /**
534 * Overwrites labels that are set via TypoScript.
535 * TS locallang labels have to be configured like:
536 * plugin.tx_form._LOCAL_LANG.languageKey.key = value
537 */
538 protected function loadTypoScriptLabels()
539 {
540 $frameworkConfiguration = $this->getConfigurationManager()
541 ->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, 'form');
542
543 if (!is_array($frameworkConfiguration['_LOCAL_LANG'])) {
544 return;
545 }
546 $this->LOCAL_LANG_UNSET = [];
547 foreach ($frameworkConfiguration['_LOCAL_LANG'] as $languageKey => $labels) {
548 if (!(is_array($labels) && isset($this->LOCAL_LANG[$languageKey]))) {
549 continue;
550 }
551 foreach ($labels as $labelKey => $labelValue) {
552 if (is_string($labelValue)) {
553 $this->LOCAL_LANG[$languageKey][$labelKey][0]['target'] = $labelValue;
554 if ($labelValue === '') {
555 $this->LOCAL_LANG_UNSET[$languageKey][$labelKey] = '';
556 }
557 } elseif (is_array($labelValue)) {
558 $labelValue = $this->flattenTypoScriptLabelArray($labelValue, $labelKey);
559 foreach ($labelValue as $key => $value) {
560 $this->LOCAL_LANG[$languageKey][$key][0]['target'] = $value;
561 if ($value === '') {
562 $this->LOCAL_LANG_UNSET[$languageKey][$key] = '';
563 }
564 }
565 }
566 }
567 }
568 }
569
570 /**
571 * Flatten TypoScript label array; converting a hierarchical array into a flat
572 * array with the keys separated by dots.
573 *
574 * Example Input: array('k1' => array('subkey1' => 'val1'))
575 * Example Output: array('k1.subkey1' => 'val1')
576 *
577 * @param array $labelValues Hierarchical array of labels
578 * @param string $parentKey the name of the parent key in the recursion; is only needed for recursion.
579 * @return array flattened array of labels.
580 */
581 protected function flattenTypoScriptLabelArray(array $labelValues, string $parentKey = ''): array
582 {
583 $result = [];
584 foreach ($labelValues as $key => $labelValue) {
585 if (!empty($parentKey)) {
586 $key = $parentKey . '.' . $key;
587 }
588 if (is_array($labelValue)) {
589 $labelValue = $this->flattenTypoScriptLabelArray($labelValue, $key);
590 $result = array_merge($result, $labelValue);
591 } else {
592 $result[$key] = $labelValue;
593 }
594 }
595 return $result;
596 }
597
598 /**
599 * If the array contains numerical keys only, sort it in descending order
600 *
601 * @param array $array
602 * @return array
603 */
604 protected function sortArrayWithIntegerKeysDescending(array $array)
605 {
606 if (count(array_filter(array_keys($array), 'is_string')) === 0) {
607 krsort($array);
608 }
609 return $array;
610 }
611
612 /**
613 * Returns instance of the configuration manager
614 *
615 * @return ConfigurationManagerInterface
616 */
617 protected function getConfigurationManager(): ConfigurationManagerInterface
618 {
619 if ($this->configurationManager !== null) {
620 return $this->configurationManager;
621 }
622
623 $this->configurationManager = GeneralUtility::makeInstance(ObjectManager::class)
624 ->get(ConfigurationManagerInterface::class);
625 return $this->configurationManager;
626 }
627
628 /**
629 * @return LanguageService
630 */
631 protected function getLanguageService(): LanguageService
632 {
633 return $GLOBALS['LANG'];
634 }
635
636 /**
637 * @return TypoScriptFrontendController
638 */
639 protected function getTypoScriptFrontendController(): TypoScriptFrontendController
640 {
641 return $GLOBALS['TSFE'];
642 }
643 }