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