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 require_once dirname(__FILE__
).'/UtfNormalUtil.php';
23 global $utfCombiningClass, $utfCanonicalComp, $utfCanonicalDecomp;
24 $utfCombiningClass = NULL;
25 $utfCanonicalComp = NULL;
26 $utfCanonicalDecomp = NULL;
28 # Load compatibility decompositions on demand if they are needed.
29 global $utfCompatibilityDecomp;
30 $utfCompatibilityDecomp = NULL;
33 * For using the ICU wrapper
35 define( 'UNORM_NONE', 1 );
36 define( 'UNORM_NFD', 2 );
37 define( 'UNORM_NFKD', 3 );
38 define( 'UNORM_NFC', 4 );
39 define( 'UNORM_DEFAULT', UNORM_NFC
);
40 define( 'UNORM_NFKC', 5 );
41 define( 'UNORM_FCD', 6 );
43 define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
46 * Unicode normalization routines for working with UTF-8 strings.
47 * Currently assumes that input strings are valid UTF-8!
49 * Not as fast as I'd like, but should be usable for most purposes.
50 * UtfNormal::toNFC() will bail early if given ASCII text or text
51 * it can quickly deterimine is already normalized.
53 * All functions can be called static.
55 * See description of forms at http://www.unicode.org/reports/tr15/
57 * @addtogroup UtfNormal
61 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
62 * and convert to normal form C, canonical composition.
64 * Fast return for pure ASCII strings; some lesser optimizations for
65 * strings containing only known-good characters. Not as fast as toNFC().
67 * @param string $string a UTF-8 string
68 * @return string a clean, shiny, normalized UTF-8 string
71 static function cleanUp( $string ) {
73 # We exclude a few chars that ICU would not.
74 $string = preg_replace(
75 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
78 $string = str_replace( UTF8_FFFE
, UTF8_REPLACEMENT
, $string );
79 $string = str_replace( UTF8_FFFF
, UTF8_REPLACEMENT
, $string );
81 # UnicodeString constructor fails if the string ends with a
82 # head byte. Add a junk char at the end, we'll strip it off.
83 return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC
), "\x01" );
84 } elseif( UtfNormal
::quickIsNFCVerify( $string ) ) {
85 # Side effect -- $string has had UTF-8 errors cleaned up.
88 return UtfNormal
::NFC( $string );
93 * Convert a UTF-8 string to normal form C, canonical composition.
94 * Fast return for pure ASCII strings; some lesser optimizations for
95 * strings containing only known-good characters.
97 * @param string $string a valid UTF-8 string. Input is not validated.
98 * @return string a UTF-8 string in normal form C
101 static function toNFC( $string ) {
103 return utf8_normalize( $string, UNORM_NFC
);
104 elseif( UtfNormal
::quickIsNFC( $string ) )
107 return UtfNormal
::NFC( $string );
111 * Convert a UTF-8 string to normal form D, canonical decomposition.
112 * Fast return for pure ASCII strings.
114 * @param string $string a valid UTF-8 string. Input is not validated.
115 * @return string a UTF-8 string in normal form D
118 static function toNFD( $string ) {
120 return utf8_normalize( $string, UNORM_NFD
);
121 elseif( preg_match( '/[\x80-\xff]/', $string ) )
122 return UtfNormal
::NFD( $string );
128 * Convert a UTF-8 string to normal form KC, compatibility composition.
129 * This may cause irreversible information loss, use judiciously.
130 * Fast return for pure ASCII strings.
132 * @param string $string a valid UTF-8 string. Input is not validated.
133 * @return string a UTF-8 string in normal form KC
136 static function toNFKC( $string ) {
138 return utf8_normalize( $string, UNORM_NFKC
);
139 elseif( preg_match( '/[\x80-\xff]/', $string ) )
140 return UtfNormal
::NFKC( $string );
146 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
147 * This may cause irreversible information loss, use judiciously.
148 * Fast return for pure ASCII strings.
150 * @param string $string a valid UTF-8 string. Input is not validated.
151 * @return string a UTF-8 string in normal form KD
154 static function toNFKD( $string ) {
156 return utf8_normalize( $string, UNORM_NFKD
);
157 elseif( preg_match( '/[\x80-\xff]/', $string ) )
158 return UtfNormal
::NFKD( $string );
164 * Load the basic composition data if necessary
168 static function loadData() {
169 global $utfCombiningClass;
170 if( !isset( $utfCombiningClass ) ) {
171 require_once( dirname(__FILE__
) . '/UtfNormalData.inc' );
176 * Returns true if the string is _definitely_ in NFC.
177 * Returns false if not or uncertain.
178 * @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.
223 static function quickIsNFCVerify( &$string ) {
224 # Screen out some characters that eg won't be allowed in XML
225 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT
, $string );
227 # ASCII is always valid NFC!
228 # If we're only ever given plain ASCII, we can avoid the overhead
229 # of initializing the decomposition tables by skipping out early.
230 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
232 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
233 if( !isset( $checkit ) ) {
234 # Load/build some scary lookup tables...
235 UtfNormal
::loadData();
236 global $utfCheckNFC, $utfCombiningClass;
238 $utfCheckOrCombining = array_merge( $utfCheckNFC, $utfCombiningClass );
240 # Head bytes for sequences which we should do further validity checks
241 $checkit = array_flip( array_map( 'chr',
242 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
243 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
244 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
246 # Each UTF-8 head byte is followed by a certain
247 # number of tail bytes.
248 $tailBytes = array();
249 for( $n = 0; $n < 256; $n++
) {
252 } elseif( $n < 0xe0 ) {
254 } elseif( $n < 0xf0 ) {
256 } elseif( $n < 0xf8 ) {
258 } elseif( $n < 0xfc ) {
260 } elseif( $n < 0xfe ) {
265 $tailBytes[chr($n)] = $remaining;
269 # Chop the text into pure-ASCII and non-ASCII areas;
270 # large ASCII parts can be handled much more quickly.
271 # Don't chop up Unicode areas for punctuation, though,
272 # that wastes energy.
275 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
281 foreach( $matches[1] as $str ) {
282 $chunk = strlen( $str );
284 if( $str{0} < "\x80" ) {
285 # ASCII chunk: guaranteed to be valid UTF-8
286 # and in normal form C, so skip over it.
291 # We'll have to examine the chunk byte by byte to ensure
292 # that it consists of valid UTF-8 sequences, and to see
293 # if any of them might not be normalized.
295 # Since PHP is not the fastest language on earth, some of
296 # this code is a little ugly with inner loop optimizations.
299 $len = $chunk +
1; # Counting down is faster. I'm *so* sorry.
301 for( $i = -1; --$len; ) {
302 if( $remaining = $tailBytes[$c = $str{++
$i}] ) {
304 $sequence = $head = $c;
306 # Look for the defined number of tail bytes...
307 if( --$len && ( $c = $str{++
$i} ) >= "\x80" && $c < "\xc0" ) {
308 # Legal tail bytes are nice.
312 # Premature end of string!
313 # Drop a replacement character into output to
314 # represent the invalid UTF-8 sequence.
315 $replace[] = array( UTF8_REPLACEMENT
,
316 $base +
$i +
1 - strlen( $sequence ),
317 strlen( $sequence ) );
320 # Illegal tail byte; abandon the sequence.
321 $replace[] = array( UTF8_REPLACEMENT
,
322 $base +
$i - strlen( $sequence ),
323 strlen( $sequence ) );
324 # Back up and reprocess this byte; it may itself
325 # be a legal ASCII or UTF-8 sequence head.
331 } while( --$remaining );
333 if( isset( $checkit[$head] ) ) {
334 # Do some more detailed validity checks, for
335 # invalid characters and illegal sequences.
336 if( $head == "\xed" ) {
337 # 0xed is relatively frequent in Korean, which
338 # abuts the surrogate area, so we're doing
339 # this check separately to speed things up.
341 if( $sequence >= UTF8_SURROGATE_FIRST
) {
342 # Surrogates are legal only in UTF-16 code.
343 # They are totally forbidden here in UTF-8
345 $replace[] = array( UTF8_REPLACEMENT
,
346 $base +
$i +
1 - strlen( $sequence ),
347 strlen( $sequence ) );
352 # Slower, but rarer checks...
355 # "Overlong sequences" are those that are syntactically
356 # correct but use more UTF-8 bytes than are necessary to
357 # encode a character. Naïve string comparisons can be
358 # tricked into failing to see a match for an ASCII
359 # character, for instance, which can be a security hole
360 # if blacklist checks are being used.
361 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A
)
362 ||
($n == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
363 ||
($n == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
365 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
367 ($sequence == UTF8_FFFE
)
368 ||
($sequence == UTF8_FFFF
) )
370 # Unicode has been limited to 21 bits; longer
371 # sequences are not allowed.
372 ||
($n >= 0xf0 && $sequence > UTF8_MAX
) ) {
374 $replace[] = array( UTF8_REPLACEMENT
,
375 $base +
$i +
1 - strlen( $sequence ),
376 strlen( $sequence ) );
383 if( isset( $utfCheckOrCombining[$sequence] ) ) {
384 # If it's NO or MAYBE, we'll have to rip
385 # the string apart and put it back together.
386 # That's going to be mighty slow.
387 $looksNormal = false;
390 # The sequence is legal!
392 } elseif( $c < "\x80" ) {
395 } elseif( $c < "\xc0" ) {
399 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
401 # Don't add if we're continuing a broken sequence;
402 # we already put a replacement character when we looked
403 # at the broken sequence.
404 $replace[] = array( '', $base +
$i, 1 );
407 # Miscellaneous freaks.
408 $replace[] = array( UTF8_REPLACEMENT
, $base +
$i, 1 );
414 if( count( $replace ) ) {
415 # There were illegal UTF-8 sequences we need to fix up.
418 foreach( $replace as $rep ) {
419 list( $replacement, $start, $length ) = $rep;
420 if( $last < $start ) {
421 $out .= substr( $string, $last, $start - $last );
423 $out .= $replacement;
424 $last = $start +
$length;
426 if( $last < strlen( $string ) ) {
427 $out .= substr( $string, $last );
434 # These take a string and run the normalization on them, without
435 # checking for validity or any optimization etc. Input must be
438 * @param string $string
443 static function NFC( $string ) {
444 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
448 * @param string $string
453 static function NFD( $string ) {
454 UtfNormal
::loadData();
455 global $utfCanonicalDecomp;
456 return UtfNormal
::fastCombiningSort(
457 UtfNormal
::fastDecompose( $string, $utfCanonicalDecomp ) );
461 * @param string $string
466 static function NFKC( $string ) {
467 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
471 * @param string $string
476 static function NFKD( $string ) {
477 global $utfCompatibilityDecomp;
478 if( !isset( $utfCompatibilityDecomp ) ) {
479 require_once( 'UtfNormalDataK.inc' );
481 return UtfNormal
::fastCombiningSort(
482 UtfNormal
::fastDecompose( $string, $utfCompatibilityDecomp ) );
487 * Perform decomposition of a UTF-8 string into either D or KD form
488 * (depending on which decomposition map is passed to us).
489 * Input is assumed to be *valid* UTF-8. Invalid code will break.
491 * @param string $string Valid UTF-8 string
492 * @param array $map hash of expanded decomposition map
493 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
496 static function fastDecompose( $string, $map ) {
497 UtfNormal
::loadData();
498 $len = strlen( $string );
500 for( $i = 0; $i < $len; $i++
) {
504 # ASCII chars never decompose
508 } elseif( $n >= 0xf0 ) {
509 $c = substr( $string, $i, 4 );
511 } elseif( $n >= 0xe0 ) {
512 $c = substr( $string, $i, 3 );
514 } elseif( $n >= 0xc0 ) {
515 $c = substr( $string, $i, 2 );
518 if( isset( $map[$c] ) ) {
522 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
523 # Decompose a hangul syllable into jamo;
524 # hardcoded for three-byte UTF-8 sequence.
525 # A lookup table would be slightly faster,
526 # but adds a lot of memory & disk needs.
528 $index = ( (ord( $c{0} ) & 0x0f) << 12
529 |
(ord( $c{1} ) & 0x3f) << 6
530 |
(ord( $c{2} ) & 0x3f) )
531 - UNICODE_HANGUL_FIRST
;
532 $l = intval( $index / UNICODE_HANGUL_NCOUNT
);
533 $v = intval( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
534 $t = $index % UNICODE_HANGUL_TCOUNT
;
535 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
537 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
539 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
550 * Sorts combining characters into canonical order. This is the
551 * final step in creating decomposed normal forms D and KD.
553 * @param string $string a valid, decomposed UTF-8 string. Input is not validated.
554 * @return string a UTF-8 string with combining characters sorted in canonical order
557 static function fastCombiningSort( $string ) {
558 UtfNormal
::loadData();
559 global $utfCombiningClass;
560 $len = strlen( $string );
562 $combiners = array();
564 for( $i = 0; $i < $len; $i++
) {
569 $c = substr( $string, $i, 4 );
571 } elseif( $n >= 0xe0 ) {
572 $c = substr( $string, $i, 3 );
574 } elseif( $n >= 0xc0 ) {
575 $c = substr( $string, $i, 2 );
578 if( isset( $utfCombiningClass[$c] ) ) {
579 $lastClass = $utfCombiningClass[$c];
580 if( isset( $combiners[$lastClass] ) ) {
581 $combiners[$lastClass] .= $c;
583 $combiners[$lastClass] = $c;
590 $out .= implode( '', $combiners );
591 $combiners = array();
598 $out .= implode( '', $combiners );
604 * Produces canonically composed sequences, i.e. normal form C or KC.
607 * @param string $string a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
608 * @return string a UTF-8 string with canonical precomposed characters used where possible
611 static function fastCompose( $string ) {
612 UtfNormal
::loadData();
613 global $utfCanonicalComp, $utfCombiningClass;
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( $utfCombiningClass[$c] ) ) {
646 # A combining char; see what we can do with it
647 $class = $utfCombiningClass[$c];
648 if( !empty( $startChar ) &&
649 $lastClass < $class &&
651 isset( $utfCanonicalComp[$pair] ) ) {
652 $startChar = $utfCanonicalComp[$pair];
663 if( $lastClass == 0 ) {
664 if( isset( $utfCanonicalComp[$pair] ) ) {
665 $startChar = $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
744 static function placebo( $string ) {
745 $len = strlen( $string );
747 for( $i = 0; $i < $len; $i++
) {