2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com> 3 # http://www.mediawiki.org/ 5 # This program is free software; you can redistribute it and/or modify 6 # it under the terms of the GNU General Public License as published by 7 # the Free Software Foundation; either version 2 of the License, or 8 # (at your option) any later version. 10 # This program is distributed in the hope that it will be useful, 11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 # GNU General Public License for more details. 15 # You should have received a copy of the GNU General Public License along 16 # with this program; if not, write to the Free Software Foundation, Inc., 17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 # http://www.gnu.org/copyleft/gpl.html 21 require_once dirname(__FILE__) .
'/UtfNormalUtil.php';
28 # Load compatibility decompositions on demand if they are needed. 32 define(
'UNICODE_HANGUL_FIRST', 0xac00);
33 define(
'UNICODE_HANGUL_LAST', 0xd7a3);
35 define(
'UNICODE_HANGUL_LBASE', 0x1100);
36 define(
'UNICODE_HANGUL_VBASE', 0x1161);
37 define(
'UNICODE_HANGUL_TBASE', 0x11a7);
39 define(
'UNICODE_HANGUL_LCOUNT', 19);
40 define(
'UNICODE_HANGUL_VCOUNT', 21);
41 define(
'UNICODE_HANGUL_TCOUNT', 28);
48 define(
'UNICODE_SURROGATE_FIRST', 0xd800);
49 define(
'UNICODE_SURROGATE_LAST', 0xdfff);
50 define(
'UNICODE_MAX', 0x10ffff);
51 define(
'UNICODE_REPLACEMENT', 0xfffd);
54 define(
'UTF8_HANGUL_FIRST',
"\xea\xb0\x80" );
55 define(
'UTF8_HANGUL_LAST',
"\xed\x9e\xa3" );
57 define(
'UTF8_HANGUL_LBASE',
"\xe1\x84\x80" );
58 define(
'UTF8_HANGUL_VBASE',
"\xe1\x85\xa1" );
59 define(
'UTF8_HANGUL_TBASE',
"\xe1\x86\xa7" );
61 define(
'UTF8_HANGUL_LEND',
"\xe1\x84\x92" );
62 define(
'UTF8_HANGUL_VEND',
"\xe1\x85\xb5" );
63 define(
'UTF8_HANGUL_TEND',
"\xe1\x87\x82" );
65 define(
'UTF8_SURROGATE_FIRST',
"\xed\xa0\x80" );
66 define(
'UTF8_SURROGATE_LAST',
"\xed\xbf\xbf" );
67 define(
'UTF8_MAX',
"\xf4\x8f\xbf\xbf" );
68 if (!defined(
'UTF8_REPLACEMENT')) {
69 define(
'UTF8_REPLACEMENT',
"\xef\xbf\xbd" );
71 #define( 'UTF8_REPLACEMENT', '!' ); 73 define(
'UTF8_OVERLONG_A',
"\xc1\xbf");
74 define(
'UTF8_OVERLONG_B',
"\xe0\x9f\xbf");
75 define(
'UTF8_OVERLONG_C',
"\xf0\x8f\xbf\xbf");
77 # These two ranges are illegal 78 define(
'UTF8_FDD0',
"\xef\xb7\x90" );
79 define(
'UTF8_FDEF',
"\xef\xb7\xaf" );
80 define(
'UTF8_FFFE',
"\xef\xbf\xbe" );
81 define(
'UTF8_FFFF',
"\xef\xbf\xbf" );
83 define(
'UTF8_HEAD',
false);
84 define(
'UTF8_TAIL',
true);
90 define(
'UNORM_NONE', 1);
91 define(
'UNORM_NFD', 2);
92 define(
'UNORM_NFKD', 3);
93 define(
'UNORM_NFC', 4);
95 define(
'UNORM_NFKC', 5);
96 define(
'UNORM_FCD', 6);
98 define(
'NORMALIZE_ICU', function_exists(
'utf8_normalize'));
130 # We exclude a few chars that ICU would not. 131 $string = preg_replace(
132 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
136 $string = str_replace(
UTF8_FFFE, UTF8_REPLACEMENT, $string);
137 $string = str_replace(
UTF8_FFFF, UTF8_REPLACEMENT, $string);
139 # UnicodeString constructor fails if the string ends with a 140 # head byte. Add a junk char at the end, we'll strip it off. 141 return rtrim(utf8_normalize($string .
"\x01",
UNORM_NFC),
"\x01");
143 # Side effect -- $string has had UTF-8 errors cleaned up. 159 public static function toNFC($string)
162 return utf8_normalize($string,
UNORM_NFC);
178 public static function toNFD($string)
181 return utf8_normalize($string,
UNORM_NFD);
182 } elseif (preg_match(
'/[\x80-\xff]/', $string)) {
202 } elseif (preg_match(
'/[\x80-\xff]/', $string)) {
222 } elseif (preg_match(
'/[\x80-\xff]/', $string)) {
237 if (!isset($utfCombiningClass)) {
238 require_once(dirname(__FILE__) .
'/UtfNormalData.inc');
251 # ASCII is always valid NFC! 252 # If it's pure ASCII, let it through. 253 if (!preg_match(
'/[\x80-\xff]/', $string)) {
259 $len = strlen($string);
260 for (
$i = 0;
$i < $len;
$i++) {
265 } elseif (
$n >= 0xf0) {
266 $c = substr($string,
$i, 4);
268 } elseif (
$n >= 0xe0) {
269 $c = substr($string,
$i, 3);
271 } elseif (
$n >= 0xc0) {
272 $c = substr($string,
$i, 2);
275 if (isset($utfCheckNFC[
$c])) {
276 # If it's NO or MAYBE, bail and do the slow check. 279 if (isset($utfCombiningClass[$c])) {
280 # Combining character? We might have to do sorting, at least. 295 # Screen out some characters that eg won't be allowed in XML 296 $string = preg_replace(
'/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT, $string);
298 # ASCII is always valid NFC! 299 # If we're only ever given plain ASCII, we can avoid the overhead 300 # of initializing the decomposition tables by skipping out early. 301 if (!preg_match(
'/[\x80-\xff]/', $string)) {
305 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
306 if (!isset($checkit)) {
307 # Load/build some scary lookup tables... 311 $utfCheckOrCombining = array_merge($utfCheckNFC, $utfCombiningClass);
313 # Head bytes for sequences which we should do further validity checks 314 $checkit = array_flip(array_map(
316 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
317 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
318 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff )
321 # Each UTF-8 head byte is followed by a certain 322 # number of tail bytes. 323 $tailBytes = array();
324 for (
$n = 0;
$n < 256;
$n++) {
327 } elseif (
$n < 0xe0) {
329 } elseif (
$n < 0xf0) {
331 } elseif (
$n < 0xf8) {
333 } elseif (
$n < 0xfc) {
335 } elseif (
$n < 0xfe) {
340 $tailBytes[chr(
$n)] = $remaining;
344 # Chop the text into pure-ASCII and non-ASCII areas; 345 # large ASCII parts can be handled much more quickly. 346 # Don't chop up Unicode areas for punctuation, though, 347 # that wastes energy. 350 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
358 foreach ($matches[1] as $str) {
359 $chunk = strlen($str);
361 if ($str[0] <
"\x80") {
362 # ASCII chunk: guaranteed to be valid UTF-8 363 # and in normal form C, so skip over it. 368 # We'll have to examine the chunk byte by byte to ensure 369 # that it consists of valid UTF-8 sequences, and to see 370 # if any of them might not be normalized. 372 # Since PHP is not the fastest language on earth, some of 373 # this code is a little ugly with inner loop optimizations. 376 $len = $chunk + 1; # Counting
down is faster.
I'm *so* sorry. 378 for ($i = -1; --$len;) { 379 if ($remaining = $tailBytes[$c = $str[++$i]]) { 381 $sequence = $head = $c; 383 # Look for the defined number of tail bytes... 384 if (--$len && ($c = $str[++$i]) >= "\x80" && $c < "\xc0") { 385 # Legal tail bytes are nice. 389 # Premature end of string! 390 # Drop a replacement character into output to 391 # represent the invalid UTF-8 sequence. 392 $replace[] = array( UTF8_REPLACEMENT, 393 $base + $i + 1 - strlen($sequence), 397 # Illegal tail byte; abandon the sequence. 398 $replace[] = array( UTF8_REPLACEMENT, 399 $base + $i - strlen($sequence), 401 # Back up and reprocess this byte; it may itself 402 # be a legal ASCII or UTF-8 sequence head. 408 } while (--$remaining); 410 if (isset($checkit[$head])) { 411 # Do some more detailed validity checks, for 412 # invalid characters and illegal sequences. 413 if ($head == "\xed") { 414 # 0xed is relatively frequent in Korean, which 415 # abuts the surrogate area, so we're doing
416 # this check separately to speed things up. 419 # Surrogates are legal only in UTF-16 code. 420 # They are totally forbidden here in UTF-8 422 $replace[] = array( UTF8_REPLACEMENT,
423 $base +
$i + 1 - strlen($sequence),
429 # Slower, but rarer checks... 432 #
"Overlong sequences" are those that are syntactically
433 # correct but use
more UTF-8 bytes than are necessary to
434 # encode a character. Naïve
string comparisons can be
435 # tricked into failing to see a match
for an ASCII
436 # character,
for instance, which can be a security hole
437 #
if blacklist checks are being used.
442 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
447 # Unicode
has been limited to 21 bits; longer
448 # sequences are not allowed.
450 $replace[] = array( UTF8_REPLACEMENT,
451 $base +
$i + 1 - strlen($sequence),
459 if (isset($utfCheckOrCombining[$sequence])) {
460 # If it's NO or MAYBE, we'll have to rip 461 # the string apart and put it back together. 462 # That's going to be mighty slow. 463 $looksNormal =
false;
466 # The sequence is legal! 468 } elseif (
$c <
"\x80") {
471 } elseif (
$c <
"\xc0") {
475 $replace[] = array( UTF8_REPLACEMENT,
$base +
$i, 1 );
477 # Don't add if we're continuing a broken sequence; 478 # we already put a replacement character when we looked 479 # at the broken sequence. 480 $replace[] = array(
'',
$base +
$i, 1 );
483 # Miscellaneous freaks. 484 $replace[] = array( UTF8_REPLACEMENT,
$base +
$i, 1 );
490 if (count($replace)) {
491 # There were illegal UTF-8 sequences we need to fix up. 494 foreach ($replace as $rep) {
495 list($replacement, $start, $length) = $rep;
496 if ($last < $start) {
497 $out .= substr($string, $last, $start - $last);
499 $out .= $replacement;
500 $last = $start + $length;
502 if ($last < strlen($string)) {
503 $out .= substr($string, $last);
510 # These take a string and run the normalization on them, without 511 # checking for validity or any optimization etc. Input must be 519 public static function NFC($string)
530 public static function NFD($string)
545 public static function NFKC($string)
556 public static function NFKD($string)
559 if (!isset($utfCompatibilityDecomp)) {
560 require_once(
'UtfNormalDataK.inc');
581 $len = strlen($string);
583 for (
$i = 0;
$i < $len;
$i++) {
587 # ASCII chars never decompose 591 } elseif (
$n >= 0xf0) {
592 $c = substr($string,
$i, 4);
594 } elseif (
$n >= 0xe0) {
595 $c = substr($string,
$i, 3);
597 } elseif (
$n >= 0xc0) {
598 $c = substr($string,
$i, 2);
601 if (isset($map[
$c])) {
606 # Decompose a hangul syllable into jamo; 607 # hardcoded for three-byte UTF-8 sequence. 608 # A lookup table would be slightly faster, 609 # but adds a lot of memory & disk needs. 611 $index = ((ord($c[0]) & 0x0f) << 12
612 | (ord($c[1]) & 0x3f) << 6
613 | (ord($c[2]) & 0x3f))
618 $out .=
"\xe1\x84" . chr(0x80 + $l) .
"\xe1\x85" . chr(0xa1 + $v);
620 $out .=
"\xe1\x87" . chr(0x80 + $t - 25);
622 $out .=
"\xe1\x86" . chr(0xa7 + $t);
644 $len = strlen($string);
646 $combiners = array();
648 for (
$i = 0;
$i < $len;
$i++) {
653 $c = substr($string,
$i, 4);
655 } elseif (
$n >= 0xe0) {
656 $c = substr($string,
$i, 3);
658 } elseif (
$n >= 0xc0) {
659 $c = substr($string,
$i, 2);
662 if (isset($utfCombiningClass[
$c])) {
663 $lastClass = $utfCombiningClass[
$c];
664 if (isset($combiners[$lastClass])) {
665 $combiners[$lastClass] .=
$c;
667 $combiners[$lastClass] =
$c;
674 $out .= implode(
'', $combiners);
675 $combiners = array();
682 $out .= implode(
'', $combiners);
699 $len = strlen($string);
707 for (
$i = 0;
$i < $len;
$i++) {
711 # No combining characters here... 718 } elseif (
$n >= 0xf0) {
719 $c = substr($string,
$i, 4);
721 } elseif (
$n >= 0xe0) {
722 $c = substr($string,
$i, 3);
724 } elseif (
$n >= 0xc0) {
725 $c = substr($string,
$i, 2);
728 $pair = $startChar .
$c;
730 if (isset($utfCombiningClass[
$c])) {
731 # A combining char; see what we can do with it 732 $class = $utfCombiningClass[
$c];
733 if (!empty($startChar) &&
734 $lastClass < $class &&
736 isset($utfCanonicalComp[$pair])) {
737 $startChar = $utfCanonicalComp[$pair];
748 if ($lastClass == 0) {
749 if (isset($utfCanonicalComp[$pair])) {
750 $startChar = $utfCanonicalComp[$pair];
754 if (
$n >= $x1 &&
$n <= $x2) {
755 # WARNING: Hangul code is painfully slow. 756 # I apologize for this ugly, ugly code; however 757 # performance is even more teh suck if we call 758 # out to nice clean functions. Lookup tables are 759 # marginally faster, but require a lot of space. 766 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE; 767 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE; 768 $lIndex = ord($startChar[2]) - 0x80;
769 $vIndex = ord(
$c[2]) - 0xa1;
775 # Hardcode the limited-range UTF-8 conversion: 776 $startChar = chr($hangulPoint >> 12 & 0x0f | 0xe0) .
777 chr($hangulPoint >> 6 & 0x3f | 0x80) .
778 chr($hangulPoint & 0x3f | 0x80);
786 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE; 787 $tIndex = ord(
$c[2]) - 0xa7;
789 $tIndex = ord(
$c[2]) - 0x80 + (0x11c0 - 0x11a7);
792 # Increment the code point by $tIndex, without 793 # the function overhead of decoding and recoding UTF-8 795 $tail = ord($startChar[2]) + $tIndex;
798 $mid = ord($startChar[1]) + 1;
800 $startChar[0] = chr(ord($startChar[0]) + 1);
803 $startChar[1] = chr($mid);
805 $startChar[2] = chr($tail);
807 # If there's another jamo char after this, *don't* try to merge it. 820 $out .= $startChar . $combining;
833 $len = strlen($string);
835 for (
$i = 0;
$i < $len;
$i++) {
const UNICODE_HANGUL_VBASE
static cleanUp($string)
The ultimate convenience function! Clean up invalid UTF-8 sequences, and convert to normal form C...
const UNICODE_HANGUL_FIRST
global $utfCombiningClass
const UNICODE_HANGUL_VCOUNT
global $utfCanonicalDecomp
static toNFD($string)
Convert a UTF-8 string to normal form D, canonical decomposition.
const UTF8_SURROGATE_FIRST
const UNICODE_HANGUL_TCOUNT
static toNFKD($string)
Convert a UTF-8 string to normal form KD, compatibility decomposition.
static fastCompose($string)
Produces canonically composed sequences, i.e.
static toNFC($string)
Convert a UTF-8 string to normal form C, canonical composition.
const UNICODE_HANGUL_TBASE
const UTF8_OVERLONG_A(!defined('UTF8_REPLACEMENT'))
static loadData()
Load the basic composition data if necessary.
static placebo($string)
This is just used for the benchmark, comparing how long it takes to interate through a string without...
static fastCombiningSort($string)
Sorts combining characters into canonical order.
static toNFKC($string)
Convert a UTF-8 string to normal form KC, compatibility composition.
static quickIsNFCVerify(&$string)
Returns true if the string is definitely in NFC.
const UNICODE_HANGUL_LBASE
const UNICODE_HANGUL_NCOUNT
static quickIsNFC($string)
Returns true if the string is definitely in NFC.
static fastDecompose($string, $map)
Perform decomposition of a UTF-8 string into either D or KD form (depending on which decomposition ma...
global $utfCompatibilityDecomp
const UNICODE_HANGUL_LCOUNT