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