MediaWiki REL1_34
IcuCollation.php
Go to the documentation of this file.
1<?php
24class IcuCollation extends Collation {
26
29
32
34 private $locale;
35
38
40 private $useNumericCollation = false;
41
44
54 private static $cjkBlocks = [
55 [ 0x2E80, 0x2EFF ], // CJK Radicals Supplement
56 [ 0x2F00, 0x2FDF ], // Kangxi Radicals
57 [ 0x2FF0, 0x2FFF ], // Ideographic Description Characters
58 [ 0x3000, 0x303F ], // CJK Symbols and Punctuation
59 [ 0x31C0, 0x31EF ], // CJK Strokes
60 [ 0x3200, 0x32FF ], // Enclosed CJK Letters and Months
61 [ 0x3300, 0x33FF ], // CJK Compatibility
62 [ 0x3400, 0x4DBF ], // CJK Unified Ideographs Extension A
63 [ 0x4E00, 0x9FFF ], // CJK Unified Ideographs
64 [ 0xF900, 0xFAFF ], // CJK Compatibility Ideographs
65 [ 0xFE30, 0xFE4F ], // CJK Compatibility Forms
66 [ 0x20000, 0x2A6DF ], // CJK Unified Ideographs Extension B
67 [ 0x2A700, 0x2B73F ], // CJK Unified Ideographs Extension C
68 [ 0x2B740, 0x2B81F ], // CJK Unified Ideographs Extension D
69 [ 0x2F800, 0x2FA1F ], // CJK Compatibility Ideographs Supplement
70 ];
71
93 private static $tailoringFirstLetters = [
94 'af' => [],
95 'am' => [],
96 'ar' => [],
97 'as' => [ "\u{0982}", "\u{0981}", "\u{0983}", "\u{09CE}", "ক্ষ " ],
98 'ast' => [ "Ch", "Ll", "Ñ" ], // not in libicu
99 'az' => [ "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ],
100 'be' => [ "Ё" ],
101 'be-tarask' => [ "Ё" ],
102 'bg' => [],
103 'bn' => [ 'ং', 'ঃ', 'ঁ' ],
104 'bn@collation=traditional' => [
105 'ং', 'ঃ', 'ঁ', 'ক্', 'খ্', 'গ্', 'ঘ্', 'ঙ্', 'চ্', 'ছ্', 'জ্', 'ঝ্',
106 'ঞ্', 'ট্', 'ঠ্', 'ড্', 'ঢ্', 'ণ্', 'ৎ', 'থ্', 'দ্', 'ধ্', 'ন্', 'প্',
107 'ফ্', 'ব্', 'ভ্', 'ম্', 'য্', 'র্', 'ৰ্', 'ল্', 'ৱ্', 'শ্', 'ষ্', 'স্', 'হ্'
108 ],
109 'bo' => [],
110 'br' => [ "Ch", "C'h" ],
111 'bs' => [ "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ],
112 'bs-Cyrl' => [],
113 'ca' => [],
114 'chr' => [],
115 'co' => [], // not in libicu
116 'cs' => [ "Č", "Ch", "Ř", "Š", "Ž" ],
117 'cy' => [ "Ch", "Dd", "Ff", "Ng", "Ll", "Ph", "Rh", "Th" ],
118 'da' => [ "Æ", "Ø", "Å" ],
119 'de' => [],
120 'de-AT@collation=phonebook' => [ 'ä', 'ö', 'ü', 'ß' ],
121 'dsb' => [ "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ],
122 'ee' => [ "Dz", "Ɖ", "Ɛ", "Ƒ", "Gb", "Ɣ", "Kp", "Ny", "Ŋ", "Ɔ", "Ts", "Ʋ" ],
123 'el' => [],
124 'en' => [],
125 'eo' => [ "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ],
126 'es' => [ "Ñ" ],
127 'et' => [ "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ],
128 'eu' => [ "Ñ" ], // not in libicu
129 'fa' => [
130 // RTL, let's put each letter on a new line
131 "آ",
132 "ء",
133 "ه",
134 "ا",
135 "و"
136 ],
137 'fi' => [ "Å", "Ä", "Ö" ],
138 'fil' => [ "Ñ", "Ng" ],
139 'fo' => [ "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ],
140 'fr' => [],
141 'fr-CA' => [], // fr-CA sorts accents slightly different from fr.
142 'fur' => [ "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ], // not in libicu
143 'fy' => [], // not in libicu
144 'ga' => [],
145 'gd' => [], // not in libicu
146 'gl' => [ "Ch", "Ll", "Ñ" ],
147 'gu' => [ "\u{0A82}", "\u{0A83}", "\u{0A81}", "\u{0AB3}" ],
148 'ha' => [ 'Ɓ', 'Ɗ', 'Ƙ', 'Sh', 'Ts', 'Ƴ' ],
149 'haw' => [ 'ʻ' ],
150 'he' => [],
151 'hi' => [ "\u{0902}", "\u{0903}" ],
152 'hr' => [ "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ],
153 'hsb' => [ "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ],
154 'hu' => [ "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ],
155 'hy' => [ "և" ],
156 'id' => [],
157 'ig' => [ "Ch", "Gb", "Gh", "Gw", "Ị", "Kp", "Kw", "Ṅ", "Nw", "Ny", "Ọ", "Sh", "Ụ" ],
158 'is' => [ "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ],
159 'it' => [],
160 'ka' => [],
161 'kk' => [ "Ү", "І" ],
162 'kl' => [ "Æ", "Ø", "Å" ],
163 'km' => [
164 "រ", "ឫ", "ឬ", "ល", "ឭ", "ឮ", "\u{17BB}\u{17C6}",
165 "\u{17C6}", "\u{17B6}\u{17C6}", "\u{17C7}",
166 "\u{17B7}\u{17C7}", "\u{17BB}\u{17C7}",
167 "\u{17C1}\u{17C7}", "\u{17C4}\u{17C7}",
168 ],
169 'kn' => [ "\u{0C81}", "\u{0C83}", "\u{0CF1}", "\u{0CF2}" ],
170 'kok' => [ "\u{0902}", "\u{0903}", "ळ", "क्ष" ],
171 'ku' => [ "Ç", "Ê", "Î", "Ş", "Û" ], // not in libicu
172 'ky' => [ "Ё" ],
173 'la' => [], // not in libicu
174 'lb' => [],
175 'lkt' => [ 'Č', 'Ǧ', 'Ȟ', 'Š', 'Ž' ],
176 'ln' => [ 'Ɛ' ],
177 'lo' => [],
178 'lt' => [ "Č", "Š", "Ž" ],
179 'lv' => [ "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ],
180 'mk' => [ "Ѓ", "Ќ" ],
181 'ml' => [],
182 'mn' => [],
183 'mo' => [ "Ă", "Â", "Î", "Ș", "Ț" ], // not in libicu
184 'mr' => [ "\u{0902}", "\u{0903}", "ळ", "क्ष", "ज्ञ" ],
185 'ms' => [],
186 'mt' => [ "Ċ", "Ġ", "Għ", "Ħ", "Ż" ],
187 'nb' => [ "Æ", "Ø", "Å" ],
188 'ne' => [],
189 'nl' => [],
190 'nn' => [ "Æ", "Ø", "Å" ],
191 'no' => [ "Æ", "Ø", "Å" ], // not in libicu. You should probably use nb or nn instead.
192 'oc' => [], // not in libicu
193 'om' => [ 'Ch', 'Dh', 'Kh', 'Ny', 'Ph', 'Sh' ],
194 'or' => [ "\u{0B01}", "\u{0B02}", "\u{0B03}", "କ୍ଷ" ],
195 'pa' => [ "\u{0A4D}" ],
196 'pl' => [ "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ],
197 'pt' => [],
198 'rm' => [], // not in libicu
199 'ro' => [ "Ă", "Â", "Î", "Ș", "Ț" ],
200 'ru' => [],
201 'rup' => [ "Ă", "Â", "Î", "Ľ", "Ń", "Ș", "Ț" ], // not in libicu
202 'sco' => [],
203 'se' => [
204 'Á', 'Č', 'Ʒ', 'Ǯ', 'Đ', 'Ǧ', 'Ǥ', 'Ǩ', 'Ŋ',
205 'Š', 'Ŧ', 'Ž', 'Ø', 'Æ', 'Ȧ', 'Ä', 'Ö'
206 ],
207 'si' => [ "\u{0D82}", "\u{0D83}", "\u{0DA4}" ],
208 'sk' => [ "Ä", "Č", "Ch", "Ô", "Š", "Ž" ],
209 'sl' => [ "Č", "Š", "Ž" ],
210 'smn' => [ "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ],
211 'sq' => [ "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ],
212 'sr' => [],
213 'sr-Latn' => [ "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ],
214 'sv' => [ "Å", "Ä", "Ö" ],
215 'sv@collation=standard' => [ "Å", "Ä", "Ö" ],
216 'sw' => [],
217 'ta' => [
218 "\u{0B82}", "ஃ", "க்ஷ", "க்", "ங்", "ச்", "ஞ்", "ட்", "ண்", "த்", "ந்",
219 "ப்", "ம்", "ய்", "ர்", "ல்", "வ்", "ழ்", "ள்", "ற்", "ன்", "ஜ்", "ஶ்", "ஷ்",
220 "ஸ்", "ஹ்", "க்ஷ்"
221 ],
222 'te' => [ "\u{0C01}", "\u{0C02}", "\u{0C03}" ],
223 'th' => [ "ฯ", "\u{0E46}", "\u{0E4D}", "\u{0E3A}" ],
224 'tk' => [ "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ],
225 'tl' => [ "Ñ", "Ng" ], // not in libicu
226 'to' => [ "Ng", "ʻ" ],
227 'tr' => [ "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ],
228 '-tr' => [ "ı" ],
229 'tt' => [ "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ], // not in libicu
230 'uk' => [ "Ґ", "Ь" ],
231 'uz' => [ "Ch", "G'", "Ng", "O'", "Sh" ], // not in libicu
232 'vi' => [ "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ],
233 'vo' => [ "Ä", "Ö", "Ü" ],
234 'yi' => [
235 "\u{05D1}\u{05BF}", "\u{05DB}\u{05BC}", "\u{05E4}\u{05BC}",
236 "\u{05E9}\u{05C2}", "\u{05EA}\u{05BC}"
237 ],
238 'yo' => [ "Ẹ", "Gb", "Ọ", "Ṣ" ],
239 'zu' => [],
240 ];
241
245 const RECORD_LENGTH = 14;
246
247 public function __construct( $locale ) {
248 if ( !extension_loaded( 'intl' ) ) {
249 throw new MWException( 'An ICU collation was requested, ' .
250 'but the intl extension is not available.' );
251 }
252
253 $this->locale = $locale;
254 // Drop everything after the '@' in locale's name
255 $localeParts = explode( '@', $locale );
256 $this->digitTransformLanguage = Language::factory( $locale === 'root' ? 'en' : $localeParts[0] );
257
258 $this->mainCollator = Collator::create( $locale );
259 if ( !$this->mainCollator ) {
260 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
261 }
262
263 $this->primaryCollator = Collator::create( $locale );
264 $this->primaryCollator->setStrength( Collator::PRIMARY );
265
266 // If the special suffix for numeric collation is present, turn on numeric collation.
267 if ( substr( $locale, -5, 5 ) === '-u-kn' ) {
268 $this->useNumericCollation = true;
269 // Strip off the special suffix so it doesn't trip up fetchFirstLetterData().
270 $this->locale = substr( $this->locale, 0, -5 );
271 $this->mainCollator->setAttribute( Collator::NUMERIC_COLLATION, Collator::ON );
272 $this->primaryCollator->setAttribute( Collator::NUMERIC_COLLATION, Collator::ON );
273 }
274 }
275
276 public function getSortKey( $string ) {
277 return $this->mainCollator->getSortKey( $string );
278 }
279
280 public function getPrimarySortKey( $string ) {
281 return $this->primaryCollator->getSortKey( $string );
282 }
283
284 public function getFirstLetter( $string ) {
285 $string = strval( $string );
286 if ( $string === '' ) {
287 return '';
288 }
289
290 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
291
292 // If the first character is a CJK character, just return that character.
293 if ( ord( $firstChar ) > 0x7f && self::isCjk( UtfNormal\Utils::utf8ToCodepoint( $firstChar ) ) ) {
294 return $firstChar;
295 }
296
297 $sortKey = $this->getPrimarySortKey( $string );
298
299 // Do a binary search to find the correct letter to sort under
300 $min = ArrayUtils::findLowerBound(
301 [ $this, 'getSortKeyByLetterIndex' ],
302 $this->getFirstLetterCount(),
303 'strcmp',
304 $sortKey );
305
306 if ( $min === false ) {
307 // Before the first letter
308 return '';
309 }
310
311 $sortLetter = $this->getLetterByIndex( $min );
312
313 if ( $this->useNumericCollation ) {
314 // If the sort letter is a number, return '0–9' (or localized equivalent).
315 // ASCII value of 0 is 48. ASCII value of 9 is 57.
316 // Note that this also applies to non-Arabic numerals since they are
317 // mapped to Arabic numeral sort letters. For example, ২ sorts as 2.
318 if ( ord( $sortLetter ) >= 48 && ord( $sortLetter ) <= 57 ) {
319 $sortLetter = wfMessage( 'category-header-numerals' )->numParams( 0, 9 )->text();
320 }
321 }
322 return $sortLetter;
323 }
324
329 public function getFirstLetterData() {
330 if ( $this->firstLetterData === null ) {
331 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
332 $cacheKey = $cache->makeKey(
333 'first-letters',
334 static::class,
335 $this->locale,
336 $this->digitTransformLanguage->getCode(),
337 INTL_ICU_VERSION,
338 self::FIRST_LETTER_VERSION
339 );
340 $this->firstLetterData = $cache->getWithSetCallback( $cacheKey, $cache::TTL_WEEK, function () {
341 return $this->fetchFirstLetterData();
342 } );
343 }
345 }
346
351 private function fetchFirstLetterData() {
352 global $IP;
353 // Generate data from serialized data file
354 if ( isset( self::$tailoringFirstLetters[$this->locale] ) ) {
355 $letters = require "$IP/includes/collation/data/first-letters-root.php";
356 // Append additional characters
357 $letters = array_merge( $letters, self::$tailoringFirstLetters[$this->locale] );
358 // Remove unnecessary ones, if any
359 if ( isset( self::$tailoringFirstLetters['-' . $this->locale] ) ) {
360 $letters = array_diff( $letters, self::$tailoringFirstLetters['-' . $this->locale] );
361 }
362 // Apply digit transforms
363 $digits = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ];
364 $letters = array_diff( $letters, $digits );
365 foreach ( $digits as $digit ) {
366 $letters[] = $this->digitTransformLanguage->formatNum( $digit, true );
367 }
368 } elseif ( $this->locale === 'root' ) {
369 $letters = require "$IP/includes/collation/data/first-letters-root.php";
370 } else {
371 // FIXME: Is this still used?
372 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
373 if ( $letters === false ) {
374 throw new MWException( "MediaWiki does not support ICU locale " .
375 "\"{$this->locale}\"" );
376 }
377 }
378
379 /* Sort the letters.
380 *
381 * It's impossible to have the precompiled data file properly sorted,
382 * because the sort order changes depending on ICU version. If the
383 * array is not properly sorted, the binary search will return random
384 * results.
385 *
386 * We also take this opportunity to remove primary collisions.
387 */
388 $letterMap = [];
389 foreach ( $letters as $letter ) {
390 $key = $this->getPrimarySortKey( $letter );
391 if ( isset( $letterMap[$key] ) ) {
392 // Primary collision (two characters with the same sort position).
393 // Keep whichever one sorts first in the main collator.
394 $comp = $this->mainCollator->compare( $letter, $letterMap[$key] );
395 wfDebug( "Primary collision '$letter' '{$letterMap[$key]}' (comparison: $comp)\n" );
396 // If that also has a collision, use codepoint as a tiebreaker.
397 if ( $comp === 0 ) {
398 $comp = UtfNormal\Utils::utf8ToCodepoint( $letter ) <=>
399 UtfNormal\Utils::utf8ToCodepoint( $letterMap[$key] );
400 }
401 if ( $comp < 0 ) {
402 $letterMap[$key] = $letter;
403 }
404 } else {
405 $letterMap[$key] = $letter;
406 }
407 }
408 ksort( $letterMap, SORT_STRING );
409
410 /* Remove duplicate prefixes. Basically if something has a sortkey
411 * which is a prefix of some other sortkey, then it is an
412 * expansion and probably should not be considered a section
413 * header.
414 *
415 * For example 'þ' is sometimes sorted as if it is the letters
416 * 'th'. Other times it is its own primary element. Another
417 * example is '₨'. Sometimes its a currency symbol. Sometimes it
418 * is an 'R' followed by an 's'.
419 *
420 * Additionally an expanded element should always sort directly
421 * after its first element due to they way sortkeys work.
422 *
423 * UCA sortkey elements are of variable length but no collation
424 * element should be a prefix of some other element, so I think
425 * this is safe. See:
426 * - https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
427 * - http://site.icu-project.org/design/collation/uca-weight-allocation
428 *
429 * Additionally, there is something called primary compression to
430 * worry about. Basically, if you have two primary elements that
431 * are more than one byte and both start with the same byte then
432 * the first byte is dropped on the second primary. Additionally
433 * either \x03 or \xFF may be added to mean that the next primary
434 * does not start with the first byte of the first primary.
435 *
436 * This shouldn't matter much, as the first primary is not
437 * changed, and that is what we are comparing against.
438 *
439 * tl;dr: This makes some assumptions about how icu implements
440 * collations. It seems incredibly unlikely these assumptions
441 * will change, but nonetheless they are assumptions.
442 */
443
444 $prev = false;
445 $duplicatePrefixes = [];
446 foreach ( $letterMap as $key => $value ) {
447 // Remove terminator byte. Otherwise the prefix
448 // comparison will get hung up on that.
449 $trimmedKey = rtrim( $key, "\0" );
450 if ( $prev === false || $prev === '' ) {
451 $prev = $trimmedKey;
452 // We don't yet have a collation element
453 // to compare against, so continue.
454 continue;
455 }
456
457 // Due to the fact the array is sorted, we only have
458 // to compare with the element directly previous
459 // to the current element (skipping expansions).
460 // An element "X" will always sort directly
461 // before "XZ" (Unless we have "XY", but we
462 // do not update $prev in that case).
463 if ( substr( $trimmedKey, 0, strlen( $prev ) ) === $prev ) {
464 $duplicatePrefixes[] = $key;
465 // If this is an expansion, we don't want to
466 // compare the next element to this element,
467 // but to what is currently $prev
468 continue;
469 }
470 $prev = $trimmedKey;
471 }
472 foreach ( $duplicatePrefixes as $badKey ) {
473 wfDebug( "Removing '{$letterMap[$badKey]}' from first letters.\n" );
474 unset( $letterMap[$badKey] );
475 // This code assumes that unsetting does not change sort order.
476 }
477 $data = [
478 'chars' => array_values( $letterMap ),
479 'keys' => array_keys( $letterMap ),
480 ];
481
482 // Reduce memory usage before caching
483 unset( $letterMap );
484
485 return $data;
486 }
487
493 public function getLetterByIndex( $index ) {
494 return $this->getFirstLetterData()['chars'][$index];
495 }
496
502 public function getSortKeyByLetterIndex( $index ) {
503 return $this->getFirstLetterData()['keys'][$index];
504 }
505
510 public function getFirstLetterCount() {
511 return count( $this->getFirstLetterData()['chars'] );
512 }
513
520 public static function isCjk( $codepoint ) {
521 foreach ( self::$cjkBlocks as $block ) {
522 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
523 return true;
524 }
525 }
526 return false;
527 }
528
536 static function getUnicodeVersionForICU() {
537 $icuVersion = INTL_ICU_VERSION;
538 if ( !$icuVersion ) {
539 return false;
540 }
541
542 $versionPrefix = substr( $icuVersion, 0, 3 );
543 // Source: http://site.icu-project.org/download
544 $map = [
545 '63.' => '11.0',
546 '62.' => '11.0',
547 '61.' => '10.0',
548 '60.' => '10.0',
549 '59.' => '9.0',
550 '58.' => '9.0',
551 '57.' => '8.0',
552 '56.' => '8.0',
553 '55.' => '7.0',
554 '54.' => '7.0',
555 '53.' => '6.3',
556 '52.' => '6.3',
557 '51.' => '6.2',
558 '50.' => '6.2',
559 '49.' => '6.1',
560 '4.8' => '6.0',
561 '4.6' => '6.0',
562 '4.4' => '5.2',
563 '4.2' => '5.1',
564 '4.0' => '5.1',
565 '3.8' => '5.0',
566 '3.6' => '5.0',
567 '3.4' => '4.1',
568 ];
569
570 return $map[$versionPrefix] ?? false;
571 }
572}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfGetPrecompiledData( $name)
Get an object from the precompiled serialized directory.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
getLetterByIndex( $index)
getSortKeyByLetterIndex( $index)
getFirstLetter( $string)
Given a string, return the logical "first letter" to be used for grouping on category pages and so on...
bool $useNumericCollation
getPrimarySortKey( $string)
__construct( $locale)
static isCjk( $codepoint)
Test if a code point is a CJK (Chinese, Japanese, Korean) character.
const FIRST_LETTER_VERSION
Collator $mainCollator
static $cjkBlocks
Unified CJK blocks.
Language $digitTransformLanguage
Collator $primaryCollator
getSortKey( $string)
Given a string, convert it to a (hopefully short) key that can be used for efficient sorting.
array $firstLetterData
static $tailoringFirstLetters
Additional characters (or character groups) to be considered separate letters for given languages,...
static getUnicodeVersionForICU()
Return the version of Unicode appropriate for the version of ICU library currently in use,...
Internationalisation code.
Definition Language.php:37
MediaWiki exception.
$IP
Definition update.php:3
const CACHE_ANYTHING
Definition Defines.php:90
$cache
Definition mcc.php:33