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