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