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