3 * Unicode normalization routines
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
28 * @defgroup UtfNormal UtfNormal
31 require_once dirname(__FILE__
).'/UtfNormalUtil.php';
34 * For using the ICU wrapper
36 define( 'UNORM_NONE', 1 );
37 define( 'UNORM_NFD', 2 );
38 define( 'UNORM_NFKD', 3 );
39 define( 'UNORM_NFC', 4 );
40 define( 'UNORM_DEFAULT', UNORM_NFC
);
41 define( 'UNORM_NFKC', 5 );
42 define( 'UNORM_FCD', 6 );
44 define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
45 define( 'NORMALIZE_INTL', function_exists( 'normalizer_normalize' ) );
48 * Unicode normalization routines for working with UTF-8 strings.
49 * Currently assumes that input strings are valid UTF-8!
51 * Not as fast as I'd like, but should be usable for most purposes.
52 * UtfNormal::toNFC() will bail early if given ASCII text or text
53 * it can quickly deterimine is already normalized.
55 * All functions can be called static.
57 * See description of forms at http://www.unicode.org/reports/tr15/
62 static $utfCombiningClass = null;
63 static $utfCanonicalComp = null;
64 static $utfCanonicalDecomp = null;
66 # Load compatibility decompositions on demand if they are needed.
67 static $utfCompatibilityDecomp = null;
72 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
73 * and convert to normal form C, canonical composition.
75 * Fast return for pure ASCII strings; some lesser optimizations for
76 * strings containing only known-good characters. Not as fast as toNFC().
78 * @param $string String: a UTF-8 string
79 * @return string a clean, shiny, normalized UTF-8 string
81 static function cleanUp( $string ) {
82 if( NORMALIZE_ICU || NORMALIZE_INTL
) {
83 # We exclude a few chars that ICU would not.
84 $string = preg_replace(
85 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
88 $string = str_replace( UTF8_FFFE
, UTF8_REPLACEMENT
, $string );
89 $string = str_replace( UTF8_FFFF
, UTF8_REPLACEMENT
, $string );
91 # UnicodeString constructor fails if the string ends with a
92 # head byte. Add a junk char at the end, we'll strip it off.
93 if ( NORMALIZE_ICU
) return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC
), "\x01" );
94 if ( NORMALIZE_INTL
) return normalizer_normalize( $string, Normalizer
::FORM_C
);
95 } elseif( UtfNormal
::quickIsNFCVerify( $string ) ) {
96 # Side effect -- $string has had UTF-8 errors cleaned up.
99 return UtfNormal
::NFC( $string );
104 * Convert a UTF-8 string to normal form C, canonical composition.
105 * Fast return for pure ASCII strings; some lesser optimizations for
106 * strings containing only known-good characters.
108 * @param $string String: a valid UTF-8 string. Input is not validated.
109 * @return string a UTF-8 string in normal form C
111 static function toNFC( $string ) {
113 return normalizer_normalize( $string, Normalizer
::FORM_C
);
114 elseif( NORMALIZE_ICU
)
115 return utf8_normalize( $string, UNORM_NFC
);
116 elseif( UtfNormal
::quickIsNFC( $string ) )
119 return UtfNormal
::NFC( $string );
123 * Convert a UTF-8 string to normal form D, canonical decomposition.
124 * Fast return for pure ASCII strings.
126 * @param $string String: a valid UTF-8 string. Input is not validated.
127 * @return string a UTF-8 string in normal form D
129 static function toNFD( $string ) {
131 return normalizer_normalize( $string, Normalizer
::FORM_D
);
132 elseif( NORMALIZE_ICU
)
133 return utf8_normalize( $string, UNORM_NFD
);
134 elseif( preg_match( '/[\x80-\xff]/', $string ) )
135 return UtfNormal
::NFD( $string );
141 * Convert a UTF-8 string to normal form KC, compatibility composition.
142 * This may cause irreversible information loss, use judiciously.
143 * Fast return for pure ASCII strings.
145 * @param $string String: a valid UTF-8 string. Input is not validated.
146 * @return string a UTF-8 string in normal form KC
148 static function toNFKC( $string ) {
150 return normalizer_normalize( $string, Normalizer
::FORM_KC
);
151 elseif( NORMALIZE_ICU
)
152 return utf8_normalize( $string, UNORM_NFKC
);
153 elseif( preg_match( '/[\x80-\xff]/', $string ) )
154 return UtfNormal
::NFKC( $string );
160 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
161 * This may cause irreversible information loss, use judiciously.
162 * Fast return for pure ASCII strings.
164 * @param $string String: a valid UTF-8 string. Input is not validated.
165 * @return string a UTF-8 string in normal form KD
167 static function toNFKD( $string ) {
169 return normalizer_normalize( $string, Normalizer
::FORM_KD
);
170 elseif( NORMALIZE_ICU
)
171 return utf8_normalize( $string, UNORM_NFKD
);
172 elseif( preg_match( '/[\x80-\xff]/', $string ) )
173 return UtfNormal
::NFKD( $string );
179 * Load the basic composition data if necessary
182 static function loadData() {
183 if( !isset( self
::$utfCombiningClass ) ) {
184 require_once( dirname(__FILE__
) . '/UtfNormalData.inc' );
189 * Returns true if the string is _definitely_ in NFC.
190 * Returns false if not or uncertain.
191 * @param $string String: a valid UTF-8 string. Input is not validated.
194 static function quickIsNFC( $string ) {
195 # ASCII is always valid NFC!
196 # If it's pure ASCII, let it through.
197 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
199 UtfNormal
::loadData();
200 $len = strlen( $string );
201 for( $i = 0; $i < $len; $i++
) {
206 } elseif( $n >= 0xf0 ) {
207 $c = substr( $string, $i, 4 );
209 } elseif( $n >= 0xe0 ) {
210 $c = substr( $string, $i, 3 );
212 } elseif( $n >= 0xc0 ) {
213 $c = substr( $string, $i, 2 );
216 if( isset( self
::$utfCheckNFC[$c] ) ) {
217 # If it's NO or MAYBE, bail and do the slow check.
220 if( isset( self
::$utfCombiningClass[$c] ) ) {
221 # Combining character? We might have to do sorting, at least.
229 * Returns true if the string is _definitely_ in NFC.
230 * Returns false if not or uncertain.
231 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
233 static function quickIsNFCVerify( &$string ) {
234 # Screen out some characters that eg won't be allowed in XML
235 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT
, $string );
237 # ASCII is always valid NFC!
238 # If we're only ever given plain ASCII, we can avoid the overhead
239 # of initializing the decomposition tables by skipping out early.
240 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
242 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
243 if( !isset( $checkit ) ) {
244 # Load/build some scary lookup tables...
245 UtfNormal
::loadData();
247 $utfCheckOrCombining = array_merge( self
::$utfCheckNFC, self
::$utfCombiningClass );
249 # Head bytes for sequences which we should do further validity checks
250 $checkit = array_flip( array_map( 'chr',
251 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
252 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
253 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
255 # Each UTF-8 head byte is followed by a certain
256 # number of tail bytes.
257 $tailBytes = array();
258 for( $n = 0; $n < 256; $n++
) {
261 } elseif( $n < 0xe0 ) {
263 } elseif( $n < 0xf0 ) {
265 } elseif( $n < 0xf8 ) {
267 } elseif( $n < 0xfc ) {
269 } elseif( $n < 0xfe ) {
274 $tailBytes[chr($n)] = $remaining;
278 # Chop the text into pure-ASCII and non-ASCII areas;
279 # large ASCII parts can be handled much more quickly.
280 # Don't chop up Unicode areas for punctuation, though,
281 # that wastes energy.
284 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
290 foreach( $matches[1] as $str ) {
291 $chunk = strlen( $str );
293 if( $str{0} < "\x80" ) {
294 # ASCII chunk: guaranteed to be valid UTF-8
295 # and in normal form C, so skip over it.
300 # We'll have to examine the chunk byte by byte to ensure
301 # that it consists of valid UTF-8 sequences, and to see
302 # if any of them might not be normalized.
304 # Since PHP is not the fastest language on earth, some of
305 # this code is a little ugly with inner loop optimizations.
308 $len = $chunk +
1; # Counting down is faster. I'm *so* sorry.
310 for( $i = -1; --$len; ) {
311 $remaining = $tailBytes[$c = $str{++
$i}];
314 $sequence = $head = $c;
316 # Look for the defined number of tail bytes...
317 if( --$len && ( $c = $str{++
$i} ) >= "\x80" && $c < "\xc0" ) {
318 # Legal tail bytes are nice.
322 # Premature end of string!
323 # Drop a replacement character into output to
324 # represent the invalid UTF-8 sequence.
325 $replace[] = array( UTF8_REPLACEMENT
,
326 $base +
$i +
1 - strlen( $sequence ),
327 strlen( $sequence ) );
330 # Illegal tail byte; abandon the sequence.
331 $replace[] = array( UTF8_REPLACEMENT
,
332 $base +
$i - strlen( $sequence ),
333 strlen( $sequence ) );
334 # Back up and reprocess this byte; it may itself
335 # be a legal ASCII or UTF-8 sequence head.
341 } while( --$remaining );
343 if( isset( $checkit[$head] ) ) {
344 # Do some more detailed validity checks, for
345 # invalid characters and illegal sequences.
346 if( $head == "\xed" ) {
347 # 0xed is relatively frequent in Korean, which
348 # abuts the surrogate area, so we're doing
349 # this check separately to speed things up.
351 if( $sequence >= UTF8_SURROGATE_FIRST
) {
352 # Surrogates are legal only in UTF-16 code.
353 # They are totally forbidden here in UTF-8
355 $replace[] = array( UTF8_REPLACEMENT
,
356 $base +
$i +
1 - strlen( $sequence ),
357 strlen( $sequence ) );
362 # Slower, but rarer checks...
365 # "Overlong sequences" are those that are syntactically
366 # correct but use more UTF-8 bytes than are necessary to
367 # encode a character. Naïve string comparisons can be
368 # tricked into failing to see a match for an ASCII
369 # character, for instance, which can be a security hole
370 # if blacklist checks are being used.
371 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A
)
372 ||
($n == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
373 ||
($n == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
375 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
377 ($sequence == UTF8_FFFE
)
378 ||
($sequence == UTF8_FFFF
) )
380 # Unicode has been limited to 21 bits; longer
381 # sequences are not allowed.
382 ||
($n >= 0xf0 && $sequence > UTF8_MAX
) ) {
384 $replace[] = array( UTF8_REPLACEMENT
,
385 $base +
$i +
1 - strlen( $sequence ),
386 strlen( $sequence ) );
393 if( isset( $utfCheckOrCombining[$sequence] ) ) {
394 # If it's NO or MAYBE, we'll have to rip
395 # the string apart and put it back together.
396 # That's going to be mighty slow.
397 $looksNormal = false;
400 # The sequence is legal!
402 } elseif( $c < "\x80" ) {
405 } elseif( $c < "\xc0" ) {
409 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
411 # Don't add if we're continuing a broken sequence;
412 # we already put a replacement character when we looked
413 # at the broken sequence.
414 $replace[] = array( '', $base +
$i, 1 );
417 # Miscellaneous freaks.
418 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
424 if( count( $replace ) ) {
425 # There were illegal UTF-8 sequences we need to fix up.
428 foreach( $replace as $rep ) {
429 list( $replacement, $start, $length ) = $rep;
430 if( $last < $start ) {
431 $out .= substr( $string, $last, $start - $last );
433 $out .= $replacement;
434 $last = $start +
$length;
436 if( $last < strlen( $string ) ) {
437 $out .= substr( $string, $last );
444 # These take a string and run the normalization on them, without
445 # checking for validity or any optimization etc. Input must be
448 * @param $string string
452 static function NFC( $string ) {
453 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
457 * @param $string string
461 static function NFD( $string ) {
462 UtfNormal
::loadData();
464 return UtfNormal
::fastCombiningSort(
465 UtfNormal
::fastDecompose( $string, self
::$utfCanonicalDecomp ) );
469 * @param $string string
473 static function NFKC( $string ) {
474 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
478 * @param $string string
482 static function NFKD( $string ) {
483 if( !isset( self
::$utfCompatibilityDecomp ) ) {
484 require_once( 'UtfNormalDataK.inc' );
486 return self
::fastCombiningSort(
487 self
::fastDecompose( $string, self
::$utfCompatibilityDecomp ) );
492 * Perform decomposition of a UTF-8 string into either D or KD form
493 * (depending on which decomposition map is passed to us).
494 * Input is assumed to be *valid* UTF-8. Invalid code will break.
496 * @param $string String: valid UTF-8 string
497 * @param $map Array: hash of expanded decomposition map
498 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
500 static function fastDecompose( $string, $map ) {
501 UtfNormal
::loadData();
502 $len = strlen( $string );
504 for( $i = 0; $i < $len; $i++
) {
508 # ASCII chars never decompose
512 } elseif( $n >= 0xf0 ) {
513 $c = substr( $string, $i, 4 );
515 } elseif( $n >= 0xe0 ) {
516 $c = substr( $string, $i, 3 );
518 } elseif( $n >= 0xc0 ) {
519 $c = substr( $string, $i, 2 );
522 if( isset( $map[$c] ) ) {
526 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
527 # Decompose a hangul syllable into jamo;
528 # hardcoded for three-byte UTF-8 sequence.
529 # A lookup table would be slightly faster,
530 # but adds a lot of memory & disk needs.
532 $index = ( (ord( $c{0} ) & 0x0f) << 12
533 |
(ord( $c{1} ) & 0x3f) << 6
534 |
(ord( $c{2} ) & 0x3f) )
535 - UNICODE_HANGUL_FIRST
;
536 $l = intval( $index / UNICODE_HANGUL_NCOUNT
);
537 $v = intval( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
538 $t = $index % UNICODE_HANGUL_TCOUNT
;
539 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
541 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
543 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
554 * Sorts combining characters into canonical order. This is the
555 * final step in creating decomposed normal forms D and KD.
557 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
558 * @return string a UTF-8 string with combining characters sorted in canonical order
560 static function fastCombiningSort( $string ) {
561 UtfNormal
::loadData();
562 $len = strlen( $string );
564 $combiners = array();
566 for( $i = 0; $i < $len; $i++
) {
571 $c = substr( $string, $i, 4 );
573 } elseif( $n >= 0xe0 ) {
574 $c = substr( $string, $i, 3 );
576 } elseif( $n >= 0xc0 ) {
577 $c = substr( $string, $i, 2 );
580 if( isset( self
::$utfCombiningClass[$c] ) ) {
581 $lastClass = self
::$utfCombiningClass[$c];
582 if( isset( $combiners[$lastClass] ) ) {
583 $combiners[$lastClass] .= $c;
585 $combiners[$lastClass] = $c;
592 $out .= implode( '', $combiners );
593 $combiners = array();
600 $out .= implode( '', $combiners );
606 * Produces canonically composed sequences, i.e. normal form C or KC.
609 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
610 * @return string a UTF-8 string with canonical precomposed characters used where possible
612 static function fastCompose( $string ) {
613 UtfNormal
::loadData();
614 $len = strlen( $string );
620 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
621 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
622 for( $i = 0; $i < $len; $i++
) {
626 # No combining characters here...
633 } elseif( $n >= 0xf0 ) {
634 $c = substr( $string, $i, 4 );
636 } elseif( $n >= 0xe0 ) {
637 $c = substr( $string, $i, 3 );
639 } elseif( $n >= 0xc0 ) {
640 $c = substr( $string, $i, 2 );
643 $pair = $startChar . $c;
645 if( isset( self
::$utfCombiningClass[$c] ) ) {
646 # A combining char; see what we can do with it
647 $class = self
::$utfCombiningClass[$c];
648 if( !empty( $startChar ) &&
649 $lastClass < $class &&
651 isset( self
::$utfCanonicalComp[$pair] ) ) {
652 $startChar = self
::$utfCanonicalComp[$pair];
663 if( $lastClass == 0 ) {
664 if( isset( self
::$utfCanonicalComp[$pair] ) ) {
665 $startChar = self
::$utfCanonicalComp[$pair];
669 if( $n >= $x1 && $n <= $x2 ) {
670 # WARNING: Hangul code is painfully slow.
671 # I apologize for this ugly, ugly code; however
672 # performance is even more teh suck if we call
673 # out to nice clean functions. Lookup tables are
674 # marginally faster, but require a lot of space.
676 if( $c >= UTF8_HANGUL_VBASE
&&
677 $c <= UTF8_HANGUL_VEND
&&
678 $startChar >= UTF8_HANGUL_LBASE
&&
679 $startChar <= UTF8_HANGUL_LEND
) {
681 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
682 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
683 $lIndex = ord( $startChar{2} ) - 0x80;
684 $vIndex = ord( $c{2} ) - 0xa1;
686 $hangulPoint = UNICODE_HANGUL_FIRST +
687 UNICODE_HANGUL_TCOUNT
*
688 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
690 # Hardcode the limited-range UTF-8 conversion:
691 $startChar = chr( $hangulPoint >> 12 & 0x0f |
0xe0 ) .
692 chr( $hangulPoint >> 6 & 0x3f |
0x80 ) .
693 chr( $hangulPoint & 0x3f |
0x80 );
696 } elseif( $c >= UTF8_HANGUL_TBASE
&&
697 $c <= UTF8_HANGUL_TEND
&&
698 $startChar >= UTF8_HANGUL_FIRST
&&
699 $startChar <= UTF8_HANGUL_LAST
&&
701 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
702 $tIndex = ord( $c{2} ) - 0xa7;
703 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 +
(0x11c0 - 0x11a7);
705 # Increment the code point by $tIndex, without
706 # the function overhead of decoding and recoding UTF-8
708 $tail = ord( $startChar{2} ) +
$tIndex;
711 $mid = ord( $startChar{1} ) +
1;
713 $startChar{0} = chr( ord( $startChar{0} ) +
1 );
716 $startChar{1} = chr( $mid );
718 $startChar{2} = chr( $tail );
720 # If there's another jamo char after this, *don't* try to merge it.
733 $out .= $startChar . $combining;
738 * This is just used for the benchmark, comparing how long it takes to
739 * interate through a string without really doing anything of substance.
740 * @param $string string
743 static function placebo( $string ) {
744 $len = strlen( $string );
746 for( $i = 0; $i < $len; $i++
) {