* Standardised file description headers
[lhc/web/wiklou.git] / includes / normal / UtfNormal.php
1 <?php
2 /**
3 * Unicode normalization routines
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup UtfNormal
25 */
26
27 /**
28 * @defgroup UtfNormal UtfNormal
29 */
30
31 require_once dirname(__FILE__).'/UtfNormalUtil.php';
32
33 /**
34 * For using the ICU wrapper
35 */
36 define( 'UNORM_NONE', 1 );
37 define( 'UNORM_NFD', 2 );
38 define( 'UNORM_NFKD', 3 );
39 define( 'UNORM_NFC', 4 );
40 define( 'UNORM_DEFAULT', UNORM_NFC );
41 define( 'UNORM_NFKC', 5 );
42 define( 'UNORM_FCD', 6 );
43
44 define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
45 define( 'NORMALIZE_INTL', function_exists( 'normalizer_normalize' ) );
46
47 /**
48 * Unicode normalization routines for working with UTF-8 strings.
49 * Currently assumes that input strings are valid UTF-8!
50 *
51 * Not as fast as I'd like, but should be usable for most purposes.
52 * UtfNormal::toNFC() will bail early if given ASCII text or text
53 * it can quickly deterimine is already normalized.
54 *
55 * All functions can be called static.
56 *
57 * See description of forms at http://www.unicode.org/reports/tr15/
58 *
59 * @ingroup UtfNormal
60 */
61 class UtfNormal {
62 static $utfCombiningClass = null;
63 static $utfCanonicalComp = null;
64 static $utfCanonicalDecomp = null;
65
66 # Load compatibility decompositions on demand if they are needed.
67 static $utfCompatibilityDecomp = null;
68
69 static $utfCheckNFC;
70
71 /**
72 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
73 * and convert to normal form C, canonical composition.
74 *
75 * Fast return for pure ASCII strings; some lesser optimizations for
76 * strings containing only known-good characters. Not as fast as toNFC().
77 *
78 * @param $string String: a UTF-8 string
79 * @return string a clean, shiny, normalized UTF-8 string
80 */
81 static function cleanUp( $string ) {
82 if( NORMALIZE_ICU || NORMALIZE_INTL ) {
83 # We exclude a few chars that ICU would not.
84 $string = preg_replace(
85 '/[\x00-\x08\x0b\x0c\x0e-\x1f]/',
86 UTF8_REPLACEMENT,
87 $string );
88 $string = str_replace( UTF8_FFFE, UTF8_REPLACEMENT, $string );
89 $string = str_replace( UTF8_FFFF, UTF8_REPLACEMENT, $string );
90
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 if ( NORMALIZE_ICU ) return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC ), "\x01" );
94 if ( NORMALIZE_INTL ) return normalizer_normalize( $string, Normalizer::FORM_C );
95 } elseif( UtfNormal::quickIsNFCVerify( $string ) ) {
96 # Side effect -- $string has had UTF-8 errors cleaned up.
97 return $string;
98 } else {
99 return UtfNormal::NFC( $string );
100 }
101 }
102
103 /**
104 * Convert a UTF-8 string to normal form C, canonical composition.
105 * Fast return for pure ASCII strings; some lesser optimizations for
106 * strings containing only known-good characters.
107 *
108 * @param $string String: a valid UTF-8 string. Input is not validated.
109 * @return string a UTF-8 string in normal form C
110 */
111 static function toNFC( $string ) {
112 if( NORMALIZE_INTL )
113 return normalizer_normalize( $string, Normalizer::FORM_C );
114 elseif( NORMALIZE_ICU )
115 return utf8_normalize( $string, UNORM_NFC );
116 elseif( UtfNormal::quickIsNFC( $string ) )
117 return $string;
118 else
119 return UtfNormal::NFC( $string );
120 }
121
122 /**
123 * Convert a UTF-8 string to normal form D, canonical decomposition.
124 * Fast return for pure ASCII strings.
125 *
126 * @param $string String: a valid UTF-8 string. Input is not validated.
127 * @return string a UTF-8 string in normal form D
128 */
129 static function toNFD( $string ) {
130 if( NORMALIZE_INTL )
131 return normalizer_normalize( $string, Normalizer::FORM_D );
132 elseif( NORMALIZE_ICU )
133 return utf8_normalize( $string, UNORM_NFD );
134 elseif( preg_match( '/[\x80-\xff]/', $string ) )
135 return UtfNormal::NFD( $string );
136 else
137 return $string;
138 }
139
140 /**
141 * Convert a UTF-8 string to normal form KC, compatibility composition.
142 * This may cause irreversible information loss, use judiciously.
143 * Fast return for pure ASCII strings.
144 *
145 * @param $string String: a valid UTF-8 string. Input is not validated.
146 * @return string a UTF-8 string in normal form KC
147 */
148 static function toNFKC( $string ) {
149 if( NORMALIZE_INTL )
150 return normalizer_normalize( $string, Normalizer::FORM_KC );
151 elseif( NORMALIZE_ICU )
152 return utf8_normalize( $string, UNORM_NFKC );
153 elseif( preg_match( '/[\x80-\xff]/', $string ) )
154 return UtfNormal::NFKC( $string );
155 else
156 return $string;
157 }
158
159 /**
160 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
161 * This may cause irreversible information loss, use judiciously.
162 * Fast return for pure ASCII strings.
163 *
164 * @param $string String: a valid UTF-8 string. Input is not validated.
165 * @return string a UTF-8 string in normal form KD
166 */
167 static function toNFKD( $string ) {
168 if( NORMALIZE_INTL )
169 return normalizer_normalize( $string, Normalizer::FORM_KD );
170 elseif( NORMALIZE_ICU )
171 return utf8_normalize( $string, UNORM_NFKD );
172 elseif( preg_match( '/[\x80-\xff]/', $string ) )
173 return UtfNormal::NFKD( $string );
174 else
175 return $string;
176 }
177
178 /**
179 * Load the basic composition data if necessary
180 * @private
181 */
182 static function loadData() {
183 if( !isset( self::$utfCombiningClass ) ) {
184 require_once( dirname(__FILE__) . '/UtfNormalData.inc' );
185 }
186 }
187
188 /**
189 * Returns true if the string is _definitely_ in NFC.
190 * Returns false if not or uncertain.
191 * @param $string String: a valid UTF-8 string. Input is not validated.
192 * @return bool
193 */
194 static function quickIsNFC( $string ) {
195 # ASCII is always valid NFC!
196 # If it's pure ASCII, let it through.
197 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
198
199 UtfNormal::loadData();
200 $len = strlen( $string );
201 for( $i = 0; $i < $len; $i++ ) {
202 $c = $string{$i};
203 $n = ord( $c );
204 if( $n < 0x80 ) {
205 continue;
206 } elseif( $n >= 0xf0 ) {
207 $c = substr( $string, $i, 4 );
208 $i += 3;
209 } elseif( $n >= 0xe0 ) {
210 $c = substr( $string, $i, 3 );
211 $i += 2;
212 } elseif( $n >= 0xc0 ) {
213 $c = substr( $string, $i, 2 );
214 $i++;
215 }
216 if( isset( self::$utfCheckNFC[$c] ) ) {
217 # If it's NO or MAYBE, bail and do the slow check.
218 return false;
219 }
220 if( isset( self::$utfCombiningClass[$c] ) ) {
221 # Combining character? We might have to do sorting, at least.
222 return false;
223 }
224 }
225 return true;
226 }
227
228 /**
229 * Returns true if the string is _definitely_ in NFC.
230 * Returns false if not or uncertain.
231 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
232 */
233 static function quickIsNFCVerify( &$string ) {
234 # Screen out some characters that eg won't be allowed in XML
235 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT, $string );
236
237 # ASCII is always valid NFC!
238 # If we're only ever given plain ASCII, we can avoid the overhead
239 # of initializing the decomposition tables by skipping out early.
240 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
241
242 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
243 if( !isset( $checkit ) ) {
244 # Load/build some scary lookup tables...
245 UtfNormal::loadData();
246
247 $utfCheckOrCombining = array_merge( self::$utfCheckNFC, self::$utfCombiningClass );
248
249 # Head bytes for sequences which we should do further validity checks
250 $checkit = array_flip( array_map( 'chr',
251 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
252 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
253 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
254
255 # Each UTF-8 head byte is followed by a certain
256 # number of tail bytes.
257 $tailBytes = array();
258 for( $n = 0; $n < 256; $n++ ) {
259 if( $n < 0xc0 ) {
260 $remaining = 0;
261 } elseif( $n < 0xe0 ) {
262 $remaining = 1;
263 } elseif( $n < 0xf0 ) {
264 $remaining = 2;
265 } elseif( $n < 0xf8 ) {
266 $remaining = 3;
267 } elseif( $n < 0xfc ) {
268 $remaining = 4;
269 } elseif( $n < 0xfe ) {
270 $remaining = 5;
271 } else {
272 $remaining = 0;
273 }
274 $tailBytes[chr($n)] = $remaining;
275 }
276 }
277
278 # Chop the text into pure-ASCII and non-ASCII areas;
279 # large ASCII parts can be handled much more quickly.
280 # Don't chop up Unicode areas for punctuation, though,
281 # that wastes energy.
282 $matches = array();
283 preg_match_all(
284 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
285 $string, $matches );
286
287 $looksNormal = true;
288 $base = 0;
289 $replace = array();
290 foreach( $matches[1] as $str ) {
291 $chunk = strlen( $str );
292
293 if( $str{0} < "\x80" ) {
294 # ASCII chunk: guaranteed to be valid UTF-8
295 # and in normal form C, so skip over it.
296 $base += $chunk;
297 continue;
298 }
299
300 # We'll have to examine the chunk byte by byte to ensure
301 # that it consists of valid UTF-8 sequences, and to see
302 # if any of them might not be normalized.
303 #
304 # Since PHP is not the fastest language on earth, some of
305 # this code is a little ugly with inner loop optimizations.
306
307 $head = '';
308 $len = $chunk + 1; # Counting down is faster. I'm *so* sorry.
309
310 for( $i = -1; --$len; ) {
311 if( $remaining = $tailBytes[$c = $str{++$i}] ) {
312 # UTF-8 head byte!
313 $sequence = $head = $c;
314 do {
315 # Look for the defined number of tail bytes...
316 if( --$len && ( $c = $str{++$i} ) >= "\x80" && $c < "\xc0" ) {
317 # Legal tail bytes are nice.
318 $sequence .= $c;
319 } else {
320 if( 0 == $len ) {
321 # Premature end of string!
322 # Drop a replacement character into output to
323 # represent the invalid UTF-8 sequence.
324 $replace[] = array( UTF8_REPLACEMENT,
325 $base + $i + 1 - strlen( $sequence ),
326 strlen( $sequence ) );
327 break 2;
328 } else {
329 # Illegal tail byte; abandon the sequence.
330 $replace[] = array( UTF8_REPLACEMENT,
331 $base + $i - strlen( $sequence ),
332 strlen( $sequence ) );
333 # Back up and reprocess this byte; it may itself
334 # be a legal ASCII or UTF-8 sequence head.
335 --$i;
336 ++$len;
337 continue 2;
338 }
339 }
340 } while( --$remaining );
341
342 if( isset( $checkit[$head] ) ) {
343 # Do some more detailed validity checks, for
344 # invalid characters and illegal sequences.
345 if( $head == "\xed" ) {
346 # 0xed is relatively frequent in Korean, which
347 # abuts the surrogate area, so we're doing
348 # this check separately to speed things up.
349
350 if( $sequence >= UTF8_SURROGATE_FIRST ) {
351 # Surrogates are legal only in UTF-16 code.
352 # They are totally forbidden here in UTF-8
353 # utopia.
354 $replace[] = array( UTF8_REPLACEMENT,
355 $base + $i + 1 - strlen( $sequence ),
356 strlen( $sequence ) );
357 $head = '';
358 continue;
359 }
360 } else {
361 # Slower, but rarer checks...
362 $n = ord( $head );
363 if(
364 # "Overlong sequences" are those that are syntactically
365 # correct but use more UTF-8 bytes than are necessary to
366 # encode a character. Naïve string comparisons can be
367 # tricked into failing to see a match for an ASCII
368 # character, for instance, which can be a security hole
369 # if blacklist checks are being used.
370 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A)
371 || ($n == 0xe0 && $sequence <= UTF8_OVERLONG_B)
372 || ($n == 0xf0 && $sequence <= UTF8_OVERLONG_C)
373
374 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
375 || ($n == 0xef &&
376 ($sequence == UTF8_FFFE)
377 || ($sequence == UTF8_FFFF) )
378
379 # Unicode has been limited to 21 bits; longer
380 # sequences are not allowed.
381 || ($n >= 0xf0 && $sequence > UTF8_MAX) ) {
382
383 $replace[] = array( UTF8_REPLACEMENT,
384 $base + $i + 1 - strlen( $sequence ),
385 strlen( $sequence ) );
386 $head = '';
387 continue;
388 }
389 }
390 }
391
392 if( isset( $utfCheckOrCombining[$sequence] ) ) {
393 # If it's NO or MAYBE, we'll have to rip
394 # the string apart and put it back together.
395 # That's going to be mighty slow.
396 $looksNormal = false;
397 }
398
399 # The sequence is legal!
400 $head = '';
401 } elseif( $c < "\x80" ) {
402 # ASCII byte.
403 $head = '';
404 } elseif( $c < "\xc0" ) {
405 # Illegal tail bytes
406 if( $head == '' ) {
407 # Out of the blue!
408 $replace[] = array( UTF8_REPLACEMENT, $base + $i, 1 );
409 } else {
410 # Don't add if we're continuing a broken sequence;
411 # we already put a replacement character when we looked
412 # at the broken sequence.
413 $replace[] = array( '', $base + $i, 1 );
414 }
415 } else {
416 # Miscellaneous freaks.
417 $replace[] = array( UTF8_REPLACEMENT, $base + $i, 1 );
418 $head = '';
419 }
420 }
421 $base += $chunk;
422 }
423 if( count( $replace ) ) {
424 # There were illegal UTF-8 sequences we need to fix up.
425 $out = '';
426 $last = 0;
427 foreach( $replace as $rep ) {
428 list( $replacement, $start, $length ) = $rep;
429 if( $last < $start ) {
430 $out .= substr( $string, $last, $start - $last );
431 }
432 $out .= $replacement;
433 $last = $start + $length;
434 }
435 if( $last < strlen( $string ) ) {
436 $out .= substr( $string, $last );
437 }
438 $string = $out;
439 }
440 return $looksNormal;
441 }
442
443 # These take a string and run the normalization on them, without
444 # checking for validity or any optimization etc. Input must be
445 # VALID UTF-8!
446 /**
447 * @param $string string
448 * @return string
449 * @private
450 */
451 static function NFC( $string ) {
452 return UtfNormal::fastCompose( UtfNormal::NFD( $string ) );
453 }
454
455 /**
456 * @param $string string
457 * @return string
458 * @private
459 */
460 static function NFD( $string ) {
461 UtfNormal::loadData();
462
463 return UtfNormal::fastCombiningSort(
464 UtfNormal::fastDecompose( $string, self::$utfCanonicalDecomp ) );
465 }
466
467 /**
468 * @param $string string
469 * @return string
470 * @private
471 */
472 static function NFKC( $string ) {
473 return UtfNormal::fastCompose( UtfNormal::NFKD( $string ) );
474 }
475
476 /**
477 * @param $string string
478 * @return string
479 * @private
480 */
481 static function NFKD( $string ) {
482 if( !isset( self::$utfCompatibilityDecomp ) ) {
483 require_once( 'UtfNormalDataK.inc' );
484 }
485 return self::fastCombiningSort(
486 self::fastDecompose( $string, self::$utfCompatibilityDecomp ) );
487 }
488
489
490 /**
491 * Perform decomposition of a UTF-8 string into either D or KD form
492 * (depending on which decomposition map is passed to us).
493 * Input is assumed to be *valid* UTF-8. Invalid code will break.
494 * @private
495 * @param $string String: valid UTF-8 string
496 * @param $map Array: hash of expanded decomposition map
497 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
498 */
499 static function fastDecompose( $string, $map ) {
500 UtfNormal::loadData();
501 $len = strlen( $string );
502 $out = '';
503 for( $i = 0; $i < $len; $i++ ) {
504 $c = $string{$i};
505 $n = ord( $c );
506 if( $n < 0x80 ) {
507 # ASCII chars never decompose
508 # THEY ARE IMMORTAL
509 $out .= $c;
510 continue;
511 } elseif( $n >= 0xf0 ) {
512 $c = substr( $string, $i, 4 );
513 $i += 3;
514 } elseif( $n >= 0xe0 ) {
515 $c = substr( $string, $i, 3 );
516 $i += 2;
517 } elseif( $n >= 0xc0 ) {
518 $c = substr( $string, $i, 2 );
519 $i++;
520 }
521 if( isset( $map[$c] ) ) {
522 $out .= $map[$c];
523 continue;
524 } else {
525 if( $c >= UTF8_HANGUL_FIRST && $c <= UTF8_HANGUL_LAST ) {
526 # Decompose a hangul syllable into jamo;
527 # hardcoded for three-byte UTF-8 sequence.
528 # A lookup table would be slightly faster,
529 # but adds a lot of memory & disk needs.
530 #
531 $index = ( (ord( $c{0} ) & 0x0f) << 12
532 | (ord( $c{1} ) & 0x3f) << 6
533 | (ord( $c{2} ) & 0x3f) )
534 - UNICODE_HANGUL_FIRST;
535 $l = intval( $index / UNICODE_HANGUL_NCOUNT );
536 $v = intval( ($index % UNICODE_HANGUL_NCOUNT) / UNICODE_HANGUL_TCOUNT);
537 $t = $index % UNICODE_HANGUL_TCOUNT;
538 $out .= "\xe1\x84" . chr( 0x80 + $l ) . "\xe1\x85" . chr( 0xa1 + $v );
539 if( $t >= 25 ) {
540 $out .= "\xe1\x87" . chr( 0x80 + $t - 25 );
541 } elseif( $t ) {
542 $out .= "\xe1\x86" . chr( 0xa7 + $t );
543 }
544 continue;
545 }
546 }
547 $out .= $c;
548 }
549 return $out;
550 }
551
552 /**
553 * Sorts combining characters into canonical order. This is the
554 * final step in creating decomposed normal forms D and KD.
555 * @private
556 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
557 * @return string a UTF-8 string with combining characters sorted in canonical order
558 */
559 static function fastCombiningSort( $string ) {
560 UtfNormal::loadData();
561 $len = strlen( $string );
562 $out = '';
563 $combiners = array();
564 $lastClass = -1;
565 for( $i = 0; $i < $len; $i++ ) {
566 $c = $string{$i};
567 $n = ord( $c );
568 if( $n >= 0x80 ) {
569 if( $n >= 0xf0 ) {
570 $c = substr( $string, $i, 4 );
571 $i += 3;
572 } elseif( $n >= 0xe0 ) {
573 $c = substr( $string, $i, 3 );
574 $i += 2;
575 } elseif( $n >= 0xc0 ) {
576 $c = substr( $string, $i, 2 );
577 $i++;
578 }
579 if( isset( self::$utfCombiningClass[$c] ) ) {
580 $lastClass = self::$utfCombiningClass[$c];
581 if( isset( $combiners[$lastClass] ) ) {
582 $combiners[$lastClass] .= $c;
583 } else {
584 $combiners[$lastClass] = $c;
585 }
586 continue;
587 }
588 }
589 if( $lastClass ) {
590 ksort( $combiners );
591 $out .= implode( '', $combiners );
592 $combiners = array();
593 }
594 $out .= $c;
595 $lastClass = 0;
596 }
597 if( $lastClass ) {
598 ksort( $combiners );
599 $out .= implode( '', $combiners );
600 }
601 return $out;
602 }
603
604 /**
605 * Produces canonically composed sequences, i.e. normal form C or KC.
606 *
607 * @private
608 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
609 * @return string a UTF-8 string with canonical precomposed characters used where possible
610 */
611 static function fastCompose( $string ) {
612 UtfNormal::loadData();
613 $len = strlen( $string );
614 $out = '';
615 $lastClass = -1;
616 $lastHangul = 0;
617 $startChar = '';
618 $combining = '';
619 $x1 = ord(substr(UTF8_HANGUL_VBASE,0,1));
620 $x2 = ord(substr(UTF8_HANGUL_TEND,0,1));
621 for( $i = 0; $i < $len; $i++ ) {
622 $c = $string{$i};
623 $n = ord( $c );
624 if( $n < 0x80 ) {
625 # No combining characters here...
626 $out .= $startChar;
627 $out .= $combining;
628 $startChar = $c;
629 $combining = '';
630 $lastClass = 0;
631 continue;
632 } elseif( $n >= 0xf0 ) {
633 $c = substr( $string, $i, 4 );
634 $i += 3;
635 } elseif( $n >= 0xe0 ) {
636 $c = substr( $string, $i, 3 );
637 $i += 2;
638 } elseif( $n >= 0xc0 ) {
639 $c = substr( $string, $i, 2 );
640 $i++;
641 }
642 $pair = $startChar . $c;
643 if( $n > 0x80 ) {
644 if( isset( self::$utfCombiningClass[$c] ) ) {
645 # A combining char; see what we can do with it
646 $class = self::$utfCombiningClass[$c];
647 if( !empty( $startChar ) &&
648 $lastClass < $class &&
649 $class > 0 &&
650 isset( self::$utfCanonicalComp[$pair] ) ) {
651 $startChar = self::$utfCanonicalComp[$pair];
652 $class = 0;
653 } else {
654 $combining .= $c;
655 }
656 $lastClass = $class;
657 $lastHangul = 0;
658 continue;
659 }
660 }
661 # New start char
662 if( $lastClass == 0 ) {
663 if( isset( self::$utfCanonicalComp[$pair] ) ) {
664 $startChar = self::$utfCanonicalComp[$pair];
665 $lastHangul = 0;
666 continue;
667 }
668 if( $n >= $x1 && $n <= $x2 ) {
669 # WARNING: Hangul code is painfully slow.
670 # I apologize for this ugly, ugly code; however
671 # performance is even more teh suck if we call
672 # out to nice clean functions. Lookup tables are
673 # marginally faster, but require a lot of space.
674 #
675 if( $c >= UTF8_HANGUL_VBASE &&
676 $c <= UTF8_HANGUL_VEND &&
677 $startChar >= UTF8_HANGUL_LBASE &&
678 $startChar <= UTF8_HANGUL_LEND ) {
679 #
680 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
681 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
682 $lIndex = ord( $startChar{2} ) - 0x80;
683 $vIndex = ord( $c{2} ) - 0xa1;
684
685 $hangulPoint = UNICODE_HANGUL_FIRST +
686 UNICODE_HANGUL_TCOUNT *
687 (UNICODE_HANGUL_VCOUNT * $lIndex + $vIndex);
688
689 # Hardcode the limited-range UTF-8 conversion:
690 $startChar = chr( $hangulPoint >> 12 & 0x0f | 0xe0 ) .
691 chr( $hangulPoint >> 6 & 0x3f | 0x80 ) .
692 chr( $hangulPoint & 0x3f | 0x80 );
693 $lastHangul = 0;
694 continue;
695 } elseif( $c >= UTF8_HANGUL_TBASE &&
696 $c <= UTF8_HANGUL_TEND &&
697 $startChar >= UTF8_HANGUL_FIRST &&
698 $startChar <= UTF8_HANGUL_LAST &&
699 !$lastHangul ) {
700 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
701 $tIndex = ord( $c{2} ) - 0xa7;
702 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 + (0x11c0 - 0x11a7);
703
704 # Increment the code point by $tIndex, without
705 # the function overhead of decoding and recoding UTF-8
706 #
707 $tail = ord( $startChar{2} ) + $tIndex;
708 if( $tail > 0xbf ) {
709 $tail -= 0x40;
710 $mid = ord( $startChar{1} ) + 1;
711 if( $mid > 0xbf ) {
712 $startChar{0} = chr( ord( $startChar{0} ) + 1 );
713 $mid -= 0x40;
714 }
715 $startChar{1} = chr( $mid );
716 }
717 $startChar{2} = chr( $tail );
718
719 # If there's another jamo char after this, *don't* try to merge it.
720 $lastHangul = 1;
721 continue;
722 }
723 }
724 }
725 $out .= $startChar;
726 $out .= $combining;
727 $startChar = $c;
728 $combining = '';
729 $lastClass = 0;
730 $lastHangul = 0;
731 }
732 $out .= $startChar . $combining;
733 return $out;
734 }
735
736 /**
737 * This is just used for the benchmark, comparing how long it takes to
738 * interate through a string without really doing anything of substance.
739 * @param $string string
740 * @return string
741 */
742 static function placebo( $string ) {
743 $len = strlen( $string );
744 $out = '';
745 for( $i = 0; $i < $len; $i++ ) {
746 $out .= $string{$i};
747 }
748 return $out;
749 }
750 }