6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
13 if (!defined('IN_PHPBB'))
19 * Some Unicode characters encoded in UTF-8
21 * Preserved for compatibility
23 define('UTF8_REPLACEMENT', "\xEF\xBF\xBD");
24 define('UTF8_MAX', "\xF4\x8F\xBF\xBF");
25 define('UTF8_FFFE', "\xEF\xBF\xBE");
26 define('UTF8_FFFF', "\xEF\xBF\xBF");
27 define('UTF8_SURROGATE_FIRST', "\xED\xA0\x80");
28 define('UTF8_SURROGATE_LAST', "\xED\xBF\xBF");
29 define('UTF8_HANGUL_FIRST', "\xEA\xB0\x80");
30 define('UTF8_HANGUL_LAST', "\xED\x9E\xA3");
32 define('UTF8_CJK_FIRST', "\xE4\xB8\x80");
33 define('UTF8_CJK_LAST', "\xE9\xBE\xBB");
34 define('UTF8_CJK_B_FIRST', "\xF0\xA0\x80\x80");
35 define('UTF8_CJK_B_LAST', "\xF0\xAA\x9B\x96");
37 // Unset global variables
38 unset($GLOBALS['utf_jamo_index'], $GLOBALS['utf_jamo_type'], $GLOBALS['utf_nfc_qc'], $GLOBALS['utf_combining_class'], $GLOBALS['utf_canonical_comp'], $GLOBALS['utf_canonical_decomp'], $GLOBALS['utf_nfkc_qc'], $GLOBALS['utf_compatibility_decomp']);
40 // NFC_QC and NFKC_QC values
41 define('UNICODE_QC_MAYBE', 0);
42 define('UNICODE_QC_NO', 1);
44 // Contains all the ASCII characters appearing in UTF-8, sorted by frequency
45 define('UTF8_ASCII_RANGE', "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F");
47 // Contains all the tail bytes that can appear in the composition of a UTF-8 char
48 define('UTF8_TRAILING_BYTES', "\xA9\xA0\xA8\x80\xAA\x99\xA7\xBB\xAB\x89\x94\x82\xB4\xA2\xAE\x83\xB0\xB9\xB8\x93\xAF\xBC\xB3\x81\xA4\xB2\x9C\xA1\xB5\xBE\xBD\xBA\x98\xAD\xB1\x84\x95\xA6\xB6\x88\x8D\x90\xB7\xBF\x92\x85\xA5\x97\x8C\x86\xA3\x8E\x9F\x8F\x87\x91\x9D\xAC\x9E\x8B\x96\x9B\x8A\x9A");
50 // Constants used by the Hangul [de]composition algorithms
51 define('UNICODE_HANGUL_SBASE', 0xAC00);
52 define('UNICODE_HANGUL_LBASE', 0x1100);
53 define('UNICODE_HANGUL_VBASE', 0x1161);
54 define('UNICODE_HANGUL_TBASE', 0x11A7);
55 define('UNICODE_HANGUL_SCOUNT', 11172);
56 define('UNICODE_HANGUL_LCOUNT', 19);
57 define('UNICODE_HANGUL_VCOUNT', 21);
58 define('UNICODE_HANGUL_TCOUNT', 28);
59 define('UNICODE_HANGUL_NCOUNT', 588);
60 define('UNICODE_JAMO_L', 0);
61 define('UNICODE_JAMO_V', 1);
62 define('UNICODE_JAMO_T', 2);
65 * Unicode normalization routines
72 * Validate, cleanup and normalize a string
74 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
75 * and convert to Normal Form C, canonical composition.
77 * @param string &$str The dirty string
78 * @return string The same string, all shiny and cleaned-up
80 function cleanup(&$str)
82 // The string below is the list of all autorized characters, sorted by frequency in latin text
83 $pos = strspn($str, "\x20\x65\x69\x61\x73\x6E\x74\x72\x6F\x6C\x75\x64\x5D\x5B\x63\x6D\x70\x27\x0A\x67\x7C\x68\x76\x2E\x66\x62\x2C\x3A\x3D\x2D\x71\x31\x30\x43\x32\x2A\x79\x78\x29\x28\x4C\x39\x41\x53\x2F\x50\x22\x45\x6A\x4D\x49\x6B\x33\x3E\x35\x54\x3C\x44\x34\x7D\x42\x7B\x38\x46\x77\x52\x36\x37\x55\x47\x4E\x3B\x4A\x7A\x56\x23\x48\x4F\x57\x5F\x26\x21\x4B\x3F\x58\x51\x25\x59\x5C\x09\x5A\x2B\x7E\x5E\x24\x40\x60\x7F\x0D");
88 // ASCII strings with no special chars return immediately
92 // Note: we do not check for $GLOBALS['utf_canonical_decomp']. It is assumed they are always loaded together
93 if (!isset($GLOBALS['utf_nfc_qc']))
95 global $phpbb_root_path, $phpEx;
96 include($phpbb_root_path . 'includes/utf/data/utf_nfc_qc.' . $phpEx);
99 if (!isset($GLOBALS['utf_canonical_decomp']))
101 global $phpbb_root_path, $phpEx;
102 include($phpbb_root_path . 'includes/utf/data/utf_canonical_decomp.' . $phpEx);
105 // Replace any byte in the range 0x00..0x1F, except for \r, \n and \t
106 // We replace those characters with a 0xFF byte, which is illegal in UTF-8 and will in turn be replaced with a UTF replacement char
109 "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
110 "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"
113 $str = utf_normalizer::recompose($str, $pos, $len, $GLOBALS['utf_nfc_qc'], $GLOBALS['utf_canonical_decomp']);
117 * Validate and normalize a UTF string to NFC
119 * @param string &$str Unchecked UTF string
120 * @return string The string, validated and in normal form
124 $pos = strspn($str, UTF8_ASCII_RANGE);
129 // ASCII strings return immediately
133 if (!isset($GLOBALS['utf_nfc_qc']))
135 global $phpbb_root_path, $phpEx;
136 include($phpbb_root_path . 'includes/utf/data/utf_nfc_qc.' . $phpEx);
139 if (!isset($GLOBALS['utf_canonical_decomp']))
141 global $phpbb_root_path, $phpEx;
142 include($phpbb_root_path . 'includes/utf/data/utf_canonical_decomp.' . $phpEx);
145 $str = utf_normalizer::recompose($str, $pos, $len, $GLOBALS['utf_nfc_qc'], $GLOBALS['utf_canonical_decomp']);
149 * Validate and normalize a UTF string to NFKC
151 * @param string &$str Unchecked UTF string
152 * @return string The string, validated and in normal form
156 $pos = strspn($str, UTF8_ASCII_RANGE);
161 // ASCII strings return immediately
165 if (!isset($GLOBALS['utf_nfkc_qc']))
167 global $phpbb_root_path, $phpEx;
168 include($phpbb_root_path . 'includes/utf/data/utf_nfkc_qc.' . $phpEx);
171 if (!isset($GLOBALS['utf_compatibility_decomp']))
173 global $phpbb_root_path, $phpEx;
174 include($phpbb_root_path . 'includes/utf/data/utf_compatibility_decomp.' . $phpEx);
177 $str = utf_normalizer::recompose($str, $pos, $len, $GLOBALS['utf_nfkc_qc'], $GLOBALS['utf_compatibility_decomp']);
181 * Validate and normalize a UTF string to NFD
183 * @param string &$str Unchecked UTF string
184 * @return string The string, validated and in normal form
188 $pos = strspn($str, UTF8_ASCII_RANGE);
193 // ASCII strings return immediately
197 if (!isset($GLOBALS['utf_canonical_decomp']))
199 global $phpbb_root_path, $phpEx;
200 include($phpbb_root_path . 'includes/utf/data/utf_canonical_decomp.' . $phpEx);
203 $str = utf_normalizer::decompose($str, $pos, $len, $GLOBALS['utf_canonical_decomp']);
207 * Validate and normalize a UTF string to NFKD
209 * @param string &$str Unchecked UTF string
210 * @return string The string, validated and in normal form
214 $pos = strspn($str, UTF8_ASCII_RANGE);
219 // ASCII strings return immediately
223 if (!isset($GLOBALS['utf_compatibility_decomp']))
225 global $phpbb_root_path, $phpEx;
226 include($phpbb_root_path . 'includes/utf/data/utf_compatibility_decomp.' . $phpEx);
229 $str = utf_normalizer::decompose($str, $pos, $len, $GLOBALS['utf_compatibility_decomp']);
234 * Recompose a UTF string
236 * @param string $str Unchecked UTF string
237 * @param integer $pos Position of the first UTF char (in bytes)
238 * @param integer $len Length of the string (in bytes)
239 * @param array &$qc Quick-check array, passed by reference but never modified
240 * @param array &$decomp_map Decomposition mapping, passed by reference but never modified
241 * @return string The string, validated and recomposed
245 function recompose($str, $pos, $len, &$qc, &$decomp_map)
247 global $utf_combining_class, $utf_canonical_comp, $utf_jamo_type, $utf_jamo_index;
249 // Load some commonly-used tables
250 if (!isset($utf_jamo_index, $utf_jamo_type, $utf_combining_class))
252 global $phpbb_root_path, $phpEx;
253 include($phpbb_root_path . 'includes/utf/data/utf_normalizer_common.' . $phpEx);
256 // Load the canonical composition table
257 if (!isset($utf_canonical_comp))
259 global $phpbb_root_path, $phpEx;
260 include($phpbb_root_path . 'includes/utf/data/utf_canonical_comp.' . $phpEx);
263 // Buffer the last ASCII char before the UTF-8 stuff if applicable
265 $i = $tmp_pos = $last_cc = 0;
267 $buffer = ($pos) ? array(++$i => $str[$pos - 1]) : array();
269 // UTF char length array
270 // This array is used to determine the length of a UTF character.
271 // Be $c the result of ($str[$pos] & "\xF0") --where $str is the string we're operating on and $pos
272 // the position of the cursor--, if $utf_len_mask[$c] does not exist, the byte is an ASCII char.
273 // Otherwise, if $utf_len_mask[$c] is greater than 0, we have a the leading byte of a multibyte character
274 // whose length is $utf_len_mask[$c] and if it is equal to 0, the byte is a trailing byte.
275 $utf_len_mask = array(
276 // Leading bytes masks
277 "\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4,
278 // Trailing bytes masks
279 "\x80" => 0, "\x90" => 0, "\xA0" => 0, "\xB0" => 0
282 $extra_check = array(
283 "\xED" => 1, "\xEF" => 1, "\xC0" => 1, "\xC1" => 1, "\xE0" => 1, "\xF0" => 1,
284 "\xF4" => 1, "\xF5" => 1, "\xF6" => 1, "\xF7" => 1, "\xF8" => 1, "\xF9" => 1,
285 "\xFA" => 1, "\xFB" => 1, "\xFC" => 1, "\xFD" => 1, "\xFE" => 1, "\xFF" => 1
288 $utf_validation_mask = array(
291 4 => "\xF8\xC0\xC0\xC0"
294 $utf_validation_check = array(
297 4 => "\xF0\x80\x80\x80"
303 // STEP 0: Capture the current char and buffer it
305 $c_mask = $c & "\xF0";
307 if (isset($utf_len_mask[$c_mask]))
309 // Byte at $pos is either a leading byte or a missplaced trailing byte
310 if ($utf_len = $utf_len_mask[$c_mask])
313 $buffer[++$i & 7] = $utf_char = substr($str, $pos, $utf_len);
315 // Let's find out if a thorough check is needed
316 if (isset($qc[$utf_char]))
318 // If the UTF char is in the qc array then it may not be in normal form. We do nothing here, the actual processing is below this "if" block
320 else if (isset($utf_combining_class[$utf_char]))
322 if ($utf_combining_class[$utf_char] < $last_cc)
324 // A combining character that is NOT canonically ordered
328 // A combining character that IS canonically ordered, skip to the next char
329 $last_cc = $utf_combining_class[$utf_char];
337 // At this point, $utf_char holds a UTF char that we know is not a NF[K]C_QC and is not a combining character.
338 // It can be a singleton, a canonical composite, a replacement char or an even an ill-formed bunch of bytes. Let's find out
341 // Check that we have the correct number of trailing bytes
342 if (($utf_char & $utf_validation_mask[$utf_len]) != $utf_validation_check[$utf_len])
344 // Current char isn't well-formed or legal: either one or several trailing bytes are missing, or the Unicode char
345 // has been encoded in a five- or six- byte sequence
346 if ($utf_char[0] >= "\xF8")
348 if ($utf_char[0] < "\xFC")
352 else if ($utf_char[0] > "\xFD")
363 $trailing_bytes = $utf_len - 1;
366 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . UTF8_REPLACEMENT;
367 $pos += strspn($str, UTF8_TRAILING_BYTES, ++$pos, $trailing_bytes);
373 if (isset($extra_check[$c]))
377 // Note: 0xED is quite common in Korean
379 if ($utf_char >= "\xED\xA0\x80")
381 // Surrogates (U+D800..U+DFFF) are not allowed in UTF-8 (UTF sequence 0xEDA080..0xEDBFBF)
382 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . UTF8_REPLACEMENT;
389 // Note: 0xEF is quite common in Japanese
391 if ($utf_char == "\xEF\xBF\xBE" || $utf_char == "\xEF\xBF\xBF")
393 // U+FFFE and U+FFFF are explicitly disallowed (UTF sequence 0xEFBFBE..0xEFBFBF)
394 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . UTF8_REPLACEMENT;
403 if ($utf_char <= "\xC1\xBF")
405 // Overlong sequence: Unicode char U+0000..U+007F encoded as a double-byte UTF char
406 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . UTF8_REPLACEMENT;
414 if ($utf_char <= "\xE0\x9F\xBF")
416 // Unicode char U+0000..U+07FF encoded in 3 bytes
417 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . UTF8_REPLACEMENT;
425 if ($utf_char <= "\xF0\x8F\xBF\xBF")
427 // Unicode char U+0000..U+FFFF encoded in 4 bytes
428 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . UTF8_REPLACEMENT;
436 // Five- and six- byte sequences do not need being checked for here anymore
437 if ($utf_char > UTF8_MAX)
439 // Out of the Unicode range
440 if ($utf_char[0] < "\xF8")
444 else if ($utf_char[0] < "\xFC")
448 else if ($utf_char[0] > "\xFD")
457 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . UTF8_REPLACEMENT;
458 $pos += strspn($str, UTF8_TRAILING_BYTES, ++$pos, $trailing_bytes);
466 // The char is a valid starter, move the cursor and go on
473 // A trailing byte came out of nowhere, we will advance the cursor and treat the this byte and all following trailing bytes as if
474 // each of them was a Unicode replacement char
475 $spn = strspn($str, UTF8_TRAILING_BYTES, $pos);
476 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . str_repeat(UTF8_REPLACEMENT, $spn);
484 // STEP 1: Decompose current char
486 // We have found a character that is either:
487 // - in the NFC_QC/NFKC_QC list
488 // - a non-starter char that is not canonically ordered
490 // We are going to capture the shortest UTF sequence that satisfies these two conditions:
492 // 1 - If the sequence does not start at the begginning of the string, it must begin with a starter,
493 // and that starter must not have the NF[K]C_QC property equal to "MAYBE"
495 // 2 - If the sequence does not end at the end of the string, it must end with a non-starter and be
496 // immediately followed by a starter that is not on the QC list
503 if (isset($decomp_map[$utf_char]))
506 $_len = strlen($decomp_map[$utf_char]);
510 $_utf_len =& $utf_len_mask[$decomp_map[$utf_char][$_pos] & "\xF0"];
512 if (isset($_utf_len))
514 $utf_seq[] = substr($decomp_map[$utf_char], $_pos, $_utf_len);
519 $utf_seq[] = $decomp_map[$utf_char][$_pos];
523 while ($_pos < $_len);
527 // The char is not decomposable
528 $utf_seq = array($utf_char);
532 // STEP 2: Capture the starter
534 // Check out the combining class of the first character of the UTF sequence
536 if (isset($utf_combining_class[$utf_seq[0]]) || $qc[$utf_char] == UNICODE_QC_MAYBE)
538 // Not a starter, inspect previous characters
539 // The last 8 characters are kept in a buffer so that we don't have to capture them everytime.
540 // This is enough for all real-life strings but even if it wasn't, we can capture characters in backward mode,
541 // although it is slower than this method.
543 // In the following loop, $j starts at the previous buffered character ($i - 1, because current character is
544 // at offset $i) and process them in backward mode until we find a starter.
546 // $k is the index on each UTF character inside of our UTF sequence. At this time, $utf_seq contains one or more
547 // characters numbered 0 to n. $k starts at 0 and for each char we prepend we pre-decrement it and for numbering
549 $j_min = max(1, $i - 7);
551 for ($j = $i - 1; $j >= $j_min && $lpos > $tmp_pos; --$j)
553 $utf_char = $buffer[$j & 7];
554 $lpos -= strlen($utf_char);
556 if (isset($decomp_map[$utf_char]))
558 // The char is a composite, decompose for storage
559 $decomp_seq = array();
561 $_len = strlen($decomp_map[$utf_char]);
565 $c = $decomp_map[$utf_char][$_pos];
566 $_utf_len =& $utf_len_mask[$c & "\xF0"];
568 if (isset($_utf_len))
570 $decomp_seq[] = substr($decomp_map[$utf_char], $_pos, $_utf_len);
579 while ($_pos < $_len);
581 // Prepend the UTF sequence with our decomposed sequence
582 if (isset($decomp_seq[1]))
584 // The char expanded into several chars
585 $decomp_cnt = sizeof($decomp_seq);
587 foreach ($decomp_seq as $decomp_i => $decomp_char)
589 $utf_seq[$k + $decomp_i - $decomp_cnt] = $decomp_char;
595 // Decomposed to a single char, easier to prepend
596 $utf_seq[--$k] = $decomp_seq[0];
601 $utf_seq[--$k] = $utf_char;
604 if (!isset($utf_combining_class[$utf_seq[$k]]))
606 // We have found our starter
612 if (!$starter_found && $lpos > $tmp_pos)
614 // The starter was not found in the buffer, let's rewind some more
617 // $utf_len_mask contains the masks of both leading bytes and trailing bytes. If $utf_en > 0 then it's a leading byte, otherwise it's a trailing byte.
619 $c_mask = $c & "\xF0";
621 if (isset($utf_len_mask[$c_mask]))
624 if ($utf_len = $utf_len_mask[$c_mask])
626 // UTF *leading* byte
627 $utf_char = substr($str, $lpos, $utf_len);
629 if (isset($decomp_map[$utf_char]))
631 // Decompose the character
632 $decomp_seq = array();
634 $_len = strlen($decomp_map[$utf_char]);
638 $c = $decomp_map[$utf_char][$_pos];
639 $_utf_len =& $utf_len_mask[$c & "\xF0"];
641 if (isset($_utf_len))
643 $decomp_seq[] = substr($decomp_map[$utf_char], $_pos, $_utf_len);
652 while ($_pos < $_len);
654 // Prepend the UTF sequence with our decomposed sequence
655 if (isset($decomp_seq[1]))
657 // The char expanded into several chars
658 $decomp_cnt = sizeof($decomp_seq);
659 foreach ($decomp_seq as $decomp_i => $utf_char)
661 $utf_seq[$k + $decomp_i - $decomp_cnt] = $utf_char;
667 // Decomposed to a single char, easier to prepend
668 $utf_seq[--$k] = $decomp_seq[0];
673 $utf_seq[--$k] = $utf_char;
683 while ($lpos > $tmp_pos);
688 // STEP 3: Capture following combining modifiers
692 $c_mask = $str[$pos] & "\xF0";
694 if (isset($utf_len_mask[$c_mask]))
696 if ($utf_len = $utf_len_mask[$c_mask])
698 $utf_char = substr($str, $pos, $utf_len);
702 // A trailing byte came out of nowhere
703 // Trailing bytes are replaced with Unicode replacement chars, we will just ignore it for now, break out of the loop
704 // as if it was a starter (replacement chars ARE starters) and let the next loop replace it
708 if (isset($utf_combining_class[$utf_char]) || isset($qc[$utf_char]))
710 // Combining character, add it to the sequence and move the cursor
711 if (isset($decomp_map[$utf_char]))
713 // Decompose the character
715 $_len = strlen($decomp_map[$utf_char]);
719 $c = $decomp_map[$utf_char][$_pos];
720 $_utf_len =& $utf_len_mask[$c & "\xF0"];
722 if (isset($_utf_len))
724 $utf_seq[] = substr($decomp_map[$utf_char], $_pos, $_utf_len);
733 while ($_pos < $_len);
737 $utf_seq[] = $utf_char;
744 // Combining class 0 and no QC, break out of the loop
745 // Note: we do not know if that character is valid. If it's not, the next iteration will replace it
751 // ASCII chars are starters
757 // STEP 4: Sort and combine
760 $k_max = $k + sizeof($utf_seq);
762 if (!$k && $k_max == 1)
764 // There is only one char in the UTF sequence, add it then jump to the next iteration of main loop
765 // Note: the two commented lines below can be enabled under PHP5 for a very small performance gain in most cases
766 // if (substr_compare($str, $utf_seq[0], $lpos, $pos - $lpos))
768 $tmp .= substr($str, $tmp_pos, $lpos - $tmp_pos) . $utf_seq[0];
775 // ...there we combine
776 if (isset($utf_combining_class[$utf_seq[$k]]))
778 $starter = $nf_seq = '';
782 $starter = $utf_seq[$k++];
787 // We add an empty char at the end of the UTF char sequence. It will act as a starter and trigger the sort/combine routine
788 // at the end of the string without altering it
793 $utf_char = $utf_seq[$k++];
795 if (isset($utf_combining_class[$utf_char]))
797 $utf_sort[$utf_combining_class[$utf_char]][] = $utf_char;
801 if (empty($utf_sort))
803 // No combining characters... check for a composite of the two starters
804 if (isset($utf_canonical_comp[$starter . $utf_char]))
806 // Good ol' composite character
807 $starter = $utf_canonical_comp[$starter . $utf_char];
809 else if (isset($utf_jamo_type[$utf_char]))
811 // Current char is a composable jamo
812 if (isset($utf_jamo_type[$starter]) && $utf_jamo_type[$starter] == UNICODE_JAMO_L && $utf_jamo_type[$utf_char] == UNICODE_JAMO_V)
814 // We have a L jamo followed by a V jamo, we are going to prefetch the next char to see if it's a T jamo
815 if (isset($utf_jamo_type[$utf_seq[$k]]) && $utf_jamo_type[$utf_seq[$k]] == UNICODE_JAMO_T)
817 // L+V+T jamos, combine to a LVT Hangul syllable ($k is incremented)
818 $cp = $utf_jamo_index[$starter] + $utf_jamo_index[$utf_char] + $utf_jamo_index[$utf_seq[$k]];
823 // L+V jamos, combine to a LV Hangul syllable
824 $cp = $utf_jamo_index[$starter] + $utf_jamo_index[$utf_char];
827 $starter = chr(0xE0 | ($cp >> 12)) . chr(0x80 | (($cp >> 6) & 0x3F)) . chr(0x80 | ($cp & 0x3F));
831 // Non-composable jamo, just add it to the sequence
833 $starter = $utf_char;
838 // No composite, just add the first starter to the sequence then continue with the other one
840 $starter = $utf_char;
847 // For each class of combining characters
848 foreach ($utf_sort as $cc => $utf_chars)
854 // Look for a composite
855 if (isset($utf_canonical_comp[$starter . $utf_chars[$j]]))
857 // Found a composite, replace the starter
858 $starter = $utf_canonical_comp[$starter . $utf_chars[$j]];
859 unset($utf_sort[$cc][$j]);
863 // No composite, all following characters in that class are blocked
867 while (isset($utf_sort[$cc][++$j]));
870 // Add the starter to the normalized sequence, followed by non-starters in canonical order
873 foreach ($utf_sort as $utf_chars)
875 if (!empty($utf_chars))
877 $nf_seq .= implode('', $utf_chars);
881 // Reset the array and go on
883 $starter = $utf_char;
887 while ($k <= $k_max);
889 $tmp .= substr($str, $tmp_pos, $lpos - $tmp_pos) . $nf_seq;
894 // Only a ASCII char can make the program get here
896 // First we skip the current byte with ++$pos, then we quickly skip following ASCII chars with strspn().
898 // The first two "if"'s here can be removed, with the consequences of being faster on latin text (lots of ASCII) and slower on
899 // multi-byte text (where the only ASCII chars are spaces and punctuation)
902 if ($str[$pos] < "\x80")
904 $pos += strspn($str, UTF8_ASCII_RANGE, ++$pos);
905 $buffer[++$i & 7] = $str[$pos - 1];
909 $buffer[++$i & 7] = $c;
916 // Now is time to return the string
919 // If the $tmp_pos cursor is not at the beggining of the string then at least one character was not in normal form. Replace $str with the fixed version
920 if ($tmp_pos == $len)
922 // The $tmp_pos cursor is at the end of $str, therefore $tmp holds the whole $str
927 // The rightmost chunk of $str has not been appended to $tmp yet
928 return $tmp . substr($str, $tmp_pos);
932 // The string was already in normal form
937 * Decompose a UTF string
939 * @param string $str UTF string
940 * @param integer $pos Position of the first UTF char (in bytes)
941 * @param integer $len Length of the string (in bytes)
942 * @param array &$decomp_map Decomposition mapping, passed by reference but never modified
943 * @return string The string, decomposed and sorted canonically
947 function decompose($str, $pos, $len, &$decomp_map)
949 global $utf_combining_class;
951 // Load some commonly-used tables
952 if (!isset($utf_combining_class))
954 global $phpbb_root_path, $phpEx;
955 include($phpbb_root_path . 'includes/utf/data/utf_normalizer_common.' . $phpEx);
958 // UTF char length array
959 $utf_len_mask = array(
960 // Leading bytes masks
961 "\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4,
962 // Trailing bytes masks
963 "\x80" => 0, "\x90" => 0, "\xA0" => 0, "\xB0" => 0
966 // Some extra checks are triggered on the first byte of a UTF sequence
967 $extra_check = array(
968 "\xED" => 1, "\xEF" => 1, "\xC0" => 1, "\xC1" => 1, "\xE0" => 1, "\xF0" => 1,
969 "\xF4" => 1, "\xF5" => 1, "\xF6" => 1, "\xF7" => 1, "\xF8" => 1, "\xF9" => 1,
970 "\xFA" => 1, "\xFB" => 1, "\xFC" => 1, "\xFD" => 1, "\xFE" => 1, "\xFF" => 1
973 // These masks are used to check if a UTF sequence is well formed. Here are the only 3 lengths we acknowledge:
974 // - 2-byte: 110? ???? 10?? ????
975 // - 3-byte: 1110 ???? 10?? ???? 10?? ????
976 // - 4-byte: 1111 0??? 10?? ???? 10?? ???? 10?? ????
977 // Note that 5- and 6- byte sequences are automatically discarded
978 $utf_validation_mask = array(
981 4 => "\xF8\xC0\xC0\xC0"
984 $utf_validation_check = array(
987 4 => "\xF0\x80\x80\x80"
992 $tmp_pos = $last_cc = $sort = $dump = 0;
999 // STEP 0: Capture the current char
1001 $cur_mask = $str[$pos] & "\xF0";
1002 if (isset($utf_len_mask[$cur_mask]))
1004 if ($utf_len = $utf_len_mask[$cur_mask])
1007 $utf_char = substr($str, $pos, $utf_len);
1012 // A trailing byte came out of nowhere, we will treat it and all following trailing bytes as if each of them was a Unicode
1013 // replacement char and we will advance the cursor
1014 $spn = strspn($str, UTF8_TRAILING_BYTES, $pos);
1018 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1021 if (!empty($utf_sort))
1028 foreach ($utf_sort as $utf_chars)
1030 $tmp .= implode('', $utf_chars);
1034 $tmp .= str_repeat(UTF8_REPLACEMENT, $spn);
1039 $tmp .= substr($str, $tmp_pos, $pos - $tmp_pos) . str_repeat(UTF8_REPLACEMENT, $spn);
1043 $tmp_pos = $starter_pos = $pos;
1045 $utf_sort = array();
1052 // STEP 1: Decide what to do with current char
1054 // Now, in that order:
1055 // - check if that character is decomposable
1056 // - check if that character is a non-starter
1057 // - check if that character requires extra checks to be performed
1058 if (isset($decomp_map[$utf_char]))
1060 // Decompose the char
1062 $_len = strlen($decomp_map[$utf_char]);
1066 $c = $decomp_map[$utf_char][$_pos];
1067 $_utf_len =& $utf_len_mask[$c & "\xF0"];
1069 if (isset($_utf_len))
1071 $_utf_char = substr($decomp_map[$utf_char], $_pos, $_utf_len);
1074 if (isset($utf_combining_class[$_utf_char]))
1076 // The character decomposed to a non-starter, buffer it for sorting
1077 $utf_sort[$utf_combining_class[$_utf_char]][] = $_utf_char;
1079 if ($utf_combining_class[$_utf_char] < $last_cc)
1081 // Not canonically ordered, will require sorting
1087 $last_cc = $utf_combining_class[$_utf_char];
1092 // This character decomposition contains a starter, dump the buffer and continue
1095 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1098 if (!empty($utf_sort))
1105 foreach ($utf_sort as $utf_chars)
1107 $tmp .= implode('', $utf_chars);
1116 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos) . $_utf_char;
1119 $tmp_pos = $starter_pos = $pos;
1120 $utf_sort = array();
1126 // This character decomposition contains an ASCII char, which is a starter. Dump the buffer and continue
1131 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1134 if (!empty($utf_sort))
1141 foreach ($utf_sort as $utf_chars)
1143 $tmp .= implode('', $utf_chars);
1152 $tmp .= substr($str, $tmp_pos, $pos - $utf_len - $tmp_pos) . $c;
1155 $tmp_pos = $starter_pos = $pos;
1156 $utf_sort = array();
1160 while ($_pos < $_len);
1162 else if (isset($utf_combining_class[$utf_char]))
1164 // Combining character
1165 if ($utf_combining_class[$utf_char] < $last_cc)
1167 // Not in canonical order
1172 $last_cc = $utf_combining_class[$utf_char];
1175 $utf_sort[$utf_combining_class[$utf_char]][] = $utf_char;
1179 // Non-decomposable starter, check out if it's a Hangul syllable
1180 if ($utf_char < UTF8_HANGUL_FIRST || $utf_char > UTF8_HANGUL_LAST)
1182 // Nope, regular UTF char, check that we have the correct number of trailing bytes
1183 if (($utf_char & $utf_validation_mask[$utf_len]) != $utf_validation_check[$utf_len])
1185 // Current char isn't well-formed or legal: either one or several trailing bytes are missing, or the Unicode char
1186 // has been encoded in a five- or six- byte sequence.
1187 // Move the cursor back to its original position then advance it to the position it should really be at
1189 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1191 if (!empty($utf_sort))
1195 foreach ($utf_sort as $utf_chars)
1197 $tmp .= implode('', $utf_chars);
1199 $utf_sort = array();
1202 // Add a replacement char then another replacement char for every trailing byte.
1204 // @todo I'm not entirely sure that's how we're supposed to mark invalidated byte sequences, check this
1205 $spn = strspn($str, UTF8_TRAILING_BYTES, ++$pos);
1206 $tmp .= str_repeat(UTF8_REPLACEMENT, $spn + 1);
1215 if (isset($extra_check[$utf_char[0]]))
1217 switch ($utf_char[0])
1219 // Note: 0xED is quite common in Korean
1221 if ($utf_char >= "\xED\xA0\x80")
1223 // Surrogates (U+D800..U+DFFF) are not allowed in UTF-8 (UTF sequence 0xEDA080..0xEDBFBF)
1224 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1226 if (!empty($utf_sort))
1230 foreach ($utf_sort as $utf_chars)
1232 $tmp .= implode('', $utf_chars);
1234 $utf_sort = array();
1237 $tmp .= UTF8_REPLACEMENT;
1240 $tmp_pos = $starter_pos = $pos;
1245 // Note: 0xEF is quite common in Japanese
1247 if ($utf_char == "\xEF\xBF\xBE" || $utf_char == "\xEF\xBF\xBF")
1249 // U+FFFE and U+FFFF are explicitly disallowed (UTF sequence 0xEFBFBE..0xEFBFBF)
1250 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1252 if (!empty($utf_sort))
1256 foreach ($utf_sort as $utf_chars)
1258 $tmp .= implode('', $utf_chars);
1260 $utf_sort = array();
1263 $tmp .= UTF8_REPLACEMENT;
1266 $tmp_pos = $starter_pos = $pos;
1273 if ($utf_char <= "\xC1\xBF")
1275 // Overlong sequence: Unicode char U+0000..U+007F encoded as a double-byte UTF char
1276 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1278 if (!empty($utf_sort))
1282 foreach ($utf_sort as $utf_chars)
1284 $tmp .= implode('', $utf_chars);
1286 $utf_sort = array();
1289 $tmp .= UTF8_REPLACEMENT;
1292 $tmp_pos = $starter_pos = $pos;
1298 if ($utf_char <= "\xE0\x9F\xBF")
1300 // Unicode char U+0000..U+07FF encoded in 3 bytes
1301 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1303 if (!empty($utf_sort))
1307 foreach ($utf_sort as $utf_chars)
1309 $tmp .= implode('', $utf_chars);
1311 $utf_sort = array();
1314 $tmp .= UTF8_REPLACEMENT;
1317 $tmp_pos = $starter_pos = $pos;
1323 if ($utf_char <= "\xF0\x8F\xBF\xBF")
1325 // Unicode char U+0000..U+FFFF encoded in 4 bytes
1326 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1328 if (!empty($utf_sort))
1332 foreach ($utf_sort as $utf_chars)
1334 $tmp .= implode('', $utf_chars);
1336 $utf_sort = array();
1339 $tmp .= UTF8_REPLACEMENT;
1342 $tmp_pos = $starter_pos = $pos;
1348 if ($utf_char > UTF8_MAX)
1350 // Out of the Unicode range
1351 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1353 if (!empty($utf_sort))
1357 foreach ($utf_sort as $utf_chars)
1359 $tmp .= implode('', $utf_chars);
1361 $utf_sort = array();
1364 $tmp .= UTF8_REPLACEMENT;
1367 $tmp_pos = $starter_pos = $pos;
1377 $idx = (((ord($utf_char[0]) & 0x0F) << 12) | ((ord($utf_char[1]) & 0x3F) << 6) | (ord($utf_char[2]) & 0x3F)) - UNICODE_HANGUL_SBASE;
1379 // LIndex can only range from 0 to 18, therefore it cannot influence the first two bytes of the L Jamo, which allows us to hardcode them (based on LBase).
1381 // The same goes for VIndex, but for TIndex there's a catch: the value of the third byte could exceed 0xBF and we would have to increment the second byte
1382 if ($t_index = $idx % UNICODE_HANGUL_TCOUNT)
1386 $utf_char = "\xE1\x84\x00\xE1\x85\x00\xE1\x86\x00";
1387 $utf_char[8] = chr(0xA7 + $t_index);
1391 $utf_char = "\xE1\x84\x00\xE1\x85\x00\xE1\x87\x00";
1392 $utf_char[8] = chr(0x67 + $t_index);
1397 $utf_char = "\xE1\x84\x00\xE1\x85\x00";
1400 $utf_char[2] = chr(0x80 + (int) ($idx / UNICODE_HANGUL_NCOUNT));
1401 $utf_char[5] = chr(0xA1 + (int) (($idx % UNICODE_HANGUL_NCOUNT) / UNICODE_HANGUL_TCOUNT));
1403 // Just like other decompositions, the resulting Jamos must be dumped to the tmp string
1407 // Do we need to dump stuff to the tmp string?
1410 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1413 if (!empty($utf_sort))
1420 foreach ($utf_sort as $utf_chars)
1422 $tmp .= implode('', $utf_chars);
1432 $utf_sort = array();
1433 $starter_pos = $pos;
1438 // ASCII char, which happens to be a starter (as any other ASCII char)
1441 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1444 if (!empty($utf_sort))
1451 foreach ($utf_sort as $utf_chars)
1453 $tmp .= implode('', $utf_chars);
1461 $pos += strspn($str, UTF8_ASCII_RANGE, $pos);
1465 $pos += strspn($str, UTF8_ASCII_RANGE, ++$pos);
1469 $utf_sort = array();
1470 $starter_pos = $pos;
1473 while ($pos < $len);
1475 // Now is time to return the string
1478 $tmp .= substr($str, $tmp_pos, $starter_pos - $tmp_pos);
1481 if (!empty($utf_sort))
1488 foreach ($utf_sort as $utf_chars)
1490 $tmp .= implode('', $utf_chars);
1498 // If the $tmp_pos cursor was moved then at least one character was not in normal form. Replace $str with the fixed version
1499 if ($tmp_pos == $len)
1501 // The $tmp_pos cursor is at the end of $str, therefore $tmp holds the whole $str
1506 // The rightmost chunk of $str has not been appended to $tmp yet
1507 return $tmp . substr($str, $tmp_pos);
1511 // The string was already in normal form