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