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