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.
260 function quickIsNFCVerify( &$string ) {
261 # ASCII is always valid NFC!
262 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
264 UtfNormal
::loadData();
265 global $utfCheckNFC, $utfCombiningClass;
266 $len = strlen( $string );
273 for( $i = 0; $i < $len; $i++
) {
276 if( $state == UTF8_TAIL
) {
277 if( $n >= 0x80 && $n < 0xc0 ) {
279 if( --$remaining == 0 ) {
280 if( $head < 0xc2 ||
$head == 0xed ||
$head == 0xe0 ||
$head > 0xee ) {
281 if( ( $sequence >= UTF8_SURROGATE_FIRST
282 && $sequence <= UTF8_SURROGATE_LAST
)
283 ||
($head == 0xc0 && $sequence <= UTF8_OVERLONG_A
)
284 ||
($head == 0xc1 && $sequence <= UTF8_OVERLONG_A
)
285 ||
($head == 0xe0 && $sequence <= UTF8_OVERLONG_B
)
287 ($sequence >= UTF8_FDD0
&& $sequence <= UTF8_FDEF
)
288 ||
($sequence == UTF8_FFFE
)
289 ||
($sequence == UTF8_FFFF
) )
290 ||
($head == 0xf0 && $sequence <= UTF8_OVERLONG_C
)
291 ||
($sequence > UTF8_MAX
) ) {
292 $out .= UTF8_REPLACEMENT
;
297 if( isset( $utfCheckNFC[$sequence] ) ||
298 isset( $utfCombiningClass[$sequence] ) ) {
299 # If it's NO or MAYBE, we'll have to do the slow check.
300 $looksNormal = false;
308 # Not a valid tail byte! DIscard the char we've been building.
309 #printf ("Invalid '%x' in tail with %d remaining bytes\n", $n, $remaining );
311 $out .= UTF8_REPLACEMENT
;
315 $out .= UTF8_REPLACEMENT
;
316 } elseif( $n == 0x0a ) {
318 } elseif( $n < 0x0d ) {
319 $out .= UTF8_REPLACEMENT
;
320 } elseif( $n == 0x0d ) {
323 $out .= UTF8_REPLACEMENT
;
325 } elseif( $n < 0x80 ) {
326 # Friendly ASCII chars.
328 } elseif( $n < 0xc0 ) {
329 # illegal tail bytes or head byte of overlong sequence
330 if( $head == 0 ) $out .= UTF8_REPLACEMENT
;
331 } elseif( $n < 0xe0 ) {
336 } elseif( $n < 0xf0 ) {
341 } elseif( $n < 0xf8 ) {
346 } elseif( $n < 0xfc ) {
351 } elseif( $n < 0xfe ) {
357 $out .= UTF8_REPLACEMENT
;
360 if( $state == UTF8_TAIL
) {
361 $out .= UTF8_REPLACEMENT
;
367 # These take a string and run the normalization on them, without
368 # checking for validity or any optimization etc. Input must be
371 * @param string $string
375 function NFC( $string ) {
376 return UtfNormal
::fastCompose( UtfNormal
::NFD( $string ) );
380 * @param string $string
384 function NFD( $string ) {
385 UtfNormal
::loadData();
386 global $utfCanonicalDecomp;
387 return UtfNormal
::fastCombiningSort(
388 UtfNormal
::fastDecompose( $string, $utfCanonicalDecomp ) );
392 * @param string $string
396 function NFKC( $string ) {
397 return UtfNormal
::fastCompose( UtfNormal
::NFKD( $string ) );
401 * @param string $string
405 function NFKD( $string ) {
406 global $utfCompatibilityDecomp;
407 if( !isset( $utfCompatibilityDecomp ) ) {
408 require_once( 'UtfNormalDataK.inc' );
410 return UtfNormal
::fastCombiningSort(
411 UtfNormal
::fastDecompose( $string, $utfCompatibilityDecomp ) );
416 * Perform decomposition of a UTF-8 string into either D or KD form
417 * (depending on which decomposition map is passed to us).
418 * Input is assumed to be *valid* UTF-8. Invalid code will break.
420 * @param string &$string Valid UTF-8 string
421 * @param array &$map hash of expanded decomposition map
422 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
424 function fastDecompose( &$string, &$map ) {
425 UtfNormal
::loadData();
426 $len = strlen( $string );
428 for( $i = 0; $i < $len; $i++
) {
432 # ASCII chars never decompose
436 } elseif( $n >= 0xf0 ) {
437 $c = substr( $string, $i, 4 );
439 } elseif( $n >= 0xe0 ) {
440 $c = substr( $string, $i, 3 );
442 } elseif( $n >= 0xc0 ) {
443 $c = substr( $string, $i, 2 );
446 if( isset( $map[$c] ) ) {
449 if( $c >= UTF8_HANGUL_FIRST
&& $c <= UTF8_HANGUL_LAST
) {
450 $out .= UtfNormal
::decomposeHangul( $c );
460 * Decompose a Hangul syllable character into its constituent jamo.
462 * @param int $c Unicode code point of the character
463 * @return string a UTF-8 string containing a sequence of jamo
465 function decomposeHangul( $c ) {
466 $codepoint = utf8ToCodepoint( $c );
467 $index = $codepoint - UNICODE_HANGUL_FIRST
;
468 $l = IntVal( $index / UNICODE_HANGUL_NCOUNT
);
469 $v = IntVal( ($index % UNICODE_HANGUL_NCOUNT
) / UNICODE_HANGUL_TCOUNT
);
470 $t = $index % UNICODE_HANGUL_TCOUNT
;
471 $out = codepointToUtf8( $l + UNICODE_HANGUL_LBASE
);
472 $out .= codepointToUtf8( $v + UNICODE_HANGUL_VBASE
);
473 if( $t ) $out .= codepointToUtf8( $t + UNICODE_HANGUL_TBASE
);
478 * Sorts combining characters into canonical order. This is the
479 * final step in creating decomposed normal forms D and KD.
481 * @param string $string a valid, decomposed UTF-8 string. Input is not validated.
482 * @return string a UTF-8 string with combining characters sorted in canonical order
484 function fastCombiningSort( $string ) {
485 UtfNormal
::loadData();
486 global $utfCombiningClass;
488 while( $replacedCount > 0 ) {
490 $len = strlen( $string );
494 for( $i = 0; $i < $len; $i++
) {
498 # No combining characters in ASCII.
503 } elseif( $n >= 0xf0 ) {
504 $c = substr( $string, $i, 4 );
506 } elseif( $n >= 0xe0 ) {
507 $c = substr( $string, $i, 3 );
509 } elseif( $n >= 0xc0 ) {
510 $c = substr( $string, $i, 2 );
514 if( $lastClass == -1 ) {
517 $class = isset( $utfCombiningClass[$c] ) ?
$utfCombiningClass[$c] : 0;
521 if( isset( $utfCombiningClass[$c] ) ) {
522 $class = $utfCombiningClass[$c];
523 if( $lastClass > $class ) {
524 # Swap -- put this one on the stack
541 * Produces canonically composed sequences, i.e. normal form C or KC.
544 * @param string $string a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
545 * @return string a UTF-8 string with canonical precomposed characters used where possible
547 function fastCompose( $string ) {
548 UtfNormal
::loadData();
549 global $utfCanonicalComp, $utfCombiningClass;
550 $len = strlen( $string );
555 $x1 = ord(substr(UTF8_HANGUL_VBASE
,0,1));
556 $x2 = ord(substr(UTF8_HANGUL_TEND
,0,1));
557 for( $i = 0; $i < $len; $i++
) {
561 # No combining characters here...
568 } elseif( $n >= 0xf0 ) {
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 $pair = $startChar . $c;
580 if( isset( $utfCombiningClass[$c] ) ) {
581 # A combining char; see what we can do with it
582 $class = $utfCombiningClass[$c];
583 if( !empty( $startChar ) &&
584 $lastClass < $class &&
586 isset( $utfCanonicalComp[$pair] ) ) {
587 $startChar = $utfCanonicalComp[$pair];
597 if( $lastClass == 0 ) {
598 if( isset( $utfCanonicalComp[$pair] ) ) {
599 $startChar = $utfCanonicalComp[$pair];
602 if( $n >= $x1 && $n <= $x2 ) {
603 # WARNING: Hangul code is painfully slow.
604 if( $c >= UTF8_HANGUL_VBASE
&&
605 $c <= UTF8_HANGUL_VEND
&&
606 $startChar >= UTF8_HANGUL_LBASE
&&
607 $startChar <= UTF8_HANGUL_LEND
) {
609 $lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE
;
610 $vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE
;
611 $hangulPoint = UNICODE_HANGUL_FIRST +
612 UNICODE_HANGUL_TCOUNT
*
613 (UNICODE_HANGUL_VCOUNT
* $lIndex +
$vIndex);
614 $startChar = codepointToUtf8( $hangulPoint );
616 } elseif( $c >= UTF8_HANGUL_TBASE
&&
617 $c <= UTF8_HANGUL_TEND
&&
618 $startChar >= UTF8_HANGUL_FIRST
&&
619 $startChar <= UTF8_HANGUL_LAST
) {
620 $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE
;
621 $hangulPoint = utf8ToCodepoint( $startChar ) +
$tIndex;
622 $startChar = codepointToUtf8( $hangulPoint );
633 $out .= $startChar . $combining;
638 * This is just used for the benchmark, comparing how long it takes to
639 * interate through a string without really doing anything of substance.
640 * @param string $string
643 function placebo( $string ) {
644 $len = strlen( $string );
646 for( $i = 0; $i < $len; $i++
) {