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( extension_loaded( 'iconv' ) ) {
77 $ret = iconv( "UTF-8","UTF-8//IGNORE", $string );
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 return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC
), "\x01" );
94 } elseif( UtfNormal
::quickIsNFCVerify( $string ) ) {
95 # Side effect -- $string has had UTF-8 errors cleaned up.
98 return UtfNormal
::NFC( $string );
103 * Convert a UTF-8 string to normal form C, canonical composition.
104 * Fast return for pure ASCII strings; some lesser optimizations for
105 * strings containing only known-good characters.
107 * @param $string String: a valid UTF-8 string. Input is not validated.
108 * @return string a UTF-8 string in normal form C
110 static function toNFC( $string ) {
112 return utf8_normalize( $string, UNORM_NFC
);
113 elseif( UtfNormal
::quickIsNFC( $string ) )
116 return UtfNormal
::NFC( $string );
120 * Convert a UTF-8 string to normal form D, canonical decomposition.
121 * Fast return for pure ASCII strings.
123 * @param $string String: a valid UTF-8 string. Input is not validated.
124 * @return string a UTF-8 string in normal form D
126 static function toNFD( $string ) {
128 return utf8_normalize( $string, UNORM_NFD
);
129 elseif( preg_match( '/[\x80-\xff]/', $string ) )
130 return UtfNormal
::NFD( $string );
136 * Convert a UTF-8 string to normal form KC, compatibility composition.
137 * This may cause irreversible information loss, use judiciously.
138 * Fast return for pure ASCII strings.
140 * @param $string String: a valid UTF-8 string. Input is not validated.
141 * @return string a UTF-8 string in normal form KC
143 static function toNFKC( $string ) {
145 return utf8_normalize( $string, UNORM_NFKC
);
146 elseif( preg_match( '/[\x80-\xff]/', $string ) )
147 return UtfNormal
::NFKC( $string );
153 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
154 * This may cause irreversible information loss, use judiciously.
155 * Fast return for pure ASCII strings.
157 * @param $string String: a valid UTF-8 string. Input is not validated.
158 * @return string a UTF-8 string in normal form KD
160 static function toNFKD( $string ) {
162 return utf8_normalize( $string, UNORM_NFKD
);
163 elseif( preg_match( '/[\x80-\xff]/', $string ) )
164 return UtfNormal
::NFKD( $string );
170 * Load the basic composition data if necessary
173 static function loadData() {
174 global $utfCombiningClass;
175 if( !isset( $utfCombiningClass ) ) {
176 require_once( dirname(__FILE__
) . '/UtfNormalData.inc' );
181 * Returns true if the string is _definitely_ in NFC.
182 * Returns false if not or uncertain.
183 * @param $string String: a valid UTF-8 string. Input is not validated.
186 static function quickIsNFC( $string ) {
187 # ASCII is always valid NFC!
188 # If it's pure ASCII, let it through.
189 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
191 UtfNormal
::loadData();
192 global $utfCheckNFC, $utfCombiningClass;
193 $len = strlen( $string );
194 for( $i = 0; $i < $len; $i++
) {
199 } elseif( $n >= 0xf0 ) {
200 $c = substr( $string, $i, 4 );
202 } elseif( $n >= 0xe0 ) {
203 $c = substr( $string, $i, 3 );
205 } elseif( $n >= 0xc0 ) {
206 $c = substr( $string, $i, 2 );
209 if( isset( $utfCheckNFC[$c] ) ) {
210 # If it's NO or MAYBE, bail and do the slow check.
213 if( isset( $utfCombiningClass[$c] ) ) {
214 # Combining character? We might have to do sorting, at least.
222 * Returns true if the string is _definitely_ in NFC.
223 * Returns false if not or uncertain.
224 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
226 static function quickIsNFCVerify( &$string ) {
227 # Screen out some characters that eg won't be allowed in XML
228 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT
, $string );
230 # ASCII is always valid NFC!
231 # If we're only ever given plain ASCII, we can avoid the overhead
232 # of initializing the decomposition tables by skipping out early.
233 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
235 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
236 if( !isset( $checkit ) ) {
237 # Load/build some scary lookup tables...
238 UtfNormal
::loadData();
239 global $utfCheckNFC, $utfCombiningClass;
241 $utfCheckOrCombining = array_merge( $utfCheckNFC, $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();
456 global $utfCanonicalDecomp;
457 return UtfNormal
::fastCombiningSort(
458 UtfNormal
::fastDecompose( $string, $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 global $utfCompatibilityDecomp;
477 if( !isset( $utfCompatibilityDecomp ) ) {
478 require_once( 'UtfNormalDataK.inc' );
480 return UtfNormal
::fastCombiningSort(
481 UtfNormal
::fastDecompose( $string, $utfCompatibilityDecomp ) );
486 * Perform decomposition of a UTF-8 string into either D or KD form
487 * (depending on which decomposition map is passed to us).
488 * Input is assumed to be *valid* UTF-8. Invalid code will break.
490 * @param $string String: valid UTF-8 string
491 * @param $map Array: hash of expanded decomposition map
492 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
494 static function fastDecompose( $string, $map ) {
495 UtfNormal
::loadData();
496 $len = strlen( $string );
498 for( $i = 0; $i < $len; $i++
) {
502 # ASCII chars never decompose
506 } elseif( $n >= 0xf0 ) {
507 $c = substr( $string, $i, 4 );
509 } elseif( $n >= 0xe0 ) {
510 $c = substr( $string, $i, 3 );
512 } elseif( $n >= 0xc0 ) {
513 $c = substr( $string, $i, 2 );
516 if( isset( $map[$c] ) ) {
520 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
521 # Decompose a hangul syllable into jamo;
522 # hardcoded for three-byte UTF-8 sequence.
523 # A lookup table would be slightly faster,
524 # but adds a lot of memory & disk needs.
526 $index = ( (ord( $c{0} ) & 0x0f) << 12
527 |
(ord( $c{1} ) & 0x3f) << 6
528 |
(ord( $c{2} ) & 0x3f) )
529 - UNICODE_HANGUL_FIRST
;
530 $l = intval( $index / UNICODE_HANGUL_NCOUNT
);
531 $v = intval( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
532 $t = $index % UNICODE_HANGUL_TCOUNT
;
533 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
535 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
537 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
548 * Sorts combining characters into canonical order. This is the
549 * final step in creating decomposed normal forms D and KD.
551 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
552 * @return string a UTF-8 string with combining characters sorted in canonical order
554 static function fastCombiningSort( $string ) {
555 UtfNormal
::loadData();
556 global $utfCombiningClass;
557 $len = strlen( $string );
559 $combiners = array();
561 for( $i = 0; $i < $len; $i++
) {
566 $c = substr( $string, $i, 4 );
568 } elseif( $n >= 0xe0 ) {
569 $c = substr( $string, $i, 3 );
571 } elseif( $n >= 0xc0 ) {
572 $c = substr( $string, $i, 2 );
575 if( isset( $utfCombiningClass[$c] ) ) {
576 $lastClass = $utfCombiningClass[$c];
577 if( isset( $combiners[$lastClass] ) ) {
578 $combiners[$lastClass] .= $c;
580 $combiners[$lastClass] = $c;
587 $out .= implode( '', $combiners );
588 $combiners = array();
595 $out .= implode( '', $combiners );
601 * Produces canonically composed sequences, i.e. normal form C or KC.
604 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
605 * @return string a UTF-8 string with canonical precomposed characters used where possible
607 static function fastCompose( $string ) {
608 UtfNormal
::loadData();
609 global $utfCanonicalComp, $utfCombiningClass;
610 $len = strlen( $string );
616 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
617 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
618 for( $i = 0; $i < $len; $i++
) {
622 # No combining characters here...
629 } elseif( $n >= 0xf0 ) {
630 $c = substr( $string, $i, 4 );
632 } elseif( $n >= 0xe0 ) {
633 $c = substr( $string, $i, 3 );
635 } elseif( $n >= 0xc0 ) {
636 $c = substr( $string, $i, 2 );
639 $pair = $startChar . $c;
641 if( isset( $utfCombiningClass[$c] ) ) {
642 # A combining char; see what we can do with it
643 $class = $utfCombiningClass[$c];
644 if( !empty( $startChar ) &&
645 $lastClass < $class &&
647 isset( $utfCanonicalComp[$pair] ) ) {
648 $startChar = $utfCanonicalComp[$pair];
659 if( $lastClass == 0 ) {
660 if( isset( $utfCanonicalComp[$pair] ) ) {
661 $startChar = $utfCanonicalComp[$pair];
665 if( $n >= $x1 && $n <= $x2 ) {
666 # WARNING: Hangul code is painfully slow.
667 # I apologize for this ugly, ugly code; however
668 # performance is even more teh suck if we call
669 # out to nice clean functions. Lookup tables are
670 # marginally faster, but require a lot of space.
672 if( $c >= UTF8_HANGUL_VBASE
&&
673 $c <= UTF8_HANGUL_VEND
&&
674 $startChar >= UTF8_HANGUL_LBASE
&&
675 $startChar <= UTF8_HANGUL_LEND
) {
677 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
678 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
679 $lIndex = ord( $startChar{2} ) - 0x80;
680 $vIndex = ord( $c{2} ) - 0xa1;
682 $hangulPoint = UNICODE_HANGUL_FIRST +
683 UNICODE_HANGUL_TCOUNT
*
684 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
686 # Hardcode the limited-range UTF-8 conversion:
687 $startChar = chr( $hangulPoint >> 12 & 0x0f |
0xe0 ) .
688 chr( $hangulPoint >> 6 & 0x3f |
0x80 ) .
689 chr( $hangulPoint & 0x3f |
0x80 );
692 } elseif( $c >= UTF8_HANGUL_TBASE
&&
693 $c <= UTF8_HANGUL_TEND
&&
694 $startChar >= UTF8_HANGUL_FIRST
&&
695 $startChar <= UTF8_HANGUL_LAST
&&
697 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
698 $tIndex = ord( $c{2} ) - 0xa7;
699 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 +
(0x11c0 - 0x11a7);
701 # Increment the code point by $tIndex, without
702 # the function overhead of decoding and recoding UTF-8
704 $tail = ord( $startChar{2} ) +
$tIndex;
707 $mid = ord( $startChar{1} ) +
1;
709 $startChar{0} = chr( ord( $startChar{0} ) +
1 );
712 $startChar{1} = chr( $mid );
714 $startChar{2} = chr( $tail );
716 # If there's another jamo char after this, *don't* try to merge it.
729 $out .= $startChar . $combining;
734 * This is just used for the benchmark, comparing how long it takes to
735 * interate through a string without really doing anything of substance.
736 * @param $string string
739 static function placebo( $string ) {
740 $len = strlen( $string );
742 for( $i = 0; $i < $len; $i++
) {