[!!!][TASK] Drop support for csConv recode
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Charset / CharsetConverter.php
1 <?php
2 namespace TYPO3\CMS\Core\Charset;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Localization\Locales;
18 use TYPO3\CMS\Core\SingletonInterface;
19 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21
22 /**
23 * Notes on UTF-8
24 *
25 * Functions working on UTF-8 strings:
26 *
27 * - strchr/strstr
28 * - strrchr
29 * - substr_count
30 * - implode/explode/join
31 *
32 * Functions nearly working on UTF-8 strings:
33 *
34 * - strlen: returns the length in BYTES, if you need the length in CHARACTERS use utf8_strlen
35 * - trim/ltrim/rtrim: the second parameter 'charlist' won't work for characters not contained in 7-bit ASCII
36 * - strpos/strrpos: they return the BYTE position, if you need the CHARACTER position use utf8_strpos/utf8_strrpos
37 * - htmlentities: charset support for UTF-8 only since PHP 4.3.0
38 * - preg_*: Support compiled into PHP by default nowadays, but could be unavailable, need to use modifier
39 *
40 * Functions NOT working on UTF-8 strings:
41 *
42 * - str*cmp
43 * - stristr
44 * - stripos
45 * - substr
46 * - strrev
47 * - split/spliti
48 * - ...
49 */
50
51 /**
52 * Class for conversion between charsets
53 */
54 class CharsetConverter implements SingletonInterface
55 {
56 /**
57 * ASCII Value for chars with no equivalent.
58 *
59 * @var int
60 */
61 public $noCharByteVal = 63;
62
63 /**
64 * This is the array where parsed conversion tables are stored (cached)
65 *
66 * @var array
67 */
68 public $parsedCharsets = array();
69
70 /**
71 * An array where case folding data will be stored (cached)
72 *
73 * @var array
74 */
75 public $caseFolding = array();
76
77 /**
78 * An array where charset-to-ASCII mappings are stored (cached)
79 *
80 * @var array
81 */
82 public $toASCII = array();
83
84 /**
85 * This tells the converter which charsets has two bytes per char:
86 *
87 * @var array
88 */
89 public $twoByteSets = array(
90 'ucs-2' => 1
91 );
92
93 /**
94 * This tells the converter which charsets has four bytes per char:
95 *
96 * @var array
97 */
98 public $fourByteSets = array(
99 'ucs-4' => 1, // 4-byte Unicode
100 'utf-32' => 1
101 );
102
103 /**
104 * This tells the converter which charsets use a scheme like the Extended Unix Code:
105 *
106 * @var array
107 */
108 public $eucBasedSets = array(
109 'gb2312' => 1, // Chinese, simplified.
110 'big5' => 1, // Chinese, traditional.
111 'euc-kr' => 1, // Korean
112 'shift_jis' => 1
113 );
114
115 /**
116 * @link http://developer.apple.com/documentation/macos8/TextIntlSvcs/TextEncodingConversionManager/TEC1.5/TEC.b0.html
117 * @link http://czyborra.com/charsets/iso8859.html
118 *
119 * @var array
120 */
121 public $synonyms = array(
122 'us' => 'ascii',
123 'us-ascii' => 'ascii',
124 'cp819' => 'iso-8859-1',
125 'ibm819' => 'iso-8859-1',
126 'iso-ir-100' => 'iso-8859-1',
127 'iso-ir-101' => 'iso-8859-2',
128 'iso-ir-109' => 'iso-8859-3',
129 'iso-ir-110' => 'iso-8859-4',
130 'iso-ir-144' => 'iso-8859-5',
131 'iso-ir-127' => 'iso-8859-6',
132 'iso-ir-126' => 'iso-8859-7',
133 'iso-ir-138' => 'iso-8859-8',
134 'iso-ir-148' => 'iso-8859-9',
135 'iso-ir-157' => 'iso-8859-10',
136 'iso-ir-179' => 'iso-8859-13',
137 'iso-ir-199' => 'iso-8859-14',
138 'iso-ir-203' => 'iso-8859-15',
139 'csisolatin1' => 'iso-8859-1',
140 'csisolatin2' => 'iso-8859-2',
141 'csisolatin3' => 'iso-8859-3',
142 'csisolatin5' => 'iso-8859-9',
143 'csisolatin8' => 'iso-8859-14',
144 'csisolatin9' => 'iso-8859-15',
145 'csisolatingreek' => 'iso-8859-7',
146 'iso-celtic' => 'iso-8859-14',
147 'latin1' => 'iso-8859-1',
148 'latin2' => 'iso-8859-2',
149 'latin3' => 'iso-8859-3',
150 'latin5' => 'iso-8859-9',
151 'latin6' => 'iso-8859-10',
152 'latin8' => 'iso-8859-14',
153 'latin9' => 'iso-8859-15',
154 'l1' => 'iso-8859-1',
155 'l2' => 'iso-8859-2',
156 'l3' => 'iso-8859-3',
157 'l5' => 'iso-8859-9',
158 'l6' => 'iso-8859-10',
159 'l8' => 'iso-8859-14',
160 'l9' => 'iso-8859-15',
161 'cyrillic' => 'iso-8859-5',
162 'arabic' => 'iso-8859-6',
163 'tis-620' => 'iso-8859-11',
164 'win874' => 'windows-874',
165 'win1250' => 'windows-1250',
166 'win1251' => 'windows-1251',
167 'win1252' => 'windows-1252',
168 'win1253' => 'windows-1253',
169 'win1254' => 'windows-1254',
170 'win1255' => 'windows-1255',
171 'win1256' => 'windows-1256',
172 'win1257' => 'windows-1257',
173 'win1258' => 'windows-1258',
174 'cp1250' => 'windows-1250',
175 'cp1251' => 'windows-1251',
176 'cp1252' => 'windows-1252',
177 'ms-ee' => 'windows-1250',
178 'ms-ansi' => 'windows-1252',
179 'ms-greek' => 'windows-1253',
180 'ms-turk' => 'windows-1254',
181 'winbaltrim' => 'windows-1257',
182 'koi-8ru' => 'koi-8r',
183 'koi8r' => 'koi-8r',
184 'cp878' => 'koi-8r',
185 'mac' => 'macroman',
186 'macintosh' => 'macroman',
187 'euc-cn' => 'gb2312',
188 'x-euc-cn' => 'gb2312',
189 'euccn' => 'gb2312',
190 'cp936' => 'gb2312',
191 'big-5' => 'big5',
192 'cp950' => 'big5',
193 'eucjp' => 'euc-jp',
194 'sjis' => 'shift_jis',
195 'shift-jis' => 'shift_jis',
196 'cp932' => 'shift_jis',
197 'cp949' => 'euc-kr',
198 'utf7' => 'utf-7',
199 'utf8' => 'utf-8',
200 'utf16' => 'utf-16',
201 'utf32' => 'utf-32',
202 'ucs2' => 'ucs-2',
203 'ucs4' => 'ucs-4'
204 );
205
206 /**
207 * Mapping of iso-639-1 language codes to script names
208 *
209 * @var array
210 */
211 public $lang_to_script = array(
212 // iso-639-1 language codes, see http://www.loc.gov/standards/iso639-2/php/code_list.php
213 'af' => 'west_european', // Afrikaans
214 'ar' => 'arabic',
215 'bg' => 'cyrillic', // Bulgarian
216 'bs' => 'east_european', // Bosnian
217 'cs' => 'east_european', // Czech
218 'da' => 'west_european', // Danish
219 'de' => 'west_european', // German
220 'es' => 'west_european', // Spanish
221 'et' => 'estonian',
222 'eo' => 'unicode', // Esperanto
223 'eu' => 'west_european', // Basque
224 'fa' => 'arabic', // Persian
225 'fi' => 'west_european', // Finish
226 'fo' => 'west_european', // Faroese
227 'fr' => 'west_european', // French
228 'ga' => 'west_european', // Irish
229 'gl' => 'west_european', // Galician
230 'gr' => 'greek',
231 'he' => 'hebrew', // Hebrew (since 1998)
232 'hi' => 'unicode', // Hindi
233 'hr' => 'east_european', // Croatian
234 'hu' => 'east_european', // Hungarian
235 'iw' => 'hebrew', // Hebrew (til 1998)
236 'is' => 'west_european', // Icelandic
237 'it' => 'west_european', // Italian
238 'ja' => 'japanese',
239 'ka' => 'unicode', // Georgian
240 'kl' => 'west_european', // Greenlandic
241 'km' => 'unicode', // Khmer
242 'ko' => 'korean',
243 'lt' => 'lithuanian',
244 'lv' => 'west_european', // Latvian/Lettish
245 'nl' => 'west_european', // Dutch
246 'no' => 'west_european', // Norwegian
247 'nb' => 'west_european', // Norwegian Bokmal
248 'nn' => 'west_european', // Norwegian Nynorsk
249 'pl' => 'east_european', // Polish
250 'pt' => 'west_european', // Portuguese
251 'ro' => 'east_european', // Romanian
252 'ru' => 'cyrillic', // Russian
253 'sk' => 'east_european', // Slovak
254 'sl' => 'east_european', // Slovenian
255 'sr' => 'cyrillic', // Serbian
256 'sv' => 'west_european', // Swedish
257 'sq' => 'albanian', // Albanian
258 'th' => 'thai',
259 'uk' => 'cyrillic', // Ukranian
260 'vi' => 'vietnamese',
261 'zh' => 'chinese',
262
263 // MS language codes, see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp
264 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wceinternational5/html/wce50conLanguageIdentifiersandLocales.asp
265 'afk' => 'west_european', // Afrikaans
266 'ara' => 'arabic',
267 'bgr' => 'cyrillic', // Bulgarian
268 'cat' => 'west_european', // Catalan
269 'chs' => 'simpl_chinese',
270 'cht' => 'trad_chinese',
271 'csy' => 'east_european', // Czech
272 'dan' => 'west_european', // Danish
273 'deu' => 'west_european', // German
274 'dea' => 'west_european', // German (Austrian)
275 'des' => 'west_european', // German (Swiss)
276 'ena' => 'west_european', // English (Australian)
277 'enc' => 'west_european', // English (Canadian)
278 'eng' => 'west_european', // English
279 'enz' => 'west_european', // English (New Zealand)
280 'enu' => 'west_european', // English (United States)
281 'euq' => 'west_european', // Basque
282 'fos' => 'west_european', // Faroese
283 'far' => 'arabic', // Persian
284 'fin' => 'west_european', // Finish
285 'fra' => 'west_european', // French
286 'frb' => 'west_european', // French (Belgian)
287 'frc' => 'west_european', // French (Canadian)
288 'frs' => 'west_european', // French (Swiss)
289 'geo' => 'unicode', // Georgian
290 'glg' => 'west_european', // Galician
291 'ell' => 'greek',
292 'heb' => 'hebrew',
293 'hin' => 'unicode', // Hindi
294 'hun' => 'east_european', // Hungarian
295 'isl' => 'west_european', // Icelandic
296 'ita' => 'west_european', // Italian
297 'its' => 'west_european', // Italian (Swiss)
298 'jpn' => 'japanese',
299 'khm' => 'unicode', // Khmer
300 'kor' => 'korean',
301 'lth' => 'lithuanian',
302 'lvi' => 'west_european', // Latvian/Lettish
303 'msl' => 'west_european', // Malay
304 'nlb' => 'west_european', // Dutch (Belgian)
305 'nld' => 'west_european', // Dutch
306 'nor' => 'west_european', // Norwegian (bokmal)
307 'non' => 'west_european', // Norwegian (nynorsk)
308 'plk' => 'east_european', // Polish
309 'ptg' => 'west_european', // Portuguese
310 'ptb' => 'west_european', // Portuguese (Brazil)
311 'rom' => 'east_european', // Romanian
312 'rus' => 'cyrillic', // Russian
313 'slv' => 'east_european', // Slovenian
314 'sky' => 'east_european', // Slovak
315 'srl' => 'east_european', // Serbian (Latin)
316 'srb' => 'cyrillic', // Serbian (Cyrillic)
317 'esp' => 'west_european', // Spanish (trad. sort)
318 'esm' => 'west_european', // Spanish (Mexican)
319 'esn' => 'west_european', // Spanish (internat. sort)
320 'sve' => 'west_european', // Swedish
321 'sqi' => 'albanian', // Albanian
322 'tha' => 'thai',
323 'trk' => 'turkish',
324 'ukr' => 'cyrillic', // Ukrainian
325
326 // English language names
327 'afrikaans' => 'west_european',
328 'albanian' => 'albanian',
329 'arabic' => 'arabic',
330 'basque' => 'west_european',
331 'bosnian' => 'east_european',
332 'bulgarian' => 'east_european',
333 'catalan' => 'west_european',
334 'croatian' => 'east_european',
335 'czech' => 'east_european',
336 'danish' => 'west_european',
337 'dutch' => 'west_european',
338 'english' => 'west_european',
339 'esperanto' => 'unicode',
340 'estonian' => 'estonian',
341 'faroese' => 'west_european',
342 'farsi' => 'arabic',
343 'finnish' => 'west_european',
344 'french' => 'west_european',
345 'galician' => 'west_european',
346 'georgian' => 'unicode',
347 'german' => 'west_european',
348 'greek' => 'greek',
349 'greenlandic' => 'west_european',
350 'hebrew' => 'hebrew',
351 'hindi' => 'unicode',
352 'hungarian' => 'east_european',
353 'icelandic' => 'west_european',
354 'italian' => 'west_european',
355 'khmer' => 'unicode',
356 'latvian' => 'west_european',
357 'lettish' => 'west_european',
358 'lithuanian' => 'lithuanian',
359 'malay' => 'west_european',
360 'norwegian' => 'west_european',
361 'persian' => 'arabic',
362 'polish' => 'east_european',
363 'portuguese' => 'west_european',
364 'russian' => 'cyrillic',
365 'romanian' => 'east_european',
366 'serbian' => 'cyrillic',
367 'slovak' => 'east_european',
368 'slovenian' => 'east_european',
369 'spanish' => 'west_european',
370 'svedish' => 'west_european',
371 'that' => 'thai',
372 'turkish' => 'turkish',
373 'ukrainian' => 'cyrillic'
374 );
375
376 /**
377 * Mapping of language (family) names to charsets on Unix
378 *
379 * @var array
380 */
381 public $script_to_charset_unix = array(
382 'west_european' => 'iso-8859-1',
383 'estonian' => 'iso-8859-1',
384 'east_european' => 'iso-8859-2',
385 'baltic' => 'iso-8859-4',
386 'cyrillic' => 'iso-8859-5',
387 'arabic' => 'iso-8859-6',
388 'greek' => 'iso-8859-7',
389 'hebrew' => 'iso-8859-8',
390 'turkish' => 'iso-8859-9',
391 'thai' => 'iso-8859-11', // = TIS-620
392 'lithuanian' => 'iso-8859-13',
393 'chinese' => 'gb2312', // = euc-cn
394 'japanese' => 'euc-jp',
395 'korean' => 'euc-kr',
396 'simpl_chinese' => 'gb2312',
397 'trad_chinese' => 'big5',
398 'vietnamese' => '',
399 'unicode' => 'utf-8',
400 'albanian' => 'utf-8'
401 );
402
403 /**
404 * Mapping of language (family) names to charsets on Windows
405 *
406 * @var array
407 */
408 public $script_to_charset_windows = array(
409 'east_european' => 'windows-1250',
410 'cyrillic' => 'windows-1251',
411 'west_european' => 'windows-1252',
412 'greek' => 'windows-1253',
413 'turkish' => 'windows-1254',
414 'hebrew' => 'windows-1255',
415 'arabic' => 'windows-1256',
416 'baltic' => 'windows-1257',
417 'estonian' => 'windows-1257',
418 'lithuanian' => 'windows-1257',
419 'vietnamese' => 'windows-1258',
420 'thai' => 'cp874',
421 'korean' => 'cp949',
422 'chinese' => 'gb2312',
423 'japanese' => 'shift_jis',
424 'simpl_chinese' => 'gb2312',
425 'trad_chinese' => 'big5',
426 'albanian' => 'windows-1250',
427 'unicode' => 'utf-8'
428 );
429
430 /**
431 * Mapping of locale names to charsets
432 *
433 * @var array
434 */
435 public $locale_to_charset = array(
436 'japanese.euc' => 'euc-jp',
437 'ja_jp.ujis' => 'euc-jp',
438 'korean.euc' => 'euc-kr',
439 'sr@Latn' => 'iso-8859-2',
440 'zh_cn' => 'gb2312',
441 'zh_hk' => 'big5',
442 'zh_tw' => 'big5'
443 );
444
445 /**
446 * TYPO3 specific: Array with the system charsets used for each system language in TYPO3:
447 * Empty values means "utf-8"
448 *
449 * @var array
450 */
451 public $charSetArray = array(
452 'af' => '',
453 'ar' => 'iso-8859-6',
454 'ba' => 'iso-8859-2',
455 'bg' => 'windows-1251',
456 'br' => '',
457 'ca' => 'iso-8859-15',
458 'ch' => 'gb2312',
459 'cs' => 'windows-1250',
460 'cz' => 'windows-1250',
461 'da' => '',
462 'de' => '',
463 'dk' => '',
464 'el' => 'iso-8859-7',
465 'eo' => 'utf-8',
466 'es' => '',
467 'et' => 'iso-8859-4',
468 'eu' => '',
469 'fa' => 'utf-8',
470 'fi' => '',
471 'fo' => 'utf-8',
472 'fr' => '',
473 'fr_CA' => '',
474 'ga' => '',
475 'ge' => 'utf-8',
476 'gl' => '',
477 'gr' => 'iso-8859-7',
478 'he' => 'utf-8',
479 'hi' => 'utf-8',
480 'hk' => 'big5',
481 'hr' => 'windows-1250',
482 'hu' => 'iso-8859-2',
483 'is' => 'utf-8',
484 'it' => '',
485 'ja' => 'shift_jis',
486 'jp' => 'shift_jis',
487 'ka' => 'utf-8',
488 'kl' => 'utf-8',
489 'km' => 'utf-8',
490 'ko' => 'euc-kr',
491 'kr' => 'euc-kr',
492 'lt' => 'windows-1257',
493 'lv' => 'utf-8',
494 'ms' => '',
495 'my' => '',
496 'nl' => '',
497 'no' => '',
498 'pl' => 'iso-8859-2',
499 'pt' => '',
500 'pt_BR' => '',
501 'qc' => '',
502 'ro' => 'iso-8859-2',
503 'ru' => 'windows-1251',
504 'se' => '',
505 'si' => 'windows-1250',
506 'sk' => 'windows-1250',
507 'sl' => 'windows-1250',
508 'sq' => 'utf-8',
509 'sr' => 'utf-8',
510 'sv' => '',
511 'th' => 'iso-8859-11',
512 'tr' => 'iso-8859-9',
513 'ua' => 'windows-1251',
514 'uk' => 'windows-1251',
515 'vi' => 'utf-8',
516 'vn' => 'utf-8',
517 'zh' => 'big5'
518 );
519
520 /**
521 * Normalize - changes input character set to lowercase letters.
522 *
523 * @param string $charset Input charset
524 * @return string Normalized charset
525 */
526 public function parse_charset($charset)
527 {
528 $charset = trim(strtolower($charset));
529 if (isset($this->synonyms[$charset])) {
530 $charset = $this->synonyms[$charset];
531 }
532 return $charset;
533 }
534
535 /**
536 * Get the charset of a locale.
537 *
538 * ln language
539 * ln_CN language / country
540 * ln_CN.cs language / country / charset
541 * ln_CN.cs@mod language / country / charset / modifier
542 *
543 * @param string $locale Locale string
544 * @return string Charset resolved for locale string
545 */
546 public function get_locale_charset($locale)
547 {
548 $locale = strtolower($locale);
549 // Exact locale specific charset?
550 if (isset($this->locale_to_charset[$locale])) {
551 return $this->locale_to_charset[$locale];
552 }
553 // Get modifier
554 list($locale, $modifier) = explode('@', $locale);
555 // Locale contains charset: use it
556 list($locale, $charset) = explode('.', $locale);
557 if ($charset) {
558 return $this->parse_charset($charset);
559 }
560 // Modifier is 'euro' (after charset check, because of xx.utf-8@euro)
561 if ($modifier === 'euro') {
562 return 'iso-8859-15';
563 }
564 // Get language
565 list($language, ) = explode('_', $locale);
566 if (isset($this->lang_to_script[$language])) {
567 $script = $this->lang_to_script[$language];
568 }
569 if (TYPO3_OS === 'WIN') {
570 $cs = $this->script_to_charset_windows[$script] ?: 'windows-1252';
571 } else {
572 $cs = $this->script_to_charset_unix[$script] ?: 'utf-8';
573 }
574 return $cs;
575 }
576
577 /********************************************
578 *
579 * Charset Conversion functions
580 *
581 ********************************************/
582 /**
583 * Convert from one charset to another charset.
584 *
585 * @param string $inputString Input string
586 * @param string $fromCharset From charset (the current charset of the string)
587 * @param string $toCharset To charset (the output charset wanted)
588 * @param bool $useEntityForNoChar If set, then characters that are not available in the destination character set will be encoded as numeric entities
589 * @return string Converted string
590 * @see convArray()
591 */
592 public function conv($inputString, $fromCharset, $toCharset, $useEntityForNoChar = false)
593 {
594 if ($fromCharset === $toCharset) {
595 return $inputString;
596 }
597 // PHP-libs don't support fallback to SGML entities, but UTF-8 handles everything
598 if ($toCharset === 'utf-8' || !$useEntityForNoChar) {
599 switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod']) {
600 case 'mbstring':
601 $convertedString = mb_convert_encoding($inputString, $toCharset, $fromCharset);
602 if (false !== $convertedString) {
603 return $convertedString;
604 }
605 // Returns FALSE for unsupported charsets
606 break;
607 case 'iconv':
608 $convertedString = iconv($fromCharset, $toCharset . '//TRANSLIT', $inputString);
609 if (false !== $convertedString) {
610 return $convertedString;
611 }
612 break;
613 }
614 }
615 if ($fromCharset !== 'utf-8') {
616 $inputString = $this->utf8_encode($inputString, $fromCharset);
617 }
618 if ($toCharset !== 'utf-8') {
619 $inputString = $this->utf8_decode($inputString, $toCharset, $useEntityForNoChar);
620 }
621 return $inputString;
622 }
623
624 /**
625 * Convert all elements in ARRAY with type string from one charset to another charset.
626 * NOTICE: Array is passed by reference!
627 *
628 * @param array $array Input array, possibly multidimensional
629 * @param string $fromCharset From charset (the current charset of the string)
630 * @param string $toCharset To charset (the output charset wanted)
631 * @param bool $useEntityForNoChar If set, then characters that are not available in the destination character set will be encoded as numeric entities
632 * @return void
633 * @see conv()
634 */
635 public function convArray(&$array, $fromCharset, $toCharset, $useEntityForNoChar = false)
636 {
637 foreach ($array as $key => $value) {
638 if (is_array($array[$key])) {
639 $this->convArray($array[$key], $fromCharset, $toCharset, $useEntityForNoChar);
640 } elseif (is_string($array[$key])) {
641 $array[$key] = $this->conv($array[$key], $fromCharset, $toCharset, $useEntityForNoChar);
642 }
643 }
644 }
645
646 /**
647 * Converts $str from $charset to UTF-8
648 *
649 * @param string $str String in local charset to convert to UTF-8
650 * @param string $charset Charset, lowercase. Must be found in csconvtbl/ folder.
651 * @return string Output string, converted to UTF-8
652 */
653 public function utf8_encode($str, $charset)
654 {
655 if ($charset === 'utf-8') {
656 return $str;
657 }
658 // Charset is case-insensitive
659 // Parse conv. table if not already
660 if ($this->initCharset($charset)) {
661 $strLen = strlen($str);
662 $outStr = '';
663 // Traverse each char in string
664 for ($a = 0; $a < $strLen; $a++) {
665 $chr = substr($str, $a, 1);
666 $ord = ord($chr);
667 // If the charset has two bytes per char
668 if (isset($this->twoByteSets[$charset])) {
669 $ord2 = ord($str[$a + 1]);
670 // Assume big endian
671 $ord = $ord << 8 | $ord2;
672 // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
673 if (isset($this->parsedCharsets[$charset]['local'][$ord])) {
674 $outStr .= $this->parsedCharsets[$charset]['local'][$ord];
675 } else {
676 $outStr .= chr($this->noCharByteVal);
677 }
678 // No char exists
679 $a++;
680 } elseif ($ord > 127) {
681 // If char has value over 127 it's a multibyte char in UTF-8
682 // EUC uses two-bytes above 127; we get both and advance pointer and make $ord a 16bit int.
683 if (isset($this->eucBasedSets[$charset])) {
684 // Shift-JIS: chars between 160 and 223 are single byte
685 if ($charset !== 'shift_jis' || ($ord < 160 || $ord > 223)) {
686 $a++;
687 $ord2 = ord(substr($str, $a, 1));
688 $ord = $ord * 256 + $ord2;
689 }
690 }
691 if (isset($this->parsedCharsets[$charset]['local'][$ord])) {
692 // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
693 $outStr .= $this->parsedCharsets[$charset]['local'][$ord];
694 } else {
695 $outStr .= chr($this->noCharByteVal);
696 }
697 } else {
698 $outStr .= $chr;
699 }
700 }
701 return $outStr;
702 }
703 }
704
705 /**
706 * Converts $str from UTF-8 to $charset
707 *
708 * @param string $str String in UTF-8 to convert to local charset
709 * @param string $charset Charset, lowercase. Must be found in csconvtbl/ folder.
710 * @param bool $useEntityForNoChar If set, then characters that are not available in the destination character set will be encoded as numeric entities
711 * @return string Output string, converted to local charset
712 */
713 public function utf8_decode($str, $charset, $useEntityForNoChar = false)
714 {
715 if ($charset === 'utf-8') {
716 return $str;
717 }
718 // Charset is case-insensitive.
719 // Parse conv. table if not already
720 if ($this->initCharset($charset)) {
721 $strLen = strlen($str);
722 $outStr = '';
723 // Traverse each char in UTF-8 string
724 for ($a = 0, $i = 0; $a < $strLen; $a++, $i++) {
725 $chr = substr($str, $a, 1);
726 $ord = ord($chr);
727 // This means multibyte! (first byte!)
728 if ($ord > 127) {
729 // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
730 if ($ord & 64) {
731 // Add first byte
732 $buf = $chr;
733 // For each byte in multibyte string
734 for ($b = 0; $b < 8; $b++) {
735 // Shift it left and
736 $ord = $ord << 1;
737 // ... and with 8th bit - if that is set, then there are still bytes in sequence.
738 if ($ord & 128) {
739 $a++;
740 // ... and add the next char.
741 $buf .= substr($str, $a, 1);
742 } else {
743 break;
744 }
745 }
746 // If the UTF-8 char-sequence is found then...
747 if (isset($this->parsedCharsets[$charset]['utf8'][$buf])) {
748 // The local number
749 $mByte = $this->parsedCharsets[$charset]['utf8'][$buf];
750 // If the local number is greater than 255 we will need to split the byte (16bit word assumed) in two chars.
751 if ($mByte > 255) {
752 $outStr .= chr(($mByte >> 8 & 255)) . chr(($mByte & 255));
753 } else {
754 $outStr .= chr($mByte);
755 }
756 } elseif ($useEntityForNoChar) {
757 // Create num entity:
758 $outStr .= '&#' . $this->utf8CharToUnumber($buf, 1) . ';';
759 } else {
760 $outStr .= chr($this->noCharByteVal);
761 }
762 } else {
763 $outStr .= chr($this->noCharByteVal);
764 }
765 } else {
766 $outStr .= $chr;
767 }
768 }
769 return $outStr;
770 }
771 }
772
773 /**
774 * Converts all chars > 127 to numeric entities.
775 *
776 * @param string $str Input string
777 * @return string Output string
778 */
779 public function utf8_to_entities($str)
780 {
781 $strLen = strlen($str);
782 $outStr = '';
783 // Traverse each char in UTF-8 string.
784 for ($a = 0; $a < $strLen; $a++) {
785 $chr = substr($str, $a, 1);
786 $ord = ord($chr);
787 // This means multibyte! (first byte!)
788 if ($ord > 127) {
789 // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
790 if ($ord & 64) {
791 // Add first byte
792 $buf = $chr;
793 // For each byte in multibyte string...
794 for ($b = 0; $b < 8; $b++) {
795 // Shift it left and ...
796 $ord = $ord << 1;
797 // ... and with 8th bit - if that is set, then there are still bytes in sequence.
798 if ($ord & 128) {
799 $a++;
800 // ... and add the next char.
801 $buf .= substr($str, $a, 1);
802 } else {
803 break;
804 }
805 }
806 $outStr .= '&#' . $this->utf8CharToUnumber($buf, 1) . ';';
807 } else {
808 $outStr .= chr($this->noCharByteVal);
809 }
810 } else {
811 $outStr .= $chr;
812 }
813 }
814 return $outStr;
815 }
816
817 /**
818 * Converts numeric entities (UNICODE, eg. decimal (&#1234;) or hexadecimal (&#x1b;)) to UTF-8 multibyte chars
819 *
820 * @param string $str Input string, UTF-8
821 * @param bool $alsoStdHtmlEnt If set, then all string-HTML entities (like &amp; or &pound; will be converted as well)
822 * @return string Output string
823 */
824 public function entities_to_utf8($str, $alsoStdHtmlEnt = false)
825 {
826 if ($alsoStdHtmlEnt) {
827 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES, ENT_COMPAT, 'UTF-8'));
828 }
829 $token = md5(microtime());
830 $parts = explode($token, preg_replace('/(&([#[:alnum:]]*);)/', $token . '${2}' . $token, $str));
831 foreach ($parts as $k => $v) {
832 // Only take every second element
833 if ($k % 2 === 0) {
834 continue;
835 }
836 $position = 0;
837 // Dec or hex entities
838 if (substr($v, $position, 1) === '#') {
839 $position++;
840 if (substr($v, $position, 1) === 'x') {
841 $v = hexdec(substr($v, ++$position));
842 } else {
843 $v = substr($v, $position);
844 }
845 $parts[$k] = $this->UnumberToChar($v);
846 } elseif ($alsoStdHtmlEnt && isset($trans_tbl['&' . $v . ';'])) {
847 // Other entities:
848 $v = $trans_tbl['&' . $v . ';'];
849 $parts[$k] = $v;
850 } else {
851 // No conversion:
852 $parts[$k] = '&' . $v . ';';
853 }
854 }
855 return implode('', $parts);
856 }
857
858 /**
859 * Converts all chars in the input UTF-8 string into integer numbers returned in an array
860 *
861 * @param string $str Input string, UTF-8
862 * @param bool $convEntities If set, then all HTML entities (like &amp; or &pound; or &#123; or &#x3f5d;) will be detected as characters.
863 * @param bool $retChar If set, then instead of integer numbers the real UTF-8 char is returned.
864 * @return array Output array with the char numbers
865 */
866 public function utf8_to_numberarray($str, $convEntities = false, $retChar = false)
867 {
868 // If entities must be registered as well...:
869 if ($convEntities) {
870 $str = $this->entities_to_utf8($str, 1);
871 }
872 // Do conversion:
873 $strLen = strlen($str);
874 $outArr = array();
875 // Traverse each char in UTF-8 string.
876 for ($a = 0; $a < $strLen; $a++) {
877 $chr = substr($str, $a, 1);
878 $ord = ord($chr);
879 // This means multibyte! (first byte!)
880 if ($ord > 127) {
881 // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
882 if ($ord & 64) {
883 // Add first byte
884 $buf = $chr;
885 // For each byte in multibyte string...
886 for ($b = 0; $b < 8; $b++) {
887 // Shift it left and ...
888 $ord = $ord << 1;
889 // ... and with 8th bit - if that is set, then there are still bytes in sequence.
890 if ($ord & 128) {
891 $a++;
892 // ... and add the next char.
893 $buf .= substr($str, $a, 1);
894 } else {
895 break;
896 }
897 }
898 $outArr[] = $retChar ? $buf : $this->utf8CharToUnumber($buf);
899 } else {
900 $outArr[] = $retChar ? chr($this->noCharByteVal) : $this->noCharByteVal;
901 }
902 } else {
903 $outArr[] = $retChar ? chr($ord) : $ord;
904 }
905 }
906 return $outArr;
907 }
908
909 /**
910 * Converts a UNICODE number to a UTF-8 multibyte character
911 * Algorithm based on script found at From: http://czyborra.com/utf/
912 * Unit-tested by Kasper
913 *
914 * The binary representation of the character's integer value is thus simply spread across the bytes
915 * and the number of high bits set in the lead byte announces the number of bytes in the multibyte sequence:
916 *
917 * bytes | bits | representation
918 * 1 | 7 | 0vvvvvvv
919 * 2 | 11 | 110vvvvv 10vvvvvv
920 * 3 | 16 | 1110vvvv 10vvvvvv 10vvvvvv
921 * 4 | 21 | 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv
922 * 5 | 26 | 111110vv 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv
923 * 6 | 31 | 1111110v 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv
924 *
925 * @param int $unicodeInteger UNICODE integer
926 * @return string UTF-8 multibyte character string
927 * @see utf8CharToUnumber()
928 */
929 public function UnumberToChar($unicodeInteger)
930 {
931 $str = '';
932 if ($unicodeInteger < 128) {
933 $str .= chr($unicodeInteger);
934 } elseif ($unicodeInteger < 2048) {
935 $str .= chr(192 | $unicodeInteger >> 6);
936 $str .= chr(128 | $unicodeInteger & 63);
937 } elseif ($unicodeInteger < 65536) {
938 $str .= chr(224 | $unicodeInteger >> 12);
939 $str .= chr(128 | $unicodeInteger >> 6 & 63);
940 $str .= chr(128 | $unicodeInteger & 63);
941 } elseif ($unicodeInteger < 2097152) {
942 $str .= chr(240 | $unicodeInteger >> 18);
943 $str .= chr(128 | $unicodeInteger >> 12 & 63);
944 $str .= chr(128 | $unicodeInteger >> 6 & 63);
945 $str .= chr(128 | $unicodeInteger & 63);
946 } elseif ($unicodeInteger < 67108864) {
947 $str .= chr(248 | $unicodeInteger >> 24);
948 $str .= chr(128 | $unicodeInteger >> 18 & 63);
949 $str .= chr(128 | $unicodeInteger >> 12 & 63);
950 $str .= chr(128 | $unicodeInteger >> 6 & 63);
951 $str .= chr(128 | $unicodeInteger & 63);
952 } elseif ($unicodeInteger < 2147483648) {
953 $str .= chr(252 | $unicodeInteger >> 30);
954 $str .= chr(128 | $unicodeInteger >> 24 & 63);
955 $str .= chr(128 | $unicodeInteger >> 18 & 63);
956 $str .= chr(128 | $unicodeInteger >> 12 & 63);
957 $str .= chr(128 | $unicodeInteger >> 6 & 63);
958 $str .= chr(128 | $unicodeInteger & 63);
959 } else {
960 // Cannot express a 32-bit character in UTF-8
961 $str .= chr($this->noCharByteVal);
962 }
963 return $str;
964 }
965
966 /**
967 * Converts a UTF-8 Multibyte character to a UNICODE number
968 * Unit-tested by Kasper
969 *
970 * @param string $str UTF-8 multibyte character string
971 * @param bool $hex If set, then a hex. number is returned.
972 * @return int UNICODE integer
973 * @see UnumberToChar()
974 */
975 public function utf8CharToUnumber($str, $hex = false)
976 {
977 // First char
978 $ord = ord($str[0]);
979 // This verifies that it IS a multi byte string
980 if (($ord & 192) === 192) {
981 $binBuf = '';
982 // For each byte in multibyte string...
983 for ($b = 0; $b < 8; $b++) {
984 // Shift it left and ...
985 $ord = $ord << 1;
986 // ... and with 8th bit - if that is set, then there are still bytes in sequence.
987 if ($ord & 128) {
988 $binBuf .= substr('00000000' . decbin(ord(substr($str, ($b + 1), 1))), -6);
989 } else {
990 break;
991 }
992 }
993 $binBuf = substr(('00000000' . decbin(ord($str[0]))), -(6 - $b)) . $binBuf;
994 $int = bindec($binBuf);
995 } else {
996 $int = $ord;
997 }
998 return $hex ? 'x' . dechex($int) : $int;
999 }
1000
1001 /********************************************
1002 *
1003 * Init functions
1004 *
1005 ********************************************/
1006 /**
1007 * This will initialize a charset for use if it's defined in the 'typo3/sysext/core/Resources/Private/Charsets/csconvtbl/' folder
1008 * This function is automatically called by the conversion functions
1009 *
1010 * PLEASE SEE: http://www.unicode.org/Public/MAPPINGS/
1011 *
1012 * @param string $charset The charset to be initialized. Use lowercase charset always (the charset must match exactly with a filename in csconvtbl/ folder ([charset].tbl)
1013 * @return int Returns '1' if already loaded. Returns FALSE if charset conversion table was not found. Returns '2' if the charset conversion table was found and parsed.
1014 * @access private
1015 */
1016 public function initCharset($charset)
1017 {
1018 // Only process if the charset is not yet loaded:
1019 if (!is_array($this->parsedCharsets[$charset])) {
1020 // Conversion table filename:
1021 $charsetConvTableFile = ExtensionManagementUtility::extPath('core') . 'Resources/Private/Charsets/csconvtbl/' . $charset . '.tbl';
1022 // If the conversion table is found:
1023 if ($charset && GeneralUtility::validPathStr($charsetConvTableFile) && @is_file($charsetConvTableFile)) {
1024 // Cache file for charsets:
1025 // Caching brought parsing time for gb2312 down from 2400 ms to 150 ms. For other charsets we are talking 11 ms down to zero.
1026 $cacheFile = GeneralUtility::getFileAbsFileName('typo3temp/cs/charset_' . $charset . '.tbl');
1027 if ($cacheFile && @is_file($cacheFile)) {
1028 $this->parsedCharsets[$charset] = unserialize(GeneralUtility::getUrl($cacheFile));
1029 } else {
1030 // Parse conversion table into lines:
1031 $lines = GeneralUtility::trimExplode(LF, GeneralUtility::getUrl($charsetConvTableFile), true);
1032 // Initialize the internal variable holding the conv. table:
1033 $this->parsedCharsets[$charset] = array('local' => array(), 'utf8' => array());
1034 // traverse the lines:
1035 $detectedType = '';
1036 foreach ($lines as $value) {
1037 // Comment line or blanks are ignored.
1038 if (trim($value) && $value[0] !== '#') {
1039 // Detect type if not done yet: (Done on first real line)
1040 // The "whitespaced" type is on the syntax "0x0A 0x000A #LINE FEED" while "ms-token" is like "B9 = U+00B9 : SUPERSCRIPT ONE"
1041 if (!$detectedType) {
1042 $detectedType = preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/', $value) ? 'whitespaced' : 'ms-token';
1043 }
1044 if ($detectedType === 'ms-token') {
1045 list($hexbyte, $utf8) = preg_split('/[=:]/', $value, 3);
1046 } elseif ($detectedType === 'whitespaced') {
1047 $regA = array();
1048 preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/', $value, $regA);
1049 $hexbyte = $regA[1];
1050 $utf8 = 'U+' . $regA[2];
1051 }
1052 $decval = hexdec(trim($hexbyte));
1053 if ($decval > 127) {
1054 $utf8decval = hexdec(substr(trim($utf8), 2));
1055 $this->parsedCharsets[$charset]['local'][$decval] = $this->UnumberToChar($utf8decval);
1056 $this->parsedCharsets[$charset]['utf8'][$this->parsedCharsets[$charset]['local'][$decval]] = $decval;
1057 }
1058 }
1059 }
1060 if ($cacheFile) {
1061 GeneralUtility::writeFileToTypo3tempDir($cacheFile, serialize($this->parsedCharsets[$charset]));
1062 }
1063 }
1064 return 2;
1065 } else {
1066 return false;
1067 }
1068 } else {
1069 return 1;
1070 }
1071 }
1072
1073 /**
1074 * This function initializes all UTF-8 character data tables.
1075 *
1076 * PLEASE SEE: http://www.unicode.org/Public/UNIDATA/
1077 *
1078 * @param string $mode Mode ("case", "ascii", ...)
1079 * @return int Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
1080 * @access private
1081 */
1082 public function initUnicodeData($mode = null)
1083 {
1084 // Cache files
1085 $cacheFileCase = GeneralUtility::getFileAbsFileName('typo3temp/cs/cscase_utf-8.tbl');
1086 $cacheFileASCII = GeneralUtility::getFileAbsFileName('typo3temp/cs/csascii_utf-8.tbl');
1087 // Only process if the tables are not yet loaded
1088 switch ($mode) {
1089 case 'case':
1090 if (is_array($this->caseFolding['utf-8'])) {
1091 return 1;
1092 }
1093 // Use cached version if possible
1094 if ($cacheFileCase && @is_file($cacheFileCase)) {
1095 $this->caseFolding['utf-8'] = unserialize(GeneralUtility::getUrl($cacheFileCase));
1096 return 2;
1097 }
1098 break;
1099 case 'ascii':
1100 if (is_array($this->toASCII['utf-8'])) {
1101 return 1;
1102 }
1103 // Use cached version if possible
1104 if ($cacheFileASCII && @is_file($cacheFileASCII)) {
1105 $this->toASCII['utf-8'] = unserialize(GeneralUtility::getUrl($cacheFileASCII));
1106 return 2;
1107 }
1108 break;
1109 }
1110 // Process main Unicode data file
1111 $unicodeDataFile = ExtensionManagementUtility::extPath('core') . 'Resources/Private/Charsets/unidata/UnicodeData.txt';
1112 if (!(GeneralUtility::validPathStr($unicodeDataFile) && @is_file($unicodeDataFile))) {
1113 return false;
1114 }
1115 $fh = fopen($unicodeDataFile, 'rb');
1116 if (!$fh) {
1117 return false;
1118 }
1119 // key = utf8 char (single codepoint), value = utf8 string (codepoint sequence)
1120 // Note: we use the UTF-8 characters here and not the Unicode numbers to avoid conversion roundtrip in utf8_strtolower/-upper)
1121 $this->caseFolding['utf-8'] = array();
1122 $utf8CaseFolding = &$this->caseFolding['utf-8'];
1123 // a shorthand
1124 $utf8CaseFolding['toUpper'] = array();
1125 $utf8CaseFolding['toLower'] = array();
1126 $utf8CaseFolding['toTitle'] = array();
1127 // Array of temp. decompositions
1128 $decomposition = array();
1129 // Array of chars that are marks (eg. composing accents)
1130 $mark = array();
1131 // Array of chars that are numbers (eg. digits)
1132 $number = array();
1133 // Array of chars to be omitted (eg. Russian hard sign)
1134 $omit = array();
1135 while (!feof($fh)) {
1136 $line = fgets($fh, 4096);
1137 // Has a lot of info
1138 list($char, $name, $cat, , , $decomp, , , $num, , , , $upper, $lower, $title, ) = explode(';', rtrim($line));
1139 $ord = hexdec($char);
1140 if ($ord > 65535) {
1141 // Only process the BMP
1142 break;
1143 }
1144 $utf8_char = $this->UnumberToChar($ord);
1145 if ($upper) {
1146 $utf8CaseFolding['toUpper'][$utf8_char] = $this->UnumberToChar(hexdec($upper));
1147 }
1148 if ($lower) {
1149 $utf8CaseFolding['toLower'][$utf8_char] = $this->UnumberToChar(hexdec($lower));
1150 }
1151 // Store "title" only when different from "upper" (only a few)
1152 if ($title && $title !== $upper) {
1153 $utf8CaseFolding['toTitle'][$utf8_char] = $this->UnumberToChar(hexdec($title));
1154 }
1155 switch ($cat[0]) {
1156 case 'M':
1157 // mark (accent, umlaut, ...)
1158 $mark['U+' . $char] = 1;
1159 break;
1160 case 'N':
1161 // numeric value
1162 if ($ord > 128 && $num !== '') {
1163 $number['U+' . $char] = $num;
1164 }
1165 }
1166 // Accented Latin letters without "official" decomposition
1167 $match = array();
1168 if (preg_match('/^LATIN (SMALL|CAPITAL) LETTER ([A-Z]) WITH/', $name, $match) && !$decomp) {
1169 $c = ord($match[2]);
1170 if ($match[1] === 'SMALL') {
1171 $c += 32;
1172 }
1173 $decomposition['U+' . $char] = array(dechex($c));
1174 continue;
1175 }
1176 $match = array();
1177 if (preg_match('/(<.*>)? *(.+)/', $decomp, $match)) {
1178 switch ($match[1]) {
1179 case '<circle>':
1180 // add parenthesis as circle replacement, eg (1)
1181 $match[2] = '0028 ' . $match[2] . ' 0029';
1182 break;
1183 case '<square>':
1184 // add square brackets as square replacement, eg [1]
1185 $match[2] = '005B ' . $match[2] . ' 005D';
1186 break;
1187 case '<compat>':
1188 // ignore multi char decompositions that start with a space
1189 if (preg_match('/^0020 /', $match[2])) {
1190 continue 2;
1191 }
1192 break;
1193 case '<initial>':
1194 case '<medial>':
1195 case '<final>':
1196 case '<isolated>':
1197 case '<vertical>':
1198 continue 2;
1199 }
1200 $decomposition['U+' . $char] = explode(' ', $match[2]);
1201 }
1202 }
1203 fclose($fh);
1204 // Process additional Unicode data for casing (allow folded characters to expand into a sequence)
1205 $specialCasingFile = ExtensionManagementUtility::extPath('core') . 'Resources/Private/Charsets/unidata/SpecialCasing.txt';
1206 if (GeneralUtility::validPathStr($specialCasingFile) && @is_file($specialCasingFile)) {
1207 $fh = fopen($specialCasingFile, 'rb');
1208 if ($fh) {
1209 while (!feof($fh)) {
1210 $line = fgets($fh, 4096);
1211 if ($line[0] !== '#' && trim($line) !== '') {
1212 list($char, $lower, $title, $upper, $cond) = GeneralUtility::trimExplode(';', $line);
1213 if ($cond === '' || $cond[0] === '#') {
1214 $utf8_char = $this->UnumberToChar(hexdec($char));
1215 if ($char !== $lower) {
1216 $arr = explode(' ', $lower);
1217 for ($i = 0; isset($arr[$i]); $i++) {
1218 $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
1219 }
1220 $utf8CaseFolding['toLower'][$utf8_char] = implode('', $arr);
1221 }
1222 if ($char !== $title && $title !== $upper) {
1223 $arr = explode(' ', $title);
1224 for ($i = 0; isset($arr[$i]); $i++) {
1225 $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
1226 }
1227 $utf8CaseFolding['toTitle'][$utf8_char] = implode('', $arr);
1228 }
1229 if ($char !== $upper) {
1230 $arr = explode(' ', $upper);
1231 for ($i = 0; isset($arr[$i]); $i++) {
1232 $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
1233 }
1234 $utf8CaseFolding['toUpper'][$utf8_char] = implode('', $arr);
1235 }
1236 }
1237 }
1238 }
1239 fclose($fh);
1240 }
1241 }
1242 // Process custom decompositions
1243 $customTranslitFile = ExtensionManagementUtility::extPath('core') . 'Resources/Private/Charsets/unidata/Translit.txt';
1244 if (GeneralUtility::validPathStr($customTranslitFile) && @is_file($customTranslitFile)) {
1245 $fh = fopen($customTranslitFile, 'rb');
1246 if ($fh) {
1247 while (!feof($fh)) {
1248 $line = fgets($fh, 4096);
1249 if ($line[0] !== '#' && trim($line) !== '') {
1250 list($char, $translit) = GeneralUtility::trimExplode(';', $line);
1251 if (!$translit) {
1252 $omit['U+' . $char] = 1;
1253 }
1254 $decomposition['U+' . $char] = explode(' ', $translit);
1255 }
1256 }
1257 fclose($fh);
1258 }
1259 }
1260 // Decompose and remove marks; inspired by unac (Loic Dachary <loic@senga.org>)
1261 foreach ($decomposition as $from => $to) {
1262 $code_decomp = array();
1263 while ($code_value = array_shift($to)) {
1264 // Do recursive decomposition
1265 if (isset($decomposition['U+' . $code_value])) {
1266 foreach (array_reverse($decomposition['U+' . $code_value]) as $cv) {
1267 array_unshift($to, $cv);
1268 }
1269 } elseif (!isset($mark['U+' . $code_value])) {
1270 // remove mark
1271 array_push($code_decomp, $code_value);
1272 }
1273 }
1274 if (!empty($code_decomp) || isset($omit[$from])) {
1275 $decomposition[$from] = $code_decomp;
1276 } else {
1277 unset($decomposition[$from]);
1278 }
1279 }
1280 // Create ascii only mapping
1281 $this->toASCII['utf-8'] = array();
1282 $ascii = &$this->toASCII['utf-8'];
1283 foreach ($decomposition as $from => $to) {
1284 $code_decomp = array();
1285 while ($code_value = array_shift($to)) {
1286 $ord = hexdec($code_value);
1287 if ($ord > 127) {
1288 continue 2;
1289 } else {
1290 // Skip decompositions containing non-ASCII chars
1291 array_push($code_decomp, chr($ord));
1292 }
1293 }
1294 $ascii[$this->UnumberToChar(hexdec($from))] = join('', $code_decomp);
1295 }
1296 // Add numeric decompositions
1297 foreach ($number as $from => $to) {
1298 $utf8_char = $this->UnumberToChar(hexdec($from));
1299 if (!isset($ascii[$utf8_char])) {
1300 $ascii[$utf8_char] = $to;
1301 }
1302 }
1303 if ($cacheFileCase) {
1304 GeneralUtility::writeFileToTypo3tempDir($cacheFileCase, serialize($utf8CaseFolding));
1305 }
1306 if ($cacheFileASCII) {
1307 GeneralUtility::writeFileToTypo3tempDir($cacheFileASCII, serialize($ascii));
1308 }
1309 return 3;
1310 }
1311
1312 /**
1313 * This function initializes the folding table for a charset other than UTF-8.
1314 * This function is automatically called by the case folding functions.
1315 *
1316 * @param string $charset Charset for which to initialize case folding.
1317 * @return int Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
1318 * @access private
1319 */
1320 public function initCaseFolding($charset)
1321 {
1322 // Only process if the case table is not yet loaded:
1323 if (is_array($this->caseFolding[$charset])) {
1324 return 1;
1325 }
1326 // Use cached version if possible
1327 $cacheFile = GeneralUtility::getFileAbsFileName('typo3temp/cs/cscase_' . $charset . '.tbl');
1328 if ($cacheFile && @is_file($cacheFile)) {
1329 $this->caseFolding[$charset] = unserialize(GeneralUtility::getUrl($cacheFile));
1330 return 2;
1331 }
1332 // init UTF-8 conversion for this charset
1333 if (!$this->initCharset($charset)) {
1334 return false;
1335 }
1336 // UTF-8 case folding is used as the base conversion table
1337 if (!$this->initUnicodeData('case')) {
1338 return false;
1339 }
1340 $nochar = chr($this->noCharByteVal);
1341 foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8) {
1342 // Reconvert to charset (don't use chr() of numeric value, might be muli-byte)
1343 $c = $this->utf8_decode($utf8, $charset);
1344 $cc = $this->utf8_decode($this->caseFolding['utf-8']['toUpper'][$utf8], $charset);
1345 if ($cc !== '' && $cc !== $nochar) {
1346 $this->caseFolding[$charset]['toUpper'][$c] = $cc;
1347 }
1348 $cc = $this->utf8_decode($this->caseFolding['utf-8']['toLower'][$utf8], $charset);
1349 if ($cc !== '' && $cc !== $nochar) {
1350 $this->caseFolding[$charset]['toLower'][$c] = $cc;
1351 }
1352 $cc = $this->utf8_decode($this->caseFolding['utf-8']['toTitle'][$utf8], $charset);
1353 if ($cc !== '' && $cc !== $nochar) {
1354 $this->caseFolding[$charset]['toTitle'][$c] = $cc;
1355 }
1356 }
1357 // Add the ASCII case table
1358 $start = ord('a');
1359 $end = ord('z');
1360 for ($i = $start; $i <= $end; $i++) {
1361 $this->caseFolding[$charset]['toUpper'][chr($i)] = chr($i - 32);
1362 }
1363 $start = ord('A');
1364 $end = ord('Z');
1365 for ($i = $start; $i <= $end; $i++) {
1366 $this->caseFolding[$charset]['toLower'][chr($i)] = chr($i + 32);
1367 }
1368 if ($cacheFile) {
1369 GeneralUtility::writeFileToTypo3tempDir($cacheFile, serialize($this->caseFolding[$charset]));
1370 }
1371 return 3;
1372 }
1373
1374 /**
1375 * This function initializes the to-ASCII conversion table for a charset other than UTF-8.
1376 * This function is automatically called by the ASCII transliteration functions.
1377 *
1378 * @param string $charset Charset for which to initialize conversion.
1379 * @return int Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
1380 * @access private
1381 */
1382 public function initToASCII($charset)
1383 {
1384 // Only process if the case table is not yet loaded:
1385 if (is_array($this->toASCII[$charset])) {
1386 return 1;
1387 }
1388 // Use cached version if possible
1389 $cacheFile = GeneralUtility::getFileAbsFileName('typo3temp/cs/csascii_' . $charset . '.tbl');
1390 if ($cacheFile && @is_file($cacheFile)) {
1391 $this->toASCII[$charset] = unserialize(GeneralUtility::getUrl($cacheFile));
1392 return 2;
1393 }
1394 // Init UTF-8 conversion for this charset
1395 if (!$this->initCharset($charset)) {
1396 return false;
1397 }
1398 // UTF-8/ASCII transliteration is used as the base conversion table
1399 if (!$this->initUnicodeData('ascii')) {
1400 return false;
1401 }
1402 foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8) {
1403 // Reconvert to charset (don't use chr() of numeric value, might be muli-byte)
1404 $c = $this->utf8_decode($utf8, $charset);
1405 if (isset($this->toASCII['utf-8'][$utf8])) {
1406 $this->toASCII[$charset][$c] = $this->toASCII['utf-8'][$utf8];
1407 }
1408 }
1409 if ($cacheFile) {
1410 GeneralUtility::writeFileToTypo3tempDir($cacheFile, serialize($this->toASCII[$charset]));
1411 }
1412 return 3;
1413 }
1414
1415 /********************************************
1416 *
1417 * String operation functions
1418 *
1419 ********************************************/
1420 /**
1421 * Returns a part of a string.
1422 * Unit-tested by Kasper (single byte charsets only)
1423 *
1424 * @param string $charset The character set
1425 * @param string $string Character string
1426 * @param int $start Start position (character position)
1427 * @param int $len Length (in characters)
1428 * @return string The substring
1429 * @see substr(), mb_substr()
1430 */
1431 public function substr($charset, $string, $start, $len = null)
1432 {
1433 if ($len === 0 || $string === '') {
1434 return '';
1435 }
1436 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'mbstring') {
1437 // Cannot omit $len, when specifying charset
1438 if ($len === null) {
1439 // Save internal encoding
1440 $enc = mb_internal_encoding();
1441 mb_internal_encoding($charset);
1442 $str = mb_substr($string, $start);
1443 // Restore internal encoding
1444 mb_internal_encoding($enc);
1445 return $str;
1446 } else {
1447 return mb_substr($string, $start, $len, $charset);
1448 }
1449 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'iconv') {
1450 // Cannot omit $len, when specifying charset
1451 if ($len === null) {
1452 // Save internal encoding
1453 $enc = iconv_get_encoding('internal_encoding');
1454 iconv_set_encoding('internal_encoding', $charset);
1455 $str = iconv_substr($string, $start);
1456 // Restore internal encoding
1457 iconv_set_encoding('internal_encoding', $enc);
1458 return $str;
1459 } else {
1460 return iconv_substr($string, $start, $len, $charset);
1461 }
1462 } elseif ($charset === 'utf-8') {
1463 return $this->utf8_substr($string, $start, $len);
1464 } elseif ($this->eucBasedSets[$charset]) {
1465 return $this->euc_substr($string, $start, $charset, $len);
1466 } elseif ($this->twoByteSets[$charset]) {
1467 return substr($string, $start * 2, $len * 2);
1468 } elseif ($this->fourByteSets[$charset]) {
1469 return substr($string, $start * 4, $len * 4);
1470 }
1471 // Treat everything else as single-byte encoding
1472 return $len === null ? substr($string, $start) : substr($string, $start, $len);
1473 }
1474
1475 /**
1476 * Counts the number of characters.
1477 * Unit-tested by Kasper (single byte charsets only)
1478 *
1479 * @param string $charset The character set
1480 * @param string $string Character string
1481 * @return int The number of characters
1482 * @see strlen()
1483 */
1484 public function strlen($charset, $string)
1485 {
1486 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'mbstring') {
1487 return mb_strlen($string, $charset);
1488 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'iconv') {
1489 return iconv_strlen($string, $charset);
1490 } elseif ($charset === 'utf-8') {
1491 return $this->utf8_strlen($string);
1492 } elseif ($this->eucBasedSets[$charset]) {
1493 return $this->euc_strlen($string, $charset);
1494 } elseif ($this->twoByteSets[$charset]) {
1495 return strlen($string) / 2;
1496 } elseif ($this->fourByteSets[$charset]) {
1497 return strlen($string) / 4;
1498 }
1499 // Treat everything else as single-byte encoding
1500 return strlen($string);
1501 }
1502
1503 /**
1504 * Method to crop strings using the mb_substr function.
1505 *
1506 * @param string $charset The character set
1507 * @param string $string String to be cropped
1508 * @param int $len Crop length (in characters)
1509 * @param string $crop Crop signifier
1510 * @return string The shortened string
1511 * @see mb_strlen(), mb_substr()
1512 */
1513 protected function cropMbstring($charset, $string, $len, $crop = '')
1514 {
1515 if ((int)$len === 0 || mb_strlen($string, $charset) <= abs($len)) {
1516 return $string;
1517 }
1518 if ($len > 0) {
1519 $string = mb_substr($string, 0, $len, $charset) . $crop;
1520 } else {
1521 $string = $crop . mb_substr($string, $len, mb_strlen($string, $charset), $charset);
1522 }
1523 return $string;
1524 }
1525
1526 /**
1527 * Truncates a string and pre-/appends a string.
1528 * Unit tested by Kasper
1529 *
1530 * @param string $charset The character set
1531 * @param string $string Character string
1532 * @param int $len Length (in characters)
1533 * @param string $crop Crop signifier
1534 * @return string The shortened string
1535 * @see substr(), mb_strimwidth()
1536 */
1537 public function crop($charset, $string, $len, $crop = '')
1538 {
1539 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'mbstring') {
1540 return $this->cropMbstring($charset, $string, $len, $crop);
1541 }
1542 if ((int)$len === 0) {
1543 return $string;
1544 }
1545 if ($charset === 'utf-8') {
1546 $i = $this->utf8_char2byte_pos($string, $len);
1547 } elseif ($this->eucBasedSets[$charset]) {
1548 $i = $this->euc_char2byte_pos($string, $len, $charset);
1549 } else {
1550 if ($len > 0) {
1551 $i = $len;
1552 } else {
1553 $i = strlen($string) + $len;
1554 if ($i <= 0) {
1555 $i = false;
1556 }
1557 }
1558 }
1559 // $len outside actual string length
1560 if ($i === false) {
1561 return $string;
1562 } else {
1563 if ($len > 0) {
1564 if (isset($string[$i])) {
1565 return substr($string, 0, $i) . $crop;
1566 }
1567 } else {
1568 if (isset($string[$i - 1])) {
1569 return $crop . substr($string, $i);
1570 }
1571 }
1572 }
1573 return $string;
1574 }
1575
1576 /**
1577 * Cuts a string short at a given byte length.
1578 *
1579 * @param string $charset The character set
1580 * @param string $string Character string
1581 * @param int $len The byte length
1582 * @return string The shortened string
1583 * @see mb_strcut()
1584 */
1585 public function strtrunc($charset, $string, $len)
1586 {
1587 if ($len <= 0) {
1588 return '';
1589 }
1590 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'mbstring') {
1591 return mb_strcut($string, 0, $len, $charset);
1592 } elseif ($charset === 'utf-8') {
1593 return $this->utf8_strtrunc($string, $len);
1594 } elseif ($this->eucBasedSets[$charset]) {
1595 return $this->euc_strtrunc($string, $len, $charset);
1596 } elseif ($this->twoByteSets[$charset]) {
1597 if ($len % 2) {
1598 $len--;
1599 }
1600 } elseif ($this->fourByteSets[$charset]) {
1601 $x = $len % 4;
1602 // Realign to position dividable by four
1603 $len -= $x;
1604 }
1605 // Treat everything else as single-byte encoding
1606 return substr($string, 0, $len);
1607 }
1608
1609 /**
1610 * Translates all characters of a string into their respective case values.
1611 * Unlike strtolower() and strtoupper() this method is locale independent.
1612 * Note that the string length may change!
1613 * eg. lower case German "ß" (sharp S) becomes upper case "SS"
1614 * Unit-tested by Kasper
1615 * Real case folding is language dependent, this method ignores this fact.
1616 *
1617 * @param string $charset Character set of string
1618 * @param string $string Input string to convert case for
1619 * @param string $case Case keyword: "toLower" means lowercase conversion, anything else is uppercase (use "toUpper" )
1620 * @return string The converted string
1621 * @see strtolower(), strtoupper()
1622 */
1623 public function conv_case($charset, $string, $case)
1624 {
1625 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'mbstring') {
1626 if ($case === 'toLower') {
1627 $string = mb_strtolower($string, $charset);
1628 } else {
1629 $string = mb_strtoupper($string, $charset);
1630 }
1631 } elseif ($charset === 'utf-8') {
1632 $string = $this->utf8_char_mapping($string, 'case', $case);
1633 } elseif (isset($this->eucBasedSets[$charset])) {
1634 $string = $this->euc_char_mapping($string, $charset, 'case', $case);
1635 } else {
1636 // Treat everything else as single-byte encoding
1637 $string = $this->sb_char_mapping($string, $charset, 'case', $case);
1638 }
1639 return $string;
1640 }
1641
1642 /**
1643 * Equivalent of lcfirst/ucfirst but using character set.
1644 *
1645 * @param string $charset
1646 * @param string $string
1647 * @param string $case
1648 * @return string
1649 * @see \TYPO3\CMS\Core\Charset\CharsetConverter::conv_case()
1650 */
1651 public function convCaseFirst($charset, $string, $case)
1652 {
1653 $firstChar = $this->substr($charset, $string, 0, 1);
1654 $firstChar = $this->conv_case($charset, $firstChar, $case);
1655 $remainder = $this->substr($charset, $string, 1);
1656 return $firstChar . $remainder;
1657 }
1658
1659 /**
1660 * Converts special chars (like æøåÆØÅ, umlauts etc) to ascii equivalents (usually double-bytes, like æ => ae etc.)
1661 *
1662 * @param string $charset Character set of string
1663 * @param string $string Input string to convert
1664 * @return string The converted string
1665 */
1666 public function specCharsToASCII($charset, $string)
1667 {
1668 if ($charset === 'utf-8') {
1669 $string = $this->utf8_char_mapping($string, 'ascii');
1670 } elseif (isset($this->eucBasedSets[$charset])) {
1671 $string = $this->euc_char_mapping($string, $charset, 'ascii');
1672 } else {
1673 // Treat everything else as single-byte encoding
1674 $string = $this->sb_char_mapping($string, $charset, 'ascii');
1675 }
1676 return $string;
1677 }
1678
1679 /**
1680 * Converts the language codes that we get from the client (usually HTTP_ACCEPT_LANGUAGE)
1681 * into a TYPO3-readable language code
1682 *
1683 * @param string $languageCodesList List of language codes. something like 'de,en-us;q=0.9,de-de;q=0.7,es-cl;q=0.6,en;q=0.4,es;q=0.3,zh;q=0.1'
1684 * @return string A preferred language that TYPO3 supports, or "default" if none found
1685 */
1686 public function getPreferredClientLanguage($languageCodesList)
1687 {
1688 $allLanguageCodes = $this->getAllLanguageCodes();
1689 $selectedLanguage = 'default';
1690 $preferredLanguages = GeneralUtility::trimExplode(',', $languageCodesList);
1691 // Order the preferred languages after they key
1692 $sortedPreferredLanguages = array();
1693 foreach ($preferredLanguages as $preferredLanguage) {
1694 $quality = 1.0;
1695 if (strpos($preferredLanguage, ';q=') !== false) {
1696 list($preferredLanguage, $quality) = explode(';q=', $preferredLanguage);
1697 }
1698 $sortedPreferredLanguages[$preferredLanguage] = $quality;
1699 }
1700 // Loop through the languages, with the highest priority first
1701 arsort($sortedPreferredLanguages, SORT_NUMERIC);
1702 foreach ($sortedPreferredLanguages as $preferredLanguage => $quality) {
1703 if (isset($allLanguageCodes[$preferredLanguage])) {
1704 $selectedLanguage = $allLanguageCodes[$preferredLanguage];
1705 break;
1706 }
1707 // Strip the country code from the end
1708 list($preferredLanguage, ) = explode('-', $preferredLanguage);
1709 if (isset($allLanguageCodes[$preferredLanguage])) {
1710 $selectedLanguage = $allLanguageCodes[$preferredLanguage];
1711 break;
1712 }
1713 }
1714 if (!$selectedLanguage || $selectedLanguage === 'en') {
1715 $selectedLanguage = 'default';
1716 }
1717 return $selectedLanguage;
1718 }
1719
1720 /**
1721 * Merges all available charsets and locales, currently only used for getPreferredClientLanguage()
1722 *
1723 * @return array
1724 */
1725 protected function getAllLanguageCodes()
1726 {
1727 // Get all languages where TYPO3 code is the same as the ISO code
1728 $typo3LanguageCodes = array_keys($this->charSetArray);
1729 $allLanguageCodes = array_combine($typo3LanguageCodes, $typo3LanguageCodes);
1730 // Get all languages where TYPO3 code differs from ISO code
1731 // or needs the country part
1732 // the iso codes will here overwrite the default typo3 language in the key
1733 /** @var Locales $locales */
1734 $locales = GeneralUtility::makeInstance(Locales::class);
1735 foreach ($locales->getIsoMapping() as $typo3Lang => $isoLang) {
1736 $isoLang = join('-', explode('_', $isoLang));
1737 $allLanguageCodes[$typo3Lang] = $isoLang;
1738 }
1739 // Move the iso codes to the (because we're comparing the keys with "isset" later on)
1740 return array_flip($allLanguageCodes);
1741 }
1742
1743 /********************************************
1744 *
1745 * Internal string operation functions
1746 *
1747 ********************************************/
1748 /**
1749 * Maps all characters of a string in a single byte charset.
1750 *
1751 * @param string $str The string
1752 * @param string $charset The charset
1753 * @param string $mode Mode: 'case' (case folding) or 'ascii' (ASCII transliteration)
1754 * @param string $opt 'case': conversion 'toLower' or 'toUpper'
1755 * @return string The converted string
1756 */
1757 public function sb_char_mapping($str, $charset, $mode, $opt = '')
1758 {
1759 switch ($mode) {
1760 case 'case':
1761 if (!$this->initCaseFolding($charset)) {
1762 return $str;
1763 }
1764 // Do nothing
1765 $map = &$this->caseFolding[$charset][$opt];
1766 break;
1767 case 'ascii':
1768 if (!$this->initToASCII($charset)) {
1769 return $str;
1770 }
1771 // Do nothing
1772 $map = &$this->toASCII[$charset];
1773 break;
1774 default:
1775 return $str;
1776 }
1777 $out = '';
1778 for ($i = 0; isset($str[$i]); $i++) {
1779 $c = $str[$i];
1780 if (isset($map[$c])) {
1781 $out .= $map[$c];
1782 } else {
1783 $out .= $c;
1784 }
1785 }
1786 return $out;
1787 }
1788
1789 /********************************************
1790 *
1791 * Internal UTF-8 string operation functions
1792 *
1793 ********************************************/
1794 /**
1795 * Returns a part of a UTF-8 string.
1796 * Unit-tested by Kasper and works 100% like substr() / mb_substr() for full range of $start/$len
1797 *
1798 * @param string $str UTF-8 string
1799 * @param int $start Start position (character position)
1800 * @param int $len Length (in characters)
1801 * @return string The substring
1802 * @see substr()
1803 */
1804 public function utf8_substr($str, $start, $len = null)
1805 {
1806 if ((string)$len === '0') {
1807 return '';
1808 }
1809 $byte_start = $this->utf8_char2byte_pos($str, $start);
1810 if ($byte_start === false) {
1811 if ($start > 0) {
1812 // $start outside string length
1813 return false;
1814 }
1815 }
1816 $str = substr($str, $byte_start);
1817 if ($len != null) {
1818 $byte_end = $this->utf8_char2byte_pos($str, $len);
1819 // $len outside actual string length
1820 if ($byte_end === false) {
1821 return $len < 0 ? '' : $str;
1822 } else {
1823 // When length is less than zero and exceeds, then we return blank string.
1824 return substr($str, 0, $byte_end);
1825 }
1826 } else {
1827 return $str;
1828 }
1829 }
1830
1831 /**
1832 * Counts the number of characters of a string in UTF-8.
1833 * Unit-tested by Kasper and works 100% like strlen() / mb_strlen()
1834 *
1835 * @param string $str UTF-8 multibyte character string
1836 * @return int The number of characters
1837 * @see strlen()
1838 */
1839 public function utf8_strlen($str)
1840 {
1841 $n = 0;
1842 for ($i = 0; isset($str[$i]); $i++) {
1843 $c = ord($str[$i]);
1844 // Single-byte (0xxxxxx)
1845 if (!($c & 128)) {
1846 $n++;
1847 } elseif (($c & 192) === 192) {
1848 // Multi-byte starting byte (11xxxxxx)
1849 $n++;
1850 }
1851 }
1852 return $n;
1853 }
1854
1855 /**
1856 * Truncates a string in UTF-8 short at a given byte length.
1857 *
1858 * @param string $str UTF-8 multibyte character string
1859 * @param int $len The byte length
1860 * @return string The shortened string
1861 * @see mb_strcut()
1862 */
1863 public function utf8_strtrunc($str, $len)
1864 {
1865 $i = $len - 1;
1866 // Part of a multibyte sequence
1867 if (ord($str[$i]) & 128) {
1868 for (; $i > 0 && !(ord($str[$i]) & 64); $i--) {
1869 }
1870 if ($i <= 0) {
1871 return '';
1872 }
1873 // Sanity check
1874 for ($bc = 0, $mbs = ord($str[$i]); $mbs & 128; $mbs = $mbs << 1) {
1875 // Calculate number of bytes
1876 $bc++;
1877 }
1878 if ($bc + $i > $len) {
1879 return substr($str, 0, $i);
1880 }
1881 }
1882 return substr($str, 0, $len);
1883 }
1884
1885 /**
1886 * Find position of first occurrence of a string, both arguments are in UTF-8.
1887 *
1888 * @param string $haystack UTF-8 string to search in
1889 * @param string $needle UTF-8 string to search for
1890 * @param int $offset Position to start the search
1891 * @return int The character position
1892 * @see strpos()
1893 */
1894 public function utf8_strpos($haystack, $needle, $offset = 0)
1895 {
1896 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'mbstring') {
1897 return mb_strpos($haystack, $needle, $offset, 'utf-8');
1898 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'iconv') {
1899 return iconv_strpos($haystack, $needle, $offset, 'utf-8');
1900 }
1901 $byte_offset = $this->utf8_char2byte_pos($haystack, $offset);
1902 if ($byte_offset === false) {
1903 // Offset beyond string length
1904 return false;
1905 }
1906 $byte_pos = strpos($haystack, $needle, $byte_offset);
1907 if ($byte_pos === false) {
1908 // Needle not found
1909 return false;
1910 }
1911 return $this->utf8_byte2char_pos($haystack, $byte_pos);
1912 }
1913
1914 /**
1915 * Find position of last occurrence of a char in a string, both arguments are in UTF-8.
1916 *
1917 * @param string $haystack UTF-8 string to search in
1918 * @param string $needle UTF-8 character to search for (single character)
1919 * @return int The character position
1920 * @see strrpos()
1921 */
1922 public function utf8_strrpos($haystack, $needle)
1923 {
1924 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'mbstring') {
1925 return mb_strrpos($haystack, $needle, 'utf-8');
1926 } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] === 'iconv') {
1927 return iconv_strrpos($haystack, $needle, 'utf-8');
1928 }
1929 $byte_pos = strrpos($haystack, $needle);
1930 if ($byte_pos === false) {
1931 // Needle not found
1932 return false;
1933 }
1934 return $this->utf8_byte2char_pos($haystack, $byte_pos);
1935 }
1936
1937 /**
1938 * Translates a character position into an 'absolute' byte position.
1939 * Unit tested by Kasper.
1940 *
1941 * @param string $str UTF-8 string
1942 * @param int $pos Character position (negative values start from the end)
1943 * @return int Byte position
1944 */
1945 public function utf8_char2byte_pos($str, $pos)
1946 {
1947 // Number of characters found
1948 $n = 0;
1949 // Number of characters wanted
1950 $p = abs($pos);
1951 if ($pos >= 0) {
1952 $i = 0;
1953 $d = 1;
1954 } else {
1955 $i = strlen($str) - 1;
1956 $d = -1;
1957 }
1958 for (; isset($str[$i]) && $n < $p; $i += $d) {
1959 $c = (int)ord($str[$i]);
1960 // single-byte (0xxxxxx)
1961 if (!($c & 128)) {
1962 $n++;
1963 } elseif (($c & 192) === 192) {
1964 // Multi-byte starting byte (11xxxxxx)
1965 $n++;
1966 }
1967 }
1968 if (!isset($str[$i])) {
1969 // Offset beyond string length
1970 return false;
1971 }
1972 if ($pos >= 0) {
1973 // Skip trailing multi-byte data bytes
1974 while (ord($str[$i]) & 128 && !(ord($str[$i]) & 64)) {
1975 $i++;
1976 }
1977 } else {
1978 // Correct offset
1979 $i++;
1980 }
1981 return $i;
1982 }
1983
1984 /**
1985 * Translates an 'absolute' byte position into a character position.
1986 * Unit tested by Kasper.
1987 *
1988 * @param string $str UTF-8 string
1989 * @param int $pos Byte position
1990 * @return int Character position
1991 */
1992 public function utf8_byte2char_pos($str, $pos)
1993 {
1994 // Number of characters
1995 $n = 0;
1996 for ($i = $pos; $i > 0; $i--) {
1997 $c = (int)ord($str[$i]);
1998 // single-byte (0xxxxxx)
1999 if (!($c & 128)) {
2000 $n++;
2001 } elseif (($c & 192) === 192) {
2002 // Multi-byte starting byte (11xxxxxx)
2003 $n++;
2004 }
2005 }
2006 if (!isset($str[$i])) {
2007 // Offset beyond string length
2008 return false;
2009 }
2010 return $n;
2011 }
2012
2013 /**
2014 * Maps all characters of an UTF-8 string.
2015 *
2016 * @param string $str UTF-8 string
2017 * @param string $mode Mode: 'case' (case folding) or 'ascii' (ASCII transliteration)
2018 * @param string $opt 'case': conversion 'toLower' or 'toUpper'
2019 * @return string The converted string
2020 */
2021 public function utf8_char_mapping($str, $mode, $opt = '')
2022 {
2023 if (!$this->initUnicodeData($mode)) {
2024 // Do nothing
2025 return $str;
2026 }
2027 $out = '';
2028 switch ($mode) {
2029 case 'case':
2030 $map = &$this->caseFolding['utf-8'][$opt];
2031 break;
2032 case 'ascii':
2033 $map = &$this->toASCII['utf-8'];
2034 break;
2035 default:
2036 return $str;
2037 }
2038 for ($i = 0; isset($str[$i]); $i++) {
2039 $c = ord($str[$i]);
2040 // single-byte (0xxxxxx)
2041 if (!($c & 128)) {
2042 $mbc = $str[$i];
2043 } elseif (($c & 192) === 192) {
2044 // multi-byte starting byte (11xxxxxx)
2045 for ($bc = 0; $c & 128; $c = $c << 1) {
2046 $bc++;
2047 }
2048 // calculate number of bytes
2049 $mbc = substr($str, $i, $bc);
2050 $i += $bc - 1;
2051 }
2052 if (isset($map[$mbc])) {
2053 $out .= $map[$mbc];
2054 } else {
2055 $out .= $mbc;
2056 }
2057 }
2058 return $out;
2059 }
2060
2061 /********************************************
2062 *
2063 * Internal EUC string operation functions
2064 *
2065 * Extended Unix Code:
2066 * ASCII compatible 7bit single bytes chars
2067 * 8bit two byte chars
2068 *
2069 * Shift-JIS is treated as a special case.
2070 *
2071 ********************************************/
2072 /**
2073 * Cuts a string in the EUC charset family short at a given byte length.
2074 *
2075 * @param string $str EUC multibyte character string
2076 * @param int $len The byte length
2077 * @param string $charset The charset
2078 * @return string The shortened string
2079 * @see mb_strcut()
2080 */
2081 public function euc_strtrunc($str, $len, $charset)
2082 {
2083 $shiftJis = $charset === 'shift_jis';
2084 for ($i = 0; isset($str[$i]) && $i < $len; $i++) {
2085 $c = ord($str[$i]);
2086 if ($shiftJis) {
2087 if ($c >= 128 && $c < 160 || $c >= 224) {
2088 $i++;
2089 }
2090 } else {
2091 if ($c >= 128) {
2092 $i++;
2093 }
2094 }
2095 }
2096 if (!isset($str[$i])) {
2097 return $str;
2098 }
2099 // string shorter than supplied length
2100 if ($i > $len) {
2101 // We ended on a first byte
2102 return substr($str, 0, $len - 1);
2103 } else {
2104 return substr($str, 0, $len);
2105 }
2106 }
2107
2108 /**
2109 * Returns a part of a string in the EUC charset family.
2110 *
2111 * @param string $str EUC multibyte character string
2112 * @param int $start Start position (character position)
2113 * @param string $charset The charset
2114 * @param int $len Length (in characters)
2115 * @return string the substring
2116 */
2117 public function euc_substr($str, $start, $charset, $len = null)
2118 {
2119 $byte_start = $this->euc_char2byte_pos($str, $start, $charset);
2120 if ($byte_start === false) {
2121 // $start outside string length
2122 return false;
2123 }
2124 $str = substr($str, $byte_start);
2125 if ($len != null) {
2126 $byte_end = $this->euc_char2byte_pos($str, $len, $charset);
2127 // $len outside actual string length
2128 if ($byte_end === false) {
2129 return $str;
2130 } else {
2131 return substr($str, 0, $byte_end);
2132 }
2133 } else {
2134 return $str;
2135 }
2136 }
2137
2138 /**
2139 * Counts the number of characters of a string in the EUC charset family.
2140 *
2141 * @param string $str EUC multibyte character string
2142 * @param string $charset The charset
2143 * @return int The number of characters
2144 * @see strlen()
2145 */
2146 public function euc_strlen($str, $charset)
2147 {
2148 $sjis = $charset === 'shift_jis';
2149 $n = 0;
2150 for ($i = 0; isset($str[$i]); $i++) {
2151 $c = ord($str[$i]);
2152 if ($sjis) {
2153 if ($c >= 128 && $c < 160 || $c >= 224) {
2154 $i++;
2155 }
2156 } else {
2157 if ($c >= 128) {
2158 $i++;
2159 }
2160 }
2161 $n++;
2162 }
2163 return $n;
2164 }
2165
2166 /**
2167 * Translates a character position into an 'absolute' byte position.
2168 *
2169 * @param string $str EUC multibyte character string
2170 * @param int $pos Character position (negative values start from the end)
2171 * @param string $charset The charset
2172 * @return int Byte position
2173 */
2174 public function euc_char2byte_pos($str, $pos, $charset)
2175 {
2176 $sjis = $charset === 'shift_jis';
2177 // Number of characters seen
2178 $n = 0;
2179 // Number of characters wanted
2180 $p = abs($pos);
2181 if ($pos >= 0) {
2182 $i = 0;
2183 $d = 1;
2184 } else {
2185 $i = strlen($str) - 1;
2186 $d = -1;
2187 }
2188 for (; isset($str[$i]) && $n < $p; $i += $d) {
2189 $c = ord($str[$i]);
2190 if ($sjis) {
2191 if ($c >= 128 && $c < 160 || $c >= 224) {
2192 $i += $d;
2193 }
2194 } else {
2195 if ($c >= 128) {
2196 $i += $d;
2197 }
2198 }
2199 $n++;
2200 }
2201 if (!isset($str[$i])) {
2202 return false;
2203 }
2204 // offset beyond string length
2205 if ($pos < 0) {
2206 $i++;
2207 }
2208 // correct offset
2209 return $i;
2210 }
2211
2212 /**
2213 * Maps all characters of a string in the EUC charset family.
2214 *
2215 * @param string $str EUC multibyte character string
2216 * @param string $charset The charset
2217 * @param string $mode Mode: 'case' (case folding) or 'ascii' (ASCII transliteration)
2218 * @param string $opt 'case': conversion 'toLower' or 'toUpper'
2219 * @return string The converted string
2220 */
2221 public function euc_char_mapping($str, $charset, $mode, $opt = '')
2222 {
2223 switch ($mode) {
2224 case 'case':
2225 if (!$this->initCaseFolding($charset)) {
2226 return $str;
2227 }
2228 // do nothing
2229 $map = &$this->caseFolding[$charset][$opt];
2230 break;
2231 case 'ascii':
2232 if (!$this->initToASCII($charset)) {
2233 return $str;
2234 }
2235 // do nothing
2236 $map = &$this->toASCII[$charset];
2237 break;
2238 default:
2239 return $str;
2240 }
2241 $sjis = $charset === 'shift_jis';
2242 $out = '';
2243 for ($i = 0; isset($str[$i]); $i++) {
2244 $mbc = $str[$i];
2245 $c = ord($mbc);
2246 if ($sjis) {
2247 // A double-byte char
2248 if ($c >= 128 && $c < 160 || $c >= 224) {
2249 $mbc = substr($str, $i, 2);
2250 $i++;
2251 }
2252 } else {
2253 // A double-byte char
2254 if ($c >= 128) {
2255 $mbc = substr($str, $i, 2);
2256 $i++;
2257 }
2258 }
2259 if (isset($map[$mbc])) {
2260 $out .= $map[$mbc];
2261 } else {
2262 $out .= $mbc;
2263 }
2264 }
2265 return $out;
2266 }
2267 }