3f08cb476a91d15a0f737c2fe87a1f9b32784b6f
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 ) {
75 if( !is_string( $string ) ) {
79 # We exclude a few chars that ICU would not.
80 $string = preg_replace(
81 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
84 $string = str_replace( UTF8_FFFE
, UTF8_REPLACEMENT
, $string );
85 $string = str_replace( UTF8_FFFF
, UTF8_REPLACEMENT
, $string );
87 # UnicodeString constructor fails if the string ends with a
88 # head byte. Add a junk char at the end, we'll strip it off.
89 return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC
), "\x01" );
90 } elseif( UtfNormal
::quickIsNFCVerify( $string ) ) {
91 # Side effect -- $string has had UTF-8 errors cleaned up.
94 return UtfNormal
::NFC( $string );
99 * Convert a UTF-8 string to normal form C, canonical composition.
100 * Fast return for pure ASCII strings; some lesser optimizations for
101 * strings containing only known-good characters.
103 * @param $string String: a valid UTF-8 string. Input is not validated.
104 * @return string a UTF-8 string in normal form C
106 static function toNFC( $string ) {
108 return utf8_normalize( $string, UNORM_NFC
);
109 elseif( UtfNormal
::quickIsNFC( $string ) )
112 return UtfNormal
::NFC( $string );
116 * Convert a UTF-8 string to normal form D, canonical decomposition.
117 * Fast return for pure ASCII strings.
119 * @param $string String: a valid UTF-8 string. Input is not validated.
120 * @return string a UTF-8 string in normal form D
122 static function toNFD( $string ) {
124 return utf8_normalize( $string, UNORM_NFD
);
125 elseif( preg_match( '/[\x80-\xff]/', $string ) )
126 return UtfNormal
::NFD( $string );
132 * Convert a UTF-8 string to normal form KC, compatibility composition.
133 * This may cause irreversible information loss, use judiciously.
134 * Fast return for pure ASCII strings.
136 * @param $string String: a valid UTF-8 string. Input is not validated.
137 * @return string a UTF-8 string in normal form KC
139 static function toNFKC( $string ) {
141 return utf8_normalize( $string, UNORM_NFKC
);
142 elseif( preg_match( '/[\x80-\xff]/', $string ) )
143 return UtfNormal
::NFKC( $string );
149 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
150 * This may cause irreversible information loss, use judiciously.
151 * Fast return for pure ASCII strings.
153 * @param $string String: a valid UTF-8 string. Input is not validated.
154 * @return string a UTF-8 string in normal form KD
156 static function toNFKD( $string ) {
158 return utf8_normalize( $string, UNORM_NFKD
);
159 elseif( preg_match( '/[\x80-\xff]/', $string ) )
160 return UtfNormal
::NFKD( $string );
166 * Load the basic composition data if necessary
169 static function loadData() {
170 global $utfCombiningClass;
171 if( !isset( $utfCombiningClass ) ) {
172 require_once( dirname(__FILE__
) . '/UtfNormalData.inc' );
177 * Returns true if the string is _definitely_ in NFC.
178 * Returns false if not or uncertain.
179 * @param $string String: a valid UTF-8 string. Input is not validated.
182 static function quickIsNFC( $string ) {
183 # ASCII is always valid NFC!
184 # If it's pure ASCII, let it through.
185 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
187 UtfNormal
::loadData();
188 global $utfCheckNFC, $utfCombiningClass;
189 $len = strlen( $string );
190 for( $i = 0; $i < $len; $i++
) {
195 } elseif( $n >= 0xf0 ) {
196 $c = substr( $string, $i, 4 );
198 } elseif( $n >= 0xe0 ) {
199 $c = substr( $string, $i, 3 );
201 } elseif( $n >= 0xc0 ) {
202 $c = substr( $string, $i, 2 );
205 if( isset( $utfCheckNFC[$c] ) ) {
206 # If it's NO or MAYBE, bail and do the slow check.
209 if( isset( $utfCombiningClass[$c] ) ) {
210 # Combining character? We might have to do sorting, at least.
218 * Returns true if the string is _definitely_ in NFC.
219 * Returns false if not or uncertain.
220 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
222 static function quickIsNFCVerify( &$string ) {
223 # Screen out some characters that eg won't be allowed in XML
224 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT
, $string );
226 # ASCII is always valid NFC!
227 # If we're only ever given plain ASCII, we can avoid the overhead
228 # of initializing the decomposition tables by skipping out early.
229 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
231 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
232 if( !isset( $checkit ) ) {
233 # Load/build some scary lookup tables...
234 UtfNormal
::loadData();
235 global $utfCheckNFC, $utfCombiningClass;
237 $utfCheckOrCombining = array_merge( $utfCheckNFC, $utfCombiningClass );
239 # Head bytes for sequences which we should do further validity checks
240 $checkit = array_flip( array_map( 'chr',
241 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
242 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
243 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
245 # Each UTF-8 head byte is followed by a certain
246 # number of tail bytes.
247 $tailBytes = array();
248 for( $n = 0; $n < 256; $n++
) {
251 } elseif( $n < 0xe0 ) {
253 } elseif( $n < 0xf0 ) {
255 } elseif( $n < 0xf8 ) {
257 } elseif( $n < 0xfc ) {
259 } elseif( $n < 0xfe ) {
264 $tailBytes[chr($n)] = $remaining;
268 # Chop the text into pure-ASCII and non-ASCII areas;
269 # large ASCII parts can be handled much more quickly.
270 # Don't chop up Unicode areas for punctuation, though,
271 # that wastes energy.
274 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
280 foreach( $matches[1] as $str ) {
281 $chunk = strlen( $str );
283 if( $str{0} < "\x80" ) {
284 # ASCII chunk: guaranteed to be valid UTF-8
285 # and in normal form C, so skip over it.
290 # We'll have to examine the chunk byte by byte to ensure
291 # that it consists of valid UTF-8 sequences, and to see
292 # if any of them might not be normalized.
294 # Since PHP is not the fastest language on earth, some of
295 # this code is a little ugly with inner loop optimizations.
298 $len = $chunk +
1; # Counting down is faster. I'm *so* sorry.
300 for( $i = -1; --$len; ) {
301 if( $remaining = $tailBytes[$c = $str{++
$i}] ) {
303 $sequence = $head = $c;
305 # Look for the defined number of tail bytes...
306 if( --$len && ( $c = $str{++
$i} ) >= "\x80" && $c < "\xc0" ) {
307 # Legal tail bytes are nice.
311 # Premature end of string!
312 # Drop a replacement character into output to
313 # represent the invalid UTF-8 sequence.
314 $replace[] = array( UTF8_REPLACEMENT
,
315 $base +
$i +
1 - strlen( $sequence ),
316 strlen( $sequence ) );
319 # Illegal tail byte; abandon the sequence.
320 $replace[] = array( UTF8_REPLACEMENT
,
321 $base +
$i - strlen( $sequence ),
322 strlen( $sequence ) );
323 # Back up and reprocess this byte; it may itself
324 # be a legal ASCII or UTF-8 sequence head.
330 } while( --$remaining );
332 if( isset( $checkit[$head] ) ) {
333 # Do some more detailed validity checks, for
334 # invalid characters and illegal sequences.
335 if( $head == "\xed" ) {
336 # 0xed is relatively frequent in Korean, which
337 # abuts the surrogate area, so we're doing
338 # this check separately to speed things up.
340 if( $sequence >= UTF8_SURROGATE_FIRST
) {
341 # Surrogates are legal only in UTF-16 code.
342 # They are totally forbidden here in UTF-8
344 $replace[] = array( UTF8_REPLACEMENT
,
345 $base +
$i +
1 - strlen( $sequence ),
346 strlen( $sequence ) );
351 # Slower, but rarer checks...
354 # "Overlong sequences" are those that are syntactically
355 # correct but use more UTF-8 bytes than are necessary to
356 # encode a character. Naïve string comparisons can be
357 # tricked into failing to see a match for an ASCII
358 # character, for instance, which can be a security hole
359 # if blacklist checks are being used.
360 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A
)
361 ||
($n == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
362 ||
($n == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
364 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
366 ($sequence == UTF8_FFFE
)
367 ||
($sequence == UTF8_FFFF
) )
369 # Unicode has been limited to 21 bits; longer
370 # sequences are not allowed.
371 ||
($n >= 0xf0 && $sequence > UTF8_MAX
) ) {
373 $replace[] = array( UTF8_REPLACEMENT
,
374 $base +
$i +
1 - strlen( $sequence ),
375 strlen( $sequence ) );
382 if( isset( $utfCheckOrCombining[$sequence] ) ) {
383 # If it's NO or MAYBE, we'll have to rip
384 # the string apart and put it back together.
385 # That's going to be mighty slow.
386 $looksNormal = false;
389 # The sequence is legal!
391 } elseif( $c < "\x80" ) {
394 } elseif( $c < "\xc0" ) {
398 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
400 # Don't add if we're continuing a broken sequence;
401 # we already put a replacement character when we looked
402 # at the broken sequence.
403 $replace[] = array( '', $base +
$i, 1 );
406 # Miscellaneous freaks.
407 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
413 if( count( $replace ) ) {
414 # There were illegal UTF-8 sequences we need to fix up.
417 foreach( $replace as $rep ) {
418 list( $replacement, $start, $length ) = $rep;
419 if( $last < $start ) {
420 $out .= substr( $string, $last, $start - $last );
422 $out .= $replacement;
423 $last = $start +
$length;
425 if( $last < strlen( $string ) ) {
426 $out .= substr( $string, $last );
433 # These take a string and run the normalization on them, without
434 # checking for validity or any optimization etc. Input must be
437 * @param $string string
441 static function NFC( $string ) {
442 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
446 * @param $string string
450 static function NFD( $string ) {
451 UtfNormal
::loadData();
452 global $utfCanonicalDecomp;
453 return UtfNormal
::fastCombiningSort(
454 UtfNormal
::fastDecompose( $string, $utfCanonicalDecomp ) );
458 * @param $string string
462 static function NFKC( $string ) {
463 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
467 * @param $string string
471 static function NFKD( $string ) {
472 global $utfCompatibilityDecomp;
473 if( !isset( $utfCompatibilityDecomp ) ) {
474 require_once( 'UtfNormalDataK.inc' );
476 return UtfNormal
::fastCombiningSort(
477 UtfNormal
::fastDecompose( $string, $utfCompatibilityDecomp ) );
482 * Perform decomposition of a UTF-8 string into either D or KD form
483 * (depending on which decomposition map is passed to us).
484 * Input is assumed to be *valid* UTF-8. Invalid code will break.
486 * @param $string String: valid UTF-8 string
487 * @param $map Array: hash of expanded decomposition map
488 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
490 static function fastDecompose( $string, $map ) {
491 UtfNormal
::loadData();
492 $len = strlen( $string );
494 for( $i = 0; $i < $len; $i++
) {
498 # ASCII chars never decompose
502 } elseif( $n >= 0xf0 ) {
503 $c = substr( $string, $i, 4 );
505 } elseif( $n >= 0xe0 ) {
506 $c = substr( $string, $i, 3 );
508 } elseif( $n >= 0xc0 ) {
509 $c = substr( $string, $i, 2 );
512 if( isset( $map[$c] ) ) {
516 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
517 # Decompose a hangul syllable into jamo;
518 # hardcoded for three-byte UTF-8 sequence.
519 # A lookup table would be slightly faster,
520 # but adds a lot of memory & disk needs.
522 $index = ( (ord( $c{0} ) & 0x0f) << 12
523 |
(ord( $c{1} ) & 0x3f) << 6
524 |
(ord( $c{2} ) & 0x3f) )
525 - UNICODE_HANGUL_FIRST
;
526 $l = intval( $index / UNICODE_HANGUL_NCOUNT
);
527 $v = intval( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
528 $t = $index % UNICODE_HANGUL_TCOUNT
;
529 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
531 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
533 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
544 * Sorts combining characters into canonical order. This is the
545 * final step in creating decomposed normal forms D and KD.
547 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
548 * @return string a UTF-8 string with combining characters sorted in canonical order
550 static function fastCombiningSort( $string ) {
551 UtfNormal
::loadData();
552 global $utfCombiningClass;
553 $len = strlen( $string );
555 $combiners = array();
557 for( $i = 0; $i < $len; $i++
) {
562 $c = substr( $string, $i, 4 );
564 } elseif( $n >= 0xe0 ) {
565 $c = substr( $string, $i, 3 );
567 } elseif( $n >= 0xc0 ) {
568 $c = substr( $string, $i, 2 );
571 if( isset( $utfCombiningClass[$c] ) ) {
572 $lastClass = $utfCombiningClass[$c];
573 if( isset( $combiners[$lastClass] ) ) {
574 $combiners[$lastClass] .= $c;
576 $combiners[$lastClass] = $c;
583 $out .= implode( '', $combiners );
584 $combiners = array();
591 $out .= implode( '', $combiners );
597 * Produces canonically composed sequences, i.e. normal form C or KC.
600 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
601 * @return string a UTF-8 string with canonical precomposed characters used where possible
603 static function fastCompose( $string ) {
604 UtfNormal
::loadData();
605 global $utfCanonicalComp, $utfCombiningClass;
606 $len = strlen( $string );
612 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
613 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
614 for( $i = 0; $i < $len; $i++
) {
618 # No combining characters here...
625 } elseif( $n >= 0xf0 ) {
626 $c = substr( $string, $i, 4 );
628 } elseif( $n >= 0xe0 ) {
629 $c = substr( $string, $i, 3 );
631 } elseif( $n >= 0xc0 ) {
632 $c = substr( $string, $i, 2 );
635 $pair = $startChar . $c;
637 if( isset( $utfCombiningClass[$c] ) ) {
638 # A combining char; see what we can do with it
639 $class = $utfCombiningClass[$c];
640 if( !empty( $startChar ) &&
641 $lastClass < $class &&
643 isset( $utfCanonicalComp[$pair] ) ) {
644 $startChar = $utfCanonicalComp[$pair];
655 if( $lastClass == 0 ) {
656 if( isset( $utfCanonicalComp[$pair] ) ) {
657 $startChar = $utfCanonicalComp[$pair];
661 if( $n >= $x1 && $n <= $x2 ) {
662 # WARNING: Hangul code is painfully slow.
663 # I apologize for this ugly, ugly code; however
664 # performance is even more teh suck if we call
665 # out to nice clean functions. Lookup tables are
666 # marginally faster, but require a lot of space.
668 if( $c >= UTF8_HANGUL_VBASE
&&
669 $c <= UTF8_HANGUL_VEND
&&
670 $startChar >= UTF8_HANGUL_LBASE
&&
671 $startChar <= UTF8_HANGUL_LEND
) {
673 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
674 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
675 $lIndex = ord( $startChar{2} ) - 0x80;
676 $vIndex = ord( $c{2} ) - 0xa1;
678 $hangulPoint = UNICODE_HANGUL_FIRST +
679 UNICODE_HANGUL_TCOUNT
*
680 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
682 # Hardcode the limited-range UTF-8 conversion:
683 $startChar = chr( $hangulPoint >> 12 & 0x0f |
0xe0 ) .
684 chr( $hangulPoint >> 6 & 0x3f |
0x80 ) .
685 chr( $hangulPoint & 0x3f |
0x80 );
688 } elseif( $c >= UTF8_HANGUL_TBASE
&&
689 $c <= UTF8_HANGUL_TEND
&&
690 $startChar >= UTF8_HANGUL_FIRST
&&
691 $startChar <= UTF8_HANGUL_LAST
&&
693 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
694 $tIndex = ord( $c{2} ) - 0xa7;
695 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 +
(0x11c0 - 0x11a7);
697 # Increment the code point by $tIndex, without
698 # the function overhead of decoding and recoding UTF-8
700 $tail = ord( $startChar{2} ) +
$tIndex;
703 $mid = ord( $startChar{1} ) +
1;
705 $startChar{0} = chr( ord( $startChar{0} ) +
1 );
708 $startChar{1} = chr( $mid );
710 $startChar{2} = chr( $tail );
712 # If there's another jamo char after this, *don't* try to merge it.
725 $out .= $startChar . $combining;
730 * This is just used for the benchmark, comparing how long it takes to
731 * interate through a string without really doing anything of substance.
732 * @param $string string
735 static function placebo( $string ) {
736 $len = strlen( $string );
738 for( $i = 0; $i < $len; $i++
) {