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