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