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