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 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
21 * Unicode normalization routines for working with UTF-8 strings.
22 * Currently assumes that input strings are valid UTF-8!
24 * Not as fast as I'd like, but should be usable for most purposes.
25 * UtfNormal::toNFC() will bail early if given ASCII text or text
26 * it can quickly deterimine is already normalized.
28 * All functions can be called static.
30 * See description of forms at http://www.unicode.org/reports/tr15/
36 require_once 'UtfNormalUtil.php';
38 global $utfCombiningClass, $utfCanonicalComp, $utfCanonicalDecomp;
39 $utfCombiningClass = NULL;
40 $utfCanonicalComp = NULL;
41 $utfCanonicalDecomp = NULL;
43 # Load compatibility decompositions on demand if they are needed.
44 global $utfCompatibilityDecomp;
45 $utfCompatibilityDecomp = NULL;
47 define( 'UNICODE_HANGUL_FIRST', 0xac00 );
48 define( 'UNICODE_HANGUL_LAST', 0xd7a3 );
50 define( 'UNICODE_HANGUL_LBASE', 0x1100 );
51 define( 'UNICODE_HANGUL_VBASE', 0x1161 );
52 define( 'UNICODE_HANGUL_TBASE', 0x11a7 );
54 define( 'UNICODE_HANGUL_LCOUNT', 19 );
55 define( 'UNICODE_HANGUL_VCOUNT', 21 );
56 define( 'UNICODE_HANGUL_TCOUNT', 28 );
57 define( 'UNICODE_HANGUL_NCOUNT', UNICODE_HANGUL_VCOUNT
* UNICODE_HANGUL_TCOUNT
);
59 define( 'UNICODE_HANGUL_LEND', UNICODE_HANGUL_LBASE + UNICODE_HANGUL_LCOUNT
- 1 );
60 define( 'UNICODE_HANGUL_VEND', UNICODE_HANGUL_VBASE + UNICODE_HANGUL_VCOUNT
- 1 );
61 define( 'UNICODE_HANGUL_TEND', UNICODE_HANGUL_TBASE + UNICODE_HANGUL_TCOUNT
- 1 );
63 define( 'UNICODE_SURROGATE_FIRST', 0xd800 );
64 define( 'UNICODE_SURROGATE_LAST', 0xdfff );
65 define( 'UNICODE_MAX', 0x10ffff );
66 define( 'UNICODE_REPLACEMENT', 0xfffd );
69 define( 'UTF8_HANGUL_FIRST', codepointToUtf8( UNICODE_HANGUL_FIRST
) );
70 define( 'UTF8_HANGUL_LAST', codepointToUtf8( UNICODE_HANGUL_LAST
) );
72 define( 'UTF8_HANGUL_LBASE', codepointToUtf8( UNICODE_HANGUL_LBASE
) );
73 define( 'UTF8_HANGUL_VBASE', codepointToUtf8( UNICODE_HANGUL_VBASE
) );
74 define( 'UTF8_HANGUL_TBASE', codepointToUtf8( UNICODE_HANGUL_TBASE
) );
76 define( 'UTF8_HANGUL_LEND', codepointToUtf8( UNICODE_HANGUL_LEND
) );
77 define( 'UTF8_HANGUL_VEND', codepointToUtf8( UNICODE_HANGUL_VEND
) );
78 define( 'UTF8_HANGUL_TEND', codepointToUtf8( UNICODE_HANGUL_TEND
) );
80 define( 'UTF8_SURROGATE_FIRST', codepointToUtf8( UNICODE_SURROGATE_FIRST
) );
81 define( 'UTF8_SURROGATE_LAST', codepointToUtf8( UNICODE_SURROGATE_LAST
) );
82 define( 'UTF8_MAX', codepointToUtf8( UNICODE_MAX
) );
83 define( 'UTF8_REPLACEMENT', codepointToUtf8( UNICODE_REPLACEMENT
) );
84 #define( 'UTF8_REPLACEMENT', '!' );
86 define( 'UTF8_OVERLONG_A', "\xc1\xbf" );
87 define( 'UTF8_OVERLONG_B', "\xe0\x9f\xbf" );
88 define( 'UTF8_OVERLONG_C', "\xf0\x8f\xbf\xbf" );
90 # These two ranges are illegal
91 define( 'UTF8_FDD0', codepointToUtf8( 0xfdd0 ) );
92 define( 'UTF8_FDEF', codepointToUtf8( 0xfdef ) );
93 define( 'UTF8_FFFE', codepointToUtf8( 0xfffe ) );
94 define( 'UTF8_FFFF', codepointToUtf8( 0xffff ) );
96 define( 'UTF8_HEAD', false );
97 define( 'UTF8_TAIL', true );
101 * For using the ICU wrapper
103 define( 'UNORM_NONE', 1 );
104 define( 'UNORM_NFD', 2 );
105 define( 'UNORM_NFKD', 3 );
106 define( 'UNORM_NFC', 4 );
107 define( 'UNORM_DEFAULT', UNORM_NFC
);
108 define( 'UNORM_NFKC', 5 );
109 define( 'UNORM_FCD', 6 );
111 define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
119 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
120 * and convert to normal form C, canonical composition.
122 * Fast return for pure ASCII strings; some lesser optimizations for
123 * strings containing only known-good characters. Not as fast as toNFC().
125 * @param string $string a UTF-8 string
126 * @return string a clean, shiny, normalized UTF-8 string
128 function cleanUp( $string ) {
129 if( UtfNormal
::quickIsNFCVerify( $string ) )
132 return UtfNormal
::NFC( $string );
136 * Convert a UTF-8 string to normal form C, canonical composition.
137 * Fast return for pure ASCII strings; some lesser optimizations for
138 * strings containing only known-good characters.
140 * @param string $string a valid UTF-8 string. Input is not validated.
141 * @return string a UTF-8 string in normal form C
143 function toNFC( $string ) {
145 return utf8_normalize( $string, UNORM_NFC
);
146 elseif( UtfNormal
::quickIsNFC( $string ) )
149 return UtfNormal
::NFC( $string );
153 * Convert a UTF-8 string to normal form D, canonical decomposition.
154 * Fast return for pure ASCII strings.
156 * @param string $string a valid UTF-8 string. Input is not validated.
157 * @return string a UTF-8 string in normal form D
159 function toNFD( $string ) {
161 return utf8_normalize( $string, UNORM_NFD
);
162 elseif( preg_match( '/[\x80-\xff]/', $string ) )
163 return UtfNormal
::NFD( $string );
169 * Convert a UTF-8 string to normal form KC, compatibility composition.
170 * This may cause irreversible information loss, use judiciously.
171 * Fast return for pure ASCII strings.
173 * @param string $string a valid UTF-8 string. Input is not validated.
174 * @return string a UTF-8 string in normal form KC
176 function toNFKC( $string ) {
178 return utf8_normalize( $string, UNORM_NFKC
);
179 elseif( preg_match( '/[\x80-\xff]/', $string ) )
180 return UtfNormal
::NFKC( $string );
186 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
187 * This may cause irreversible information loss, use judiciously.
188 * Fast return for pure ASCII strings.
190 * @param string $string a valid UTF-8 string. Input is not validated.
191 * @return string a UTF-8 string in normal form KD
193 function toNFKD( $string ) {
195 return utf8_normalize( $string, UNORM_NFKD
);
196 elseif( preg_match( '/[\x80-\xff]/', $string ) )
197 return UtfNormal
::NFKD( $string );
203 * Load the basic composition data if necessary
206 function loadData() {
207 global $utfCombiningClass, $utfCanonicalComp, $utfCanonicalDecomp;
208 if( !isset( $utfCombiningClass ) ) {
209 require_once( 'UtfNormalData.inc' );
214 * Returns true if the string is _definitely_ in NFC.
215 * Returns false if not or uncertain.
216 * @param string $string a valid UTF-8 string. Input is not validated.
219 function quickIsNFC( $string ) {
220 # ASCII is always valid NFC!
221 # If it's pure ASCII, let it through.
222 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
224 UtfNormal
::loadData();
225 global $utfCheckNFC, $utfCombiningClass;
226 $len = strlen( $string );
227 for( $i = 0; $i < $len; $i++
) {
232 } elseif( $n >= 0xf0 ) {
233 $c = substr( $string, $i, 4 );
235 } elseif( $n >= 0xe0 ) {
236 $c = substr( $string, $i, 3 );
238 } elseif( $n >= 0xc0 ) {
239 $c = substr( $string, $i, 2 );
242 if( isset( $utfCheckNFC[$c] ) ) {
243 # If it's NO or MAYBE, bail and do the slow check.
246 if( isset( $utfCombiningClass[$c] ) ) {
247 # Combining character? We might have to do sorting, at least.
255 * Returns true if the string is _definitely_ in NFC.
256 * Returns false if not or uncertain.
257 * @param string $string a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
259 function quickIsNFCVerify( &$string ) {
260 # Screen out some characters that eg won't be allowed in XML
261 preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT
, $string );
263 # ASCII is always valid NFC!
264 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
266 UtfNormal
::loadData();
267 global $utfCheckNFC, $utfCombiningClass;
269 static $checkit = null, $tailBytes = null;
270 if( !isset( $checkit ) ) {
271 # Head bytes for sequences which we should do further validity checks
272 $checkit = array_flip( array_map( 'chr',
273 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
274 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
275 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
277 $tailBytes = array();
278 for( $n = 0; $n < 256; $n++
) {
281 } elseif( $n < 0xe0 ) {
283 } elseif( $n < 0xf0 ) {
285 } elseif( $n < 0xf8 ) {
287 } elseif( $n < 0xfc ) {
289 } elseif( $n < 0xfe ) {
294 $tailBytes[chr($n)] = $remaining;
298 # Chop the text into pure-ASCII and non-ASCII areas;
299 # large ASCII parts can be handled much more quickly.
300 # Don't chop up for little newlines or spaces, though,
301 # that wastes energy.
302 preg_match_all( '/([\x00-\x7f]+|[\x80-\xff][\x0a\x20\x80-\xff]*)/', $string, $matches );
306 foreach( $matches[1] as $str ) {
307 if( $str{0} < "\x80" ) {
311 $len = strlen( $str );
315 for( $i = 0; $i < $len; $i++
) {
318 if( $c >= "\x80" && $c < "\xc0" ) {
321 # Keep adding bytes...
325 if( isset( $checkit[$head] ) ) {
326 # Do some more detailed validity checks, for
327 # invalid characters and illegal sequences.
328 $head = ord( $head );
329 if( ( $head == 0xed && $sequence >= UTF8_SURROGATE_FIRST
330 && $sequence <= UTF8_SURROGATE_LAST
)
331 ||
($head < 0xc2 && $sequence <= UTF8_OVERLONG_A
)
332 ||
($head == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
334 ($sequence >= UTF8_FDD0
&& $sequence <= UTF8_FDEF
)
335 ||
($sequence == UTF8_FFFE
)
336 ||
($sequence == UTF8_FFFF
) )
337 ||
($head == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
338 ||
($head >= 0xf0 && $sequence > UTF8_MAX
) ) {
339 $out .= UTF8_REPLACEMENT
;
345 if( isset( $utfCheckNFC[$sequence] ) ||
346 isset( $utfCombiningClass[$sequence] ) ) {
347 # If it's NO or MAYBE, we'll have to do the slow check.
348 $looksNormal = false;
351 # The sequence is legal!
357 # Not a valid tail byte! DIscard the char we've been building.
358 #printf ("Invalid '%x' in tail with %d remaining bytes\n", $n, $remaining );
360 $out .= UTF8_REPLACEMENT
;
362 if( $remaining = $tailBytes[$c] ) {
366 } elseif( $c < "\x80" ) {
368 } elseif( $c < "\xc0" ) {
369 # illegal tail bytes or head byte of overlong sequence
371 # Don't add if we're continuing a too-long sequence
372 $out .= UTF8_REPLACEMENT
;
375 $out .= UTF8_REPLACEMENT
;
379 $out .= UTF8_REPLACEMENT
;
386 # These take a string and run the normalization on them, without
387 # checking for validity or any optimization etc. Input must be
390 * @param string $string
394 function NFC( $string ) {
395 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
399 * @param string $string
403 function NFD( $string ) {
404 UtfNormal
::loadData();
405 global $utfCanonicalDecomp;
406 return UtfNormal
::fastCombiningSort(
407 UtfNormal
::fastDecompose( $string, $utfCanonicalDecomp ) );
411 * @param string $string
415 function NFKC( $string ) {
416 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
420 * @param string $string
424 function NFKD( $string ) {
425 global $utfCompatibilityDecomp;
426 if( !isset( $utfCompatibilityDecomp ) ) {
427 require_once( 'UtfNormalDataK.inc' );
429 return UtfNormal
::fastCombiningSort(
430 UtfNormal
::fastDecompose( $string, $utfCompatibilityDecomp ) );
435 * Perform decomposition of a UTF-8 string into either D or KD form
436 * (depending on which decomposition map is passed to us).
437 * Input is assumed to be *valid* UTF-8. Invalid code will break.
439 * @param string $string Valid UTF-8 string
440 * @param array $map hash of expanded decomposition map
441 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
443 function fastDecompose( $string, &$map ) {
444 UtfNormal
::loadData();
445 $len = strlen( $string );
447 for( $i = 0; $i < $len; $i++
) {
451 # ASCII chars never decompose
455 } elseif( $n >= 0xf0 ) {
456 $c = substr( $string, $i, 4 );
458 } elseif( $n >= 0xe0 ) {
459 $c = substr( $string, $i, 3 );
461 } elseif( $n >= 0xc0 ) {
462 $c = substr( $string, $i, 2 );
465 if( isset( $map[$c] ) ) {
469 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
470 # Decompose a hangul syllable into jamo;
471 # hardcoded for three-byte UTF-8 sequence.
472 # A lookup table would be slightly faster,
473 # but adds a lot of memory & disk needs.
475 $index = ( (ord( $c{0} ) & 0x0f) << 12
476 |
(ord( $c{1} ) & 0x3f) << 6
477 |
(ord( $c{2} ) & 0x3f) )
478 - UNICODE_HANGUL_FIRST
;
479 $l = IntVal( $index / UNICODE_HANGUL_NCOUNT
);
480 $v = IntVal( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
481 $t = $index % UNICODE_HANGUL_TCOUNT
;
482 $out .= "\xe1\x84" . chr( 0x80 +
$l ) . "\xe1\x85" . chr( 0xa1 +
$v );
484 $out .= "\xe1\x87" . chr( 0x80 +
$t - 25 );
486 $out .= "\xe1\x86" . chr( 0xa7 +
$t );
497 * Sorts combining characters into canonical order. This is the
498 * final step in creating decomposed normal forms D and KD.
500 * @param string $string a valid, decomposed UTF-8 string. Input is not validated.
501 * @return string a UTF-8 string with combining characters sorted in canonical order
503 function fastCombiningSort( $string ) {
504 UtfNormal
::loadData();
505 global $utfCombiningClass;
506 $len = strlen( $string );
508 $combiners = array();
510 for( $i = 0; $i < $len; $i++
) {
515 $c = substr( $string, $i, 4 );
517 } elseif( $n >= 0xe0 ) {
518 $c = substr( $string, $i, 3 );
520 } elseif( $n >= 0xc0 ) {
521 $c = substr( $string, $i, 2 );
524 if( isset( $utfCombiningClass[$c] ) ) {
525 $lastClass = $utfCombiningClass[$c];
526 @$combiners[$lastClass] .= $c;
532 $out .= implode( '', $combiners );
533 $combiners = array();
540 $out .= implode( '', $combiners );
546 * Produces canonically composed sequences, i.e. normal form C or KC.
549 * @param string $string a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
550 * @return string a UTF-8 string with canonical precomposed characters used where possible
552 function fastCompose( $string ) {
553 UtfNormal
::loadData();
554 global $utfCanonicalComp, $utfCombiningClass;
555 $len = strlen( $string );
560 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
561 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
562 for( $i = 0; $i < $len; $i++
) {
566 # No combining characters here...
573 } elseif( $n >= 0xf0 ) {
574 $c = substr( $string, $i, 4 );
576 } elseif( $n >= 0xe0 ) {
577 $c = substr( $string, $i, 3 );
579 } elseif( $n >= 0xc0 ) {
580 $c = substr( $string, $i, 2 );
583 $pair = $startChar . $c;
585 if( isset( $utfCombiningClass[$c] ) ) {
586 # A combining char; see what we can do with it
587 $class = $utfCombiningClass[$c];
588 if( !empty( $startChar ) &&
589 $lastClass < $class &&
591 isset( $utfCanonicalComp[$pair] ) ) {
592 $startChar = $utfCanonicalComp[$pair];
602 if( $lastClass == 0 ) {
603 if( isset( $utfCanonicalComp[$pair] ) ) {
604 $startChar = $utfCanonicalComp[$pair];
607 if( $n >= $x1 && $n <= $x2 ) {
608 # WARNING: Hangul code is painfully slow.
609 # I apologize for this ugly, ugly code; however
610 # performance is even more teh suck if we call
611 # out to nice clean functions. Lookup tables are
612 # marginally faster, but require a lot of space.
614 if( $c >= UTF8_HANGUL_VBASE
&&
615 $c <= UTF8_HANGUL_VEND
&&
616 $startChar >= UTF8_HANGUL_LBASE
&&
617 $startChar <= UTF8_HANGUL_LEND
) {
619 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
620 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
621 $lIndex = ord( $startChar{2} ) - 0x80;
622 $vIndex = ord( $c{2} ) - 0xa1;
624 $hangulPoint = UNICODE_HANGUL_FIRST +
625 UNICODE_HANGUL_TCOUNT
*
626 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
628 # Hardcode the limited-range UTF-8 conversion:
629 $startChar = chr( $hangulPoint >> 12 & 0x0f |
0xe0 ) .
630 chr( $hangulPoint >> 6 & 0x3f |
0x80 ) .
631 chr( $hangulPoint & 0x3f |
0x80 );
633 } elseif( $c >= UTF8_HANGUL_TBASE
&&
634 $c <= UTF8_HANGUL_TEND
&&
635 $startChar >= UTF8_HANGUL_FIRST
&&
636 $startChar <= UTF8_HANGUL_LAST
) {
637 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
638 $tIndex = ord( $c{2} ) - 0xa7;
639 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 +
(0x11c0 - 0x11a7);
641 # Increment the code point by $tIndex, without
642 # the function overhead of decoding and recoding UTF-8
644 $tail = ord( $startChar{2} ) +
$tIndex;
647 $mid = ord( $startChar{1} ) +
1;
649 $startChar{0} = chr( ord( $startChar{0} ) +
1 );
652 $startChar{1} = chr( $mid );
654 $startChar{2} = chr( $tail );
665 $out .= $startChar . $combining;
670 * This is just used for the benchmark, comparing how long it takes to
671 * interate through a string without really doing anything of substance.
672 * @param string $string
675 function placebo( $string ) {
676 $len = strlen( $string );
678 for( $i = 0; $i < $len; $i++
) {