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 if( $remaining = $tailBytes[$c = $str{++
$i}] ) {
313 $sequence = $head = $c;
315 # Look for the defined number of tail bytes...
316 if( --$len && ( $c = $str{++
$i} ) >= "\x80" && $c < "\xc0" ) {
317 # Legal tail bytes are nice.
321 # Premature end of string!
322 # Drop a replacement character into output to
323 # represent the invalid UTF-8 sequence.
324 $replace[] = array( UTF8_REPLACEMENT
,
325 $base +
$i +
1 - strlen( $sequence ),
326 strlen( $sequence ) );
329 # Illegal tail byte; abandon the sequence.
330 $replace[] = array( UTF8_REPLACEMENT
,
331 $base +
$i - strlen( $sequence ),
332 strlen( $sequence ) );
333 # Back up and reprocess this byte; it may itself
334 # be a legal ASCII or UTF-8 sequence head.
340 } while( --$remaining );
342 if( isset( $checkit[$head] ) ) {
343 # Do some more detailed validity checks, for
344 # invalid characters and illegal sequences.
345 if( $head == "\xed" ) {
346 # 0xed is relatively frequent in Korean, which
347 # abuts the surrogate area, so we're doing
348 # this check separately to speed things up.
350 if( $sequence >= UTF8_SURROGATE_FIRST
) {
351 # Surrogates are legal only in UTF-16 code.
352 # They are totally forbidden here in UTF-8
354 $replace[] = array( UTF8_REPLACEMENT
,
355 $base +
$i +
1 - strlen( $sequence ),
356 strlen( $sequence ) );
361 # Slower, but rarer checks...
364 # "Overlong sequences" are those that are syntactically
365 # correct but use more UTF-8 bytes than are necessary to
366 # encode a character. Naïve string comparisons can be
367 # tricked into failing to see a match for an ASCII
368 # character, for instance, which can be a security hole
369 # if blacklist checks are being used.
370 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A
)
371 ||
($n == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
372 ||
($n == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
374 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
376 ($sequence == UTF8_FFFE
)
377 ||
($sequence == UTF8_FFFF
) )
379 # Unicode has been limited to 21 bits; longer
380 # sequences are not allowed.
381 ||
($n >= 0xf0 && $sequence > UTF8_MAX
) ) {
383 $replace[] = array( UTF8_REPLACEMENT
,
384 $base +
$i +
1 - strlen( $sequence ),
385 strlen( $sequence ) );
392 if( isset( $utfCheckOrCombining[$sequence] ) ) {
393 # If it's NO or MAYBE, we'll have to rip
394 # the string apart and put it back together.
395 # That's going to be mighty slow.
396 $looksNormal = false;
399 # The sequence is legal!
401 } elseif( $c < "\x80" ) {
404 } elseif( $c < "\xc0" ) {
408 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
410 # Don't add if we're continuing a broken sequence;
411 # we already put a replacement character when we looked
412 # at the broken sequence.
413 $replace[] = array( '', $base +
$i, 1 );
416 # Miscellaneous freaks.
417 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
423 if( count( $replace ) ) {
424 # There were illegal UTF-8 sequences we need to fix up.
427 foreach( $replace as $rep ) {
428 list( $replacement, $start, $length ) = $rep;
429 if( $last < $start ) {
430 $out .= substr( $string, $last, $start - $last );
432 $out .= $replacement;
433 $last = $start +
$length;
435 if( $last < strlen( $string ) ) {
436 $out .= substr( $string, $last );
443 # These take a string and run the normalization on them, without
444 # checking for validity or any optimization etc. Input must be
447 * @param $string string
451 static function NFC( $string ) {
452 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
456 * @param $string string
460 static function NFD( $string ) {
461 UtfNormal
::loadData();
463 return UtfNormal
::fastCombiningSort(
464 UtfNormal
::fastDecompose( $string, self
::$utfCanonicalDecomp ) );
468 * @param $string string
472 static function NFKC( $string ) {
473 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
477 * @param $string string
481 static function NFKD( $string ) {
482 if( !isset( self
::$utfCompatibilityDecomp ) ) {
483 require_once( 'UtfNormalDataK.inc' );
485 return self
::fastCombiningSort(
486 self
::fastDecompose( $string, self
::$utfCompatibilityDecomp ) );
491 * Perform decomposition of a UTF-8 string into either D or KD form
492 * (depending on which decomposition map is passed to us).
493 * Input is assumed to be *valid* UTF-8. Invalid code will break.
495 * @param $string String: valid UTF-8 string
496 * @param $map Array: hash of expanded decomposition map
497 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
499 static function fastDecompose( $string, $map ) {
500 UtfNormal
::loadData();
501 $len = strlen( $string );
503 for( $i = 0; $i < $len; $i++
) {
507 # ASCII chars never decompose
511 } elseif( $n >= 0xf0 ) {
512 $c = substr( $string, $i, 4 );
514 } elseif( $n >= 0xe0 ) {
515 $c = substr( $string, $i, 3 );
517 } elseif( $n >= 0xc0 ) {
518 $c = substr( $string, $i, 2 );
521 if( isset( $map[$c] ) ) {
525 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
526 # Decompose a hangul syllable into jamo;
527 # hardcoded for three-byte UTF-8 sequence.
528 # A lookup table would be slightly faster,
529 # but adds a lot of memory & disk needs.
531 $index = ( (ord( $c{0} ) & 0x0f) << 12
532 |
(ord( $c{1} ) & 0x3f) << 6
533 |
(ord( $c{2} ) & 0x3f) )
534 - UNICODE_HANGUL_FIRST
;
535 $l = intval( $index / UNICODE_HANGUL_NCOUNT
);
536 $v = intval( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
537 $t = $index % UNICODE_HANGUL_TCOUNT
;
538 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
540 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
542 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
553 * Sorts combining characters into canonical order. This is the
554 * final step in creating decomposed normal forms D and KD.
556 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
557 * @return string a UTF-8 string with combining characters sorted in canonical order
559 static function fastCombiningSort( $string ) {
560 UtfNormal
::loadData();
561 $len = strlen( $string );
563 $combiners = array();
565 for( $i = 0; $i < $len; $i++
) {
570 $c = substr( $string, $i, 4 );
572 } elseif( $n >= 0xe0 ) {
573 $c = substr( $string, $i, 3 );
575 } elseif( $n >= 0xc0 ) {
576 $c = substr( $string, $i, 2 );
579 if( isset( self
::$utfCombiningClass[$c] ) ) {
580 $lastClass = self
::$utfCombiningClass[$c];
581 if( isset( $combiners[$lastClass] ) ) {
582 $combiners[$lastClass] .= $c;
584 $combiners[$lastClass] = $c;
591 $out .= implode( '', $combiners );
592 $combiners = array();
599 $out .= implode( '', $combiners );
605 * Produces canonically composed sequences, i.e. normal form C or KC.
608 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
609 * @return string a UTF-8 string with canonical precomposed characters used where possible
611 static function fastCompose( $string ) {
612 UtfNormal
::loadData();
613 $len = strlen( $string );
619 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
620 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
621 for( $i = 0; $i < $len; $i++
) {
625 # No combining characters here...
632 } elseif( $n >= 0xf0 ) {
633 $c = substr( $string, $i, 4 );
635 } elseif( $n >= 0xe0 ) {
636 $c = substr( $string, $i, 3 );
638 } elseif( $n >= 0xc0 ) {
639 $c = substr( $string, $i, 2 );
642 $pair = $startChar . $c;
644 if( isset( self
::$utfCombiningClass[$c] ) ) {
645 # A combining char; see what we can do with it
646 $class = self
::$utfCombiningClass[$c];
647 if( !empty( $startChar ) &&
648 $lastClass < $class &&
650 isset( self
::$utfCanonicalComp[$pair] ) ) {
651 $startChar = self
::$utfCanonicalComp[$pair];
662 if( $lastClass == 0 ) {
663 if( isset( self
::$utfCanonicalComp[$pair] ) ) {
664 $startChar = self
::$utfCanonicalComp[$pair];
668 if( $n >= $x1 && $n <= $x2 ) {
669 # WARNING: Hangul code is painfully slow.
670 # I apologize for this ugly, ugly code; however
671 # performance is even more teh suck if we call
672 # out to nice clean functions. Lookup tables are
673 # marginally faster, but require a lot of space.
675 if( $c >= UTF8_HANGUL_VBASE
&&
676 $c <= UTF8_HANGUL_VEND
&&
677 $startChar >= UTF8_HANGUL_LBASE
&&
678 $startChar <= UTF8_HANGUL_LEND
) {
680 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
681 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
682 $lIndex = ord( $startChar{2} ) - 0x80;
683 $vIndex = ord( $c{2} ) - 0xa1;
685 $hangulPoint = UNICODE_HANGUL_FIRST +
686 UNICODE_HANGUL_TCOUNT
*
687 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
689 # Hardcode the limited-range UTF-8 conversion:
690 $startChar = chr( $hangulPoint >> 12 & 0x0f |
0xe0 ) .
691 chr( $hangulPoint >> 6 & 0x3f |
0x80 ) .
692 chr( $hangulPoint & 0x3f |
0x80 );
695 } elseif( $c >= UTF8_HANGUL_TBASE
&&
696 $c <= UTF8_HANGUL_TEND
&&
697 $startChar >= UTF8_HANGUL_FIRST
&&
698 $startChar <= UTF8_HANGUL_LAST
&&
700 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
701 $tIndex = ord( $c{2} ) - 0xa7;
702 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 +
(0x11c0 - 0x11a7);
704 # Increment the code point by $tIndex, without
705 # the function overhead of decoding and recoding UTF-8
707 $tail = ord( $startChar{2} ) +
$tIndex;
710 $mid = ord( $startChar{1} ) +
1;
712 $startChar{0} = chr( ord( $startChar{0} ) +
1 );
715 $startChar{1} = chr( $mid );
717 $startChar{2} = chr( $tail );
719 # If there's another jamo char after this, *don't* try to merge it.
732 $out .= $startChar . $combining;
737 * This is just used for the benchmark, comparing how long it takes to
738 * interate through a string without really doing anything of substance.
739 * @param $string string
742 static function placebo( $string ) {
743 $len = strlen( $string );
745 for( $i = 0; $i < $len; $i++
) {