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