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