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';
28 * For using the ICU wrapper
30 define( 'UNORM_NONE', 1 );
31 define( 'UNORM_NFD', 2 );
32 define( 'UNORM_NFKD', 3 );
33 define( 'UNORM_NFC', 4 );
34 define( 'UNORM_DEFAULT', UNORM_NFC
);
35 define( 'UNORM_NFKC', 5 );
36 define( 'UNORM_FCD', 6 );
38 define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
39 define( 'NORMALIZE_INTL', function_exists( 'normalizer_normalize' ) );
42 * Unicode normalization routines for working with UTF-8 strings.
43 * Currently assumes that input strings are valid UTF-8!
45 * Not as fast as I'd like, but should be usable for most purposes.
46 * UtfNormal::toNFC() will bail early if given ASCII text or text
47 * it can quickly deterimine is already normalized.
49 * All functions can be called static.
51 * See description of forms at http://www.unicode.org/reports/tr15/
56 static $utfCombiningClass = null;
57 static $utfCanonicalComp = null;
58 static $utfCanonicalDecomp = null;
60 # Load compatibility decompositions on demand if they are needed.
61 static $utfCompatibilityDecomp = null;
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( NORMALIZE_ICU || NORMALIZE_INTL
) {
77 # We exclude a few chars that ICU would not.
78 $string = preg_replace(
79 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
82 $string = str_replace( UTF8_FFFE
, UTF8_REPLACEMENT
, $string );
83 $string = str_replace( UTF8_FFFF
, UTF8_REPLACEMENT
, $string );
85 # UnicodeString constructor fails if the string ends with a
86 # head byte. Add a junk char at the end, we'll strip it off.
87 if ( NORMALIZE_ICU
) return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC
), "\x01" );
88 if ( NORMALIZE_INTL
) return normalizer_normalize( $string, Normalizer
::FORM_C
);
89 } elseif( UtfNormal
::quickIsNFCVerify( $string ) ) {
90 # Side effect -- $string has had UTF-8 errors cleaned up.
93 return UtfNormal
::NFC( $string );
98 * Convert a UTF-8 string to normal form C, canonical composition.
99 * Fast return for pure ASCII strings; some lesser optimizations for
100 * strings containing only known-good characters.
102 * @param $string String: a valid UTF-8 string. Input is not validated.
103 * @return string a UTF-8 string in normal form C
105 static function toNFC( $string ) {
107 return normalizer_normalize( $string, Normalizer
::FORM_C
);
108 elseif( NORMALIZE_ICU
)
109 return utf8_normalize( $string, UNORM_NFC
);
110 elseif( UtfNormal
::quickIsNFC( $string ) )
113 return UtfNormal
::NFC( $string );
117 * Convert a UTF-8 string to normal form D, canonical decomposition.
118 * Fast return for pure ASCII strings.
120 * @param $string String: a valid UTF-8 string. Input is not validated.
121 * @return string a UTF-8 string in normal form D
123 static function toNFD( $string ) {
125 return normalizer_normalize( $string, Normalizer
::FORM_D
);
126 elseif( NORMALIZE_ICU
)
127 return utf8_normalize( $string, UNORM_NFD
);
128 elseif( preg_match( '/[\x80-\xff]/', $string ) )
129 return UtfNormal
::NFD( $string );
135 * Convert a UTF-8 string to normal form KC, compatibility composition.
136 * This may cause irreversible information loss, use judiciously.
137 * Fast return for pure ASCII strings.
139 * @param $string String: a valid UTF-8 string. Input is not validated.
140 * @return string a UTF-8 string in normal form KC
142 static function toNFKC( $string ) {
144 return normalizer_normalize( $string, Normalizer
::FORM_KC
);
145 elseif( NORMALIZE_ICU
)
146 return utf8_normalize( $string, UNORM_NFKC
);
147 elseif( preg_match( '/[\x80-\xff]/', $string ) )
148 return UtfNormal
::NFKC( $string );
154 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
155 * This may cause irreversible information loss, use judiciously.
156 * Fast return for pure ASCII strings.
158 * @param $string String: a valid UTF-8 string. Input is not validated.
159 * @return string a UTF-8 string in normal form KD
161 static function toNFKD( $string ) {
163 return normalizer_normalize( $string, Normalizer
::FORM_KD
);
164 elseif( NORMALIZE_ICU
)
165 return utf8_normalize( $string, UNORM_NFKD
);
166 elseif( preg_match( '/[\x80-\xff]/', $string ) )
167 return UtfNormal
::NFKD( $string );
173 * Load the basic composition data if necessary
176 static function loadData() {
177 if( !isset( self
::$utfCombiningClass ) ) {
178 require_once( dirname(__FILE__
) . '/UtfNormalData.inc' );
183 * Returns true if the string is _definitely_ in NFC.
184 * Returns false if not or uncertain.
185 * @param $string String: a valid UTF-8 string. Input is not validated.
188 static function quickIsNFC( $string ) {
189 # ASCII is always valid NFC!
190 # If it's pure ASCII, let it through.
191 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
193 UtfNormal
::loadData();
194 $len = strlen( $string );
195 for( $i = 0; $i < $len; $i++
) {
200 } elseif( $n >= 0xf0 ) {
201 $c = substr( $string, $i, 4 );
203 } elseif( $n >= 0xe0 ) {
204 $c = substr( $string, $i, 3 );
206 } elseif( $n >= 0xc0 ) {
207 $c = substr( $string, $i, 2 );
210 if( isset( self
::$utfCheckNFC[$c] ) ) {
211 # If it's NO or MAYBE, bail and do the slow check.
214 if( isset( self
::$utfCombiningClass[$c] ) ) {
215 # Combining character? We might have to do sorting, at least.
223 * Returns true if the string is _definitely_ in NFC.
224 * Returns false if not or uncertain.
225 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
227 static function quickIsNFCVerify( &$string ) {
228 # Screen out some characters that eg won't be allowed in XML
229 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT
, $string );
231 # ASCII is always valid NFC!
232 # If we're only ever given plain ASCII, we can avoid the overhead
233 # of initializing the decomposition tables by skipping out early.
234 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
236 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
237 if( !isset( $checkit ) ) {
238 # Load/build some scary lookup tables...
239 UtfNormal
::loadData();
241 $utfCheckOrCombining = array_merge( self
::$utfCheckNFC, self
::$utfCombiningClass );
243 # Head bytes for sequences which we should do further validity checks
244 $checkit = array_flip( array_map( 'chr',
245 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
246 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
247 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
249 # Each UTF-8 head byte is followed by a certain
250 # number of tail bytes.
251 $tailBytes = array();
252 for( $n = 0; $n < 256; $n++
) {
255 } elseif( $n < 0xe0 ) {
257 } elseif( $n < 0xf0 ) {
259 } elseif( $n < 0xf8 ) {
261 } elseif( $n < 0xfc ) {
263 } elseif( $n < 0xfe ) {
268 $tailBytes[chr($n)] = $remaining;
272 # Chop the text into pure-ASCII and non-ASCII areas;
273 # large ASCII parts can be handled much more quickly.
274 # Don't chop up Unicode areas for punctuation, though,
275 # that wastes energy.
278 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
284 foreach( $matches[1] as $str ) {
285 $chunk = strlen( $str );
287 if( $str{0} < "\x80" ) {
288 # ASCII chunk: guaranteed to be valid UTF-8
289 # and in normal form C, so skip over it.
294 # We'll have to examine the chunk byte by byte to ensure
295 # that it consists of valid UTF-8 sequences, and to see
296 # if any of them might not be normalized.
298 # Since PHP is not the fastest language on earth, some of
299 # this code is a little ugly with inner loop optimizations.
302 $len = $chunk +
1; # Counting down is faster. I'm *so* sorry.
304 for( $i = -1; --$len; ) {
305 if( $remaining = $tailBytes[$c = $str{++
$i}] ) {
307 $sequence = $head = $c;
309 # Look for the defined number of tail bytes...
310 if( --$len && ( $c = $str{++
$i} ) >= "\x80" && $c < "\xc0" ) {
311 # Legal tail bytes are nice.
315 # Premature end of string!
316 # Drop a replacement character into output to
317 # represent the invalid UTF-8 sequence.
318 $replace[] = array( UTF8_REPLACEMENT
,
319 $base +
$i +
1 - strlen( $sequence ),
320 strlen( $sequence ) );
323 # Illegal tail byte; abandon the sequence.
324 $replace[] = array( UTF8_REPLACEMENT
,
325 $base +
$i - strlen( $sequence ),
326 strlen( $sequence ) );
327 # Back up and reprocess this byte; it may itself
328 # be a legal ASCII or UTF-8 sequence head.
334 } while( --$remaining );
336 if( isset( $checkit[$head] ) ) {
337 # Do some more detailed validity checks, for
338 # invalid characters and illegal sequences.
339 if( $head == "\xed" ) {
340 # 0xed is relatively frequent in Korean, which
341 # abuts the surrogate area, so we're doing
342 # this check separately to speed things up.
344 if( $sequence >= UTF8_SURROGATE_FIRST
) {
345 # Surrogates are legal only in UTF-16 code.
346 # They are totally forbidden here in UTF-8
348 $replace[] = array( UTF8_REPLACEMENT
,
349 $base +
$i +
1 - strlen( $sequence ),
350 strlen( $sequence ) );
355 # Slower, but rarer checks...
358 # "Overlong sequences" are those that are syntactically
359 # correct but use more UTF-8 bytes than are necessary to
360 # encode a character. Naïve string comparisons can be
361 # tricked into failing to see a match for an ASCII
362 # character, for instance, which can be a security hole
363 # if blacklist checks are being used.
364 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A
)
365 ||
($n == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
366 ||
($n == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
368 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
370 ($sequence == UTF8_FFFE
)
371 ||
($sequence == UTF8_FFFF
) )
373 # Unicode has been limited to 21 bits; longer
374 # sequences are not allowed.
375 ||
($n >= 0xf0 && $sequence > UTF8_MAX
) ) {
377 $replace[] = array( UTF8_REPLACEMENT
,
378 $base +
$i +
1 - strlen( $sequence ),
379 strlen( $sequence ) );
386 if( isset( $utfCheckOrCombining[$sequence] ) ) {
387 # If it's NO or MAYBE, we'll have to rip
388 # the string apart and put it back together.
389 # That's going to be mighty slow.
390 $looksNormal = false;
393 # The sequence is legal!
395 } elseif( $c < "\x80" ) {
398 } elseif( $c < "\xc0" ) {
402 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
404 # Don't add if we're continuing a broken sequence;
405 # we already put a replacement character when we looked
406 # at the broken sequence.
407 $replace[] = array( '', $base +
$i, 1 );
410 # Miscellaneous freaks.
411 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
417 if( count( $replace ) ) {
418 # There were illegal UTF-8 sequences we need to fix up.
421 foreach( $replace as $rep ) {
422 list( $replacement, $start, $length ) = $rep;
423 if( $last < $start ) {
424 $out .= substr( $string, $last, $start - $last );
426 $out .= $replacement;
427 $last = $start +
$length;
429 if( $last < strlen( $string ) ) {
430 $out .= substr( $string, $last );
437 # These take a string and run the normalization on them, without
438 # checking for validity or any optimization etc. Input must be
441 * @param $string string
445 static function NFC( $string ) {
446 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
450 * @param $string string
454 static function NFD( $string ) {
455 UtfNormal
::loadData();
457 return UtfNormal
::fastCombiningSort(
458 UtfNormal
::fastDecompose( $string, self
::$utfCanonicalDecomp ) );
462 * @param $string string
466 static function NFKC( $string ) {
467 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
471 * @param $string string
475 static function NFKD( $string ) {
476 if( !isset( self
::$utfCompatibilityDecomp ) ) {
477 require_once( 'UtfNormalDataK.inc' );
479 return self
::fastCombiningSort(
480 self
::fastDecompose( $string, self
::$utfCompatibilityDecomp ) );
485 * Perform decomposition of a UTF-8 string into either D or KD form
486 * (depending on which decomposition map is passed to us).
487 * Input is assumed to be *valid* UTF-8. Invalid code will break.
489 * @param $string String: valid UTF-8 string
490 * @param $map Array: hash of expanded decomposition map
491 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
493 static function fastDecompose( $string, $map ) {
494 UtfNormal
::loadData();
495 $len = strlen( $string );
497 for( $i = 0; $i < $len; $i++
) {
501 # ASCII chars never decompose
505 } elseif( $n >= 0xf0 ) {
506 $c = substr( $string, $i, 4 );
508 } elseif( $n >= 0xe0 ) {
509 $c = substr( $string, $i, 3 );
511 } elseif( $n >= 0xc0 ) {
512 $c = substr( $string, $i, 2 );
515 if( isset( $map[$c] ) ) {
519 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
520 # Decompose a hangul syllable into jamo;
521 # hardcoded for three-byte UTF-8 sequence.
522 # A lookup table would be slightly faster,
523 # but adds a lot of memory & disk needs.
525 $index = ( (ord( $c{0} ) & 0x0f) << 12
526 |
(ord( $c{1} ) & 0x3f) << 6
527 |
(ord( $c{2} ) & 0x3f) )
528 - UNICODE_HANGUL_FIRST
;
529 $l = intval( $index / UNICODE_HANGUL_NCOUNT
);
530 $v = intval( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
531 $t = $index % UNICODE_HANGUL_TCOUNT
;
532 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
534 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
536 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
547 * Sorts combining characters into canonical order. This is the
548 * final step in creating decomposed normal forms D and KD.
550 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
551 * @return string a UTF-8 string with combining characters sorted in canonical order
553 static function fastCombiningSort( $string ) {
554 UtfNormal
::loadData();
555 $len = strlen( $string );
557 $combiners = array();
559 for( $i = 0; $i < $len; $i++
) {
564 $c = substr( $string, $i, 4 );
566 } elseif( $n >= 0xe0 ) {
567 $c = substr( $string, $i, 3 );
569 } elseif( $n >= 0xc0 ) {
570 $c = substr( $string, $i, 2 );
573 if( isset( self
::$utfCombiningClass[$c] ) ) {
574 $lastClass = self
::$utfCombiningClass[$c];
575 if( isset( $combiners[$lastClass] ) ) {
576 $combiners[$lastClass] .= $c;
578 $combiners[$lastClass] = $c;
585 $out .= implode( '', $combiners );
586 $combiners = array();
593 $out .= implode( '', $combiners );
599 * Produces canonically composed sequences, i.e. normal form C or KC.
602 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
603 * @return string a UTF-8 string with canonical precomposed characters used where possible
605 static function fastCompose( $string ) {
606 UtfNormal
::loadData();
607 $len = strlen( $string );
613 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
614 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
615 for( $i = 0; $i < $len; $i++
) {
619 # No combining characters here...
626 } elseif( $n >= 0xf0 ) {
627 $c = substr( $string, $i, 4 );
629 } elseif( $n >= 0xe0 ) {
630 $c = substr( $string, $i, 3 );
632 } elseif( $n >= 0xc0 ) {
633 $c = substr( $string, $i, 2 );
636 $pair = $startChar . $c;
638 if( isset( self
::$utfCombiningClass[$c] ) ) {
639 # A combining char; see what we can do with it
640 $class = self
::$utfCombiningClass[$c];
641 if( !empty( $startChar ) &&
642 $lastClass < $class &&
644 isset( self
::$utfCanonicalComp[$pair] ) ) {
645 $startChar = self
::$utfCanonicalComp[$pair];
656 if( $lastClass == 0 ) {
657 if( isset( self
::$utfCanonicalComp[$pair] ) ) {
658 $startChar = self
::$utfCanonicalComp[$pair];
662 if( $n >= $x1 && $n <= $x2 ) {
663 # WARNING: Hangul code is painfully slow.
664 # I apologize for this ugly, ugly code; however
665 # performance is even more teh suck if we call
666 # out to nice clean functions. Lookup tables are
667 # marginally faster, but require a lot of space.
669 if( $c >= UTF8_HANGUL_VBASE
&&
670 $c <= UTF8_HANGUL_VEND
&&
671 $startChar >= UTF8_HANGUL_LBASE
&&
672 $startChar <= UTF8_HANGUL_LEND
) {
674 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
675 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
676 $lIndex = ord( $startChar{2} ) - 0x80;
677 $vIndex = ord( $c{2} ) - 0xa1;
679 $hangulPoint = UNICODE_HANGUL_FIRST +
680 UNICODE_HANGUL_TCOUNT
*
681 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
683 # Hardcode the limited-range UTF-8 conversion:
684 $startChar = chr( $hangulPoint >> 12 & 0x0f |
0xe0 ) .
685 chr( $hangulPoint >> 6 & 0x3f |
0x80 ) .
686 chr( $hangulPoint & 0x3f |
0x80 );
689 } elseif( $c >= UTF8_HANGUL_TBASE
&&
690 $c <= UTF8_HANGUL_TEND
&&
691 $startChar >= UTF8_HANGUL_FIRST
&&
692 $startChar <= UTF8_HANGUL_LAST
&&
694 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
695 $tIndex = ord( $c{2} ) - 0xa7;
696 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 +
(0x11c0 - 0x11a7);
698 # Increment the code point by $tIndex, without
699 # the function overhead of decoding and recoding UTF-8
701 $tail = ord( $startChar{2} ) +
$tIndex;
704 $mid = ord( $startChar{1} ) +
1;
706 $startChar{0} = chr( ord( $startChar{0} ) +
1 );
709 $startChar{1} = chr( $mid );
711 $startChar{2} = chr( $tail );
713 # If there's another jamo char after this, *don't* try to merge it.
726 $out .= $startChar . $combining;
731 * This is just used for the benchmark, comparing how long it takes to
732 * interate through a string without really doing anything of substance.
733 * @param $string string
736 static function placebo( $string ) {
737 $len = strlen( $string );
739 for( $i = 0; $i < $len; $i++
) {