Fix regression in even sizing of diff columns; forgot to restore a couple bits I...
[mediawiki.git] / includes / normal / UtfNormal.php
blob43bbafd864d892d482ca978ae4f9dae59e79a910
1 <?php
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
20 /** */
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;
32 define( 'UNICODE_HANGUL_FIRST', 0xac00 );
33 define( 'UNICODE_HANGUL_LAST', 0xd7a3 );
35 define( 'UNICODE_HANGUL_LBASE', 0x1100 );
36 define( 'UNICODE_HANGUL_VBASE', 0x1161 );
37 define( 'UNICODE_HANGUL_TBASE', 0x11a7 );
39 define( 'UNICODE_HANGUL_LCOUNT', 19 );
40 define( 'UNICODE_HANGUL_VCOUNT', 21 );
41 define( 'UNICODE_HANGUL_TCOUNT', 28 );
42 define( 'UNICODE_HANGUL_NCOUNT', UNICODE_HANGUL_VCOUNT * UNICODE_HANGUL_TCOUNT );
44 define( 'UNICODE_HANGUL_LEND', UNICODE_HANGUL_LBASE + UNICODE_HANGUL_LCOUNT - 1 );
45 define( 'UNICODE_HANGUL_VEND', UNICODE_HANGUL_VBASE + UNICODE_HANGUL_VCOUNT - 1 );
46 define( 'UNICODE_HANGUL_TEND', UNICODE_HANGUL_TBASE + UNICODE_HANGUL_TCOUNT - 1 );
48 define( 'UNICODE_SURROGATE_FIRST', 0xd800 );
49 define( 'UNICODE_SURROGATE_LAST', 0xdfff );
50 define( 'UNICODE_MAX', 0x10ffff );
51 define( 'UNICODE_REPLACEMENT', 0xfffd );
54 define( 'UTF8_HANGUL_FIRST', "\xea\xb0\x80" /*codepointToUtf8( UNICODE_HANGUL_FIRST )*/ );
55 define( 'UTF8_HANGUL_LAST', "\xed\x9e\xa3" /*codepointToUtf8( UNICODE_HANGUL_LAST )*/ );
57 define( 'UTF8_HANGUL_LBASE', "\xe1\x84\x80" /*codepointToUtf8( UNICODE_HANGUL_LBASE )*/ );
58 define( 'UTF8_HANGUL_VBASE', "\xe1\x85\xa1" /*codepointToUtf8( UNICODE_HANGUL_VBASE )*/ );
59 define( 'UTF8_HANGUL_TBASE', "\xe1\x86\xa7" /*codepointToUtf8( UNICODE_HANGUL_TBASE )*/ );
61 define( 'UTF8_HANGUL_LEND', "\xe1\x84\x92" /*codepointToUtf8( UNICODE_HANGUL_LEND )*/ );
62 define( 'UTF8_HANGUL_VEND', "\xe1\x85\xb5" /*codepointToUtf8( UNICODE_HANGUL_VEND )*/ );
63 define( 'UTF8_HANGUL_TEND', "\xe1\x87\x82" /*codepointToUtf8( UNICODE_HANGUL_TEND )*/ );
65 define( 'UTF8_SURROGATE_FIRST', "\xed\xa0\x80" /*codepointToUtf8( UNICODE_SURROGATE_FIRST )*/ );
66 define( 'UTF8_SURROGATE_LAST', "\xed\xbf\xbf" /*codepointToUtf8( UNICODE_SURROGATE_LAST )*/ );
67 define( 'UTF8_MAX', "\xf4\x8f\xbf\xbf" /*codepointToUtf8( UNICODE_MAX )*/ );
68 define( 'UTF8_REPLACEMENT', "\xef\xbf\xbd" /*codepointToUtf8( UNICODE_REPLACEMENT )*/ );
69 #define( 'UTF8_REPLACEMENT', '!' );
71 define( 'UTF8_OVERLONG_A', "\xc1\xbf" );
72 define( 'UTF8_OVERLONG_B', "\xe0\x9f\xbf" );
73 define( 'UTF8_OVERLONG_C', "\xf0\x8f\xbf\xbf" );
75 # These two ranges are illegal
76 define( 'UTF8_FDD0', "\xef\xb7\x90" /*codepointToUtf8( 0xfdd0 )*/ );
77 define( 'UTF8_FDEF', "\xef\xb7\xaf" /*codepointToUtf8( 0xfdef )*/ );
78 define( 'UTF8_FFFE', "\xef\xbf\xbe" /*codepointToUtf8( 0xfffe )*/ );
79 define( 'UTF8_FFFF', "\xef\xbf\xbf" /*codepointToUtf8( 0xffff )*/ );
81 define( 'UTF8_HEAD', false );
82 define( 'UTF8_TAIL', true );
85 /**
86 * For using the ICU wrapper
88 define( 'UNORM_NONE', 1 );
89 define( 'UNORM_NFD', 2 );
90 define( 'UNORM_NFKD', 3 );
91 define( 'UNORM_NFC', 4 );
92 define( 'UNORM_DEFAULT', UNORM_NFC );
93 define( 'UNORM_NFKC', 5 );
94 define( 'UNORM_FCD', 6 );
96 define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
98 /**
99 * Unicode normalization routines for working with UTF-8 strings.
100 * Currently assumes that input strings are valid UTF-8!
102 * Not as fast as I'd like, but should be usable for most purposes.
103 * UtfNormal::toNFC() will bail early if given ASCII text or text
104 * it can quickly deterimine is already normalized.
106 * All functions can be called static.
108 * See description of forms at http://www.unicode.org/reports/tr15/
110 * @addtogroup UtfNormal
112 class UtfNormal {
114 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
115 * and convert to normal form C, canonical composition.
117 * Fast return for pure ASCII strings; some lesser optimizations for
118 * strings containing only known-good characters. Not as fast as toNFC().
120 * @param string $string a UTF-8 string
121 * @return string a clean, shiny, normalized UTF-8 string
122 * @static
124 static function cleanUp( $string ) {
125 if( NORMALIZE_ICU ) {
126 # We exclude a few chars that ICU would not.
127 $string = preg_replace(
128 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
129 UTF8_REPLACEMENT,
130 $string );
131 $string = str_replace( UTF8_FFFE, UTF8_REPLACEMENT, $string );
132 $string = str_replace( UTF8_FFFF, UTF8_REPLACEMENT, $string );
134 # UnicodeString constructor fails if the string ends with a
135 # head byte. Add a junk char at the end, we'll strip it off.
136 return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC ), "\x01" );
137 } elseif( UtfNormal::quickIsNFCVerify( $string ) ) {
138 # Side effect -- $string has had UTF-8 errors cleaned up.
139 return $string;
140 } else {
141 return UtfNormal::NFC( $string );
146 * Convert a UTF-8 string to normal form C, canonical composition.
147 * Fast return for pure ASCII strings; some lesser optimizations for
148 * strings containing only known-good characters.
150 * @param string $string a valid UTF-8 string. Input is not validated.
151 * @return string a UTF-8 string in normal form C
152 * @static
154 static function toNFC( $string ) {
155 if( NORMALIZE_ICU )
156 return utf8_normalize( $string, UNORM_NFC );
157 elseif( UtfNormal::quickIsNFC( $string ) )
158 return $string;
159 else
160 return UtfNormal::NFC( $string );
164 * Convert a UTF-8 string to normal form D, canonical decomposition.
165 * Fast return for pure ASCII strings.
167 * @param string $string a valid UTF-8 string. Input is not validated.
168 * @return string a UTF-8 string in normal form D
169 * @static
171 static function toNFD( $string ) {
172 if( NORMALIZE_ICU )
173 return utf8_normalize( $string, UNORM_NFD );
174 elseif( preg_match( '/[\x80-\xff]/', $string ) )
175 return UtfNormal::NFD( $string );
176 else
177 return $string;
181 * Convert a UTF-8 string to normal form KC, compatibility composition.
182 * This may cause irreversible information loss, use judiciously.
183 * Fast return for pure ASCII strings.
185 * @param string $string a valid UTF-8 string. Input is not validated.
186 * @return string a UTF-8 string in normal form KC
187 * @static
189 static function toNFKC( $string ) {
190 if( NORMALIZE_ICU )
191 return utf8_normalize( $string, UNORM_NFKC );
192 elseif( preg_match( '/[\x80-\xff]/', $string ) )
193 return UtfNormal::NFKC( $string );
194 else
195 return $string;
199 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
200 * This may cause irreversible information loss, use judiciously.
201 * Fast return for pure ASCII strings.
203 * @param string $string a valid UTF-8 string. Input is not validated.
204 * @return string a UTF-8 string in normal form KD
205 * @static
207 static function toNFKD( $string ) {
208 if( NORMALIZE_ICU )
209 return utf8_normalize( $string, UNORM_NFKD );
210 elseif( preg_match( '/[\x80-\xff]/', $string ) )
211 return UtfNormal::NFKD( $string );
212 else
213 return $string;
217 * Load the basic composition data if necessary
218 * @private
219 * @static
221 static function loadData() {
222 global $utfCombiningClass;
223 if( !isset( $utfCombiningClass ) ) {
224 require_once( dirname(__FILE__) . '/UtfNormalData.inc' );
229 * Returns true if the string is _definitely_ in NFC.
230 * Returns false if not or uncertain.
231 * @param string $string a valid UTF-8 string. Input is not validated.
232 * @return bool
233 * @static
235 static function quickIsNFC( $string ) {
236 # ASCII is always valid NFC!
237 # If it's pure ASCII, let it through.
238 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
240 UtfNormal::loadData();
241 global $utfCheckNFC, $utfCombiningClass;
242 $len = strlen( $string );
243 for( $i = 0; $i < $len; $i++ ) {
244 $c = $string{$i};
245 $n = ord( $c );
246 if( $n < 0x80 ) {
247 continue;
248 } elseif( $n >= 0xf0 ) {
249 $c = substr( $string, $i, 4 );
250 $i += 3;
251 } elseif( $n >= 0xe0 ) {
252 $c = substr( $string, $i, 3 );
253 $i += 2;
254 } elseif( $n >= 0xc0 ) {
255 $c = substr( $string, $i, 2 );
256 $i++;
258 if( isset( $utfCheckNFC[$c] ) ) {
259 # If it's NO or MAYBE, bail and do the slow check.
260 return false;
262 if( isset( $utfCombiningClass[$c] ) ) {
263 # Combining character? We might have to do sorting, at least.
264 return false;
267 return true;
271 * Returns true if the string is _definitely_ in NFC.
272 * Returns false if not or uncertain.
273 * @param string $string a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
274 * @static
276 static function quickIsNFCVerify( &$string ) {
277 # Screen out some characters that eg won't be allowed in XML
278 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT, $string );
280 # ASCII is always valid NFC!
281 # If we're only ever given plain ASCII, we can avoid the overhead
282 # of initializing the decomposition tables by skipping out early.
283 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
285 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
286 if( !isset( $checkit ) ) {
287 # Load/build some scary lookup tables...
288 UtfNormal::loadData();
289 global $utfCheckNFC, $utfCombiningClass;
291 $utfCheckOrCombining = array_merge( $utfCheckNFC, $utfCombiningClass );
293 # Head bytes for sequences which we should do further validity checks
294 $checkit = array_flip( array_map( 'chr',
295 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
296 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
297 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
299 # Each UTF-8 head byte is followed by a certain
300 # number of tail bytes.
301 $tailBytes = array();
302 for( $n = 0; $n < 256; $n++ ) {
303 if( $n < 0xc0 ) {
304 $remaining = 0;
305 } elseif( $n < 0xe0 ) {
306 $remaining = 1;
307 } elseif( $n < 0xf0 ) {
308 $remaining = 2;
309 } elseif( $n < 0xf8 ) {
310 $remaining = 3;
311 } elseif( $n < 0xfc ) {
312 $remaining = 4;
313 } elseif( $n < 0xfe ) {
314 $remaining = 5;
315 } else {
316 $remaining = 0;
318 $tailBytes[chr($n)] = $remaining;
322 # Chop the text into pure-ASCII and non-ASCII areas;
323 # large ASCII parts can be handled much more quickly.
324 # Don't chop up Unicode areas for punctuation, though,
325 # that wastes energy.
326 $matches = array();
327 preg_match_all(
328 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
329 $string, $matches );
331 $looksNormal = true;
332 $base = 0;
333 $replace = array();
334 foreach( $matches[1] as $str ) {
335 $chunk = strlen( $str );
337 if( $str{0} < "\x80" ) {
338 # ASCII chunk: guaranteed to be valid UTF-8
339 # and in normal form C, so skip over it.
340 $base += $chunk;
341 continue;
344 # We'll have to examine the chunk byte by byte to ensure
345 # that it consists of valid UTF-8 sequences, and to see
346 # if any of them might not be normalized.
348 # Since PHP is not the fastest language on earth, some of
349 # this code is a little ugly with inner loop optimizations.
351 $head = '';
352 $len = $chunk + 1; # Counting down is faster. I'm *so* sorry.
354 for( $i = -1; --$len; ) {
355 if( $remaining = $tailBytes[$c = $str{++$i}] ) {
356 # UTF-8 head byte!
357 $sequence = $head = $c;
358 do {
359 # Look for the defined number of tail bytes...
360 if( --$len && ( $c = $str{++$i} ) >= "\x80" && $c < "\xc0" ) {
361 # Legal tail bytes are nice.
362 $sequence .= $c;
363 } else {
364 if( 0 == $len ) {
365 # Premature end of string!
366 # Drop a replacement character into output to
367 # represent the invalid UTF-8 sequence.
368 $replace[] = array( UTF8_REPLACEMENT,
369 $base + $i + 1 - strlen( $sequence ),
370 strlen( $sequence ) );
371 break 2;
372 } else {
373 # Illegal tail byte; abandon the sequence.
374 $replace[] = array( UTF8_REPLACEMENT,
375 $base + $i - strlen( $sequence ),
376 strlen( $sequence ) );
377 # Back up and reprocess this byte; it may itself
378 # be a legal ASCII or UTF-8 sequence head.
379 --$i;
380 ++$len;
381 continue 2;
384 } while( --$remaining );
386 if( isset( $checkit[$head] ) ) {
387 # Do some more detailed validity checks, for
388 # invalid characters and illegal sequences.
389 if( $head == "\xed" ) {
390 # 0xed is relatively frequent in Korean, which
391 # abuts the surrogate area, so we're doing
392 # this check separately to speed things up.
394 if( $sequence >= UTF8_SURROGATE_FIRST ) {
395 # Surrogates are legal only in UTF-16 code.
396 # They are totally forbidden here in UTF-8
397 # utopia.
398 $replace[] = array( UTF8_REPLACEMENT,
399 $base + $i + 1 - strlen( $sequence ),
400 strlen( $sequence ) );
401 $head = '';
402 continue;
404 } else {
405 # Slower, but rarer checks...
406 $n = ord( $head );
408 # "Overlong sequences" are those that are syntactically
409 # correct but use more UTF-8 bytes than are necessary to
410 # encode a character. Naïve string comparisons can be
411 # tricked into failing to see a match for an ASCII
412 # character, for instance, which can be a security hole
413 # if blacklist checks are being used.
414 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A)
415 || ($n == 0xe0 && $sequence <= UTF8_OVERLONG_B)
416 || ($n == 0xf0 && $sequence <= UTF8_OVERLONG_C)
418 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
419 || ($n == 0xef &&
420 ($sequence == UTF8_FFFE)
421 || ($sequence == UTF8_FFFF) )
423 # Unicode has been limited to 21 bits; longer
424 # sequences are not allowed.
425 || ($n >= 0xf0 && $sequence > UTF8_MAX) ) {
427 $replace[] = array( UTF8_REPLACEMENT,
428 $base + $i + 1 - strlen( $sequence ),
429 strlen( $sequence ) );
430 $head = '';
431 continue;
436 if( isset( $utfCheckOrCombining[$sequence] ) ) {
437 # If it's NO or MAYBE, we'll have to rip
438 # the string apart and put it back together.
439 # That's going to be mighty slow.
440 $looksNormal = false;
443 # The sequence is legal!
444 $head = '';
445 } elseif( $c < "\x80" ) {
446 # ASCII byte.
447 $head = '';
448 } elseif( $c < "\xc0" ) {
449 # Illegal tail bytes
450 if( $head == '' ) {
451 # Out of the blue!
452 $replace[] = array( UTF8_REPLACEMENT, $base + $i, 1 );
453 } else {
454 # Don't add if we're continuing a broken sequence;
455 # we already put a replacement character when we looked
456 # at the broken sequence.
457 $replace[] = array( '', $base + $i, 1 );
459 } else {
460 # Miscellaneous freaks.
461 $replace[] = array( UTF8_REPLACEMENT, $base + $i, 1 );
462 $head = '';
465 $base += $chunk;
467 if( count( $replace ) ) {
468 # There were illegal UTF-8 sequences we need to fix up.
469 $out = '';
470 $last = 0;
471 foreach( $replace as $rep ) {
472 list( $replacement, $start, $length ) = $rep;
473 if( $last < $start ) {
474 $out .= substr( $string, $last, $start - $last );
476 $out .= $replacement;
477 $last = $start + $length;
479 if( $last < strlen( $string ) ) {
480 $out .= substr( $string, $last );
482 $string = $out;
484 return $looksNormal;
487 # These take a string and run the normalization on them, without
488 # checking for validity or any optimization etc. Input must be
489 # VALID UTF-8!
491 * @param string $string
492 * @return string
493 * @private
494 * @static
496 static function NFC( $string ) {
497 return UtfNormal::fastCompose( UtfNormal::NFD( $string ) );
501 * @param string $string
502 * @return string
503 * @private
504 * @static
506 static function NFD( $string ) {
507 UtfNormal::loadData();
508 global $utfCanonicalDecomp;
509 return UtfNormal::fastCombiningSort(
510 UtfNormal::fastDecompose( $string, $utfCanonicalDecomp ) );
514 * @param string $string
515 * @return string
516 * @private
517 * @static
519 static function NFKC( $string ) {
520 return UtfNormal::fastCompose( UtfNormal::NFKD( $string ) );
524 * @param string $string
525 * @return string
526 * @private
527 * @static
529 static function NFKD( $string ) {
530 global $utfCompatibilityDecomp;
531 if( !isset( $utfCompatibilityDecomp ) ) {
532 require_once( 'UtfNormalDataK.inc' );
534 return UtfNormal::fastCombiningSort(
535 UtfNormal::fastDecompose( $string, $utfCompatibilityDecomp ) );
540 * Perform decomposition of a UTF-8 string into either D or KD form
541 * (depending on which decomposition map is passed to us).
542 * Input is assumed to be *valid* UTF-8. Invalid code will break.
543 * @private
544 * @param string $string Valid UTF-8 string
545 * @param array $map hash of expanded decomposition map
546 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
547 * @static
549 static function fastDecompose( $string, $map ) {
550 UtfNormal::loadData();
551 $len = strlen( $string );
552 $out = '';
553 for( $i = 0; $i < $len; $i++ ) {
554 $c = $string{$i};
555 $n = ord( $c );
556 if( $n < 0x80 ) {
557 # ASCII chars never decompose
558 # THEY ARE IMMORTAL
559 $out .= $c;
560 continue;
561 } elseif( $n >= 0xf0 ) {
562 $c = substr( $string, $i, 4 );
563 $i += 3;
564 } elseif( $n >= 0xe0 ) {
565 $c = substr( $string, $i, 3 );
566 $i += 2;
567 } elseif( $n >= 0xc0 ) {
568 $c = substr( $string, $i, 2 );
569 $i++;
571 if( isset( $map[$c] ) ) {
572 $out .= $map[$c];
573 continue;
574 } else {
575 if( $c >= UTF8_HANGUL_FIRST && $c <= UTF8_HANGUL_LAST ) {
576 # Decompose a hangul syllable into jamo;
577 # hardcoded for three-byte UTF-8 sequence.
578 # A lookup table would be slightly faster,
579 # but adds a lot of memory & disk needs.
581 $index = ( (ord( $c{0} ) & 0x0f) << 12
582 | (ord( $c{1} ) & 0x3f) << 6
583 | (ord( $c{2} ) & 0x3f) )
584 - UNICODE_HANGUL_FIRST;
585 $l = intval( $index / UNICODE_HANGUL_NCOUNT );
586 $v = intval( ($index % UNICODE_HANGUL_NCOUNT) / UNICODE_HANGUL_TCOUNT);
587 $t = $index % UNICODE_HANGUL_TCOUNT;
588 $out .= "\xe1\x84" . chr( 0x80 + $l ) . "\xe1\x85" . chr( 0xa1 + $v );
589 if( $t >= 25 ) {
590 $out .= "\xe1\x87" . chr( 0x80 + $t - 25 );
591 } elseif( $t ) {
592 $out .= "\xe1\x86" . chr( 0xa7 + $t );
594 continue;
597 $out .= $c;
599 return $out;
603 * Sorts combining characters into canonical order. This is the
604 * final step in creating decomposed normal forms D and KD.
605 * @private
606 * @param string $string a valid, decomposed UTF-8 string. Input is not validated.
607 * @return string a UTF-8 string with combining characters sorted in canonical order
608 * @static
610 static function fastCombiningSort( $string ) {
611 UtfNormal::loadData();
612 global $utfCombiningClass;
613 $len = strlen( $string );
614 $out = '';
615 $combiners = array();
616 $lastClass = -1;
617 for( $i = 0; $i < $len; $i++ ) {
618 $c = $string{$i};
619 $n = ord( $c );
620 if( $n >= 0x80 ) {
621 if( $n >= 0xf0 ) {
622 $c = substr( $string, $i, 4 );
623 $i += 3;
624 } elseif( $n >= 0xe0 ) {
625 $c = substr( $string, $i, 3 );
626 $i += 2;
627 } elseif( $n >= 0xc0 ) {
628 $c = substr( $string, $i, 2 );
629 $i++;
631 if( isset( $utfCombiningClass[$c] ) ) {
632 $lastClass = $utfCombiningClass[$c];
633 if( isset( $combiners[$lastClass] ) ) {
634 $combiners[$lastClass] .= $c;
635 } else {
636 $combiners[$lastClass] = $c;
638 continue;
641 if( $lastClass ) {
642 ksort( $combiners );
643 $out .= implode( '', $combiners );
644 $combiners = array();
646 $out .= $c;
647 $lastClass = 0;
649 if( $lastClass ) {
650 ksort( $combiners );
651 $out .= implode( '', $combiners );
653 return $out;
657 * Produces canonically composed sequences, i.e. normal form C or KC.
659 * @private
660 * @param string $string a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
661 * @return string a UTF-8 string with canonical precomposed characters used where possible
662 * @static
664 static function fastCompose( $string ) {
665 UtfNormal::loadData();
666 global $utfCanonicalComp, $utfCombiningClass;
667 $len = strlen( $string );
668 $out = '';
669 $lastClass = -1;
670 $lastHangul = 0;
671 $startChar = '';
672 $combining = '';
673 $x1 = ord(substr(UTF8_HANGUL_VBASE,0,1));
674 $x2 = ord(substr(UTF8_HANGUL_TEND,0,1));
675 for( $i = 0; $i < $len; $i++ ) {
676 $c = $string{$i};
677 $n = ord( $c );
678 if( $n < 0x80 ) {
679 # No combining characters here...
680 $out .= $startChar;
681 $out .= $combining;
682 $startChar = $c;
683 $combining = '';
684 $lastClass = 0;
685 continue;
686 } elseif( $n >= 0xf0 ) {
687 $c = substr( $string, $i, 4 );
688 $i += 3;
689 } elseif( $n >= 0xe0 ) {
690 $c = substr( $string, $i, 3 );
691 $i += 2;
692 } elseif( $n >= 0xc0 ) {
693 $c = substr( $string, $i, 2 );
694 $i++;
696 $pair = $startChar . $c;
697 if( $n > 0x80 ) {
698 if( isset( $utfCombiningClass[$c] ) ) {
699 # A combining char; see what we can do with it
700 $class = $utfCombiningClass[$c];
701 if( !empty( $startChar ) &&
702 $lastClass < $class &&
703 $class > 0 &&
704 isset( $utfCanonicalComp[$pair] ) ) {
705 $startChar = $utfCanonicalComp[$pair];
706 $class = 0;
707 } else {
708 $combining .= $c;
710 $lastClass = $class;
711 $lastHangul = 0;
712 continue;
715 # New start char
716 if( $lastClass == 0 ) {
717 if( isset( $utfCanonicalComp[$pair] ) ) {
718 $startChar = $utfCanonicalComp[$pair];
719 $lastHangul = 0;
720 continue;
722 if( $n >= $x1 && $n <= $x2 ) {
723 # WARNING: Hangul code is painfully slow.
724 # I apologize for this ugly, ugly code; however
725 # performance is even more teh suck if we call
726 # out to nice clean functions. Lookup tables are
727 # marginally faster, but require a lot of space.
729 if( $c >= UTF8_HANGUL_VBASE &&
730 $c <= UTF8_HANGUL_VEND &&
731 $startChar >= UTF8_HANGUL_LBASE &&
732 $startChar <= UTF8_HANGUL_LEND ) {
734 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
735 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
736 $lIndex = ord( $startChar{2} ) - 0x80;
737 $vIndex = ord( $c{2} ) - 0xa1;
739 $hangulPoint = UNICODE_HANGUL_FIRST +
740 UNICODE_HANGUL_TCOUNT *
741 (UNICODE_HANGUL_VCOUNT * $lIndex + $vIndex);
743 # Hardcode the limited-range UTF-8 conversion:
744 $startChar = chr( $hangulPoint >> 12 & 0x0f | 0xe0 ) .
745 chr( $hangulPoint >> 6 & 0x3f | 0x80 ) .
746 chr( $hangulPoint & 0x3f | 0x80 );
747 $lastHangul = 0;
748 continue;
749 } elseif( $c >= UTF8_HANGUL_TBASE &&
750 $c <= UTF8_HANGUL_TEND &&
751 $startChar >= UTF8_HANGUL_FIRST &&
752 $startChar <= UTF8_HANGUL_LAST &&
753 !$lastHangul ) {
754 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
755 $tIndex = ord( $c{2} ) - 0xa7;
756 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 + (0x11c0 - 0x11a7);
758 # Increment the code point by $tIndex, without
759 # the function overhead of decoding and recoding UTF-8
761 $tail = ord( $startChar{2} ) + $tIndex;
762 if( $tail > 0xbf ) {
763 $tail -= 0x40;
764 $mid = ord( $startChar{1} ) + 1;
765 if( $mid > 0xbf ) {
766 $startChar{0} = chr( ord( $startChar{0} ) + 1 );
767 $mid -= 0x40;
769 $startChar{1} = chr( $mid );
771 $startChar{2} = chr( $tail );
773 # If there's another jamo char after this, *don't* try to merge it.
774 $lastHangul = 1;
775 continue;
779 $out .= $startChar;
780 $out .= $combining;
781 $startChar = $c;
782 $combining = '';
783 $lastClass = 0;
784 $lastHangul = 0;
786 $out .= $startChar . $combining;
787 return $out;
791 * This is just used for the benchmark, comparing how long it takes to
792 * interate through a string without really doing anything of substance.
793 * @param string $string
794 * @return string
795 * @static
797 static function placebo( $string ) {
798 $len = strlen( $string );
799 $out = '';
800 for( $i = 0; $i < $len; $i++ ) {
801 $out .= $string{$i};
803 return $out;