[CLEANUP] Code cleanup for LanguageService
[Packages/TYPO3.CMS.git] / typo3 / sysext / lang / Classes / LanguageService.php
1 <?php
2 namespace TYPO3\CMS\Lang;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29 use TYPO3\CMS\Core\Utility\ArrayUtility;
30 use TYPO3\CMS\Core\Utility\GeneralUtility;
31
32 /**
33 * Contains the TYPO3 Backend Language class
34 * For detailed information about how localization is handled,
35 * please refer to the 'Inside TYPO3' document which describes this.
36 * This class is normally instantiated as the global variable $GLOBALS['LANG']
37 * It's only available in the backend and under certain circumstances in the frontend
38 *
39 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
40 * @see \TYPO3\CMS\Backend\Template\DocumentTemplate
41 */
42 class LanguageService {
43
44 /**
45 * This is set to the language that is currently running for the user
46 *
47 * @var string
48 */
49 public $lang = 'default';
50
51 /**
52 * Default charset in backend
53 *
54 * @var string
55 */
56 public $charSet = 'utf-8';
57
58 /**
59 * Array with alternative charsets for other languages.
60 * Moved to \TYPO3\CMS\Core\Charset\CharsetConverter, set internally from csConvObj!
61 *
62 * @var array
63 */
64 public $charSetArray = array();
65
66 /**
67 * This is the url to the TYPO3 manual
68 *
69 * @var string
70 */
71 public $typo3_help_url = 'http://typo3.org/documentation/document-library/';
72
73 /**
74 * If TRUE, will show the key/location of labels in the backend.
75 *
76 * @var boolean
77 */
78 public $debugKey = FALSE;
79
80 /**
81 * Can contain labels and image references from the backend modules.
82 * Relies on \TYPO3\CMS\Backend\Module\ModuleLoader to initialize modules after a global instance of $LANG has been created.
83 *
84 * @var array
85 */
86 public $moduleLabels = array();
87
88 /**
89 * Internal cache for read LL-files
90 *
91 * @var array
92 */
93 public $LL_files_cache = array();
94
95 /**
96 * Internal cache for ll-labels (filled as labels are requested)
97 *
98 * @var array
99 */
100 public $LL_labels_cache = array();
101
102 /**
103 * instance of the "\TYPO3\CMS\Core\Charset\CharsetConverter" class. May be used by any application.
104 *
105 * @var \TYPO3\CMS\Core\Charset\CharsetConverter
106 */
107 public $csConvObj;
108
109 /**
110 * instance of the parser factory
111 *
112 * @var \TYPO3\CMS\Core\Localization\LocalizationFactory
113 */
114 public $parserFactory;
115
116 /**
117 * List of language dependencies for actual language. This is used for local variants of a language
118 * that depend on their "main" language, like Brazilian Portuguese or Canadian French.
119 *
120 * @var array
121 */
122 protected $languageDependencies = array();
123
124 /**
125 * Initializes the backend language.
126 * This is for example done in \TYPO3\CMS\Backend\Template\DocumentTemplate with lines like these:
127 * require (PATH_typo3 . 'sysext/lang/lang.php');
128 * $LANG = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('language');
129 * $LANG->init($GLOBALS['BE_USER']->uc['lang']);
130 *
131 * @throws \RuntimeException
132 * @param string $lang The language key (two character string from backend users profile)
133 * @return void
134 */
135 public function init($lang) {
136 // Initialize the conversion object:
137 $this->csConvObj = GeneralUtility::makeInstance('TYPO3\CMS\Core\Charset\CharsetConverter');
138 $this->charSetArray = $this->csConvObj->charSetArray;
139 // Initialize the parser factory object
140 $this->parserFactory = GeneralUtility::makeInstance('TYPO3\CMS\Core\Localization\LocalizationFactory');
141 // Find the requested language in this list based
142 // on the $lang key being inputted to this function.
143 /** @var $locales \TYPO3\CMS\Core\Localization\Locales */
144 $locales = GeneralUtility::makeInstance('TYPO3\CMS\Core\Localization\Locales');
145 // Language is found. Configure it:
146 if (in_array($lang, $locales->getLocales())) {
147 // The current language key
148 $this->lang = $lang;
149 $this->languageDependencies[] = $this->lang;
150 foreach ($locales->getLocaleDependencies($this->lang) as $language) {
151 $this->languageDependencies[] = $language;
152 }
153 }
154 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['lang']['debug']) {
155 $this->debugKey = TRUE;
156 }
157 }
158
159 /**
160 * Gets the parser factory.
161 *
162 * @return \TYPO3\CMS\Core\Localization\LocalizationFactory
163 */
164 public function getParserFactory() {
165 return $this->parserFactory;
166 }
167
168 /**
169 * Adds labels and image references from the backend modules to the internal moduleLabels array
170 *
171 * @param array $arr Array with references to module labels, keys: ['labels']['table'],
172 * @param string $prefix Module name prefix
173 * @return void
174 * @see \TYPO3\CMS\Backend\Module\ModuleLoader
175 */
176 public function addModuleLabels($arr, $prefix) {
177 if (is_array($arr)) {
178 foreach ($arr as $k => $larr) {
179 if (!isset($this->moduleLabels[$k])) {
180 $this->moduleLabels[$k] = array();
181 }
182 if (is_array($larr)) {
183 foreach ($larr as $l => $v) {
184 $this->moduleLabels[$k][$prefix . $l] = $v;
185 }
186 }
187 }
188 }
189 }
190
191 /**
192 * Will convert the input strings special chars (all above 127) to entities.
193 * The string is expected to be encoded in UTF-8
194 * This function is used to create strings that can be used in the Click Menu
195 * (Context Sensitive Menus). The reason is that the values that are dynamically
196 * written into the <div> layer is decoded as iso-8859-1 no matter what charset
197 * is used in the document otherwise (only MSIE, Mozilla is OK).
198 * So by converting we by-pass this problem.
199 *
200 * @param string $str Input string
201 * @return string Output string
202 */
203 public function makeEntities($str) {
204 // Convert string back again, but using the full entity conversion:
205 return $this->csConvObj->utf8_to_entities($str);
206 }
207
208 /**
209 * Converts the input string to a JavaScript function returning the same string, but charset-safe.
210 * Used for confirm and alert boxes where we must make sure that any string content
211 * does not break the script AND want to make sure the charset is preserved.
212 * Originally I used the JS function unescape() in combination with PHP function
213 * rawurlencode() in order to pass strings in a safe way. This could still be done
214 * for iso-8859-1 charsets but now I have applied the same method here for all charsets.
215 *
216 * @param string $str Input string, encoded with UTF-8
217 * @return string Output string, a JavaScript function: "String.fromCharCode(......)
218 * @depreacted since 6.2 - will be removed two versions later; use GeneralUtility::quoteJSvalue() instead
219 */
220 public function JScharCode($str) {
221 GeneralUtility::logDeprecatedFunction();
222
223 // Convert the UTF-8 string into a array of char numbers:
224 $nArr = $this->csConvObj->utf8_to_numberarray($str);
225 return 'String.fromCharCode(' . implode(',', $nArr) . ')';
226 }
227
228 /**
229 * Debugs localization key.
230 *
231 * @param string $value value to debug
232 * @return string
233 */
234 public function debugLL($value) {
235 return $this->debugKey ? '[' . $value . ']' : '';
236 }
237
238 /**
239 * Returns the label with key $index form the globally loaded $LOCAL_LANG array.
240 * Mostly used from modules with only one LOCAL_LANG file loaded into the global space.
241 *
242 * @param string $index Label key
243 * @param boolean $hsc If set, the return value is htmlspecialchar'ed
244 * @return string
245 */
246 public function getLL($index, $hsc = FALSE) {
247 // Get Local Language
248 if (isset($GLOBALS['LOCAL_LANG'][$this->lang][$index][0]['target'])) {
249 $output = $GLOBALS['LOCAL_LANG'][$this->lang][$index][0]['target'];
250 } else {
251 $output = $GLOBALS['LOCAL_LANG']['default'][$index][0]['target'];
252 }
253 if ($hsc) {
254 $output = htmlspecialchars($output);
255 }
256 return $output . $this->debugLL($index);
257 }
258
259 /**
260 * Works like ->getLL() but takes the $LOCAL_LANG array
261 * used as the second argument instead of using the global array.
262 *
263 * @param string $index Label key
264 * @param array $localLanguage $LOCAL_LANG array to get label key from
265 * @param boolean $hsc If set, the return value is htmlspecialchar'ed
266 * @return string
267 */
268 public function getLLL($index, $localLanguage, $hsc = FALSE) {
269 // Get Local Language. Special handling for all extensions that
270 // read PHP LL files and pass arrays here directly.
271 $value = is_string($localLanguage[$this->lang][$index]) ?
272 $localLanguage[$this->lang][$index] :
273 $localLanguage[$this->lang][$index][0]['target'];
274 // Fallback to default language
275 if (trim($value) === '') {
276 $value = is_string($localLanguage['default'][$index]) ?
277 $localLanguage['default'][$index] :
278 $localLanguage['default'][$index][0]['target'];
279 }
280 if ($hsc) {
281 $value = htmlspecialchars($value);
282 }
283 return $value . $this->debugLL($index);
284 }
285
286 /**
287 * splitLabel function
288 *
289 * All translations are based on $LOCAL_LANG variables.
290 * 'language-splitted' labels can therefore refer to a local-lang file + index.
291 * Refer to 'Inside TYPO3' for more details
292 *
293 * @param string $input Label key/reference
294 * @param boolean $hsc If set, the return value is htmlspecialchar'ed
295 * @return string
296 */
297 public function sL($input, $hsc = FALSE) {
298 $identifier = $input . '_' . (int)$hsc . '_' . (int)$this->debugKey;
299 if (isset($this->LL_labels_cache[$this->lang][$identifier])) {
300 return $this->LL_labels_cache[$this->lang][$identifier];
301 }
302 if (strpos($input, 'LLL:') === 0) {
303 $restStr = trim(substr($input, 4));
304 $extPrfx = '';
305 // ll-file refered to is found in an extension.
306 if (strpos($restStr, 'EXT:') === 0) {
307 $restStr = trim(substr($restStr, 4));
308 $extPrfx = 'EXT:';
309 }
310 $parts = explode(':', $restStr);
311 $parts[0] = $extPrfx . $parts[0];
312 // Getting data if not cached
313 if (!isset($this->LL_files_cache[$parts[0]])) {
314 $this->LL_files_cache[$parts[0]] = $this->readLLfile($parts[0]);
315 // If the current language is found in another file, load that as well:
316 $lFileRef = $this->localizedFileRef($parts[0]);
317 if ($lFileRef && $this->LL_files_cache[$parts[0]][$this->lang] === 'EXT') {
318 $tempLL = $this->readLLfile($lFileRef);
319 $this->LL_files_cache[$parts[0]][$this->lang] = $tempLL[$this->lang];
320 }
321 }
322 $output = $this->getLLL($parts[1], $this->LL_files_cache[$parts[0]]);
323 } else {
324 // Use a constant non-localizable label
325 $output = $input;
326 }
327 if ($hsc) {
328 $output = htmlspecialchars($output, ENT_COMPAT, 'UTF-8', FALSE);
329 }
330 $output .= $this->debugLL($input);
331 $this->LL_labels_cache[$this->lang][$identifier] = $output;
332 return $output;
333 }
334
335 /**
336 * Loading $TCA_DESCR[$table]['columns'] with content from locallang files
337 * as defined in $TCA_DESCR[$table]['refs']
338 * $TCA_DESCR is a global var
339 *
340 * @param string $table Table name found as key in global array $TCA_DESCR
341 * @return void
342 */
343 public function loadSingleTableDescription($table) {
344 // First the 'table' cannot already be loaded in [columns]
345 // and secondly there must be a references to locallang files available in [refs]
346 if (is_array($GLOBALS['TCA_DESCR'][$table]) && !isset($GLOBALS['TCA_DESCR'][$table]['columns']) && is_array($GLOBALS['TCA_DESCR'][$table]['refs'])) {
347 // Init $TCA_DESCR for $table-key
348 $GLOBALS['TCA_DESCR'][$table]['columns'] = array();
349 // Get local-lang for each file in $TCA_DESCR[$table]['refs'] as they are ordered.
350 foreach ($GLOBALS['TCA_DESCR'][$table]['refs'] as $llfile) {
351 $localLanguage = $this->includeLLFile($llfile, 0, 1);
352 // Traverse all keys
353 if (is_array($localLanguage['default'])) {
354 foreach ($localLanguage['default'] as $lkey => $lVal) {
355 // Exploding by '.':
356 // 0-n => fieldname,
357 // n+1 => type from (alttitle, description, details, syntax, image_descr,image,seeAlso),
358 // n+2 => special instruction, if any
359 $keyParts = explode('.', $lkey);
360 $keyPartsCount = count($keyParts);
361 // Check if last part is special instruction
362 // Only "+" is currently supported
363 $specialInstruction = $keyParts[$keyPartsCount - 1] === '+';
364 if ($specialInstruction) {
365 array_pop($keyParts);
366 }
367 // If there are more than 2 parts, get the type from the last part
368 // and merge back the other parts with a dot (.)
369 // Otherwise just get type and field name straightaway
370 if ($keyPartsCount > 2) {
371 $type = array_pop($keyParts);
372 $fieldName = implode('.', $keyParts);
373 } else {
374 $fieldName = $keyParts[0];
375 $type = $keyParts[1];
376 }
377 // Detecting 'hidden' labels, converting to normal fieldname
378 if ($fieldName === '_') {
379 $fieldName = '';
380 }
381 if ($fieldName !== '' && $fieldName[0] === '_') {
382 $fieldName = substr($fieldName, 1);
383 }
384 // Append label
385 $label = $lVal[0]['target'] ? :
386 $lVal[0]['source'];
387 if ($specialInstruction) {
388 $GLOBALS['TCA_DESCR'][$table]['columns'][$fieldName][$type] .= LF . $label;
389 } else {
390 // Substitute label
391 $GLOBALS['TCA_DESCR'][$table]['columns'][$fieldName][$type] = $label;
392 }
393 }
394 }
395 }
396 }
397 }
398
399 /**
400 * Includes locallang file (and possibly additional localized version if configured for)
401 * Read language labels will be merged with $LOCAL_LANG (if $setGlobal = TRUE).
402 *
403 * @param string $fileRef $fileRef is a file-reference
404 * @param boolean $setGlobal Setting in global variable $LOCAL_LANG (or returning the variable)
405 * @param boolean $mergeLocalOntoDefault
406 * @return mixed if $setGlobal===TRUE, LL-files set $LOCAL_LANG in global scope, or array is returned from function
407 */
408 public function includeLLFile($fileRef, $setGlobal = TRUE, $mergeLocalOntoDefault = FALSE) {
409 $globalLanguage = array();
410 // Get default file
411 $localLanguage = $this->readLLfile($fileRef);
412 if (is_array($localLanguage) && !empty($localLanguage)) {
413 // it depends on, whether we should return the result or set it in the global $LOCAL_LANG array
414 if ($setGlobal) {
415 $globalLanguage = (array)$GLOBALS['LOCAL_LANG'];
416 ArrayUtility::mergeRecursiveWithOverrule($globalLanguage, $localLanguage);
417 } else {
418 $globalLanguage = $localLanguage;
419 }
420 // Localized addition?
421 $lFileRef = $this->localizedFileRef($fileRef);
422 if ($lFileRef && (string) $globalLanguage[$this->lang] === 'EXT') {
423 $localLanguage = $this->readLLfile($lFileRef);
424 ArrayUtility::mergeRecursiveWithOverrule($globalLanguage, $localLanguage);
425 }
426 // Merge local onto default
427 if ($mergeLocalOntoDefault && $this->lang !== 'default' && is_array($globalLanguage[$this->lang]) && is_array($globalLanguage['default'])) {
428 // array_merge can be used so far the keys are not
429 // numeric - which we assume they are not...
430 $globalLanguage['default'] = array_merge($globalLanguage['default'], $globalLanguage[$this->lang]);
431 unset($globalLanguage[$this->lang]);
432 }
433 }
434 // Return value if not global is set.
435 if (!$setGlobal) {
436 return $globalLanguage;
437 } else {
438 $GLOBALS['LOCAL_LANG'] = $globalLanguage;
439 return NULL;
440 }
441 }
442
443 /**
444 * Includes a locallang file and returns the $LOCAL_LANG array found inside.
445 *
446 * @param string $fileRef Input is a file-reference to be a 'local_lang' file containing a $LOCAL_LANG array
447 * @return array value of $LOCAL_LANG found in the included file, empty if non found
448 */
449 protected function readLLfile($fileRef) {
450 if ($this->lang !== 'default') {
451 $languages = array_reverse($this->languageDependencies);
452 } else {
453 $languages = array('default');
454 }
455 $localLanguage = array();
456 foreach ($languages as $language) {
457 $tempLL = GeneralUtility::readLLfile($fileRef, $language, $this->charSet);
458 $localLanguage['default'] = $tempLL['default'];
459 if (!isset($localLanguage[$this->lang])) {
460 $localLanguage[$this->lang] = $localLanguage['default'];
461 }
462 if ($this->lang !== 'default' && isset($tempLL[$language])) {
463 // Merge current language labels onto labels from previous language
464 // This way we have a labels with fall back applied
465 ArrayUtility::mergeRecursiveWithOverrule($localLanguage[$this->lang], $tempLL[$language], TRUE, FALSE);
466 }
467 }
468 return $localLanguage;
469 }
470
471 /**
472 * Returns localized fileRef (.[langkey].php)
473 *
474 * @param string $fileRef Filename/path of a 'locallang.php' file
475 * @return string Input filename with a '.[lang-key].php' ending added if $this->lang is not 'default'
476 */
477 protected function localizedFileRef($fileRef) {
478 if ($this->lang !== 'default' && substr($fileRef, -4) === '.php') {
479 return substr($fileRef, 0, -4) . '.' . $this->lang . '.php';
480 } else {
481 return NULL;
482 }
483 }
484
485 /**
486 * Overrides a label.
487 *
488 * @param string $index
489 * @param string $value
490 * @param boolean $overrideDefault Overrides default language
491 * @return void
492 */
493 public function overrideLL($index, $value, $overrideDefault = TRUE) {
494 if (!isset($GLOBALS['LOCAL_LANG'])) {
495 $GLOBALS['LOCAL_LANG'] = array();
496 }
497 $GLOBALS['LOCAL_LANG'][$this->lang][$index][0]['target'] = $value;
498 if ($overrideDefault) {
499 $GLOBALS['LOCAL_LANG']['default'][$index][0]['target'] = $value;
500 }
501 }
502 }