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' ) );
48 define( 'NORMALIZE_INTL', function_exists( 'normalizer_normalize' ) );
51 * Unicode normalization routines for working with UTF-8 strings.
52 * Currently assumes that input strings are valid UTF-8!
54 * Not as fast as I'd like, but should be usable for most purposes.
55 * UtfNormal::toNFC() will bail early if given ASCII text or text
56 * it can quickly deterimine is already normalized.
58 * All functions can be called static.
60 * See description of forms at http://www.unicode.org/reports/tr15/
66 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
67 * and convert to normal form C, canonical composition.
69 * Fast return for pure ASCII strings; some lesser optimizations for
70 * strings containing only known-good characters. Not as fast as toNFC().
72 * @param $string String: a UTF-8 string
73 * @return string a clean, shiny, normalized UTF-8 string
75 static function cleanUp( $string ) {
76 if( extension_loaded( 'iconv' ) ) {
78 $ret = iconv( "UTF-8","UTF-8//IGNORE", $string );
83 if( NORMALIZE_ICU || NORMALIZE_INTL
) {
84 # We exclude a few chars that ICU would not.
85 $string = preg_replace(
86 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
89 $string = str_replace( UTF8_FFFE
, UTF8_REPLACEMENT
, $string );
90 $string = str_replace( UTF8_FFFF
, UTF8_REPLACEMENT
, $string );
92 # UnicodeString constructor fails if the string ends with a
93 # head byte. Add a junk char at the end, we'll strip it off.
94 if ( NORMALIZE_ICU
) return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC
), "\x01" );
95 if ( NORMALIZE_INTL
) return normalizer_normalize( $string, Normalizer
::FORM_C
);
96 } elseif( UtfNormal
::quickIsNFCVerify( $string ) ) {
97 # Side effect -- $string has had UTF-8 errors cleaned up.
100 return UtfNormal
::NFC( $string );
105 * Convert a UTF-8 string to normal form C, canonical composition.
106 * Fast return for pure ASCII strings; some lesser optimizations for
107 * strings containing only known-good characters.
109 * @param $string String: a valid UTF-8 string. Input is not validated.
110 * @return string a UTF-8 string in normal form C
112 static function toNFC( $string ) {
114 return normalizer_normalize( $string, Normalizer
::FORM_C
);
115 elseif( NORMALIZE_ICU
)
116 return utf8_normalize( $string, UNORM_NFC
);
117 elseif( UtfNormal
::quickIsNFC( $string ) )
120 return UtfNormal
::NFC( $string );
124 * Convert a UTF-8 string to normal form D, canonical decomposition.
125 * Fast return for pure ASCII strings.
127 * @param $string String: a valid UTF-8 string. Input is not validated.
128 * @return string a UTF-8 string in normal form D
130 static function toNFD( $string ) {
132 return normalizer_normalize( $string, Normalizer
::FORM_D
);
133 elseif( NORMALIZE_ICU
)
134 return utf8_normalize( $string, UNORM_NFD
);
135 elseif( preg_match( '/[\x80-\xff]/', $string ) )
136 return UtfNormal
::NFD( $string );
142 * Convert a UTF-8 string to normal form KC, compatibility composition.
143 * This may cause irreversible information loss, use judiciously.
144 * Fast return for pure ASCII strings.
146 * @param $string String: a valid UTF-8 string. Input is not validated.
147 * @return string a UTF-8 string in normal form KC
149 static function toNFKC( $string ) {
151 return normalizer_normalize( $string, Normalizer
::FORM_KC
);
152 elseif( NORMALIZE_ICU
)
153 return utf8_normalize( $string, UNORM_NFKC
);
154 elseif( preg_match( '/[\x80-\xff]/', $string ) )
155 return UtfNormal
::NFKC( $string );
161 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
162 * This may cause irreversible information loss, use judiciously.
163 * Fast return for pure ASCII strings.
165 * @param $string String: a valid UTF-8 string. Input is not validated.
166 * @return string a UTF-8 string in normal form KD
168 static function toNFKD( $string ) {
170 return normalizer_normalize( $string, Normalizer
::FORM_KD
);
171 elseif( NORMALIZE_ICU
)
172 return utf8_normalize( $string, UNORM_NFKD
);
173 elseif( preg_match( '/[\x80-\xff]/', $string ) )
174 return UtfNormal
::NFKD( $string );
180 * Load the basic composition data if necessary
183 static function loadData() {
184 global $utfCombiningClass;
185 if( !isset( $utfCombiningClass ) ) {
186 require_once( dirname(__FILE__
) . '/UtfNormalData.inc' );
191 * Returns true if the string is _definitely_ in NFC.
192 * Returns false if not or uncertain.
193 * @param $string String: a valid UTF-8 string. Input is not validated.
196 static function quickIsNFC( $string ) {
197 # ASCII is always valid NFC!
198 # If it's pure ASCII, let it through.
199 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
201 UtfNormal
::loadData();
202 global $utfCheckNFC, $utfCombiningClass;
203 $len = strlen( $string );
204 for( $i = 0; $i < $len; $i++
) {
209 } elseif( $n >= 0xf0 ) {
210 $c = substr( $string, $i, 4 );
212 } elseif( $n >= 0xe0 ) {
213 $c = substr( $string, $i, 3 );
215 } elseif( $n >= 0xc0 ) {
216 $c = substr( $string, $i, 2 );
219 if( isset( $utfCheckNFC[$c] ) ) {
220 # If it's NO or MAYBE, bail and do the slow check.
223 if( isset( $utfCombiningClass[$c] ) ) {
224 # Combining character? We might have to do sorting, at least.
232 * Returns true if the string is _definitely_ in NFC.
233 * Returns false if not or uncertain.
234 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
236 static function quickIsNFCVerify( &$string ) {
237 # Screen out some characters that eg won't be allowed in XML
238 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT
, $string );
240 # ASCII is always valid NFC!
241 # If we're only ever given plain ASCII, we can avoid the overhead
242 # of initializing the decomposition tables by skipping out early.
243 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
245 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
246 if( !isset( $checkit ) ) {
247 # Load/build some scary lookup tables...
248 UtfNormal
::loadData();
249 global $utfCheckNFC, $utfCombiningClass;
251 $utfCheckOrCombining = array_merge( $utfCheckNFC, $utfCombiningClass );
253 # Head bytes for sequences which we should do further validity checks
254 $checkit = array_flip( array_map( 'chr',
255 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
256 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
257 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
259 # Each UTF-8 head byte is followed by a certain
260 # number of tail bytes.
261 $tailBytes = array();
262 for( $n = 0; $n < 256; $n++
) {
265 } elseif( $n < 0xe0 ) {
267 } elseif( $n < 0xf0 ) {
269 } elseif( $n < 0xf8 ) {
271 } elseif( $n < 0xfc ) {
273 } elseif( $n < 0xfe ) {
278 $tailBytes[chr($n)] = $remaining;
282 # Chop the text into pure-ASCII and non-ASCII areas;
283 # large ASCII parts can be handled much more quickly.
284 # Don't chop up Unicode areas for punctuation, though,
285 # that wastes energy.
288 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
294 foreach( $matches[1] as $str ) {
295 $chunk = strlen( $str );
297 if( $str{0} < "\x80" ) {
298 # ASCII chunk: guaranteed to be valid UTF-8
299 # and in normal form C, so skip over it.
304 # We'll have to examine the chunk byte by byte to ensure
305 # that it consists of valid UTF-8 sequences, and to see
306 # if any of them might not be normalized.
308 # Since PHP is not the fastest language on earth, some of
309 # this code is a little ugly with inner loop optimizations.
312 $len = $chunk +
1; # Counting down is faster. I'm *so* sorry.
314 for( $i = -1; --$len; ) {
315 if( $remaining = $tailBytes[$c = $str{++
$i}] ) {
317 $sequence = $head = $c;
319 # Look for the defined number of tail bytes...
320 if( --$len && ( $c = $str{++
$i} ) >= "\x80" && $c < "\xc0" ) {
321 # Legal tail bytes are nice.
325 # Premature end of string!
326 # Drop a replacement character into output to
327 # represent the invalid UTF-8 sequence.
328 $replace[] = array( UTF8_REPLACEMENT
,
329 $base +
$i +
1 - strlen( $sequence ),
330 strlen( $sequence ) );
333 # Illegal tail byte; abandon the sequence.
334 $replace[] = array( UTF8_REPLACEMENT
,
335 $base +
$i - strlen( $sequence ),
336 strlen( $sequence ) );
337 # Back up and reprocess this byte; it may itself
338 # be a legal ASCII or UTF-8 sequence head.
344 } while( --$remaining );
346 if( isset( $checkit[$head] ) ) {
347 # Do some more detailed validity checks, for
348 # invalid characters and illegal sequences.
349 if( $head == "\xed" ) {
350 # 0xed is relatively frequent in Korean, which
351 # abuts the surrogate area, so we're doing
352 # this check separately to speed things up.
354 if( $sequence >= UTF8_SURROGATE_FIRST
) {
355 # Surrogates are legal only in UTF-16 code.
356 # They are totally forbidden here in UTF-8
358 $replace[] = array( UTF8_REPLACEMENT
,
359 $base +
$i +
1 - strlen( $sequence ),
360 strlen( $sequence ) );
365 # Slower, but rarer checks...
368 # "Overlong sequences" are those that are syntactically
369 # correct but use more UTF-8 bytes than are necessary to
370 # encode a character. Naïve string comparisons can be
371 # tricked into failing to see a match for an ASCII
372 # character, for instance, which can be a security hole
373 # if blacklist checks are being used.
374 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A
)
375 ||
($n == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
376 ||
($n == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
378 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
380 ($sequence == UTF8_FFFE
)
381 ||
($sequence == UTF8_FFFF
) )
383 # Unicode has been limited to 21 bits; longer
384 # sequences are not allowed.
385 ||
($n >= 0xf0 && $sequence > UTF8_MAX
) ) {
387 $replace[] = array( UTF8_REPLACEMENT
,
388 $base +
$i +
1 - strlen( $sequence ),
389 strlen( $sequence ) );
396 if( isset( $utfCheckOrCombining[$sequence] ) ) {
397 # If it's NO or MAYBE, we'll have to rip
398 # the string apart and put it back together.
399 # That's going to be mighty slow.
400 $looksNormal = false;
403 # The sequence is legal!
405 } elseif( $c < "\x80" ) {
408 } elseif( $c < "\xc0" ) {
412 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
414 # Don't add if we're continuing a broken sequence;
415 # we already put a replacement character when we looked
416 # at the broken sequence.
417 $replace[] = array( '', $base +
$i, 1 );
420 # Miscellaneous freaks.
421 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
427 if( count( $replace ) ) {
428 # There were illegal UTF-8 sequences we need to fix up.
431 foreach( $replace as $rep ) {
432 list( $replacement, $start, $length ) = $rep;
433 if( $last < $start ) {
434 $out .= substr( $string, $last, $start - $last );
436 $out .= $replacement;
437 $last = $start +
$length;
439 if( $last < strlen( $string ) ) {
440 $out .= substr( $string, $last );
447 # These take a string and run the normalization on them, without
448 # checking for validity or any optimization etc. Input must be
451 * @param $string string
455 static function NFC( $string ) {
456 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
460 * @param $string string
464 static function NFD( $string ) {
465 UtfNormal
::loadData();
466 global $utfCanonicalDecomp;
467 return UtfNormal
::fastCombiningSort(
468 UtfNormal
::fastDecompose( $string, $utfCanonicalDecomp ) );
472 * @param $string string
476 static function NFKC( $string ) {
477 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
481 * @param $string string
485 static function NFKD( $string ) {
486 global $utfCompatibilityDecomp;
487 if( !isset( $utfCompatibilityDecomp ) ) {
488 require_once( 'UtfNormalDataK.inc' );
490 return UtfNormal
::fastCombiningSort(
491 UtfNormal
::fastDecompose( $string, $utfCompatibilityDecomp ) );
496 * Perform decomposition of a UTF-8 string into either D or KD form
497 * (depending on which decomposition map is passed to us).
498 * Input is assumed to be *valid* UTF-8. Invalid code will break.
500 * @param $string String: valid UTF-8 string
501 * @param $map Array: hash of expanded decomposition map
502 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
504 static function fastDecompose( $string, $map ) {
505 UtfNormal
::loadData();
506 $len = strlen( $string );
508 for( $i = 0; $i < $len; $i++
) {
512 # ASCII chars never decompose
516 } elseif( $n >= 0xf0 ) {
517 $c = substr( $string, $i, 4 );
519 } elseif( $n >= 0xe0 ) {
520 $c = substr( $string, $i, 3 );
522 } elseif( $n >= 0xc0 ) {
523 $c = substr( $string, $i, 2 );
526 if( isset( $map[$c] ) ) {
530 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
531 # Decompose a hangul syllable into jamo;
532 # hardcoded for three-byte UTF-8 sequence.
533 # A lookup table would be slightly faster,
534 # but adds a lot of memory & disk needs.
536 $index = ( (ord( $c{0} ) & 0x0f) << 12
537 |
(ord( $c{1} ) & 0x3f) << 6
538 |
(ord( $c{2} ) & 0x3f) )
539 - UNICODE_HANGUL_FIRST
;
540 $l = intval( $index / UNICODE_HANGUL_NCOUNT
);
541 $v = intval( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
542 $t = $index % UNICODE_HANGUL_TCOUNT
;
543 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
545 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
547 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
558 * Sorts combining characters into canonical order. This is the
559 * final step in creating decomposed normal forms D and KD.
561 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
562 * @return string a UTF-8 string with combining characters sorted in canonical order
564 static function fastCombiningSort( $string ) {
565 UtfNormal
::loadData();
566 global $utfCombiningClass;
567 $len = strlen( $string );
569 $combiners = array();
571 for( $i = 0; $i < $len; $i++
) {
576 $c = substr( $string, $i, 4 );
578 } elseif( $n >= 0xe0 ) {
579 $c = substr( $string, $i, 3 );
581 } elseif( $n >= 0xc0 ) {
582 $c = substr( $string, $i, 2 );
585 if( isset( $utfCombiningClass[$c] ) ) {
586 $lastClass = $utfCombiningClass[$c];
587 if( isset( $combiners[$lastClass] ) ) {
588 $combiners[$lastClass] .= $c;
590 $combiners[$lastClass] = $c;
597 $out .= implode( '', $combiners );
598 $combiners = array();
605 $out .= implode( '', $combiners );
611 * Produces canonically composed sequences, i.e. normal form C or KC.
614 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
615 * @return string a UTF-8 string with canonical precomposed characters used where possible
617 static function fastCompose( $string ) {
618 UtfNormal
::loadData();
619 global $utfCanonicalComp, $utfCombiningClass;
620 $len = strlen( $string );
626 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
627 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
628 for( $i = 0; $i < $len; $i++
) {
632 # No combining characters here...
639 } elseif( $n >= 0xf0 ) {
640 $c = substr( $string, $i, 4 );
642 } elseif( $n >= 0xe0 ) {
643 $c = substr( $string, $i, 3 );
645 } elseif( $n >= 0xc0 ) {
646 $c = substr( $string, $i, 2 );
649 $pair = $startChar . $c;
651 if( isset( $utfCombiningClass[$c] ) ) {
652 # A combining char; see what we can do with it
653 $class = $utfCombiningClass[$c];
654 if( !empty( $startChar ) &&
655 $lastClass < $class &&
657 isset( $utfCanonicalComp[$pair] ) ) {
658 $startChar = $utfCanonicalComp[$pair];
669 if( $lastClass == 0 ) {
670 if( isset( $utfCanonicalComp[$pair] ) ) {
671 $startChar = $utfCanonicalComp[$pair];
675 if( $n >= $x1 && $n <= $x2 ) {
676 # WARNING: Hangul code is painfully slow.
677 # I apologize for this ugly, ugly code; however
678 # performance is even more teh suck if we call
679 # out to nice clean functions. Lookup tables are
680 # marginally faster, but require a lot of space.
682 if( $c >= UTF8_HANGUL_VBASE
&&
683 $c <= UTF8_HANGUL_VEND
&&
684 $startChar >= UTF8_HANGUL_LBASE
&&
685 $startChar <= UTF8_HANGUL_LEND
) {
687 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
688 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
689 $lIndex = ord( $startChar{2} ) - 0x80;
690 $vIndex = ord( $c{2} ) - 0xa1;
692 $hangulPoint = UNICODE_HANGUL_FIRST +
693 UNICODE_HANGUL_TCOUNT
*
694 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
696 # Hardcode the limited-range UTF-8 conversion:
697 $startChar = chr( $hangulPoint >> 12 & 0x0f |
0xe0 ) .
698 chr( $hangulPoint >> 6 & 0x3f |
0x80 ) .
699 chr( $hangulPoint & 0x3f |
0x80 );
702 } elseif( $c >= UTF8_HANGUL_TBASE
&&
703 $c <= UTF8_HANGUL_TEND
&&
704 $startChar >= UTF8_HANGUL_FIRST
&&
705 $startChar <= UTF8_HANGUL_LAST
&&
707 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
708 $tIndex = ord( $c{2} ) - 0xa7;
709 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 +
(0x11c0 - 0x11a7);
711 # Increment the code point by $tIndex, without
712 # the function overhead of decoding and recoding UTF-8
714 $tail = ord( $startChar{2} ) +
$tIndex;
717 $mid = ord( $startChar{1} ) +
1;
719 $startChar{0} = chr( ord( $startChar{0} ) +
1 );
722 $startChar{1} = chr( $mid );
724 $startChar{2} = chr( $tail );
726 # If there's another jamo char after this, *don't* try to merge it.
739 $out .= $startChar . $combining;
744 * This is just used for the benchmark, comparing how long it takes to
745 * interate through a string without really doing anything of substance.
746 * @param $string string
749 static function placebo( $string ) {
750 $len = strlen( $string );
752 for( $i = 0; $i < $len; $i++
) {