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 * @defgroup UtfNormal UtfNormal
25 require_once dirname(__FILE__
).'/UtfNormalUtil.php';
27 global $utfCombiningClass, $utfCanonicalComp, $utfCanonicalDecomp;
28 $utfCombiningClass = NULL;
29 $utfCanonicalComp = NULL;
30 $utfCanonicalDecomp = NULL;
32 # Load compatibility decompositions on demand if they are needed.
33 global $utfCompatibilityDecomp;
34 $utfCompatibilityDecomp = NULL;
37 * For using the ICU wrapper
39 define( 'UNORM_NONE', 1 );
40 define( 'UNORM_NFD', 2 );
41 define( 'UNORM_NFKD', 3 );
42 define( 'UNORM_NFC', 4 );
43 define( 'UNORM_DEFAULT', UNORM_NFC
);
44 define( 'UNORM_NFKC', 5 );
45 define( 'UNORM_FCD', 6 );
47 define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
50 * Unicode normalization routines for working with UTF-8 strings.
51 * Currently assumes that input strings are valid UTF-8!
53 * Not as fast as I'd like, but should be usable for most purposes.
54 * UtfNormal::toNFC() will bail early if given ASCII text or text
55 * it can quickly deterimine is already normalized.
57 * All functions can be called static.
59 * See description of forms at http://www.unicode.org/reports/tr15/
65 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
66 * and convert to normal form C, canonical composition.
68 * Fast return for pure ASCII strings; some lesser optimizations for
69 * strings containing only known-good characters. Not as fast as toNFC().
71 * @param $string String: a UTF-8 string
72 * @return string a clean, shiny, normalized UTF-8 string
74 static function cleanUp( $string ) {
76 # We exclude a few chars that ICU would not.
77 $string = preg_replace(
78 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
81 $string = str_replace( UTF8_FFFE
, UTF8_REPLACEMENT
, $string );
82 $string = str_replace( UTF8_FFFF
, UTF8_REPLACEMENT
, $string );
84 # UnicodeString constructor fails if the string ends with a
85 # head byte. Add a junk char at the end, we'll strip it off.
86 return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC
), "\x01" );
87 } elseif( UtfNormal
::quickIsNFCVerify( $string ) ) {
88 # Side effect -- $string has had UTF-8 errors cleaned up.
91 return UtfNormal
::NFC( $string );
96 * Convert a UTF-8 string to normal form C, canonical composition.
97 * Fast return for pure ASCII strings; some lesser optimizations for
98 * strings containing only known-good characters.
100 * @param $string String: a valid UTF-8 string. Input is not validated.
101 * @return string a UTF-8 string in normal form C
103 static function toNFC( $string ) {
105 return utf8_normalize( $string, UNORM_NFC
);
106 elseif( UtfNormal
::quickIsNFC( $string ) )
109 return UtfNormal
::NFC( $string );
113 * Convert a UTF-8 string to normal form D, canonical decomposition.
114 * Fast return for pure ASCII strings.
116 * @param $string String: a valid UTF-8 string. Input is not validated.
117 * @return string a UTF-8 string in normal form D
119 static function toNFD( $string ) {
121 return utf8_normalize( $string, UNORM_NFD
);
122 elseif( preg_match( '/[\x80-\xff]/', $string ) )
123 return UtfNormal
::NFD( $string );
129 * Convert a UTF-8 string to normal form KC, compatibility composition.
130 * This may cause irreversible information loss, use judiciously.
131 * Fast return for pure ASCII strings.
133 * @param $string String: a valid UTF-8 string. Input is not validated.
134 * @return string a UTF-8 string in normal form KC
136 static function toNFKC( $string ) {
138 return utf8_normalize( $string, UNORM_NFKC
);
139 elseif( preg_match( '/[\x80-\xff]/', $string ) )
140 return UtfNormal
::NFKC( $string );
146 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
147 * This may cause irreversible information loss, use judiciously.
148 * Fast return for pure ASCII strings.
150 * @param $string String: a valid UTF-8 string. Input is not validated.
151 * @return string a UTF-8 string in normal form KD
153 static function toNFKD( $string ) {
155 return utf8_normalize( $string, UNORM_NFKD
);
156 elseif( preg_match( '/[\x80-\xff]/', $string ) )
157 return UtfNormal
::NFKD( $string );
163 * Load the basic composition data if necessary
166 static function loadData() {
167 global $utfCombiningClass;
168 if( !isset( $utfCombiningClass ) ) {
169 require_once( dirname(__FILE__
) . '/UtfNormalData.inc' );
174 * Returns true if the string is _definitely_ in NFC.
175 * Returns false if not or uncertain.
176 * @param $string String: a valid UTF-8 string. Input is not validated.
179 static function quickIsNFC( $string ) {
180 # ASCII is always valid NFC!
181 # If it's pure ASCII, let it through.
182 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
184 UtfNormal
::loadData();
185 global $utfCheckNFC, $utfCombiningClass;
186 $len = strlen( $string );
187 for( $i = 0; $i < $len; $i++
) {
192 } elseif( $n >= 0xf0 ) {
193 $c = substr( $string, $i, 4 );
195 } elseif( $n >= 0xe0 ) {
196 $c = substr( $string, $i, 3 );
198 } elseif( $n >= 0xc0 ) {
199 $c = substr( $string, $i, 2 );
202 if( isset( $utfCheckNFC[$c] ) ) {
203 # If it's NO or MAYBE, bail and do the slow check.
206 if( isset( $utfCombiningClass[$c] ) ) {
207 # Combining character? We might have to do sorting, at least.
215 * Returns true if the string is _definitely_ in NFC.
216 * Returns false if not or uncertain.
217 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
219 static function quickIsNFCVerify( &$string ) {
220 # Screen out some characters that eg won't be allowed in XML
221 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT
, $string );
223 # ASCII is always valid NFC!
224 # If we're only ever given plain ASCII, we can avoid the overhead
225 # of initializing the decomposition tables by skipping out early.
226 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
228 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
229 if( !isset( $checkit ) ) {
230 # Load/build some scary lookup tables...
231 UtfNormal
::loadData();
232 global $utfCheckNFC, $utfCombiningClass;
234 $utfCheckOrCombining = array_merge( $utfCheckNFC, $utfCombiningClass );
236 # Head bytes for sequences which we should do further validity checks
237 $checkit = array_flip( array_map( 'chr',
238 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
239 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
240 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
242 # Each UTF-8 head byte is followed by a certain
243 # number of tail bytes.
244 $tailBytes = array();
245 for( $n = 0; $n < 256; $n++
) {
248 } elseif( $n < 0xe0 ) {
250 } elseif( $n < 0xf0 ) {
252 } elseif( $n < 0xf8 ) {
254 } elseif( $n < 0xfc ) {
256 } elseif( $n < 0xfe ) {
261 $tailBytes[chr($n)] = $remaining;
265 # Chop the text into pure-ASCII and non-ASCII areas;
266 # large ASCII parts can be handled much more quickly.
267 # Don't chop up Unicode areas for punctuation, though,
268 # that wastes energy.
271 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
277 foreach( $matches[1] as $str ) {
278 $chunk = strlen( $str );
280 if( $str{0} < "\x80" ) {
281 # ASCII chunk: guaranteed to be valid UTF-8
282 # and in normal form C, so skip over it.
287 # We'll have to examine the chunk byte by byte to ensure
288 # that it consists of valid UTF-8 sequences, and to see
289 # if any of them might not be normalized.
291 # Since PHP is not the fastest language on earth, some of
292 # this code is a little ugly with inner loop optimizations.
295 $len = $chunk +
1; # Counting down is faster. I'm *so* sorry.
297 for( $i = -1; --$len; ) {
298 if( $remaining = $tailBytes[$c = $str{++
$i}] ) {
300 $sequence = $head = $c;
302 # Look for the defined number of tail bytes...
303 if( --$len && ( $c = $str{++
$i} ) >= "\x80" && $c < "\xc0" ) {
304 # Legal tail bytes are nice.
308 # Premature end of string!
309 # Drop a replacement character into output to
310 # represent the invalid UTF-8 sequence.
311 $replace[] = array( UTF8_REPLACEMENT
,
312 $base +
$i +
1 - strlen( $sequence ),
313 strlen( $sequence ) );
316 # Illegal tail byte; abandon the sequence.
317 $replace[] = array( UTF8_REPLACEMENT
,
318 $base +
$i - strlen( $sequence ),
319 strlen( $sequence ) );
320 # Back up and reprocess this byte; it may itself
321 # be a legal ASCII or UTF-8 sequence head.
327 } while( --$remaining );
329 if( isset( $checkit[$head] ) ) {
330 # Do some more detailed validity checks, for
331 # invalid characters and illegal sequences.
332 if( $head == "\xed" ) {
333 # 0xed is relatively frequent in Korean, which
334 # abuts the surrogate area, so we're doing
335 # this check separately to speed things up.
337 if( $sequence >= UTF8_SURROGATE_FIRST
) {
338 # Surrogates are legal only in UTF-16 code.
339 # They are totally forbidden here in UTF-8
341 $replace[] = array( UTF8_REPLACEMENT
,
342 $base +
$i +
1 - strlen( $sequence ),
343 strlen( $sequence ) );
348 # Slower, but rarer checks...
351 # "Overlong sequences" are those that are syntactically
352 # correct but use more UTF-8 bytes than are necessary to
353 # encode a character. Naïve string comparisons can be
354 # tricked into failing to see a match for an ASCII
355 # character, for instance, which can be a security hole
356 # if blacklist checks are being used.
357 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A
)
358 ||
($n == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
359 ||
($n == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
361 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
363 ($sequence == UTF8_FFFE
)
364 ||
($sequence == UTF8_FFFF
) )
366 # Unicode has been limited to 21 bits; longer
367 # sequences are not allowed.
368 ||
($n >= 0xf0 && $sequence > UTF8_MAX
) ) {
370 $replace[] = array( UTF8_REPLACEMENT
,
371 $base +
$i +
1 - strlen( $sequence ),
372 strlen( $sequence ) );
379 if( isset( $utfCheckOrCombining[$sequence] ) ) {
380 # If it's NO or MAYBE, we'll have to rip
381 # the string apart and put it back together.
382 # That's going to be mighty slow.
383 $looksNormal = false;
386 # The sequence is legal!
388 } elseif( $c < "\x80" ) {
391 } elseif( $c < "\xc0" ) {
395 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
397 # Don't add if we're continuing a broken sequence;
398 # we already put a replacement character when we looked
399 # at the broken sequence.
400 $replace[] = array( '', $base +
$i, 1 );
403 # Miscellaneous freaks.
404 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
410 if( count( $replace ) ) {
411 # There were illegal UTF-8 sequences we need to fix up.
414 foreach( $replace as $rep ) {
415 list( $replacement, $start, $length ) = $rep;
416 if( $last < $start ) {
417 $out .= substr( $string, $last, $start - $last );
419 $out .= $replacement;
420 $last = $start +
$length;
422 if( $last < strlen( $string ) ) {
423 $out .= substr( $string, $last );
430 # These take a string and run the normalization on them, without
431 # checking for validity or any optimization etc. Input must be
434 * @param $string string
438 static function NFC( $string ) {
439 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
443 * @param $string string
447 static function NFD( $string ) {
448 UtfNormal
::loadData();
449 global $utfCanonicalDecomp;
450 return UtfNormal
::fastCombiningSort(
451 UtfNormal
::fastDecompose( $string, $utfCanonicalDecomp ) );
455 * @param $string string
459 static function NFKC( $string ) {
460 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
464 * @param $string string
468 static function NFKD( $string ) {
469 global $utfCompatibilityDecomp;
470 if( !isset( $utfCompatibilityDecomp ) ) {
471 require_once( 'UtfNormalDataK.inc' );
473 return UtfNormal
::fastCombiningSort(
474 UtfNormal
::fastDecompose( $string, $utfCompatibilityDecomp ) );
479 * Perform decomposition of a UTF-8 string into either D or KD form
480 * (depending on which decomposition map is passed to us).
481 * Input is assumed to be *valid* UTF-8. Invalid code will break.
483 * @param $string String: valid UTF-8 string
484 * @param $map Array: hash of expanded decomposition map
485 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
487 static function fastDecompose( $string, $map ) {
488 UtfNormal
::loadData();
489 $len = strlen( $string );
491 for( $i = 0; $i < $len; $i++
) {
495 # ASCII chars never decompose
499 } elseif( $n >= 0xf0 ) {
500 $c = substr( $string, $i, 4 );
502 } elseif( $n >= 0xe0 ) {
503 $c = substr( $string, $i, 3 );
505 } elseif( $n >= 0xc0 ) {
506 $c = substr( $string, $i, 2 );
509 if( isset( $map[$c] ) ) {
513 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
514 # Decompose a hangul syllable into jamo;
515 # hardcoded for three-byte UTF-8 sequence.
516 # A lookup table would be slightly faster,
517 # but adds a lot of memory & disk needs.
519 $index = ( (ord( $c{0} ) & 0x0f) << 12
520 |
(ord( $c{1} ) & 0x3f) << 6
521 |
(ord( $c{2} ) & 0x3f) )
522 - UNICODE_HANGUL_FIRST
;
523 $l = intval( $index / UNICODE_HANGUL_NCOUNT
);
524 $v = intval( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
525 $t = $index % UNICODE_HANGUL_TCOUNT
;
526 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
528 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
530 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
541 * Sorts combining characters into canonical order. This is the
542 * final step in creating decomposed normal forms D and KD.
544 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
545 * @return string a UTF-8 string with combining characters sorted in canonical order
547 static function fastCombiningSort( $string ) {
548 UtfNormal
::loadData();
549 global $utfCombiningClass;
550 $len = strlen( $string );
552 $combiners = array();
554 for( $i = 0; $i < $len; $i++
) {
559 $c = substr( $string, $i, 4 );
561 } elseif( $n >= 0xe0 ) {
562 $c = substr( $string, $i, 3 );
564 } elseif( $n >= 0xc0 ) {
565 $c = substr( $string, $i, 2 );
568 if( isset( $utfCombiningClass[$c] ) ) {
569 $lastClass = $utfCombiningClass[$c];
570 if( isset( $combiners[$lastClass] ) ) {
571 $combiners[$lastClass] .= $c;
573 $combiners[$lastClass] = $c;
580 $out .= implode( '', $combiners );
581 $combiners = array();
588 $out .= implode( '', $combiners );
594 * Produces canonically composed sequences, i.e. normal form C or KC.
597 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
598 * @return string a UTF-8 string with canonical precomposed characters used where possible
600 static function fastCompose( $string ) {
601 UtfNormal
::loadData();
602 global $utfCanonicalComp, $utfCombiningClass;
603 $len = strlen( $string );
609 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
610 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
611 for( $i = 0; $i < $len; $i++
) {
615 # No combining characters here...
622 } elseif( $n >= 0xf0 ) {
623 $c = substr( $string, $i, 4 );
625 } elseif( $n >= 0xe0 ) {
626 $c = substr( $string, $i, 3 );
628 } elseif( $n >= 0xc0 ) {
629 $c = substr( $string, $i, 2 );
632 $pair = $startChar . $c;
634 if( isset( $utfCombiningClass[$c] ) ) {
635 # A combining char; see what we can do with it
636 $class = $utfCombiningClass[$c];
637 if( !empty( $startChar ) &&
638 $lastClass < $class &&
640 isset( $utfCanonicalComp[$pair] ) ) {
641 $startChar = $utfCanonicalComp[$pair];
652 if( $lastClass == 0 ) {
653 if( isset( $utfCanonicalComp[$pair] ) ) {
654 $startChar = $utfCanonicalComp[$pair];
658 if( $n >= $x1 && $n <= $x2 ) {
659 # WARNING: Hangul code is painfully slow.
660 # I apologize for this ugly, ugly code; however
661 # performance is even more teh suck if we call
662 # out to nice clean functions. Lookup tables are
663 # marginally faster, but require a lot of space.
665 if( $c >= UTF8_HANGUL_VBASE
&&
666 $c <= UTF8_HANGUL_VEND
&&
667 $startChar >= UTF8_HANGUL_LBASE
&&
668 $startChar <= UTF8_HANGUL_LEND
) {
670 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
671 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
672 $lIndex = ord( $startChar{2} ) - 0x80;
673 $vIndex = ord( $c{2} ) - 0xa1;
675 $hangulPoint = UNICODE_HANGUL_FIRST +
676 UNICODE_HANGUL_TCOUNT
*
677 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
679 # Hardcode the limited-range UTF-8 conversion:
680 $startChar = chr( $hangulPoint >> 12 & 0x0f |
0xe0 ) .
681 chr( $hangulPoint >> 6 & 0x3f |
0x80 ) .
682 chr( $hangulPoint & 0x3f |
0x80 );
685 } elseif( $c >= UTF8_HANGUL_TBASE
&&
686 $c <= UTF8_HANGUL_TEND
&&
687 $startChar >= UTF8_HANGUL_FIRST
&&
688 $startChar <= UTF8_HANGUL_LAST
&&
690 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
691 $tIndex = ord( $c{2} ) - 0xa7;
692 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 +
(0x11c0 - 0x11a7);
694 # Increment the code point by $tIndex, without
695 # the function overhead of decoding and recoding UTF-8
697 $tail = ord( $startChar{2} ) +
$tIndex;
700 $mid = ord( $startChar{1} ) +
1;
702 $startChar{0} = chr( ord( $startChar{0} ) +
1 );
705 $startChar{1} = chr( $mid );
707 $startChar{2} = chr( $tail );
709 # If there's another jamo char after this, *don't* try to merge it.
722 $out .= $startChar . $combining;
727 * This is just used for the benchmark, comparing how long it takes to
728 * interate through a string without really doing anything of substance.
729 * @param $string string
732 static function placebo( $string ) {
733 $len = strlen( $string );
735 for( $i = 0; $i < $len; $i++
) {