bfababa89934e0c5e74bf0b6747d83df9cb47e7a
[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 = [];
69
70 /**
71 * An array where case folding data will be stored (cached)
72 *
73 * @var array
74 */
75 public $caseFolding = [];
76
77 /**
78 * An array where charset-to-ASCII mappings are stored (cached)
79 *
80 * @var array
81 */
82 public $toASCII = [];
83
84 /**
85 * This tells the converter which charsets has two bytes per char:
86 *
87 * @var array
88 */
89 public $twoByteSets = [
90 'ucs-2' => 1
91 ];
92
93 /**
94 * This tells the converter which charsets has four bytes per char:
95 *
96 * @var array
97 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9
98 */
99 public $fourByteSets = [
100 'ucs-4' => 1, // 4-byte Unicode
101 'utf-32' => 1
102 ];
103
104 /**
105 * This tells the converter which charsets use a scheme like the Extended Unix Code:
106 *
107 * @var array
108 */
109 public $eucBasedSets = [
110 'gb2312' => 1, // Chinese, simplified.
111 'big5' => 1, // Chinese, traditional.
112 'euc-kr' => 1, // Korean
113 'shift_jis' => 1
114 ];
115
116 /**
117 * @link http://developer.apple.com/documentation/macos8/TextIntlSvcs/TextEncodingConversionManager/TEC1.5/TEC.b0.html
118 * @link http://czyborra.com/charsets/iso8859.html
119 *
120 * @var array
121 */
122 public $synonyms = [
123 'us' => 'ascii',
124 'us-ascii' => 'ascii',
125 'cp819' => 'iso-8859-1',
126 'ibm819' => 'iso-8859-1',
127 'iso-ir-100' => 'iso-8859-1',
128 'iso-ir-101' => 'iso-8859-2',
129 'iso-ir-109' => 'iso-8859-3',
130 'iso-ir-110' => 'iso-8859-4',
131 'iso-ir-144' => 'iso-8859-5',
132 'iso-ir-127' => 'iso-8859-6',
133 'iso-ir-126' => 'iso-8859-7',
134 'iso-ir-138' => 'iso-8859-8',
135 'iso-ir-148' => 'iso-8859-9',
136 'iso-ir-157' => 'iso-8859-10',
137 'iso-ir-179' => 'iso-8859-13',
138 'iso-ir-199' => 'iso-8859-14',
139 'iso-ir-203' => 'iso-8859-15',
140 'csisolatin1' => 'iso-8859-1',
141 'csisolatin2' => 'iso-8859-2',
142 'csisolatin3' => 'iso-8859-3',
143 'csisolatin5' => 'iso-8859-9',
144 'csisolatin8' => 'iso-8859-14',
145 'csisolatin9' => 'iso-8859-15',
146 'csisolatingreek' => 'iso-8859-7',
147 'iso-celtic' => 'iso-8859-14',
148 'latin1' => 'iso-8859-1',
149 'latin2' => 'iso-8859-2',
150 'latin3' => 'iso-8859-3',
151 'latin5' => 'iso-8859-9',
152 'latin6' => 'iso-8859-10',
153 'latin8' => 'iso-8859-14',
154 'latin9' => 'iso-8859-15',
155 'l1' => 'iso-8859-1',
156 'l2' => 'iso-8859-2',
157 'l3' => 'iso-8859-3',
158 'l5' => 'iso-8859-9',
159 'l6' => 'iso-8859-10',
160 'l8' => 'iso-8859-14',
161 'l9' => 'iso-8859-15',
162 'cyrillic' => 'iso-8859-5',
163 'arabic' => 'iso-8859-6',
164 'tis-620' => 'iso-8859-11',
165 'win874' => 'windows-874',
166 'win1250' => 'windows-1250',
167 'win1251' => 'windows-1251',
168 'win1252' => 'windows-1252',
169 'win1253' => 'windows-1253',
170 'win1254' => 'windows-1254',
171 'win1255' => 'windows-1255',
172 'win1256' => 'windows-1256',
173 'win1257' => 'windows-1257',
174 'win1258' => 'windows-1258',
175 'cp1250' => 'windows-1250',
176 'cp1251' => 'windows-1251',
177 'cp1252' => 'windows-1252',
178 'ms-ee' => 'windows-1250',
179 'ms-ansi' => 'windows-1252',
180 'ms-greek' => 'windows-1253',
181 'ms-turk' => 'windows-1254',
182 'winbaltrim' => 'windows-1257',
183 'koi-8ru' => 'koi-8r',
184 'koi8r' => 'koi-8r',
185 'cp878' => 'koi-8r',
186 'mac' => 'macroman',
187 'macintosh' => 'macroman',
188 'euc-cn' => 'gb2312',
189 'x-euc-cn' => 'gb2312',
190 'euccn' => 'gb2312',
191 'cp936' => 'gb2312',
192 'big-5' => 'big5',
193 'cp950' => 'big5',
194 'eucjp' => 'euc-jp',
195 'sjis' => 'shift_jis',
196 'shift-jis' => 'shift_jis',
197 'cp932' => 'shift_jis',
198 'cp949' => 'euc-kr',
199 'utf7' => 'utf-7',
200 'utf8' => 'utf-8',
201 'utf16' => 'utf-16',
202 'utf32' => 'utf-32',
203 'ucs2' => 'ucs-2',
204 'ucs4' => 'ucs-4'
205 ];
206
207 /**
208 * TYPO3 specific: Array with the system charsets used for each system language in TYPO3:
209 * Empty values means "utf-8"
210 *
211 * @var array
212 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9, use Locales
213 */
214 public $charSetArray = [
215 'af' => '',
216 'ar' => 'iso-8859-6',
217 'ba' => 'iso-8859-2',
218 'bg' => 'windows-1251',
219 'br' => '',
220 'ca' => 'iso-8859-15',
221 'ch' => 'gb2312',
222 'cs' => 'windows-1250',
223 'cz' => 'windows-1250',
224 'da' => '',
225 'de' => '',
226 'dk' => '',
227 'el' => 'iso-8859-7',
228 'eo' => 'utf-8',
229 'es' => '',
230 'et' => 'iso-8859-4',
231 'eu' => '',
232 'fa' => 'utf-8',
233 'fi' => '',
234 'fo' => 'utf-8',
235 'fr' => '',
236 'fr_CA' => '',
237 'ga' => '',
238 'ge' => 'utf-8',
239 'gl' => '',
240 'gr' => 'iso-8859-7',
241 'he' => 'utf-8',
242 'hi' => 'utf-8',
243 'hk' => 'big5',
244 'hr' => 'windows-1250',
245 'hu' => 'iso-8859-2',
246 'is' => 'utf-8',
247 'it' => '',
248 'ja' => 'shift_jis',
249 'jp' => 'shift_jis',
250 'ka' => 'utf-8',
251 'kl' => 'utf-8',
252 'km' => 'utf-8',
253 'ko' => 'euc-kr',
254 'kr' => 'euc-kr',
255 'lt' => 'windows-1257',
256 'lv' => 'utf-8',
257 'ms' => '',
258 'my' => '',
259 'nl' => '',
260 'no' => '',
261 'pl' => 'iso-8859-2',
262 'pt' => '',
263 'pt_BR' => '',
264 'qc' => '',
265 'ro' => 'iso-8859-2',
266 'ru' => 'windows-1251',
267 'se' => '',
268 'si' => 'windows-1250',
269 'sk' => 'windows-1250',
270 'sl' => 'windows-1250',
271 'sq' => 'utf-8',
272 'sr' => 'utf-8',
273 'sv' => '',
274 'th' => 'iso-8859-11',
275 'tr' => 'iso-8859-9',
276 'ua' => 'windows-1251',
277 'uk' => 'windows-1251',
278 'vi' => 'utf-8',
279 'vn' => 'utf-8',
280 'zh' => 'big5'
281 ];
282
283 /**
284 * Normalize - changes input character set to lowercase letters.
285 *
286 * @param string $charset Input charset
287 * @return string Normalized charset
288 */
289 public function parse_charset($charset)
290 {
291 $charset = trim(strtolower($charset));
292 if (isset($this->synonyms[$charset])) {
293 $charset = $this->synonyms[$charset];
294 }
295 return $charset;
296 }
297
298 /********************************************
299 *
300 * Charset Conversion functions
301 *
302 ********************************************/
303 /**
304 * Convert from one charset to another charset.
305 *
306 * @param string $inputString Input string
307 * @param string $fromCharset From charset (the current charset of the string)
308 * @param string $toCharset To charset (the output charset wanted)
309 * @param bool $useEntityForNoChar If set, then characters that are not available in the destination character set will be encoded as numeric entities
310 * @return string Converted string
311 * @see convArray()
312 */
313 public function conv($inputString, $fromCharset, $toCharset, $useEntityForNoChar = false)
314 {
315 if ($fromCharset === $toCharset) {
316 return $inputString;
317 }
318 // PHP-libs don't support fallback to SGML entities, but UTF-8 handles everything
319 if ($toCharset === 'utf-8' || !$useEntityForNoChar) {
320 // Returns FALSE for unsupported charsets
321 $convertedString = mb_convert_encoding($inputString, $toCharset, $fromCharset);
322 if (false !== $convertedString) {
323 return $convertedString;
324 }
325 }
326 if ($fromCharset !== 'utf-8') {
327 $inputString = $this->utf8_encode($inputString, $fromCharset);
328 }
329 if ($toCharset !== 'utf-8') {
330 $inputString = $this->utf8_decode($inputString, $toCharset, $useEntityForNoChar);
331 }
332 return $inputString;
333 }
334
335 /**
336 * Convert all elements in ARRAY with type string from one charset to another charset.
337 * NOTICE: Array is passed by reference!
338 *
339 * @param array $array Input array, possibly multidimensional
340 * @param string $fromCharset From charset (the current charset of the string)
341 * @param string $toCharset To charset (the output charset wanted)
342 * @param bool $useEntityForNoChar If set, then characters that are not available in the destination character set will be encoded as numeric entities
343 * @return void
344 * @see conv()
345 */
346 public function convArray(&$array, $fromCharset, $toCharset, $useEntityForNoChar = false)
347 {
348 foreach ($array as $key => $value) {
349 if (is_array($array[$key])) {
350 $this->convArray($array[$key], $fromCharset, $toCharset, $useEntityForNoChar);
351 } elseif (is_string($array[$key])) {
352 $array[$key] = $this->conv($array[$key], $fromCharset, $toCharset, $useEntityForNoChar);
353 }
354 }
355 }
356
357 /**
358 * Converts $str from $charset to UTF-8
359 *
360 * @param string $str String in local charset to convert to UTF-8
361 * @param string $charset Charset, lowercase. Must be found in csconvtbl/ folder.
362 * @return string Output string, converted to UTF-8
363 */
364 public function utf8_encode($str, $charset)
365 {
366 if ($charset === 'utf-8') {
367 return $str;
368 }
369 // Charset is case-insensitive
370 // Parse conv. table if not already
371 if ($this->initCharset($charset)) {
372 $strLen = strlen($str);
373 $outStr = '';
374 // Traverse each char in string
375 for ($a = 0; $a < $strLen; $a++) {
376 $chr = substr($str, $a, 1);
377 $ord = ord($chr);
378 // If the charset has two bytes per char
379 if (isset($this->twoByteSets[$charset])) {
380 $ord2 = ord($str[$a + 1]);
381 // Assume big endian
382 $ord = $ord << 8 | $ord2;
383 // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
384 if (isset($this->parsedCharsets[$charset]['local'][$ord])) {
385 $outStr .= $this->parsedCharsets[$charset]['local'][$ord];
386 } else {
387 $outStr .= chr($this->noCharByteVal);
388 }
389 // No char exists
390 $a++;
391 } elseif ($ord > 127) {
392 // If char has value over 127 it's a multibyte char in UTF-8
393 // EUC uses two-bytes above 127; we get both and advance pointer and make $ord a 16bit int.
394 if (isset($this->eucBasedSets[$charset])) {
395 // Shift-JIS: chars between 160 and 223 are single byte
396 if ($charset !== 'shift_jis' || ($ord < 160 || $ord > 223)) {
397 $a++;
398 $ord2 = ord(substr($str, $a, 1));
399 $ord = $ord * 256 + $ord2;
400 }
401 }
402 if (isset($this->parsedCharsets[$charset]['local'][$ord])) {
403 // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
404 $outStr .= $this->parsedCharsets[$charset]['local'][$ord];
405 } else {
406 $outStr .= chr($this->noCharByteVal);
407 }
408 } else {
409 $outStr .= $chr;
410 }
411 }
412 return $outStr;
413 }
414 return '';
415 }
416
417 /**
418 * Converts $str from UTF-8 to $charset
419 *
420 * @param string $str String in UTF-8 to convert to local charset
421 * @param string $charset Charset, lowercase. Must be found in csconvtbl/ folder.
422 * @param bool $useEntityForNoChar If set, then characters that are not available in the destination character set will be encoded as numeric entities
423 * @return string Output string, converted to local charset
424 */
425 public function utf8_decode($str, $charset, $useEntityForNoChar = false)
426 {
427 if ($charset === 'utf-8') {
428 return $str;
429 }
430 // Charset is case-insensitive.
431 // Parse conv. table if not already
432 if ($this->initCharset($charset)) {
433 $strLen = strlen($str);
434 $outStr = '';
435 // Traverse each char in UTF-8 string
436 for ($a = 0, $i = 0; $a < $strLen; $a++, $i++) {
437 $chr = substr($str, $a, 1);
438 $ord = ord($chr);
439 // This means multibyte! (first byte!)
440 if ($ord > 127) {
441 // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
442 if ($ord & 64) {
443 // Add first byte
444 $buf = $chr;
445 // For each byte in multibyte string
446 for ($b = 0; $b < 8; $b++) {
447 // Shift it left and
448 $ord = $ord << 1;
449 // ... and with 8th bit - if that is set, then there are still bytes in sequence.
450 if ($ord & 128) {
451 $a++;
452 // ... and add the next char.
453 $buf .= substr($str, $a, 1);
454 } else {
455 break;
456 }
457 }
458 // If the UTF-8 char-sequence is found then...
459 if (isset($this->parsedCharsets[$charset]['utf8'][$buf])) {
460 // The local number
461 $mByte = $this->parsedCharsets[$charset]['utf8'][$buf];
462 // If the local number is greater than 255 we will need to split the byte (16bit word assumed) in two chars.
463 if ($mByte > 255) {
464 $outStr .= chr(($mByte >> 8 & 255)) . chr(($mByte & 255));
465 } else {
466 $outStr .= chr($mByte);
467 }
468 } elseif ($useEntityForNoChar) {
469 // Create num entity:
470 $outStr .= '&#' . $this->utf8CharToUnumber($buf, 1) . ';';
471 } else {
472 $outStr .= chr($this->noCharByteVal);
473 }
474 } else {
475 $outStr .= chr($this->noCharByteVal);
476 }
477 } else {
478 $outStr .= $chr;
479 }
480 }
481 return $outStr;
482 }
483 return '';
484 }
485
486 /**
487 * Converts all chars > 127 to numeric entities.
488 *
489 * @param string $str Input string
490 * @return string Output string
491 */
492 public function utf8_to_entities($str)
493 {
494 $strLen = strlen($str);
495 $outStr = '';
496 // Traverse each char in UTF-8 string.
497 for ($a = 0; $a < $strLen; $a++) {
498 $chr = substr($str, $a, 1);
499 $ord = ord($chr);
500 // This means multibyte! (first byte!)
501 if ($ord > 127) {
502 // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
503 if ($ord & 64) {
504 // Add first byte
505 $buf = $chr;
506 // For each byte in multibyte string...
507 for ($b = 0; $b < 8; $b++) {
508 // Shift it left and ...
509 $ord = $ord << 1;
510 // ... and with 8th bit - if that is set, then there are still bytes in sequence.
511 if ($ord & 128) {
512 $a++;
513 // ... and add the next char.
514 $buf .= substr($str, $a, 1);
515 } else {
516 break;
517 }
518 }
519 $outStr .= '&#' . $this->utf8CharToUnumber($buf, 1) . ';';
520 } else {
521 $outStr .= chr($this->noCharByteVal);
522 }
523 } else {
524 $outStr .= $chr;
525 }
526 }
527 return $outStr;
528 }
529
530 /**
531 * Converts numeric entities (UNICODE, eg. decimal (&#1234;) or hexadecimal (&#x1b;)) to UTF-8 multibyte chars.
532 * All string-HTML entities (like &amp; or &pound;) will be converted as well
533 * @param string $str Input string, UTF-8
534 * @return string Output string
535 */
536 public function entities_to_utf8($str)
537 {
538 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES, ENT_COMPAT));
539 $token = md5(microtime());
540 $parts = explode($token, preg_replace('/(&([#[:alnum:]]*);)/', $token . '${2}' . $token, $str));
541 foreach ($parts as $k => $v) {
542 // Only take every second element
543 if ($k % 2 === 0) {
544 continue;
545 }
546 $position = 0;
547 // Dec or hex entities
548 if (substr($v, $position, 1) === '#') {
549 $position++;
550 if (substr($v, $position, 1) === 'x') {
551 $v = hexdec(substr($v, ++$position));
552 } else {
553 $v = substr($v, $position);
554 }
555 $parts[$k] = $this->UnumberToChar($v);
556 } elseif (isset($trans_tbl['&' . $v . ';'])) {
557 // Other entities:
558 $v = $trans_tbl['&' . $v . ';'];
559 $parts[$k] = $v;
560 } else {
561 // No conversion:
562 $parts[$k] = '&' . $v . ';';
563 }
564 }
565 return implode('', $parts);
566 }
567
568 /**
569 * Converts all chars in the input UTF-8 string into integer numbers returned in an array.
570 * All HTML entities (like &amp; or &pound; or &#123; or &#x3f5d;) will be detected as characters.
571 * Also, instead of integer numbers the real UTF-8 char is returned.
572 *
573 * @param string $str Input string, UTF-8
574 * @return array Output array with the char numbers
575 */
576 public function utf8_to_numberarray($str)
577 {
578 // Entities must be registered as well
579 $str = $this->entities_to_utf8($str);
580
581 // Do conversion:
582 $strLen = strlen($str);
583 $outArr = [];
584 // Traverse each char in UTF-8 string.
585 for ($a = 0; $a < $strLen; $a++) {
586 $chr = substr($str, $a, 1);
587 $ord = ord($chr);
588 // This means multibyte! (first byte!)
589 if ($ord > 127) {
590 // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
591 if ($ord & 64) {
592 // Add first byte
593 $buf = $chr;
594 // For each byte in multibyte string...
595 for ($b = 0; $b < 8; $b++) {
596 // Shift it left and ...
597 $ord = $ord << 1;
598 // ... and with 8th bit - if that is set, then there are still bytes in sequence.
599 if ($ord & 128) {
600 $a++;
601 // ... and add the next char.
602 $buf .= substr($str, $a, 1);
603 } else {
604 break;
605 }
606 }
607 $outArr[] = $buf;
608 } else {
609 $outArr[] = chr($this->noCharByteVal);
610 }
611 } else {
612 $outArr[] = chr($ord);
613 }
614 }
615 return $outArr;
616 }
617
618 /**
619 * Converts a UNICODE number to a UTF-8 multibyte character
620 * Algorithm based on script found at From: http://czyborra.com/utf/
621 * Unit-tested by Kasper
622 *
623 * The binary representation of the character's integer value is thus simply spread across the bytes
624 * and the number of high bits set in the lead byte announces the number of bytes in the multibyte sequence:
625 *
626 * bytes | bits | representation
627 * 1 | 7 | 0vvvvvvv
628 * 2 | 11 | 110vvvvv 10vvvvvv
629 * 3 | 16 | 1110vvvv 10vvvvvv 10vvvvvv
630 * 4 | 21 | 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv
631 * 5 | 26 | 111110vv 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv
632 * 6 | 31 | 1111110v 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv
633 *
634 * @param int $unicodeInteger UNICODE integer
635 * @return string UTF-8 multibyte character string
636 * @see utf8CharToUnumber()
637 */
638 public function UnumberToChar($unicodeInteger)
639 {
640 $str = '';
641 if ($unicodeInteger < 128) {
642 $str .= chr($unicodeInteger);
643 } elseif ($unicodeInteger < 2048) {
644 $str .= chr(192 | $unicodeInteger >> 6);
645 $str .= chr(128 | $unicodeInteger & 63);
646 } elseif ($unicodeInteger < 65536) {
647 $str .= chr(224 | $unicodeInteger >> 12);
648 $str .= chr(128 | $unicodeInteger >> 6 & 63);
649 $str .= chr(128 | $unicodeInteger & 63);
650 } elseif ($unicodeInteger < 2097152) {
651 $str .= chr(240 | $unicodeInteger >> 18);
652 $str .= chr(128 | $unicodeInteger >> 12 & 63);
653 $str .= chr(128 | $unicodeInteger >> 6 & 63);
654 $str .= chr(128 | $unicodeInteger & 63);
655 } elseif ($unicodeInteger < 67108864) {
656 $str .= chr(248 | $unicodeInteger >> 24);
657 $str .= chr(128 | $unicodeInteger >> 18 & 63);
658 $str .= chr(128 | $unicodeInteger >> 12 & 63);
659 $str .= chr(128 | $unicodeInteger >> 6 & 63);
660 $str .= chr(128 | $unicodeInteger & 63);
661 } elseif ($unicodeInteger < 2147483648) {
662 $str .= chr(252 | $unicodeInteger >> 30);
663 $str .= chr(128 | $unicodeInteger >> 24 & 63);
664 $str .= chr(128 | $unicodeInteger >> 18 & 63);
665 $str .= chr(128 | $unicodeInteger >> 12 & 63);
666 $str .= chr(128 | $unicodeInteger >> 6 & 63);
667 $str .= chr(128 | $unicodeInteger & 63);
668 } else {
669 // Cannot express a 32-bit character in UTF-8
670 $str .= chr($this->noCharByteVal);
671 }
672 return $str;
673 }
674
675 /**
676 * Converts a UTF-8 Multibyte character to a UNICODE number
677 * Unit-tested by Kasper
678 *
679 * @param string $str UTF-8 multibyte character string
680 * @param bool $hex If set, then a hex. number is returned.
681 * @return int UNICODE integer
682 * @see UnumberToChar()
683 */
684 public function utf8CharToUnumber($str, $hex = false)
685 {
686 // First char
687 $ord = ord($str[0]);
688 // This verifies that it IS a multi byte string
689 if (($ord & 192) === 192) {
690 $binBuf = '';
691 // For each byte in multibyte string...
692 for ($b = 0; $b < 8; $b++) {
693 // Shift it left and ...
694 $ord = $ord << 1;
695 // ... and with 8th bit - if that is set, then there are still bytes in sequence.
696 if ($ord & 128) {
697 $binBuf .= substr('00000000' . decbin(ord(substr($str, ($b + 1), 1))), -6);
698 } else {
699 break;
700 }
701 }
702 $binBuf = substr(('00000000' . decbin(ord($str[0]))), -(6 - $b)) . $binBuf;
703 $int = bindec($binBuf);
704 } else {
705 $int = $ord;
706 }
707 return $hex ? 'x' . dechex($int) : $int;
708 }
709
710 /********************************************
711 *
712 * Init functions
713 *
714 ********************************************/
715 /**
716 * This will initialize a charset for use if it's defined in the 'typo3/sysext/core/Resources/Private/Charsets/csconvtbl/' folder
717 * This function is automatically called by the conversion functions
718 *
719 * PLEASE SEE: http://www.unicode.org/Public/MAPPINGS/
720 *
721 * @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)
722 * @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.
723 * @access private
724 */
725 public function initCharset($charset)
726 {
727 // Only process if the charset is not yet loaded:
728 if (!is_array($this->parsedCharsets[$charset])) {
729 // Conversion table filename:
730 $charsetConvTableFile = ExtensionManagementUtility::extPath('core') . 'Resources/Private/Charsets/csconvtbl/' . $charset . '.tbl';
731 // If the conversion table is found:
732 if ($charset && GeneralUtility::validPathStr($charsetConvTableFile) && @is_file($charsetConvTableFile)) {
733 // Cache file for charsets:
734 // Caching brought parsing time for gb2312 down from 2400 ms to 150 ms. For other charsets we are talking 11 ms down to zero.
735 $cacheFile = GeneralUtility::getFileAbsFileName('typo3temp/var/charset/charset_' . $charset . '.tbl');
736 if ($cacheFile && @is_file($cacheFile)) {
737 $this->parsedCharsets[$charset] = unserialize(file_get_contents($cacheFile));
738 } else {
739 // Parse conversion table into lines:
740 $lines = GeneralUtility::trimExplode(LF, file_get_contents($charsetConvTableFile), true);
741 // Initialize the internal variable holding the conv. table:
742 $this->parsedCharsets[$charset] = ['local' => [], 'utf8' => []];
743 // traverse the lines:
744 $detectedType = '';
745 foreach ($lines as $value) {
746 // Comment line or blanks are ignored.
747 if (trim($value) && $value[0] !== '#') {
748 // Detect type if not done yet: (Done on first real line)
749 // The "whitespaced" type is on the syntax "0x0A 0x000A #LINE FEED" while "ms-token" is like "B9 = U+00B9 : SUPERSCRIPT ONE"
750 if (!$detectedType) {
751 $detectedType = preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/', $value) ? 'whitespaced' : 'ms-token';
752 }
753 $hexbyte = '';
754 $utf8 = '';
755 if ($detectedType === 'ms-token') {
756 list($hexbyte, $utf8) = preg_split('/[=:]/', $value, 3);
757 } elseif ($detectedType === 'whitespaced') {
758 $regA = [];
759 preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/', $value, $regA);
760 $hexbyte = $regA[1];
761 $utf8 = 'U+' . $regA[2];
762 }
763 $decval = hexdec(trim($hexbyte));
764 if ($decval > 127) {
765 $utf8decval = hexdec(substr(trim($utf8), 2));
766 $this->parsedCharsets[$charset]['local'][$decval] = $this->UnumberToChar($utf8decval);
767 $this->parsedCharsets[$charset]['utf8'][$this->parsedCharsets[$charset]['local'][$decval]] = $decval;
768 }
769 }
770 }
771 if ($cacheFile) {
772 GeneralUtility::writeFileToTypo3tempDir($cacheFile, serialize($this->parsedCharsets[$charset]));
773 }
774 }
775 return 2;
776 } else {
777 return false;
778 }
779 } else {
780 return 1;
781 }
782 }
783
784 /**
785 * This function initializes all UTF-8 character data tables.
786 *
787 * PLEASE SEE: http://www.unicode.org/Public/UNIDATA/
788 *
789 * @param string $mode Mode ("case", "ascii", ...)
790 * @return int Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
791 * @access private
792 */
793 public function initUnicodeData($mode = null)
794 {
795 // Cache files
796 $cacheFileCase = GeneralUtility::getFileAbsFileName('typo3temp/var/charset/cscase_utf-8.tbl');
797 $cacheFileASCII = GeneralUtility::getFileAbsFileName('typo3temp/var/charset/csascii_utf-8.tbl');
798 // Only process if the tables are not yet loaded
799 switch ($mode) {
800 case 'case':
801 if (is_array($this->caseFolding['utf-8'])) {
802 return 1;
803 }
804 // Use cached version if possible
805 if ($cacheFileCase && @is_file($cacheFileCase)) {
806 $this->caseFolding['utf-8'] = unserialize(file_get_contents($cacheFileCase));
807 return 2;
808 }
809 break;
810 case 'ascii':
811 if (is_array($this->toASCII['utf-8'])) {
812 return 1;
813 }
814 // Use cached version if possible
815 if ($cacheFileASCII && @is_file($cacheFileASCII)) {
816 $this->toASCII['utf-8'] = unserialize(file_get_contents($cacheFileASCII));
817 return 2;
818 }
819 break;
820 }
821 // Process main Unicode data file
822 $unicodeDataFile = ExtensionManagementUtility::extPath('core') . 'Resources/Private/Charsets/unidata/UnicodeData.txt';
823 if (!(GeneralUtility::validPathStr($unicodeDataFile) && @is_file($unicodeDataFile))) {
824 return false;
825 }
826 $fh = fopen($unicodeDataFile, 'rb');
827 if (!$fh) {
828 return false;
829 }
830 // key = utf8 char (single codepoint), value = utf8 string (codepoint sequence)
831 // Note: we use the UTF-8 characters here and not the Unicode numbers to avoid conversion roundtrip in utf8_strtolower/-upper)
832 $this->caseFolding['utf-8'] = [];
833 $utf8CaseFolding = &$this->caseFolding['utf-8'];
834 // a shorthand
835 $utf8CaseFolding['toUpper'] = [];
836 $utf8CaseFolding['toLower'] = [];
837 $utf8CaseFolding['toTitle'] = [];
838 // Array of temp. decompositions
839 $decomposition = [];
840 // Array of chars that are marks (eg. composing accents)
841 $mark = [];
842 // Array of chars that are numbers (eg. digits)
843 $number = [];
844 // Array of chars to be omitted (eg. Russian hard sign)
845 $omit = [];
846 while (!feof($fh)) {
847 $line = fgets($fh, 4096);
848 // Has a lot of info
849 list($char, $name, $cat, , , $decomp, , , $num, , , , $upper, $lower, $title, ) = explode(';', rtrim($line));
850 $ord = hexdec($char);
851 if ($ord > 65535) {
852 // Only process the BMP
853 break;
854 }
855 $utf8_char = $this->UnumberToChar($ord);
856 if ($upper) {
857 $utf8CaseFolding['toUpper'][$utf8_char] = $this->UnumberToChar(hexdec($upper));
858 }
859 if ($lower) {
860 $utf8CaseFolding['toLower'][$utf8_char] = $this->UnumberToChar(hexdec($lower));
861 }
862 // Store "title" only when different from "upper" (only a few)
863 if ($title && $title !== $upper) {
864 $utf8CaseFolding['toTitle'][$utf8_char] = $this->UnumberToChar(hexdec($title));
865 }
866 switch ($cat[0]) {
867 case 'M':
868 // mark (accent, umlaut, ...)
869 $mark['U+' . $char] = 1;
870 break;
871 case 'N':
872 // numeric value
873 if ($ord > 128 && $num !== '') {
874 $number['U+' . $char] = $num;
875 }
876 }
877 // Accented Latin letters without "official" decomposition
878 $match = [];
879 if (preg_match('/^LATIN (SMALL|CAPITAL) LETTER ([A-Z]) WITH/', $name, $match) && !$decomp) {
880 $c = ord($match[2]);
881 if ($match[1] === 'SMALL') {
882 $c += 32;
883 }
884 $decomposition['U+' . $char] = [dechex($c)];
885 continue;
886 }
887 $match = [];
888 if (preg_match('/(<.*>)? *(.+)/', $decomp, $match)) {
889 switch ($match[1]) {
890 case '<circle>':
891 // add parenthesis as circle replacement, eg (1)
892 $match[2] = '0028 ' . $match[2] . ' 0029';
893 break;
894 case '<square>':
895 // add square brackets as square replacement, eg [1]
896 $match[2] = '005B ' . $match[2] . ' 005D';
897 break;
898 case '<compat>':
899 // ignore multi char decompositions that start with a space
900 if (preg_match('/^0020 /', $match[2])) {
901 continue 2;
902 }
903 break;
904 case '<initial>':
905 case '<medial>':
906 case '<final>':
907 case '<isolated>':
908 case '<vertical>':
909 continue 2;
910 }
911 $decomposition['U+' . $char] = explode(' ', $match[2]);
912 }
913 }
914 fclose($fh);
915 // Process additional Unicode data for casing (allow folded characters to expand into a sequence)
916 $specialCasingFile = ExtensionManagementUtility::extPath('core') . 'Resources/Private/Charsets/unidata/SpecialCasing.txt';
917 if (GeneralUtility::validPathStr($specialCasingFile) && @is_file($specialCasingFile)) {
918 $fh = fopen($specialCasingFile, 'rb');
919 if ($fh) {
920 while (!feof($fh)) {
921 $line = fgets($fh, 4096);
922 if ($line[0] !== '#' && trim($line) !== '') {
923 list($char, $lower, $title, $upper, $cond) = GeneralUtility::trimExplode(';', $line);
924 if ($cond === '' || $cond[0] === '#') {
925 $utf8_char = $this->UnumberToChar(hexdec($char));
926 if ($char !== $lower) {
927 $arr = explode(' ', $lower);
928 for ($i = 0; isset($arr[$i]); $i++) {
929 $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
930 }
931 $utf8CaseFolding['toLower'][$utf8_char] = implode('', $arr);
932 }
933 if ($char !== $title && $title !== $upper) {
934 $arr = explode(' ', $title);
935 for ($i = 0; isset($arr[$i]); $i++) {
936 $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
937 }
938 $utf8CaseFolding['toTitle'][$utf8_char] = implode('', $arr);
939 }
940 if ($char !== $upper) {
941 $arr = explode(' ', $upper);
942 for ($i = 0; isset($arr[$i]); $i++) {
943 $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
944 }
945 $utf8CaseFolding['toUpper'][$utf8_char] = implode('', $arr);
946 }
947 }
948 }
949 }
950 fclose($fh);
951 }
952 }
953 // Process custom decompositions
954 $customTranslitFile = ExtensionManagementUtility::extPath('core') . 'Resources/Private/Charsets/unidata/Translit.txt';
955 if (GeneralUtility::validPathStr($customTranslitFile) && @is_file($customTranslitFile)) {
956 $fh = fopen($customTranslitFile, 'rb');
957 if ($fh) {
958 while (!feof($fh)) {
959 $line = fgets($fh, 4096);
960 if ($line[0] !== '#' && trim($line) !== '') {
961 list($char, $translit) = GeneralUtility::trimExplode(';', $line);
962 if (!$translit) {
963 $omit['U+' . $char] = 1;
964 }
965 $decomposition['U+' . $char] = explode(' ', $translit);
966 }
967 }
968 fclose($fh);
969 }
970 }
971 // Decompose and remove marks; inspired by unac (Loic Dachary <loic@senga.org>)
972 foreach ($decomposition as $from => $to) {
973 $code_decomp = [];
974 while ($code_value = array_shift($to)) {
975 // Do recursive decomposition
976 if (isset($decomposition['U+' . $code_value])) {
977 foreach (array_reverse($decomposition['U+' . $code_value]) as $cv) {
978 array_unshift($to, $cv);
979 }
980 } elseif (!isset($mark['U+' . $code_value])) {
981 // remove mark
982 array_push($code_decomp, $code_value);
983 }
984 }
985 if (!empty($code_decomp) || isset($omit[$from])) {
986 $decomposition[$from] = $code_decomp;
987 } else {
988 unset($decomposition[$from]);
989 }
990 }
991 // Create ascii only mapping
992 $this->toASCII['utf-8'] = [];
993 $ascii = &$this->toASCII['utf-8'];
994 foreach ($decomposition as $from => $to) {
995 $code_decomp = [];
996 while ($code_value = array_shift($to)) {
997 $ord = hexdec($code_value);
998 if ($ord > 127) {
999 continue 2;
1000 } else {
1001 // Skip decompositions containing non-ASCII chars
1002 array_push($code_decomp, chr($ord));
1003 }
1004 }
1005 $ascii[$this->UnumberToChar(hexdec($from))] = implode('', $code_decomp);
1006 }
1007 // Add numeric decompositions
1008 foreach ($number as $from => $to) {
1009 $utf8_char = $this->UnumberToChar(hexdec($from));
1010 if (!isset($ascii[$utf8_char])) {
1011 $ascii[$utf8_char] = $to;
1012 }
1013 }
1014 if ($cacheFileCase) {
1015 GeneralUtility::writeFileToTypo3tempDir($cacheFileCase, serialize($utf8CaseFolding));
1016 }
1017 if ($cacheFileASCII) {
1018 GeneralUtility::writeFileToTypo3tempDir($cacheFileASCII, serialize($ascii));
1019 }
1020 return 3;
1021 }
1022
1023 /**
1024 * This function initializes the folding table for a charset other than UTF-8.
1025 * This function is automatically called by the case folding functions.
1026 *
1027 * @param string $charset Charset for which to initialize case folding.
1028 * @return int Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
1029 * @access private
1030 */
1031 public function initCaseFolding($charset)
1032 {
1033 // Only process if the case table is not yet loaded:
1034 if (is_array($this->caseFolding[$charset])) {
1035 return 1;
1036 }
1037 // Use cached version if possible
1038 $cacheFile = GeneralUtility::getFileAbsFileName('typo3temp/var/charset/cscase_' . $charset . '.tbl');
1039 if ($cacheFile && @is_file($cacheFile)) {
1040 $this->caseFolding[$charset] = unserialize(file_get_contents($cacheFile));
1041 return 2;
1042 }
1043 // init UTF-8 conversion for this charset
1044 if (!$this->initCharset($charset)) {
1045 return false;
1046 }
1047 // UTF-8 case folding is used as the base conversion table
1048 if (!$this->initUnicodeData('case')) {
1049 return false;
1050 }
1051 $nochar = chr($this->noCharByteVal);
1052 foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8) {
1053 // Reconvert to charset (don't use chr() of numeric value, might be muli-byte)
1054 $c = $this->utf8_decode($utf8, $charset);
1055 $cc = $this->utf8_decode($this->caseFolding['utf-8']['toUpper'][$utf8], $charset);
1056 if ($cc !== '' && $cc !== $nochar) {
1057 $this->caseFolding[$charset]['toUpper'][$c] = $cc;
1058 }
1059 $cc = $this->utf8_decode($this->caseFolding['utf-8']['toLower'][$utf8], $charset);
1060 if ($cc !== '' && $cc !== $nochar) {
1061 $this->caseFolding[$charset]['toLower'][$c] = $cc;
1062 }
1063 $cc = $this->utf8_decode($this->caseFolding['utf-8']['toTitle'][$utf8], $charset);
1064 if ($cc !== '' && $cc !== $nochar) {
1065 $this->caseFolding[$charset]['toTitle'][$c] = $cc;
1066 }
1067 }
1068 // Add the ASCII case table
1069 $start = ord('a');
1070 $end = ord('z');
1071 for ($i = $start; $i <= $end; $i++) {
1072 $this->caseFolding[$charset]['toUpper'][chr($i)] = chr($i - 32);
1073 }
1074 $start = ord('A');
1075 $end = ord('Z');
1076 for ($i = $start; $i <= $end; $i++) {
1077 $this->caseFolding[$charset]['toLower'][chr($i)] = chr($i + 32);
1078 }
1079 if ($cacheFile) {
1080 GeneralUtility::writeFileToTypo3tempDir($cacheFile, serialize($this->caseFolding[$charset]));
1081 }
1082 return 3;
1083 }
1084
1085 /**
1086 * This function initializes the to-ASCII conversion table for a charset other than UTF-8.
1087 * This function is automatically called by the ASCII transliteration functions.
1088 *
1089 * @param string $charset Charset for which to initialize conversion.
1090 * @return int Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
1091 * @access private
1092 */
1093 public function initToASCII($charset)
1094 {
1095 // Only process if the case table is not yet loaded:
1096 if (is_array($this->toASCII[$charset])) {
1097 return 1;
1098 }
1099 // Use cached version if possible
1100 $cacheFile = GeneralUtility::getFileAbsFileName('typo3temp/var/charset/csascii_' . $charset . '.tbl');
1101 if ($cacheFile && @is_file($cacheFile)) {
1102 $this->toASCII[$charset] = unserialize(file_get_contents($cacheFile));
1103 return 2;
1104 }
1105 // Init UTF-8 conversion for this charset
1106 if (!$this->initCharset($charset)) {
1107 return false;
1108 }
1109 // UTF-8/ASCII transliteration is used as the base conversion table
1110 if (!$this->initUnicodeData('ascii')) {
1111 return false;
1112 }
1113 foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8) {
1114 // Reconvert to charset (don't use chr() of numeric value, might be muli-byte)
1115 $c = $this->utf8_decode($utf8, $charset);
1116 if (isset($this->toASCII['utf-8'][$utf8])) {
1117 $this->toASCII[$charset][$c] = $this->toASCII['utf-8'][$utf8];
1118 }
1119 }
1120 if ($cacheFile) {
1121 GeneralUtility::writeFileToTypo3tempDir($cacheFile, serialize($this->toASCII[$charset]));
1122 }
1123 return 3;
1124 }
1125
1126 /********************************************
1127 *
1128 * String operation functions
1129 *
1130 ********************************************/
1131 /**
1132 * Returns a part of a string.
1133 * Unit-tested by Kasper (single byte charsets only)
1134 *
1135 * @param string $charset The character set
1136 * @param string $string Character string
1137 * @param int $start Start position (character position)
1138 * @param int $len Length (in characters)
1139 * @return string The substring
1140 * @see substr(), mb_substr()
1141 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_substr() directly
1142 */
1143 public function substr($charset, $string, $start, $len = null)
1144 {
1145 GeneralUtility::logDeprecatedFunction();
1146 return mb_substr($string, $start, $len, $charset);
1147 }
1148
1149 /**
1150 * Counts the number of characters.
1151 * Unit-tested by Kasper (single byte charsets only)
1152 *
1153 * @param string $charset The character set
1154 * @param string $string Character string
1155 * @return int The number of characters
1156 * @see strlen()
1157 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strlen() directly
1158 */
1159 public function strlen($charset, $string)
1160 {
1161 GeneralUtility::logDeprecatedFunction();
1162 return mb_strlen($string, $charset);
1163 }
1164
1165 /**
1166 * Truncates a string and pre-/appends a string.
1167 * Unit tested by Kasper
1168 *
1169 * @param string $charset The character set
1170 * @param string $string Character string
1171 * @param int $len Length (in characters)
1172 * @param string $crop Crop signifier
1173 * @return string The shortened string
1174 * @see substr(), mb_strimwidth()
1175 */
1176 public function crop($charset, $string, $len, $crop = '')
1177 {
1178 if ((int)$len === 0 || mb_strlen($string, $charset) <= abs($len)) {
1179 return $string;
1180 }
1181 if ($len > 0) {
1182 $string = mb_substr($string, 0, $len, $charset) . $crop;
1183 } else {
1184 $string = $crop . mb_substr($string, $len, mb_strlen($string, $charset), $charset);
1185 }
1186 return $string;
1187 }
1188
1189 /**
1190 * Cuts a string short at a given byte length.
1191 *
1192 * @param string $charset The character set
1193 * @param string $string Character string
1194 * @param int $len The byte length
1195 * @return string The shortened string
1196 * @see mb_strcut()
1197 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strcut() directly
1198 */
1199 public function strtrunc($charset, $string, $len)
1200 {
1201 GeneralUtility::logDeprecatedFunction();
1202 if ($len <= 0) {
1203 return '';
1204 }
1205 return mb_strcut($string, 0, $len, $charset);
1206 }
1207
1208 /**
1209 * Translates all characters of a string into their respective case values.
1210 * Unlike strtolower() and strtoupper() this method is locale independent.
1211 * Note that the string length may change!
1212 * eg. lower case German "ß" (sharp S) becomes upper case "SS"
1213 * Unit-tested by Kasper
1214 * Real case folding is language dependent, this method ignores this fact.
1215 *
1216 * @param string $charset Character set of string
1217 * @param string $string Input string to convert case for
1218 * @param string $case Case keyword: "toLower" means lowercase conversion, anything else is uppercase (use "toUpper" )
1219 * @return string The converted string
1220 * @see strtolower(), strtoupper()
1221 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strtolower() or mb_strtoupper() directly
1222 */
1223 public function conv_case($charset, $string, $case)
1224 {
1225 GeneralUtility::logDeprecatedFunction();
1226 return $case === 'toLower'
1227 ? mb_strtolower($string, $charset)
1228 : mb_strtoupper($string, $charset);
1229 }
1230
1231 /**
1232 * Equivalent of lcfirst/ucfirst but using character set.
1233 *
1234 * @param string $charset
1235 * @param string $string
1236 * @param string $case can be 'toLower' or 'toUpper'
1237 * @return string
1238 */
1239 public function convCaseFirst($charset, $string, $case)
1240 {
1241 $firstChar = mb_substr($string, 0, 1, $charset);
1242 $firstChar = $case === 'toLower'
1243 ? mb_strtolower($firstChar, $charset)
1244 : mb_strtoupper($firstChar, $charset);
1245 $remainder = mb_substr($string, 1, null, $charset);
1246 return $firstChar . $remainder;
1247 }
1248
1249 /**
1250 * Capitalize the given string
1251 *
1252 * @param string $charset
1253 * @param string $string
1254 * @return string
1255 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_convert_case() directly
1256 */
1257 public function convCapitalize($charset, $string)
1258 {
1259 GeneralUtility::logDeprecatedFunction();
1260 return mb_convert_case($string, MB_CASE_TITLE, $charset);
1261 }
1262
1263 /**
1264 * Converts special chars (like æøåÆØÅ, umlauts etc) to ascii equivalents (usually double-bytes, like æ => ae etc.)
1265 *
1266 * @param string $charset Character set of string
1267 * @param string $string Input string to convert
1268 * @return string The converted string
1269 */
1270 public function specCharsToASCII($charset, $string)
1271 {
1272 if ($charset === 'utf-8') {
1273 $string = $this->utf8_char_mapping($string, 'ascii');
1274 } elseif (isset($this->eucBasedSets[$charset])) {
1275 $string = $this->euc_char_mapping($string, $charset, 'ascii');
1276 } else {
1277 // Treat everything else as single-byte encoding
1278 $string = $this->sb_char_mapping($string, $charset, 'ascii');
1279 }
1280 return $string;
1281 }
1282
1283 /**
1284 * Converts the language codes that we get from the client (usually HTTP_ACCEPT_LANGUAGE)
1285 * into a TYPO3-readable language code
1286 *
1287 * @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'
1288 * @return string A preferred language that TYPO3 supports, or "default" if none found
1289 * @deprecated since TYPO3 v8, will be removed in TYPO3 v9, use Locales::getPreferredClientLanguage() for usage
1290 */
1291 public function getPreferredClientLanguage($languageCodesList)
1292 {
1293 GeneralUtility::logDeprecatedFunction();
1294 /** @var Locales $locales */
1295 $locales = GeneralUtility::makeInstance(Locales::class);
1296 return $locales->getPreferredClientLanguage($languageCodesList);
1297 }
1298
1299 /********************************************
1300 *
1301 * Internal string operation functions
1302 *
1303 ********************************************/
1304 /**
1305 * Maps all characters of a string in a single byte charset.
1306 *
1307 * @param string $str The string
1308 * @param string $charset The charset
1309 * @param string $mode Mode: 'case' (case folding) or 'ascii' (ASCII transliteration)
1310 * @param string $opt 'case': conversion 'toLower' or 'toUpper'
1311 * @return string The converted string
1312 */
1313 public function sb_char_mapping($str, $charset, $mode, $opt = '')
1314 {
1315 switch ($mode) {
1316 case 'case':
1317 if (!$this->initCaseFolding($charset)) {
1318 return $str;
1319 }
1320 // Do nothing
1321 $map = &$this->caseFolding[$charset][$opt];
1322 break;
1323 case 'ascii':
1324 if (!$this->initToASCII($charset)) {
1325 return $str;
1326 }
1327 // Do nothing
1328 $map = &$this->toASCII[$charset];
1329 break;
1330 default:
1331 return $str;
1332 }
1333 $out = '';
1334 for ($i = 0; isset($str[$i]); $i++) {
1335 $c = $str[$i];
1336 if (isset($map[$c])) {
1337 $out .= $map[$c];
1338 } else {
1339 $out .= $c;
1340 }
1341 }
1342 return $out;
1343 }
1344
1345 /********************************************
1346 *
1347 * Internal UTF-8 string operation functions
1348 *
1349 ********************************************/
1350 /**
1351 * Returns a part of a UTF-8 string.
1352 * Unit-tested by Kasper and works 100% like substr() / mb_substr() for full range of $start/$len
1353 *
1354 * @param string $str UTF-8 string
1355 * @param int $start Start position (character position)
1356 * @param int $len Length (in characters)
1357 * @return string The substring
1358 * @see substr()
1359 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_substr() directly
1360 */
1361 public function utf8_substr($str, $start, $len = null)
1362 {
1363 GeneralUtility::logDeprecatedFunction();
1364 if ((string)$len === '0') {
1365 return '';
1366 }
1367 $byte_start = $this->utf8_char2byte_pos($str, $start);
1368 if ($byte_start === false) {
1369 if ($start > 0) {
1370 // $start outside string length
1371 return false;
1372 }
1373 }
1374 $str = substr($str, $byte_start);
1375 if ($len != null) {
1376 $byte_end = $this->utf8_char2byte_pos($str, $len);
1377 // $len outside actual string length
1378 if ($byte_end === false) {
1379 return $len < 0 ? '' : $str;
1380 } else {
1381 // When length is less than zero and exceeds, then we return blank string.
1382 return substr($str, 0, $byte_end);
1383 }
1384 } else {
1385 return $str;
1386 }
1387 }
1388
1389 /**
1390 * Counts the number of characters of a string in UTF-8.
1391 * Unit-tested by Kasper and works 100% like strlen() / mb_strlen()
1392 *
1393 * @param string $str UTF-8 multibyte character string
1394 * @return int The number of characters
1395 * @see strlen()
1396 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strlen() directly
1397 */
1398 public function utf8_strlen($str)
1399 {
1400 GeneralUtility::logDeprecatedFunction();
1401 $n = 0;
1402 for ($i = 0; isset($str[$i]); $i++) {
1403 $c = ord($str[$i]);
1404 // Single-byte (0xxxxxx)
1405 if (!($c & 128)) {
1406 $n++;
1407 } elseif (($c & 192) === 192) {
1408 // Multi-byte starting byte (11xxxxxx)
1409 $n++;
1410 }
1411 }
1412 return $n;
1413 }
1414
1415 /**
1416 * Truncates a string in UTF-8 short at a given byte length.
1417 *
1418 * @param string $str UTF-8 multibyte character string
1419 * @param int $len The byte length
1420 * @return string The shortened string
1421 * @see mb_strcut()
1422 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strcut() directly
1423 */
1424 public function utf8_strtrunc($str, $len)
1425 {
1426 GeneralUtility::logDeprecatedFunction();
1427 $i = $len - 1;
1428 // Part of a multibyte sequence
1429 if (ord($str[$i]) & 128) {
1430 for (; $i > 0 && !(ord($str[$i]) & 64); $i--) {
1431 }
1432 if ($i <= 0) {
1433 return '';
1434 }
1435 // Sanity check
1436 for ($bc = 0, $mbs = ord($str[$i]); $mbs & 128; $mbs = $mbs << 1) {
1437 // Calculate number of bytes
1438 $bc++;
1439 }
1440 if ($bc + $i > $len) {
1441 return substr($str, 0, $i);
1442 }
1443 }
1444 return substr($str, 0, $len);
1445 }
1446
1447 /**
1448 * Find position of first occurrence of a string, both arguments are in UTF-8.
1449 *
1450 * @param string $haystack UTF-8 string to search in
1451 * @param string $needle UTF-8 string to search for
1452 * @param int $offset Position to start the search
1453 * @return int The character position
1454 * @see strpos()
1455 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strpos() directly
1456 */
1457 public function utf8_strpos($haystack, $needle, $offset = 0)
1458 {
1459 GeneralUtility::logDeprecatedFunction();
1460 return mb_strpos($haystack, $needle, $offset, 'utf-8');
1461 }
1462
1463 /**
1464 * Find position of last occurrence of a char in a string, both arguments are in UTF-8.
1465 *
1466 * @param string $haystack UTF-8 string to search in
1467 * @param string $needle UTF-8 character to search for (single character)
1468 * @return int The character position
1469 * @see strrpos()
1470 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strrpos() directly
1471 */
1472 public function utf8_strrpos($haystack, $needle)
1473 {
1474 GeneralUtility::logDeprecatedFunction();
1475 return mb_strrpos($haystack, $needle, 'utf-8');
1476 }
1477
1478 /**
1479 * Translates a character position into an 'absolute' byte position.
1480 * Unit tested by Kasper.
1481 *
1482 * @param string $str UTF-8 string
1483 * @param int $pos Character position (negative values start from the end)
1484 * @return int Byte position
1485 */
1486 public function utf8_char2byte_pos($str, $pos)
1487 {
1488 // Number of characters found
1489 $n = 0;
1490 // Number of characters wanted
1491 $p = abs($pos);
1492 if ($pos >= 0) {
1493 $i = 0;
1494 $d = 1;
1495 } else {
1496 $i = strlen($str) - 1;
1497 $d = -1;
1498 }
1499 for (; isset($str[$i]) && $n < $p; $i += $d) {
1500 $c = (int)ord($str[$i]);
1501 // single-byte (0xxxxxx)
1502 if (!($c & 128)) {
1503 $n++;
1504 } elseif (($c & 192) === 192) {
1505 // Multi-byte starting byte (11xxxxxx)
1506 $n++;
1507 }
1508 }
1509 if (!isset($str[$i])) {
1510 // Offset beyond string length
1511 return false;
1512 }
1513 if ($pos >= 0) {
1514 // Skip trailing multi-byte data bytes
1515 while (ord($str[$i]) & 128 && !(ord($str[$i]) & 64)) {
1516 $i++;
1517 }
1518 } else {
1519 // Correct offset
1520 $i++;
1521 }
1522 return $i;
1523 }
1524
1525 /**
1526 * Translates an 'absolute' byte position into a character position.
1527 * Unit tested by Kasper.
1528 *
1529 * @param string $str UTF-8 string
1530 * @param int $pos Byte position
1531 * @return int Character position
1532 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, former internal function only
1533 */
1534 public function utf8_byte2char_pos($str, $pos)
1535 {
1536 GeneralUtility::logDeprecatedFunction();
1537 // Number of characters
1538 $n = 0;
1539 for ($i = $pos; $i > 0; $i--) {
1540 $c = (int)ord($str[$i]);
1541 // single-byte (0xxxxxx)
1542 if (!($c & 128)) {
1543 $n++;
1544 } elseif (($c & 192) === 192) {
1545 // Multi-byte starting byte (11xxxxxx)
1546 $n++;
1547 }
1548 }
1549 if (!isset($str[$i])) {
1550 // Offset beyond string length
1551 return false;
1552 }
1553 return $n;
1554 }
1555
1556 /**
1557 * Maps all characters of an UTF-8 string.
1558 *
1559 * @param string $str UTF-8 string
1560 * @param string $mode Mode: 'case' (case folding) or 'ascii' (ASCII transliteration)
1561 * @param string $opt 'case': conversion 'toLower' or 'toUpper'
1562 * @return string The converted string
1563 */
1564 public function utf8_char_mapping($str, $mode, $opt = '')
1565 {
1566 if (!$this->initUnicodeData($mode)) {
1567 // Do nothing
1568 return $str;
1569 }
1570 $out = '';
1571 switch ($mode) {
1572 case 'case':
1573 $map = &$this->caseFolding['utf-8'][$opt];
1574 break;
1575 case 'ascii':
1576 $map = &$this->toASCII['utf-8'];
1577 break;
1578 default:
1579 return $str;
1580 }
1581 for ($i = 0; isset($str[$i]); $i++) {
1582 $c = ord($str[$i]);
1583 $mbc = '';
1584 // single-byte (0xxxxxx)
1585 if (!($c & 128)) {
1586 $mbc = $str[$i];
1587 } elseif (($c & 192) === 192) {
1588 // multi-byte starting byte (11xxxxxx)
1589 for ($bc = 0; $c & 128; $c = $c << 1) {
1590 $bc++;
1591 }
1592 // calculate number of bytes
1593 $mbc = substr($str, $i, $bc);
1594 $i += $bc - 1;
1595 }
1596 if (isset($map[$mbc])) {
1597 $out .= $map[$mbc];
1598 } else {
1599 $out .= $mbc;
1600 }
1601 }
1602 return $out;
1603 }
1604
1605 /********************************************
1606 *
1607 * Internal EUC string operation functions
1608 *
1609 * Extended Unix Code:
1610 * ASCII compatible 7bit single bytes chars
1611 * 8bit two byte chars
1612 *
1613 * Shift-JIS is treated as a special case.
1614 *
1615 ********************************************/
1616 /**
1617 * Cuts a string in the EUC charset family short at a given byte length.
1618 *
1619 * @param string $str EUC multibyte character string
1620 * @param int $len The byte length
1621 * @param string $charset The charset
1622 * @return string The shortened string
1623 * @see mb_strcut()
1624 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strcut() directly
1625 */
1626 public function euc_strtrunc($str, $len, $charset)
1627 {
1628 GeneralUtility::logDeprecatedFunction();
1629 $shiftJis = $charset === 'shift_jis';
1630 for ($i = 0; isset($str[$i]) && $i < $len; $i++) {
1631 $c = ord($str[$i]);
1632 if ($shiftJis) {
1633 if ($c >= 128 && $c < 160 || $c >= 224) {
1634 $i++;
1635 }
1636 } else {
1637 if ($c >= 128) {
1638 $i++;
1639 }
1640 }
1641 }
1642 if (!isset($str[$i])) {
1643 return $str;
1644 }
1645 // string shorter than supplied length
1646 if ($i > $len) {
1647 // We ended on a first byte
1648 return substr($str, 0, $len - 1);
1649 } else {
1650 return substr($str, 0, $len);
1651 }
1652 }
1653
1654 /**
1655 * Returns a part of a string in the EUC charset family.
1656 *
1657 * @param string $str EUC multibyte character string
1658 * @param int $start Start position (character position)
1659 * @param string $charset The charset
1660 * @param int $len Length (in characters)
1661 * @return string the substring
1662 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_substr() directly
1663 */
1664 public function euc_substr($str, $start, $charset, $len = null)
1665 {
1666 GeneralUtility::logDeprecatedFunction();
1667 $byte_start = $this->euc_char2byte_pos($str, $start, $charset);
1668 if ($byte_start === false) {
1669 // $start outside string length
1670 return false;
1671 }
1672 $str = substr($str, $byte_start);
1673 if ($len != null) {
1674 $byte_end = $this->euc_char2byte_pos($str, $len, $charset);
1675 // $len outside actual string length
1676 if ($byte_end === false) {
1677 return $str;
1678 } else {
1679 return substr($str, 0, $byte_end);
1680 }
1681 } else {
1682 return $str;
1683 }
1684 }
1685
1686 /**
1687 * Counts the number of characters of a string in the EUC charset family.
1688 *
1689 * @param string $str EUC multibyte character string
1690 * @param string $charset The charset
1691 * @return int The number of characters
1692 * @see strlen()
1693 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, use mb_strlen() directly
1694 */
1695 public function euc_strlen($str, $charset)
1696 {
1697 GeneralUtility::logDeprecatedFunction();
1698 $sjis = $charset === 'shift_jis';
1699 $n = 0;
1700 for ($i = 0; isset($str[$i]); $i++) {
1701 $c = ord($str[$i]);
1702 if ($sjis) {
1703 if ($c >= 128 && $c < 160 || $c >= 224) {
1704 $i++;
1705 }
1706 } else {
1707 if ($c >= 128) {
1708 $i++;
1709 }
1710 }
1711 $n++;
1712 }
1713 return $n;
1714 }
1715
1716 /**
1717 * Translates a character position into an 'absolute' byte position.
1718 *
1719 * @param string $str EUC multibyte character string
1720 * @param int $pos Character position (negative values start from the end)
1721 * @param string $charset The charset
1722 * @return int Byte position
1723 * @deprecated since TYPO3 v8, will be removed with TYPO3 v9, former internal function only
1724 */
1725 public function euc_char2byte_pos($str, $pos, $charset)
1726 {
1727 GeneralUtility::logDeprecatedFunction();
1728 $sjis = $charset === 'shift_jis';
1729 // Number of characters seen
1730 $n = 0;
1731 // Number of characters wanted
1732 $p = abs($pos);
1733 if ($pos >= 0) {
1734 $i = 0;
1735 $d = 1;
1736 } else {
1737 $i = strlen($str) - 1;
1738 $d = -1;
1739 }
1740 for (; isset($str[$i]) && $n < $p; $i += $d) {
1741 $c = ord($str[$i]);
1742 if ($sjis) {
1743 if ($c >= 128 && $c < 160 || $c >= 224) {
1744 $i += $d;
1745 }
1746 } else {
1747 if ($c >= 128) {
1748 $i += $d;
1749 }
1750 }
1751 $n++;
1752 }
1753 if (!isset($str[$i])) {
1754 return false;
1755 }
1756 // offset beyond string length
1757 if ($pos < 0) {
1758 $i++;
1759 }
1760 // correct offset
1761 return $i;
1762 }
1763
1764 /**
1765 * Maps all characters of a string in the EUC charset family.
1766 *
1767 * @param string $str EUC multibyte character string
1768 * @param string $charset The charset
1769 * @param string $mode Mode: 'case' (case folding) or 'ascii' (ASCII transliteration)
1770 * @param string $opt 'case': conversion 'toLower' or 'toUpper'
1771 * @return string The converted string
1772 */
1773 public function euc_char_mapping($str, $charset, $mode, $opt = '')
1774 {
1775 switch ($mode) {
1776 case 'case':
1777 if (!$this->initCaseFolding($charset)) {
1778 return $str;
1779 }
1780 // do nothing
1781 $map = &$this->caseFolding[$charset][$opt];
1782 break;
1783 case 'ascii':
1784 if (!$this->initToASCII($charset)) {
1785 return $str;
1786 }
1787 // do nothing
1788 $map = &$this->toASCII[$charset];
1789 break;
1790 default:
1791 return $str;
1792 }
1793 $sjis = $charset === 'shift_jis';
1794 $out = '';
1795 for ($i = 0; isset($str[$i]); $i++) {
1796 $mbc = $str[$i];
1797 $c = ord($mbc);
1798 if ($sjis) {
1799 // A double-byte char
1800 if ($c >= 128 && $c < 160 || $c >= 224) {
1801 $mbc = substr($str, $i, 2);
1802 $i++;
1803 }
1804 } else {
1805 // A double-byte char
1806 if ($c >= 128) {
1807 $mbc = substr($str, $i, 2);
1808 $i++;
1809 }
1810 }
1811 if (isset($map[$mbc])) {
1812 $out .= $map[$mbc];
1813 } else {
1814 $out .= $mbc;
1815 }
1816 }
1817 return $out;
1818 }
1819 }