* revert r61258
[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( extension_loaded( 'iconv' ) ) {
76 wfSuppressWarnings();
77 $ret = iconv( "UTF-8","UTF-8//IGNORE", $string );
78 wfRestoreWarnings();
79 return $ret;
80 }
81
82 if( NORMALIZE_ICU ) {
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 return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC ), "\x01" );
94 } elseif( UtfNormal::quickIsNFCVerify( $string ) ) {
95 # Side effect -- $string has had UTF-8 errors cleaned up.
96 return $string;
97 } else {
98 return UtfNormal::NFC( $string );
99 }
100 }
101
102 /**
103 * Convert a UTF-8 string to normal form C, canonical composition.
104 * Fast return for pure ASCII strings; some lesser optimizations for
105 * strings containing only known-good characters.
106 *
107 * @param $string String: a valid UTF-8 string. Input is not validated.
108 * @return string a UTF-8 string in normal form C
109 */
110 static function toNFC( $string ) {
111 if( NORMALIZE_ICU )
112 return utf8_normalize( $string, UNORM_NFC );
113 elseif( UtfNormal::quickIsNFC( $string ) )
114 return $string;
115 else
116 return UtfNormal::NFC( $string );
117 }
118
119 /**
120 * Convert a UTF-8 string to normal form D, canonical decomposition.
121 * Fast return for pure ASCII strings.
122 *
123 * @param $string String: a valid UTF-8 string. Input is not validated.
124 * @return string a UTF-8 string in normal form D
125 */
126 static function toNFD( $string ) {
127 if( NORMALIZE_ICU )
128 return utf8_normalize( $string, UNORM_NFD );
129 elseif( preg_match( '/[\x80-\xff]/', $string ) )
130 return UtfNormal::NFD( $string );
131 else
132 return $string;
133 }
134
135 /**
136 * Convert a UTF-8 string to normal form KC, compatibility composition.
137 * This may cause irreversible information loss, use judiciously.
138 * Fast return for pure ASCII strings.
139 *
140 * @param $string String: a valid UTF-8 string. Input is not validated.
141 * @return string a UTF-8 string in normal form KC
142 */
143 static function toNFKC( $string ) {
144 if( NORMALIZE_ICU )
145 return utf8_normalize( $string, UNORM_NFKC );
146 elseif( preg_match( '/[\x80-\xff]/', $string ) )
147 return UtfNormal::NFKC( $string );
148 else
149 return $string;
150 }
151
152 /**
153 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
154 * This may cause irreversible information loss, use judiciously.
155 * Fast return for pure ASCII strings.
156 *
157 * @param $string String: a valid UTF-8 string. Input is not validated.
158 * @return string a UTF-8 string in normal form KD
159 */
160 static function toNFKD( $string ) {
161 if( NORMALIZE_ICU )
162 return utf8_normalize( $string, UNORM_NFKD );
163 elseif( preg_match( '/[\x80-\xff]/', $string ) )
164 return UtfNormal::NFKD( $string );
165 else
166 return $string;
167 }
168
169 /**
170 * Load the basic composition data if necessary
171 * @private
172 */
173 static function loadData() {
174 global $utfCombiningClass;
175 if( !isset( $utfCombiningClass ) ) {
176 require_once( dirname(__FILE__) . '/UtfNormalData.inc' );
177 }
178 }
179
180 /**
181 * Returns true if the string is _definitely_ in NFC.
182 * Returns false if not or uncertain.
183 * @param $string String: a valid UTF-8 string. Input is not validated.
184 * @return bool
185 */
186 static function quickIsNFC( $string ) {
187 # ASCII is always valid NFC!
188 # If it's pure ASCII, let it through.
189 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
190
191 UtfNormal::loadData();
192 global $utfCheckNFC, $utfCombiningClass;
193 $len = strlen( $string );
194 for( $i = 0; $i < $len; $i++ ) {
195 $c = $string{$i};
196 $n = ord( $c );
197 if( $n < 0x80 ) {
198 continue;
199 } elseif( $n >= 0xf0 ) {
200 $c = substr( $string, $i, 4 );
201 $i += 3;
202 } elseif( $n >= 0xe0 ) {
203 $c = substr( $string, $i, 3 );
204 $i += 2;
205 } elseif( $n >= 0xc0 ) {
206 $c = substr( $string, $i, 2 );
207 $i++;
208 }
209 if( isset( $utfCheckNFC[$c] ) ) {
210 # If it's NO or MAYBE, bail and do the slow check.
211 return false;
212 }
213 if( isset( $utfCombiningClass[$c] ) ) {
214 # Combining character? We might have to do sorting, at least.
215 return false;
216 }
217 }
218 return true;
219 }
220
221 /**
222 * Returns true if the string is _definitely_ in NFC.
223 * Returns false if not or uncertain.
224 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
225 */
226 static function quickIsNFCVerify( &$string ) {
227 # Screen out some characters that eg won't be allowed in XML
228 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT, $string );
229
230 # ASCII is always valid NFC!
231 # If we're only ever given plain ASCII, we can avoid the overhead
232 # of initializing the decomposition tables by skipping out early.
233 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
234
235 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
236 if( !isset( $checkit ) ) {
237 # Load/build some scary lookup tables...
238 UtfNormal::loadData();
239 global $utfCheckNFC, $utfCombiningClass;
240
241 $utfCheckOrCombining = array_merge( $utfCheckNFC, $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 global $utfCanonicalDecomp;
457 return UtfNormal::fastCombiningSort(
458 UtfNormal::fastDecompose( $string, $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 global $utfCompatibilityDecomp;
477 if( !isset( $utfCompatibilityDecomp ) ) {
478 require_once( 'UtfNormalDataK.inc' );
479 }
480 return UtfNormal::fastCombiningSort(
481 UtfNormal::fastDecompose( $string, $utfCompatibilityDecomp ) );
482 }
483
484
485 /**
486 * Perform decomposition of a UTF-8 string into either D or KD form
487 * (depending on which decomposition map is passed to us).
488 * Input is assumed to be *valid* UTF-8. Invalid code will break.
489 * @private
490 * @param $string String: valid UTF-8 string
491 * @param $map Array: hash of expanded decomposition map
492 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
493 */
494 static function fastDecompose( $string, $map ) {
495 UtfNormal::loadData();
496 $len = strlen( $string );
497 $out = '';
498 for( $i = 0; $i < $len; $i++ ) {
499 $c = $string{$i};
500 $n = ord( $c );
501 if( $n < 0x80 ) {
502 # ASCII chars never decompose
503 # THEY ARE IMMORTAL
504 $out .= $c;
505 continue;
506 } elseif( $n >= 0xf0 ) {
507 $c = substr( $string, $i, 4 );
508 $i += 3;
509 } elseif( $n >= 0xe0 ) {
510 $c = substr( $string, $i, 3 );
511 $i += 2;
512 } elseif( $n >= 0xc0 ) {
513 $c = substr( $string, $i, 2 );
514 $i++;
515 }
516 if( isset( $map[$c] ) ) {
517 $out .= $map[$c];
518 continue;
519 } else {
520 if( $c >= UTF8_HANGUL_FIRST && $c <= UTF8_HANGUL_LAST ) {
521 # Decompose a hangul syllable into jamo;
522 # hardcoded for three-byte UTF-8 sequence.
523 # A lookup table would be slightly faster,
524 # but adds a lot of memory & disk needs.
525 #
526 $index = ( (ord( $c{0} ) & 0x0f) << 12
527 | (ord( $c{1} ) & 0x3f) << 6
528 | (ord( $c{2} ) & 0x3f) )
529 - UNICODE_HANGUL_FIRST;
530 $l = intval( $index / UNICODE_HANGUL_NCOUNT );
531 $v = intval( ($index % UNICODE_HANGUL_NCOUNT) / UNICODE_HANGUL_TCOUNT);
532 $t = $index % UNICODE_HANGUL_TCOUNT;
533 $out .= "\xe1\x84" . chr( 0x80 + $l ) . "\xe1\x85" . chr( 0xa1 + $v );
534 if( $t >= 25 ) {
535 $out .= "\xe1\x87" . chr( 0x80 + $t - 25 );
536 } elseif( $t ) {
537 $out .= "\xe1\x86" . chr( 0xa7 + $t );
538 }
539 continue;
540 }
541 }
542 $out .= $c;
543 }
544 return $out;
545 }
546
547 /**
548 * Sorts combining characters into canonical order. This is the
549 * final step in creating decomposed normal forms D and KD.
550 * @private
551 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
552 * @return string a UTF-8 string with combining characters sorted in canonical order
553 */
554 static function fastCombiningSort( $string ) {
555 UtfNormal::loadData();
556 global $utfCombiningClass;
557 $len = strlen( $string );
558 $out = '';
559 $combiners = array();
560 $lastClass = -1;
561 for( $i = 0; $i < $len; $i++ ) {
562 $c = $string{$i};
563 $n = ord( $c );
564 if( $n >= 0x80 ) {
565 if( $n >= 0xf0 ) {
566 $c = substr( $string, $i, 4 );
567 $i += 3;
568 } elseif( $n >= 0xe0 ) {
569 $c = substr( $string, $i, 3 );
570 $i += 2;
571 } elseif( $n >= 0xc0 ) {
572 $c = substr( $string, $i, 2 );
573 $i++;
574 }
575 if( isset( $utfCombiningClass[$c] ) ) {
576 $lastClass = $utfCombiningClass[$c];
577 if( isset( $combiners[$lastClass] ) ) {
578 $combiners[$lastClass] .= $c;
579 } else {
580 $combiners[$lastClass] = $c;
581 }
582 continue;
583 }
584 }
585 if( $lastClass ) {
586 ksort( $combiners );
587 $out .= implode( '', $combiners );
588 $combiners = array();
589 }
590 $out .= $c;
591 $lastClass = 0;
592 }
593 if( $lastClass ) {
594 ksort( $combiners );
595 $out .= implode( '', $combiners );
596 }
597 return $out;
598 }
599
600 /**
601 * Produces canonically composed sequences, i.e. normal form C or KC.
602 *
603 * @private
604 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
605 * @return string a UTF-8 string with canonical precomposed characters used where possible
606 */
607 static function fastCompose( $string ) {
608 UtfNormal::loadData();
609 global $utfCanonicalComp, $utfCombiningClass;
610 $len = strlen( $string );
611 $out = '';
612 $lastClass = -1;
613 $lastHangul = 0;
614 $startChar = '';
615 $combining = '';
616 $x1 = ord(substr(UTF8_HANGUL_VBASE,0,1));
617 $x2 = ord(substr(UTF8_HANGUL_TEND,0,1));
618 for( $i = 0; $i < $len; $i++ ) {
619 $c = $string{$i};
620 $n = ord( $c );
621 if( $n < 0x80 ) {
622 # No combining characters here...
623 $out .= $startChar;
624 $out .= $combining;
625 $startChar = $c;
626 $combining = '';
627 $lastClass = 0;
628 continue;
629 } elseif( $n >= 0xf0 ) {
630 $c = substr( $string, $i, 4 );
631 $i += 3;
632 } elseif( $n >= 0xe0 ) {
633 $c = substr( $string, $i, 3 );
634 $i += 2;
635 } elseif( $n >= 0xc0 ) {
636 $c = substr( $string, $i, 2 );
637 $i++;
638 }
639 $pair = $startChar . $c;
640 if( $n > 0x80 ) {
641 if( isset( $utfCombiningClass[$c] ) ) {
642 # A combining char; see what we can do with it
643 $class = $utfCombiningClass[$c];
644 if( !empty( $startChar ) &&
645 $lastClass < $class &&
646 $class > 0 &&
647 isset( $utfCanonicalComp[$pair] ) ) {
648 $startChar = $utfCanonicalComp[$pair];
649 $class = 0;
650 } else {
651 $combining .= $c;
652 }
653 $lastClass = $class;
654 $lastHangul = 0;
655 continue;
656 }
657 }
658 # New start char
659 if( $lastClass == 0 ) {
660 if( isset( $utfCanonicalComp[$pair] ) ) {
661 $startChar = $utfCanonicalComp[$pair];
662 $lastHangul = 0;
663 continue;
664 }
665 if( $n >= $x1 && $n <= $x2 ) {
666 # WARNING: Hangul code is painfully slow.
667 # I apologize for this ugly, ugly code; however
668 # performance is even more teh suck if we call
669 # out to nice clean functions. Lookup tables are
670 # marginally faster, but require a lot of space.
671 #
672 if( $c >= UTF8_HANGUL_VBASE &&
673 $c <= UTF8_HANGUL_VEND &&
674 $startChar >= UTF8_HANGUL_LBASE &&
675 $startChar <= UTF8_HANGUL_LEND ) {
676 #
677 #$lIndex = utf8ToCodepoint( $startChar ) - UNICODE_HANGUL_LBASE;
678 #$vIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_VBASE;
679 $lIndex = ord( $startChar{2} ) - 0x80;
680 $vIndex = ord( $c{2} ) - 0xa1;
681
682 $hangulPoint = UNICODE_HANGUL_FIRST +
683 UNICODE_HANGUL_TCOUNT *
684 (UNICODE_HANGUL_VCOUNT * $lIndex + $vIndex);
685
686 # Hardcode the limited-range UTF-8 conversion:
687 $startChar = chr( $hangulPoint >> 12 & 0x0f | 0xe0 ) .
688 chr( $hangulPoint >> 6 & 0x3f | 0x80 ) .
689 chr( $hangulPoint & 0x3f | 0x80 );
690 $lastHangul = 0;
691 continue;
692 } elseif( $c >= UTF8_HANGUL_TBASE &&
693 $c <= UTF8_HANGUL_TEND &&
694 $startChar >= UTF8_HANGUL_FIRST &&
695 $startChar <= UTF8_HANGUL_LAST &&
696 !$lastHangul ) {
697 # $tIndex = utf8ToCodepoint( $c ) - UNICODE_HANGUL_TBASE;
698 $tIndex = ord( $c{2} ) - 0xa7;
699 if( $tIndex < 0 ) $tIndex = ord( $c{2} ) - 0x80 + (0x11c0 - 0x11a7);
700
701 # Increment the code point by $tIndex, without
702 # the function overhead of decoding and recoding UTF-8
703 #
704 $tail = ord( $startChar{2} ) + $tIndex;
705 if( $tail > 0xbf ) {
706 $tail -= 0x40;
707 $mid = ord( $startChar{1} ) + 1;
708 if( $mid > 0xbf ) {
709 $startChar{0} = chr( ord( $startChar{0} ) + 1 );
710 $mid -= 0x40;
711 }
712 $startChar{1} = chr( $mid );
713 }
714 $startChar{2} = chr( $tail );
715
716 # If there's another jamo char after this, *don't* try to merge it.
717 $lastHangul = 1;
718 continue;
719 }
720 }
721 }
722 $out .= $startChar;
723 $out .= $combining;
724 $startChar = $c;
725 $combining = '';
726 $lastClass = 0;
727 $lastHangul = 0;
728 }
729 $out .= $startChar . $combining;
730 return $out;
731 }
732
733 /**
734 * This is just used for the benchmark, comparing how long it takes to
735 * interate through a string without really doing anything of substance.
736 * @param $string string
737 * @return string
738 */
739 static function placebo( $string ) {
740 $len = strlen( $string );
741 $out = '';
742 for( $i = 0; $i < $len; $i++ ) {
743 $out .= $string{$i};
744 }
745 return $out;
746 }
747 }