Revert "[TASK] Avoid slow array functions in loops"
[Packages/TYPO3.CMS.git] / typo3 / sysext / extbase / Classes / Utility / LocalizationUtility.php
1 <?php
2 declare(strict_types = 1);
3
4 namespace TYPO3\CMS\Extbase\Utility;
5
6 /*
7 * This file is part of the TYPO3 CMS project.
8 *
9 * It is free software; you can redistribute it and/or modify it under
10 * the terms of the GNU General Public License, either version 2
11 * of the License, or any later version.
12 *
13 * For the full copyright and license information, please read the
14 * LICENSE.txt file that was distributed with this source code.
15 *
16 * The TYPO3 project - inspiring people to share!
17 */
18
19 use Psr\Http\Message\ServerRequestInterface;
20 use TYPO3\CMS\Core\Localization\Locales;
21 use TYPO3\CMS\Core\Localization\LocalizationFactory;
22 use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
23 use TYPO3\CMS\Core\Utility\GeneralUtility;
24 use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
25 use TYPO3\CMS\Extbase\Object\ObjectManager;
26
27 /**
28 * Localization helper which should be used to fetch localized labels.
29 */
30 class LocalizationUtility
31 {
32 /**
33 * @var string
34 */
35 protected static $locallangPath = 'Resources/Private/Language/';
36
37 /**
38 * Local Language content
39 *
40 * @var array
41 */
42 protected static $LOCAL_LANG = [];
43
44 /**
45 * Contains those LL keys, which have been set to (empty) in TypoScript.
46 * This is necessary, as we cannot distinguish between a nonexisting
47 * translation and a label that has been cleared by TS.
48 * In both cases ['key'][0]['target'] is "".
49 *
50 * @var array
51 */
52 protected static $LOCAL_LANG_UNSET = [];
53
54 /**
55 * @var \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
56 */
57 protected static $configurationManager;
58
59 /**
60 * Returns the localized label of the LOCAL_LANG key, $key.
61 *
62 * @param string $key The key from the LOCAL_LANG array for which to return the value.
63 * @param string|null $extensionName The name of the extension
64 * @param array $arguments The arguments of the extension, being passed over to vsprintf
65 * @param string $languageKey The language key or null for using the current language from the system
66 * @param string[] $alternativeLanguageKeys The alternative language keys if no translation was found.
67 * @return string|null The value from LOCAL_LANG or null if no translation was found.
68 */
69 public static function translate(string $key, ?string $extensionName = null, array $arguments = null, string $languageKey = null, array $alternativeLanguageKeys = null): ?string
70 {
71 if ($key === '') {
72 // Early return guard: returns null if the key was empty, because the key may be a dynamic value
73 // (from for example Fluid). Returning null allows null coalescing to a default value when that happens.
74 return null;
75 }
76 $value = null;
77 if (GeneralUtility::isFirstPartOfStr($key, 'LLL:')) {
78 $keyParts = explode(':', $key);
79 unset($keyParts[0]);
80 $key = array_pop($keyParts);
81 $languageFilePath = implode(':', $keyParts);
82 } else {
83 if (empty($extensionName)) {
84 throw new \InvalidArgumentException(
85 'Parameter $extensionName cannot be empty if a fully-qualified key is not specified.',
86 1498144052
87 );
88 }
89 $languageFilePath = static::getLanguageFilePath($extensionName);
90 }
91 $languageKeys = static::getLanguageKeys();
92 if ($languageKey === null) {
93 $languageKey = $languageKeys['languageKey'];
94 }
95 if (empty($alternativeLanguageKeys)) {
96 $alternativeLanguageKeys = $languageKeys['alternativeLanguageKeys'];
97 }
98 static::initializeLocalization($languageFilePath, $languageKey, $alternativeLanguageKeys, $extensionName);
99
100 // The "from" charset of csConv() is only set for strings from TypoScript via _LOCAL_LANG
101 if (!empty(self::$LOCAL_LANG[$languageFilePath][$languageKey][$key][0]['target'])
102 || isset(self::$LOCAL_LANG_UNSET[$languageFilePath][$languageKey][$key])
103 ) {
104 // Local language translation for key exists
105 $value = self::$LOCAL_LANG[$languageFilePath][$languageKey][$key][0]['target'];
106 } elseif (!empty($alternativeLanguageKeys)) {
107 $languages = array_reverse($alternativeLanguageKeys);
108 foreach ($languages as $language) {
109 if (!empty(self::$LOCAL_LANG[$languageFilePath][$language][$key][0]['target'])
110 || isset(self::$LOCAL_LANG_UNSET[$languageFilePath][$language][$key])
111 ) {
112 // Alternative language translation for key exists
113 $value = self::$LOCAL_LANG[$languageFilePath][$language][$key][0]['target'];
114 break;
115 }
116 }
117 }
118 if ($value === null && (!empty(self::$LOCAL_LANG[$languageFilePath]['default'][$key][0]['target'])
119 || isset(self::$LOCAL_LANG_UNSET[$languageFilePath]['default'][$key]))
120 ) {
121 // Default language translation for key exists
122 // No charset conversion because default is English and thereby ASCII
123 $value = self::$LOCAL_LANG[$languageFilePath]['default'][$key][0]['target'];
124 }
125
126 if (is_array($arguments) && $value !== null) {
127 // This unrolls arguments from $arguments - instead of calling vsprintf which receives arguments as an array.
128 // The reason is that only sprintf() will return an error message if the number of arguments does not match
129 // the number of placeholders in the format string. Whereas, vsprintf would silently return nothing.
130 return sprintf($value, ...array_values($arguments)) ?: sprintf('Error: could not translate key "%s" with value "%s" and %d argument(s)!', $key, $value, count($arguments));
131 }
132 return $value;
133 }
134
135 /**
136 * Loads local-language values by looking for a "locallang.xlf" (or "locallang.xml") file in the plugin resources directory and if found includes it.
137 * Also locallang values set in the TypoScript property "_LOCAL_LANG" are merged onto the values found in the "locallang.xlf" file.
138 *
139 * @param string $languageFilePath
140 * @param string $languageKey
141 * @param string[] $alternativeLanguageKeys
142 * @param string $extensionName
143 */
144 protected static function initializeLocalization(string $languageFilePath, string $languageKey, array $alternativeLanguageKeys, string $extensionName = null): void
145 {
146 $languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
147
148 if (empty(self::$LOCAL_LANG[$languageFilePath][$languageKey])) {
149 $parsedData = $languageFactory->getParsedData($languageFilePath, $languageKey);
150 foreach ($parsedData as $tempLanguageKey => $data) {
151 if (!empty($data)) {
152 self::$LOCAL_LANG[$languageFilePath][$tempLanguageKey] = $data;
153 }
154 }
155 }
156 if ($languageKey !== 'default') {
157 foreach ($alternativeLanguageKeys as $alternativeLanguageKey) {
158 if (empty(self::$LOCAL_LANG[$languageFilePath][$alternativeLanguageKey])) {
159 $tempLL = $languageFactory->getParsedData($languageFilePath, $alternativeLanguageKey);
160 if (isset($tempLL[$alternativeLanguageKey])) {
161 self::$LOCAL_LANG[$languageFilePath][$alternativeLanguageKey] = $tempLL[$alternativeLanguageKey];
162 }
163 }
164 }
165 }
166 if (!empty($extensionName)) {
167 static::loadTypoScriptLabels($extensionName, $languageFilePath);
168 }
169 }
170
171 /**
172 * Returns the default path and filename for an extension
173 *
174 * @param string $extensionName
175 * @return string
176 */
177 protected static function getLanguageFilePath(string $extensionName): string
178 {
179 return 'EXT:' . GeneralUtility::camelCaseToLowerCaseUnderscored($extensionName) . '/' . self::$locallangPath . 'locallang.xlf';
180 }
181
182 /**
183 * Sets the currently active language keys.
184 *
185 * @return array
186 */
187 protected static function getLanguageKeys(): array
188 {
189 $languageKeys = [
190 'languageKey' => 'default',
191 'alternativeLanguageKeys' => [],
192 ];
193 if (TYPO3_MODE === 'FE') {
194 $siteLanguage = self::getCurrentSiteLanguage();
195
196 // Get values from site language
197 $languageKeys['languageKey'] = $siteLanguage->getTypo3Language();
198
199 $locales = GeneralUtility::makeInstance(Locales::class);
200 if (in_array($languageKeys['languageKey'], $locales->getLocales())) {
201 foreach ($locales->getLocaleDependencies($languageKeys['languageKey']) as $language) {
202 $languageKeys['alternativeLanguageKeys'][] = $language;
203 }
204 }
205 } elseif (!empty($GLOBALS['BE_USER']->uc['lang'])) {
206 $languageKeys['languageKey'] = $GLOBALS['BE_USER']->uc['lang'];
207 } elseif (!empty(static::getLanguageService()->lang)) {
208 $languageKeys['languageKey'] = static::getLanguageService()->lang;
209 }
210 return $languageKeys;
211 }
212
213 /**
214 * Overwrites labels that are set via TypoScript.
215 * TS locallang labels have to be configured like:
216 * plugin.tx_myextension._LOCAL_LANG.languageKey.key = value
217 *
218 * @param string $extensionName
219 * @param string $languageFilePath
220 */
221 protected static function loadTypoScriptLabels(string $extensionName, string $languageFilePath): void
222 {
223 $configurationManager = static::getConfigurationManager();
224 $frameworkConfiguration = $configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK, $extensionName);
225 if (!is_array($frameworkConfiguration['_LOCAL_LANG'] ?? false)) {
226 return;
227 }
228 self::$LOCAL_LANG_UNSET[$languageFilePath] = [];
229 foreach ($frameworkConfiguration['_LOCAL_LANG'] as $languageKey => $labels) {
230 if (!is_array($labels)) {
231 continue;
232 }
233 foreach ($labels as $labelKey => $labelValue) {
234 if (is_string($labelValue)) {
235 self::$LOCAL_LANG[$languageFilePath][$languageKey][$labelKey][0]['target'] = $labelValue;
236 if ($labelValue === '') {
237 self::$LOCAL_LANG_UNSET[$languageFilePath][$languageKey][$labelKey] = '';
238 }
239 } elseif (is_array($labelValue)) {
240 $labelValue = self::flattenTypoScriptLabelArray($labelValue, $labelKey);
241 foreach ($labelValue as $key => $value) {
242 self::$LOCAL_LANG[$languageFilePath][$languageKey][$key][0]['target'] = $value;
243 if ($value === '') {
244 self::$LOCAL_LANG_UNSET[$languageFilePath][$languageKey][$key] = '';
245 }
246 }
247 }
248 }
249 }
250 }
251
252 /**
253 * Flatten TypoScript label array; converting a hierarchical array into a flat
254 * array with the keys separated by dots.
255 *
256 * Example Input: array('k1' => array('subkey1' => 'val1'))
257 * Example Output: array('k1.subkey1' => 'val1')
258 *
259 * @param array $labelValues Hierarchical array of labels
260 * @param string $parentKey the name of the parent key in the recursion; is only needed for recursion.
261 * @return array flattened array of labels.
262 */
263 protected static function flattenTypoScriptLabelArray(array $labelValues, string $parentKey = ''): array
264 {
265 $result = [];
266 foreach ($labelValues as $key => $labelValue) {
267 if (!empty($parentKey)) {
268 if ($key === '_typoScriptNodeValue') {
269 $key = $parentKey;
270 } else {
271 $key = $parentKey . '.' . $key;
272 }
273 }
274 if (is_array($labelValue)) {
275 $labelValue = self::flattenTypoScriptLabelArray($labelValue, $key);
276 $result = array_merge($result, $labelValue);
277 } else {
278 $result[$key] = $labelValue;
279 }
280 }
281 return $result;
282 }
283
284 /**
285 * Returns instance of the configuration manager
286 *
287 * @return \TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface
288 */
289 protected static function getConfigurationManager(): ConfigurationManagerInterface
290 {
291 if (static::$configurationManager !== null) {
292 return static::$configurationManager;
293 }
294 $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
295 $configurationManager = $objectManager->get(ConfigurationManagerInterface::class);
296 static::$configurationManager = $configurationManager;
297 return $configurationManager;
298 }
299
300 /**
301 * Returns the currently configured "site language" if a site is configured (= resolved)
302 * in the current request.
303 *
304 * @return SiteLanguage|null
305 */
306 protected static function getCurrentSiteLanguage(): ?SiteLanguage
307 {
308 if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface) {
309 return $GLOBALS['TYPO3_REQUEST']->getAttribute('language', null);
310 }
311 return null;
312 }
313
314 /**
315 * @return \TYPO3\CMS\Core\Localization\LanguageService
316 */
317 protected static function getLanguageService(): \TYPO3\CMS\Core\Localization\LanguageService
318 {
319 return $GLOBALS['LANG'];
320 }
321 }