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