bug 25517 Assignment in conditions should be avoided/ http://www.mediawiki.org/wiki...
[lhc/web/wiklou.git] / includes / normal / UtfNormal.php
1 <?php
2 /**
3 * Unicode normalization routines
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup UtfNormal
25 */
26
27 /**
28 * @defgroup UtfNormal UtfNormal
29 */
30
31 require_once dirname(__FILE__).'/UtfNormalUtil.php';
32
33 /**
34 * For using the ICU wrapper
35 */
36 define( 'UNORM_NONE', 1 );
37 define( 'UNORM_NFD', 2 );
38 define( 'UNORM_NFKD', 3 );
39 define( 'UNORM_NFC', 4 );
40 define( 'UNORM_DEFAULT', UNORM_NFC );
41 define( 'UNORM_NFKC', 5 );
42 define( 'UNORM_FCD', 6 );
43
44 define( 'NORMALIZE_ICU', function_exists( 'utf8_normalize' ) );
45 define( 'NORMALIZE_INTL', function_exists( 'normalizer_normalize' ) );
46
47 /**
48 * Unicode normalization routines for working with UTF-8 strings.
49 * Currently assumes that input strings are valid UTF-8!
50 *
51 * Not as fast as I'd like, but should be usable for most purposes.
52 * UtfNormal::toNFC() will bail early if given ASCII text or text
53 * it can quickly deterimine is already normalized.
54 *
55 * All functions can be called static.
56 *
57 * See description of forms at http://www.unicode.org/reports/tr15/
58 *
59 * @ingroup UtfNormal
60 */
61 class UtfNormal {
62 static $utfCombiningClass = null;
63 static $utfCanonicalComp = null;
64 static $utfCanonicalDecomp = null;
65
66 # Load compatibility decompositions on demand if they are needed.
67 static $utfCompatibilityDecomp = null;
68
69 static $utfCheckNFC;
70
71 /**
72 * The ultimate convenience function! Clean up invalid UTF-8 sequences,
73 * and convert to normal form C, canonical composition.
74 *
75 * Fast return for pure ASCII strings; some lesser optimizations for
76 * strings containing only known-good characters. Not as fast as toNFC().
77 *
78 * @param $string String: a UTF-8 string
79 * @return string a clean, shiny, normalized UTF-8 string
80 */
81 static function cleanUp( $string ) {
82 if( NORMALIZE_ICU || NORMALIZE_INTL ) {
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 if ( NORMALIZE_ICU ) return rtrim( utf8_normalize( $string . "\x01", UNORM_NFC ), "\x01" );
94 if ( NORMALIZE_INTL ) return normalizer_normalize( $string, Normalizer::FORM_C );
95 } elseif( UtfNormal::quickIsNFCVerify( $string ) ) {
96 # Side effect -- $string has had UTF-8 errors cleaned up.
97 return $string;
98 } else {
99 return UtfNormal::NFC( $string );
100 }
101 }
102
103 /**
104 * Convert a UTF-8 string to normal form C, canonical composition.
105 * Fast return for pure ASCII strings; some lesser optimizations for
106 * strings containing only known-good characters.
107 *
108 * @param $string String: a valid UTF-8 string. Input is not validated.
109 * @return string a UTF-8 string in normal form C
110 */
111 static function toNFC( $string ) {
112 if( NORMALIZE_INTL )
113 return normalizer_normalize( $string, Normalizer::FORM_C );
114 elseif( NORMALIZE_ICU )
115 return utf8_normalize( $string, UNORM_NFC );
116 elseif( UtfNormal::quickIsNFC( $string ) )
117 return $string;
118 else
119 return UtfNormal::NFC( $string );
120 }
121
122 /**
123 * Convert a UTF-8 string to normal form D, canonical decomposition.
124 * Fast return for pure ASCII strings.
125 *
126 * @param $string String: a valid UTF-8 string. Input is not validated.
127 * @return string a UTF-8 string in normal form D
128 */
129 static function toNFD( $string ) {
130 if( NORMALIZE_INTL )
131 return normalizer_normalize( $string, Normalizer::FORM_D );
132 elseif( NORMALIZE_ICU )
133 return utf8_normalize( $string, UNORM_NFD );
134 elseif( preg_match( '/[\x80-\xff]/', $string ) )
135 return UtfNormal::NFD( $string );
136 else
137 return $string;
138 }
139
140 /**
141 * Convert a UTF-8 string to normal form KC, compatibility composition.
142 * This may cause irreversible information loss, use judiciously.
143 * Fast return for pure ASCII strings.
144 *
145 * @param $string String: a valid UTF-8 string. Input is not validated.
146 * @return string a UTF-8 string in normal form KC
147 */
148 static function toNFKC( $string ) {
149 if( NORMALIZE_INTL )
150 return normalizer_normalize( $string, Normalizer::FORM_KC );
151 elseif( NORMALIZE_ICU )
152 return utf8_normalize( $string, UNORM_NFKC );
153 elseif( preg_match( '/[\x80-\xff]/', $string ) )
154 return UtfNormal::NFKC( $string );
155 else
156 return $string;
157 }
158
159 /**
160 * Convert a UTF-8 string to normal form KD, compatibility decomposition.
161 * This may cause irreversible information loss, use judiciously.
162 * Fast return for pure ASCII strings.
163 *
164 * @param $string String: a valid UTF-8 string. Input is not validated.
165 * @return string a UTF-8 string in normal form KD
166 */
167 static function toNFKD( $string ) {
168 if( NORMALIZE_INTL )
169 return normalizer_normalize( $string, Normalizer::FORM_KD );
170 elseif( NORMALIZE_ICU )
171 return utf8_normalize( $string, UNORM_NFKD );
172 elseif( preg_match( '/[\x80-\xff]/', $string ) )
173 return UtfNormal::NFKD( $string );
174 else
175 return $string;
176 }
177
178 /**
179 * Load the basic composition data if necessary
180 * @private
181 */
182 static function loadData() {
183 if( !isset( self::$utfCombiningClass ) ) {
184 require_once( dirname(__FILE__) . '/UtfNormalData.inc' );
185 }
186 }
187
188 /**
189 * Returns true if the string is _definitely_ in NFC.
190 * Returns false if not or uncertain.
191 * @param $string String: a valid UTF-8 string. Input is not validated.
192 * @return bool
193 */
194 static function quickIsNFC( $string ) {
195 # ASCII is always valid NFC!
196 # If it's pure ASCII, let it through.
197 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
198
199 UtfNormal::loadData();
200 $len = strlen( $string );
201 for( $i = 0; $i < $len; $i++ ) {
202 $c = $string{$i};
203 $n = ord( $c );
204 if( $n < 0x80 ) {
205 continue;
206 } elseif( $n >= 0xf0 ) {
207 $c = substr( $string, $i, 4 );
208 $i += 3;
209 } elseif( $n >= 0xe0 ) {
210 $c = substr( $string, $i, 3 );
211 $i += 2;
212 } elseif( $n >= 0xc0 ) {
213 $c = substr( $string, $i, 2 );
214 $i++;
215 }
216 if( isset( self::$utfCheckNFC[$c] ) ) {
217 # If it's NO or MAYBE, bail and do the slow check.
218 return false;
219 }
220 if( isset( self::$utfCombiningClass[$c] ) ) {
221 # Combining character? We might have to do sorting, at least.
222 return false;
223 }
224 }
225 return true;
226 }
227
228 /**
229 * Returns true if the string is _definitely_ in NFC.
230 * Returns false if not or uncertain.
231 * @param $string String: a UTF-8 string, altered on output to be valid UTF-8 safe for XML.
232 */
233 static function quickIsNFCVerify( &$string ) {
234 # Screen out some characters that eg won't be allowed in XML
235 $string = preg_replace( '/[\x00-\x08\x0b\x0c\x0e-\x1f]/', UTF8_REPLACEMENT, $string );
236
237 # ASCII is always valid NFC!
238 # If we're only ever given plain ASCII, we can avoid the overhead
239 # of initializing the decomposition tables by skipping out early.
240 if( !preg_match( '/[\x80-\xff]/', $string ) ) return true;
241
242 static $checkit = null, $tailBytes = null, $utfCheckOrCombining = null;
243 if( !isset( $checkit ) ) {
244 # Load/build some scary lookup tables...
245 UtfNormal::loadData();
246
247 $utfCheckOrCombining = array_merge( self::$utfCheckNFC, self::$utfCombiningClass );
248
249 # Head bytes for sequences which we should do further validity checks
250 $checkit = array_flip( array_map( 'chr',
251 array( 0xc0, 0xc1, 0xe0, 0xed, 0xef,
252 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
253 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff ) ) );
254
255 # Each UTF-8 head byte is followed by a certain
256 # number of tail bytes.
257 $tailBytes = array();
258 for( $n = 0; $n < 256; $n++ ) {
259 if( $n < 0xc0 ) {
260 $remaining = 0;
261 } elseif( $n < 0xe0 ) {
262 $remaining = 1;
263 } elseif( $n < 0xf0 ) {
264 $remaining = 2;
265 } elseif( $n < 0xf8 ) {
266 $remaining = 3;
267 } elseif( $n < 0xfc ) {
268 $remaining = 4;
269 } elseif( $n < 0xfe ) {
270 $remaining = 5;
271 } else {
272 $remaining = 0;
273 }
274 $tailBytes[chr($n)] = $remaining;
275 }
276 }
277
278 # Chop the text into pure-ASCII and non-ASCII areas;
279 # large ASCII parts can be handled much more quickly.
280 # Don't chop up Unicode areas for punctuation, though,
281 # that wastes energy.
282 $matches = array();
283 preg_match_all(
284 '/([\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*)/',
285 $string, $matches );
286
287 $looksNormal = true;
288 $base = 0;
289 $replace = array();
290 foreach( $matches[1] as $str ) {
291 $chunk = strlen( $str );
292
293 if( $str{0} < "\x80" ) {
294 # ASCII chunk: guaranteed to be valid UTF-8
295 # and in normal form C, so skip over it.
296 $base += $chunk;
297 continue;
298 }
299
300 # We'll have to examine the chunk byte by byte to ensure
301 # that it consists of valid UTF-8 sequences, and to see
302 # if any of them might not be normalized.
303 #
304 # Since PHP is not the fastest language on earth, some of
305 # this code is a little ugly with inner loop optimizations.
306
307 $head = '';
308 $len = $chunk + 1; # Counting down is faster. I'm *so* sorry.
309
310 for( $i = -1; --$len; ) {
311 $remaining = $tailBytes[$c = $str{++$i}]
312 if( $remaining ) {
313 # UTF-8 head byte!
314 $sequence = $head = $c;
315 do {
316 # Look for the defined number of tail bytes...
317 if( --$len && ( $c = $str{++$i} ) >= "\x80" && $c < "\xc0" ) {
318 # Legal tail bytes are nice.
319 $sequence .= $c;
320 } else {
321 if( 0 == $len ) {
322 # Premature end of string!
323 # Drop a replacement character into output to
324 # represent the invalid UTF-8 sequence.
325 $replace[] = array( UTF8_REPLACEMENT,
326 $base + $i + 1 - strlen( $sequence ),
327 strlen( $sequence ) );
328 break 2;
329 } else {
330 # Illegal tail byte; abandon the sequence.
331 $replace[] = array( UTF8_REPLACEMENT,
332 $base + $i - strlen( $sequence ),
333 strlen( $sequence ) );
334 # Back up and reprocess this byte; it may itself
335 # be a legal ASCII or UTF-8 sequence head.
336 --$i;
337 ++$len;
338 continue 2;
339 }
340 }
341 } while( --$remaining );
342
343 if( isset( $checkit[$head] ) ) {
344 # Do some more detailed validity checks, for
345 # invalid characters and illegal sequences.
346 if( $head == "\xed" ) {
347 # 0xed is relatively frequent in Korean, which
348 # abuts the surrogate area, so we're doing
349 # this check separately to speed things up.
350
351 if( $sequence >= UTF8_SURROGATE_FIRST ) {
352 # Surrogates are legal only in UTF-16 code.
353 # They are totally forbidden here in UTF-8
354 # utopia.
355 $replace[] = array( UTF8_REPLACEMENT,
356 $base + $i + 1 - strlen( $sequence ),
357 strlen( $sequence ) );
358 $head = '';
359 continue;
360 }
361 } else {
362 # Slower, but rarer checks...
363 $n = ord( $head );
364 if(
365 # "Overlong sequences" are those that are syntactically
366 # correct but use more UTF-8 bytes than are necessary to
367 # encode a character. Naïve string comparisons can be
368 # tricked into failing to see a match for an ASCII
369 # character, for instance, which can be a security hole
370 # if blacklist checks are being used.
371 ($n < 0xc2 && $sequence <= UTF8_OVERLONG_A)
372 || ($n == 0xe0 && $sequence <= UTF8_OVERLONG_B)
373 || ($n == 0xf0 && $sequence <= UTF8_OVERLONG_C)
374
375 # U+FFFE and U+FFFF are explicitly forbidden in Unicode.
376 || ($n == 0xef &&
377 ($sequence == UTF8_FFFE)
378 || ($sequence == UTF8_FFFF) )
379
380 # Unicode has been limited to 21 bits; longer
381 # sequences are not allowed.
382 || ($n >= 0xf0 && $sequence > UTF8_MAX) ) {
383
384 $replace[] = array( UTF8_REPLACEMENT,
385 $base + $i + 1 - strlen( $sequence ),
386 strlen( $sequence ) );
387 $head = '';
388 continue;
389 }
390 }
391 }
392
393 if( isset( $utfCheckOrCombining[$sequence] ) ) {
394 # If it's NO or MAYBE, we'll have to rip
395 # the string apart and put it back together.
396 # That's going to be mighty slow.
397 $looksNormal = false;
398 }
399
400 # The sequence is legal!
401 $head = '';
402 } elseif( $c < "\x80" ) {
403 # ASCII byte.
404 $head = '';
405 } elseif( $c < "\xc0" ) {
406 # Illegal tail bytes
407 if( $head == '' ) {
408 # Out of the blue!
409 $replace[] = array( UTF8_REPLACEMENT, $base + $i, 1 );
410 } else {
411 # Don't add if we're continuing a broken sequence;
412 # we already put a replacement character when we looked
413 # at the broken sequence.
414 $replace[] = array( '', $base + $i, 1 );
415 }
416 } else {
417 # Miscellaneous freaks.
418 $replace[] = array( UTF8_REPLACEMENT, $base + $i, 1 );
419 $head = '';
420 }
421 }
422 $base += $chunk;
423 }
424 if( count( $replace ) ) {
425 # There were illegal UTF-8 sequences we need to fix up.
426 $out = '';
427 $last = 0;
428 foreach( $replace as $rep ) {
429 list( $replacement, $start, $length ) = $rep;
430 if( $last < $start ) {
431 $out .= substr( $string, $last, $start - $last );
432 }
433 $out .= $replacement;
434 $last = $start + $length;
435 }
436 if( $last < strlen( $string ) ) {
437 $out .= substr( $string, $last );
438 }
439 $string = $out;
440 }
441 return $looksNormal;
442 }
443
444 # These take a string and run the normalization on them, without
445 # checking for validity or any optimization etc. Input must be
446 # VALID UTF-8!
447 /**
448 * @param $string string
449 * @return string
450 * @private
451 */
452 static function NFC( $string ) {
453 return UtfNormal::fastCompose( UtfNormal::NFD( $string ) );
454 }
455
456 /**
457 * @param $string string
458 * @return string
459 * @private
460 */
461 static function NFD( $string ) {
462 UtfNormal::loadData();
463
464 return UtfNormal::fastCombiningSort(
465 UtfNormal::fastDecompose( $string, self::$utfCanonicalDecomp ) );
466 }
467
468 /**
469 * @param $string string
470 * @return string
471 * @private
472 */
473 static function NFKC( $string ) {
474 return UtfNormal::fastCompose( UtfNormal::NFKD( $string ) );
475 }
476
477 /**
478 * @param $string string
479 * @return string
480 * @private
481 */
482 static function NFKD( $string ) {
483 if( !isset( self::$utfCompatibilityDecomp ) ) {
484 require_once( 'UtfNormalDataK.inc' );
485 }
486 return self::fastCombiningSort(
487 self::fastDecompose( $string, self::$utfCompatibilityDecomp ) );
488 }
489
490
491 /**
492 * Perform decomposition of a UTF-8 string into either D or KD form
493 * (depending on which decomposition map is passed to us).
494 * Input is assumed to be *valid* UTF-8. Invalid code will break.
495 * @private
496 * @param $string String: valid UTF-8 string
497 * @param $map Array: hash of expanded decomposition map
498 * @return string a UTF-8 string decomposed, not yet normalized (needs sorting)
499 */
500 static function fastDecompose( $string, $map ) {
501 UtfNormal::loadData();
502 $len = strlen( $string );
503 $out = '';
504 for( $i = 0; $i < $len; $i++ ) {
505 $c = $string{$i};
506 $n = ord( $c );
507 if( $n < 0x80 ) {
508 # ASCII chars never decompose
509 # THEY ARE IMMORTAL
510 $out .= $c;
511 continue;
512 } elseif( $n >= 0xf0 ) {
513 $c = substr( $string, $i, 4 );
514 $i += 3;
515 } elseif( $n >= 0xe0 ) {
516 $c = substr( $string, $i, 3 );
517 $i += 2;
518 } elseif( $n >= 0xc0 ) {
519 $c = substr( $string, $i, 2 );
520 $i++;
521 }
522 if( isset( $map[$c] ) ) {
523 $out .= $map[$c];
524 continue;
525 } else {
526 if( $c >= UTF8_HANGUL_FIRST && $c <= UTF8_HANGUL_LAST ) {
527 # Decompose a hangul syllable into jamo;
528 # hardcoded for three-byte UTF-8 sequence.
529 # A lookup table would be slightly faster,
530 # but adds a lot of memory & disk needs.
531 #
532 $index = ( (ord( $c{0} ) & 0x0f) << 12
533 | (ord( $c{1} ) & 0x3f) << 6
534 | (ord( $c{2} ) & 0x3f) )
535 - UNICODE_HANGUL_FIRST;
536 $l = intval( $index / UNICODE_HANGUL_NCOUNT );
537 $v = intval( ($index % UNICODE_HANGUL_NCOUNT) / UNICODE_HANGUL_TCOUNT);
538 $t = $index % UNICODE_HANGUL_TCOUNT;
539 $out .= "\xe1\x84" . chr( 0x80 + $l ) . "\xe1\x85" . chr( 0xa1 + $v );
540 if( $t >= 25 ) {
541 $out .= "\xe1\x87" . chr( 0x80 + $t - 25 );
542 } elseif( $t ) {
543 $out .= "\xe1\x86" . chr( 0xa7 + $t );
544 }
545 continue;
546 }
547 }
548 $out .= $c;
549 }
550 return $out;
551 }
552
553 /**
554 * Sorts combining characters into canonical order. This is the
555 * final step in creating decomposed normal forms D and KD.
556 * @private
557 * @param $string String: a valid, decomposed UTF-8 string. Input is not validated.
558 * @return string a UTF-8 string with combining characters sorted in canonical order
559 */
560 static function fastCombiningSort( $string ) {
561 UtfNormal::loadData();
562 $len = strlen( $string );
563 $out = '';
564 $combiners = array();
565 $lastClass = -1;
566 for( $i = 0; $i < $len; $i++ ) {
567 $c = $string{$i};
568 $n = ord( $c );
569 if( $n >= 0x80 ) {
570 if( $n >= 0xf0 ) {
571 $c = substr( $string, $i, 4 );
572 $i += 3;
573 } elseif( $n >= 0xe0 ) {
574 $c = substr( $string, $i, 3 );
575 $i += 2;
576 } elseif( $n >= 0xc0 ) {
577 $c = substr( $string, $i, 2 );
578 $i++;
579 }
580 if( isset( self::$utfCombiningClass[$c] ) ) {
581 $lastClass = self::$utfCombiningClass[$c];
582 if( isset( $combiners[$lastClass] ) ) {
583 $combiners[$lastClass] .= $c;
584 } else {
585 $combiners[$lastClass] = $c;
586 }
587 continue;
588 }
589 }
590 if( $lastClass ) {
591 ksort( $combiners );
592 $out .= implode( '', $combiners );
593 $combiners = array();
594 }
595 $out .= $c;
596 $lastClass = 0;
597 }
598 if( $lastClass ) {
599 ksort( $combiners );
600 $out .= implode( '', $combiners );
601 }
602 return $out;
603 }
604
605 /**
606 * Produces canonically composed sequences, i.e. normal form C or KC.
607 *
608 * @private
609 * @param $string String: a valid UTF-8 string in sorted normal form D or KD. Input is not validated.
610 * @return string a UTF-8 string with canonical precomposed characters used where possible
611 */
612 static function fastCompose( $string ) {
613 UtfNormal::loadData();
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( self::$utfCombiningClass[$c] ) ) {
646 # A combining char; see what we can do with it
647 $class = self::$utfCombiningClass[$c];
648 if( !empty( $startChar ) &&
649 $lastClass < $class &&
650 $class > 0 &&
651 isset( self::$utfCanonicalComp[$pair] ) ) {
652 $startChar = self::$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( self::$utfCanonicalComp[$pair] ) ) {
665 $startChar = self::$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 */
743 static function placebo( $string ) {
744 $len = strlen( $string );
745 $out = '';
746 for( $i = 0; $i < $len; $i++ ) {
747 $out .= $string{$i};
748 }
749 return $out;
750 }
751 }