IcuCollation: Sort digits under localised digits' headings
[lhc/web/wiklou.git] / includes / Collation.php
1 <?php
2 /**
3 * Database row sorting.
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 * @file
21 */
22
23 abstract class Collation {
24 static $instance;
25
26 /**
27 * @return Collation
28 */
29 static function singleton() {
30 if ( !self::$instance ) {
31 global $wgCategoryCollation;
32 self::$instance = self::factory( $wgCategoryCollation );
33 }
34 return self::$instance;
35 }
36
37 /**
38 * @throws MWException
39 * @param $collationName string
40 * @return Collation
41 */
42 static function factory( $collationName ) {
43 switch ( $collationName ) {
44 case 'uppercase':
45 return new UppercaseCollation;
46 case 'identity':
47 return new IdentityCollation;
48 case 'uca-default':
49 return new IcuCollation( 'root' );
50 default:
51 $match = array();
52 if ( preg_match( '/^uca-([a-z@=-]+)$/', $collationName, $match ) ) {
53 return new IcuCollation( $match[1] );
54 }
55
56 # Provide a mechanism for extensions to hook in.
57 $collationObject = null;
58 wfRunHooks( 'Collation::factory', array( $collationName, &$collationObject ) );
59
60 if ( $collationObject instanceof Collation ) {
61 return $collationObject;
62 }
63
64 // If all else fails...
65 throw new MWException( __METHOD__ . ": unknown collation type \"$collationName\"" );
66 }
67 }
68
69 /**
70 * Given a string, convert it to a (hopefully short) key that can be used
71 * for efficient sorting. A binary sort according to the sortkeys
72 * corresponds to a logical sort of the corresponding strings. Current
73 * code expects that a line feed character should sort before all others, but
74 * has no other particular expectations (and that one can be changed if
75 * necessary).
76 *
77 * @param string $string UTF-8 string
78 * @return string Binary sortkey
79 */
80 abstract function getSortKey( $string );
81
82 /**
83 * Given a string, return the logical "first letter" to be used for
84 * grouping on category pages and so on. This has to be coordinated
85 * carefully with convertToSortkey(), or else the sorted list might jump
86 * back and forth between the same "initial letters" or other pathological
87 * behavior. For instance, if you just return the first character, but "a"
88 * sorts the same as "A" based on getSortKey(), then you might get a
89 * list like
90 *
91 * == A ==
92 * * [[Aardvark]]
93 *
94 * == a ==
95 * * [[antelope]]
96 *
97 * == A ==
98 * * [[Ape]]
99 *
100 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
101 *
102 * @param string $string UTF-8 string
103 * @return string UTF-8 string corresponding to the first letter of input
104 */
105 abstract function getFirstLetter( $string );
106 }
107
108 class UppercaseCollation extends Collation {
109 var $lang;
110 function __construct() {
111 // Get a language object so that we can use the generic UTF-8 uppercase
112 // function there
113 $this->lang = Language::factory( 'en' );
114 }
115
116 function getSortKey( $string ) {
117 return $this->lang->uc( $string );
118 }
119
120 function getFirstLetter( $string ) {
121 if ( $string[0] == "\0" ) {
122 $string = substr( $string, 1 );
123 }
124 return $this->lang->ucfirst( $this->lang->firstChar( $string ) );
125 }
126 }
127
128 /**
129 * Collation class that's essentially a no-op.
130 *
131 * Does sorting based on binary value of the string.
132 * Like how things were pre 1.17.
133 */
134 class IdentityCollation extends Collation {
135
136 function getSortKey( $string ) {
137 return $string;
138 }
139
140 function getFirstLetter( $string ) {
141 global $wgContLang;
142 // Copied from UppercaseCollation.
143 // I'm kind of unclear on when this could happen...
144 if ( $string[0] == "\0" ) {
145 $string = substr( $string, 1 );
146 }
147 return $wgContLang->firstChar( $string );
148 }
149 }
150
151 class IcuCollation extends Collation {
152 const FIRST_LETTER_VERSION = 2;
153
154 var $primaryCollator, $mainCollator, $locale, $digitTransformLanguage;
155 var $firstLetterData;
156
157 /**
158 * Unified CJK blocks.
159 *
160 * The same definition of a CJK block must be used for both Collation and
161 * generateCollationData.php. These blocks are omitted from the first
162 * letter data, as an optimisation measure and because the default UCA table
163 * is pretty useless for sorting Chinese text anyway. Japanese and Korean
164 * blocks are not included here, because they are smaller and more useful.
165 */
166 static $cjkBlocks = array(
167 array( 0x2E80, 0x2EFF ), // CJK Radicals Supplement
168 array( 0x2F00, 0x2FDF ), // Kangxi Radicals
169 array( 0x2FF0, 0x2FFF ), // Ideographic Description Characters
170 array( 0x3000, 0x303F ), // CJK Symbols and Punctuation
171 array( 0x31C0, 0x31EF ), // CJK Strokes
172 array( 0x3200, 0x32FF ), // Enclosed CJK Letters and Months
173 array( 0x3300, 0x33FF ), // CJK Compatibility
174 array( 0x3400, 0x4DBF ), // CJK Unified Ideographs Extension A
175 array( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
176 array( 0xF900, 0xFAFF ), // CJK Compatibility Ideographs
177 array( 0xFE30, 0xFE4F ), // CJK Compatibility Forms
178 array( 0x20000, 0x2A6DF ), // CJK Unified Ideographs Extension B
179 array( 0x2A700, 0x2B73F ), // CJK Unified Ideographs Extension C
180 array( 0x2B740, 0x2B81F ), // CJK Unified Ideographs Extension D
181 array( 0x2F800, 0x2FA1F ), // CJK Compatibility Ideographs Supplement
182 );
183
184 /**
185 * Additional characters (or character groups) to be considered separate
186 * letters for given languages, or to be removed from the list of such
187 * letters (denoted by keys starting with '-').
188 *
189 * These are additions to (or subtractions from) the data stored in the
190 * first-letters-root.ser file (which among others includes full basic latin,
191 * cyrillic and greek alphabets).
192 *
193 * "Separate letter" is a letter that would have a separate heading/section
194 * for it in a dictionary or a phone book in this language. This data isn't
195 * used for sorting (the ICU library handles that), only for deciding which
196 * characters (or character groups) to use as headings.
197 *
198 * Initially generated based on the primary level of Unicode collation
199 * tailorings available at http://developer.mimer.com/charts/tailorings.htm ,
200 * later modified.
201 *
202 * Empty arrays are intended; this signifies that the data for the language is
203 * available and that there are, in fact, no additional letters to consider.
204 */
205 static $tailoringFirstLetters = array(
206 // Verified by native speakers
207 'be' => array( "Ё" ),
208 'be-tarask' => array( "Ё" ),
209 'en' => array(),
210 'fi' => array( "Å", "Ä", "Ö" ),
211 'hu' => array( "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ),
212 'it' => array(),
213 'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
214 'pt' => array(),
215 'ru' => array(),
216 'sv' => array( "Å", "Ä", "Ö" ),
217 'sv@collation=standard' => array( "Å", "Ä", "Ö" ),
218 'uk' => array( "Ґ", "Ь" ),
219 'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
220 // Not verified, but likely correct
221 'af' => array(),
222 'ast' => array( "Ch", "Ll", "Ñ" ),
223 'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
224 'bg' => array(),
225 'br' => array( "Ch", "C'h" ),
226 'bs' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
227 'ca' => array(),
228 'co' => array(),
229 'cs' => array( "Č", "Ch", "Ř", "Š", "Ž" ),
230 'cy' => array( "Ch", "Dd", "Ff", "Ng", "Ll", "Ph", "Rh", "Th" ),
231 'da' => array( "Æ", "Ø", "Å" ),
232 'de' => array(),
233 'dsb' => array( "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
234 'el' => array(),
235 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
236 'es' => array( "Ñ" ),
237 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ),
238 'eu' => array( "Ñ" ),
239 'fa' => array( "آ", "ء", "ه" ),
240 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
241 'fr' => array(),
242 'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
243 'fy' => array(),
244 'ga' => array(),
245 'gd' => array(),
246 'gl' => array( "Ch", "Ll", "Ñ" ),
247 'hr' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
248 'hsb' => array( "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ),
249 'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
250 'kk' => array( "Ү", "І" ),
251 'kl' => array( "Æ", "Ø", "Å" ),
252 'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
253 'ky' => array( "Ё" ),
254 'la' => array(),
255 'lb' => array(),
256 'lt' => array( "Č", "Š", "Ž" ),
257 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
258 'mk' => array(),
259 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
260 'mt' => array( "Ċ", "Ġ", "Għ", "Ħ", "Ż" ),
261 'nl' => array(),
262 'no' => array( "Æ", "Ø", "Å" ),
263 'oc' => array(),
264 'rm' => array(),
265 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
266 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
267 'sco' => array(),
268 'sk' => array( "Ä", "Č", "Ch", "Ô", "Š", "Ž" ),
269 'sl' => array( "Č", "Š", "Ž" ),
270 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
271 'sq' => array( "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ),
272 'sr' => array(),
273 'tk' => array( "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ),
274 'tl' => array( "Ñ", "Ng" ),
275 'tr' => array( "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ),
276 'tt' => array( "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ),
277 'uz' => array( "Ch", "G'", "Ng", "O'", "Sh" ),
278 );
279
280 const RECORD_LENGTH = 14;
281
282 function __construct( $locale ) {
283 if ( !extension_loaded( 'intl' ) ) {
284 throw new MWException( 'An ICU collation was requested, ' .
285 'but the intl extension is not available.' );
286 }
287
288 $this->locale = $locale;
289 // Drop everything after the '@' in locale's name
290 $localeParts = explode( '@', $locale );
291 $this->digitTransformLanguage = Language::factory( $locale === 'root' ? 'en' : $localeParts[0] );
292
293 $this->mainCollator = Collator::create( $locale );
294 if ( !$this->mainCollator ) {
295 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
296 }
297
298 $this->primaryCollator = Collator::create( $locale );
299 $this->primaryCollator->setStrength( Collator::PRIMARY );
300 }
301
302 function getSortKey( $string ) {
303 // intl extension produces non null-terminated
304 // strings. Appending '' fixes it so that it doesn't generate
305 // a warning on each access in debug php.
306 wfSuppressWarnings();
307 $key = $this->mainCollator->getSortKey( $string ) . '';
308 wfRestoreWarnings();
309 return $key;
310 }
311
312 function getPrimarySortKey( $string ) {
313 wfSuppressWarnings();
314 $key = $this->primaryCollator->getSortKey( $string ) . '';
315 wfRestoreWarnings();
316 return $key;
317 }
318
319 function getFirstLetter( $string ) {
320 $string = strval( $string );
321 if ( $string === '' ) {
322 return '';
323 }
324
325 // Check for CJK
326 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
327 if ( ord( $firstChar ) > 0x7f && self::isCjk( utf8ToCodepoint( $firstChar ) ) ) {
328 return $firstChar;
329 }
330
331 $sortKey = $this->getPrimarySortKey( $string );
332
333 // Do a binary search to find the correct letter to sort under
334 $min = $this->findLowerBound(
335 array( $this, 'getSortKeyByLetterIndex' ),
336 $this->getFirstLetterCount(),
337 'strcmp',
338 $sortKey );
339
340 if ( $min === false ) {
341 // Before the first letter
342 return '';
343 }
344 return $this->getLetterByIndex( $min );
345 }
346
347 function getFirstLetterData() {
348 if ( $this->firstLetterData !== null ) {
349 return $this->firstLetterData;
350 }
351
352 $cache = wfGetCache( CACHE_ANYTHING );
353 $cacheKey = wfMemcKey( 'first-letters', $this->locale );
354 $cacheEntry = $cache->get( $cacheKey );
355
356 if ( $cacheEntry && isset( $cacheEntry['version'] )
357 && $cacheEntry['version'] == self::FIRST_LETTER_VERSION
358 ) {
359 $this->firstLetterData = $cacheEntry;
360 return $this->firstLetterData;
361 }
362
363 // Generate data from serialized data file
364
365 if ( isset( self::$tailoringFirstLetters[$this->locale] ) ) {
366 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
367 // Append additional characters
368 $letters = array_merge( $letters, self::$tailoringFirstLetters[$this->locale] );
369 // Remove unnecessary ones, if any
370 if ( isset( self::$tailoringFirstLetters['-' . $this->locale] ) ) {
371 $letters = array_diff( $letters, self::$tailoringFirstLetters['-' . $this->locale] );
372 }
373 // Apply digit transforms
374 $digits = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' );
375 $letters = array_diff( $letters, $digits );
376 foreach ( $digits as $digit ) {
377 $letters[] = $this->digitTransformLanguage->formatNum( $digit, true );
378 }
379 } else {
380 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
381 if ( $letters === false ) {
382 throw new MWException( "MediaWiki does not support ICU locale " .
383 "\"{$this->locale}\"" );
384 }
385 }
386
387 // Sort the letters.
388 //
389 // It's impossible to have the precompiled data file properly sorted,
390 // because the sort order changes depending on ICU version. If the
391 // array is not properly sorted, the binary search will return random
392 // results.
393 //
394 // We also take this opportunity to remove primary collisions.
395 $letterMap = array();
396 foreach ( $letters as $letter ) {
397 $key = $this->getPrimarySortKey( $letter );
398 if ( isset( $letterMap[$key] ) ) {
399 // Primary collision
400 // Keep whichever one sorts first in the main collator
401 if ( $this->mainCollator->compare( $letter, $letterMap[$key] ) < 0 ) {
402 $letterMap[$key] = $letter;
403 }
404 } else {
405 $letterMap[$key] = $letter;
406 }
407 }
408 ksort( $letterMap, SORT_STRING );
409 // Remove duplicate prefixes. Basically if something has a sortkey
410 // which is a prefix of some other sortkey, then it is an
411 // expansion and probably should not be considered a section
412 // header.
413 //
414 // For example 'þ' is sometimes sorted as if it is the letters
415 // 'th'. Other times it is its own primary element. Another
416 // example is '₨'. Sometimes its a currency symbol. Sometimes it
417 // is an 'R' followed by an 's'.
418 //
419 // Additionally an expanded element should always sort directly
420 // after its first element due to they way sortkeys work.
421 //
422 // UCA sortkey elements are of variable length but no collation
423 // element should be a prefix of some other element, so I think
424 // this is safe. See:
425 // * https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
426 // * http://site.icu-project.org/design/collation/uca-weight-allocation
427 //
428 // Additionally, there is something called primary compression to
429 // worry about. Basically, if you have two primary elements that
430 // are more than one byte and both start with the same byte then
431 // the first byte is dropped on the second primary. Additionally
432 // either \x03 or \xFF may be added to mean that the next primary
433 // does not start with the first byte of the first primary.
434 //
435 // This shouldn't matter much, as the first primary is not
436 // changed, and that is what we are comparing against.
437 //
438 // tl;dr: This makes some assumptions about how icu implements
439 // collations. It seems incredibly unlikely these assumptions
440 // will change, but nonetheless they are assumptions.
441
442 $prev = false;
443 $duplicatePrefixes = array();
444 foreach ( $letterMap as $key => $value ) {
445 // Remove terminator byte. Otherwise the prefix
446 // comparison will get hung up on that.
447 $trimmedKey = rtrim( $key, "\0" );
448 if ( $prev === false || $prev === '' ) {
449 $prev = $trimmedKey;
450 // We don't yet have a collation element
451 // to compare against, so continue.
452 continue;
453 }
454
455 // Due to the fact the array is sorted, we only have
456 // to compare with the element directly previous
457 // to the current element (skipping expansions).
458 // An element "X" will always sort directly
459 // before "XZ" (Unless we have "XY", but we
460 // do not update $prev in that case).
461 if ( substr( $trimmedKey, 0, strlen( $prev ) ) === $prev ) {
462 $duplicatePrefixes[] = $key;
463 // If this is an expansion, we don't want to
464 // compare the next element to this element,
465 // but to what is currently $prev
466 continue;
467 }
468 $prev = $trimmedKey;
469 }
470 foreach ( $duplicatePrefixes as $badKey ) {
471 wfDebug( "Removing '{$letterMap[$badKey]}' from first letters." );
472 unset( $letterMap[$badKey] );
473 // This code assumes that unsetting does not change sort order.
474 }
475 $data = array(
476 'chars' => array_values( $letterMap ),
477 'keys' => array_keys( $letterMap ),
478 'version' => self::FIRST_LETTER_VERSION,
479 );
480
481 // Reduce memory usage before caching
482 unset( $letterMap );
483
484 // Save to cache
485 $this->firstLetterData = $data;
486 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
487 return $data;
488 }
489
490 function getLetterByIndex( $index ) {
491 if ( $this->firstLetterData === null ) {
492 $this->getFirstLetterData();
493 }
494 return $this->firstLetterData['chars'][$index];
495 }
496
497 function getSortKeyByLetterIndex( $index ) {
498 if ( $this->firstLetterData === null ) {
499 $this->getFirstLetterData();
500 }
501 return $this->firstLetterData['keys'][$index];
502 }
503
504 function getFirstLetterCount() {
505 if ( $this->firstLetterData === null ) {
506 $this->getFirstLetterData();
507 }
508 return count( $this->firstLetterData['chars'] );
509 }
510
511 /**
512 * Do a binary search, and return the index of the largest item that sorts
513 * less than or equal to the target value.
514 *
515 * @param array $valueCallback A function to call to get the value with
516 * a given array index.
517 * @param int $valueCount The number of items accessible via $valueCallback,
518 * indexed from 0 to $valueCount - 1
519 * @param array $comparisonCallback A callback to compare two values, returning
520 * -1, 0 or 1 in the style of strcmp().
521 * @param string $target The target value to find.
522 *
523 * @return int|bool The item index of the lower bound, or false if the target value
524 * sorts before all items.
525 */
526 function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) {
527 if ( $valueCount === 0 ) {
528 return false;
529 }
530
531 $min = 0;
532 $max = $valueCount;
533 do {
534 $mid = $min + ( ( $max - $min ) >> 1 );
535 $item = call_user_func( $valueCallback, $mid );
536 $comparison = call_user_func( $comparisonCallback, $target, $item );
537 if ( $comparison > 0 ) {
538 $min = $mid;
539 } elseif ( $comparison == 0 ) {
540 $min = $mid;
541 break;
542 } else {
543 $max = $mid;
544 }
545 } while ( $min < $max - 1 );
546
547 if ( $min == 0 ) {
548 $item = call_user_func( $valueCallback, $min );
549 $comparison = call_user_func( $comparisonCallback, $target, $item );
550 if ( $comparison < 0 ) {
551 // Before the first item
552 return false;
553 }
554 }
555 return $min;
556 }
557
558 static function isCjk( $codepoint ) {
559 foreach ( self::$cjkBlocks as $block ) {
560 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
561 return true;
562 }
563 }
564 return false;
565 }
566
567 /**
568 * Return the version of ICU library used by PHP's intl extension,
569 * or false when the extension is not installed of the version
570 * can't be determined.
571 *
572 * The constant INTL_ICU_VERSION this function refers to isn't really
573 * documented. It is available since PHP 5.3.7 (see PHP bug 54561).
574 * This function will return false on older PHPs.
575 *
576 * @since 1.21
577 * @return string|false
578 */
579 static function getICUVersion() {
580 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION : false;
581 }
582
583 /**
584 * Return the version of Unicode appropriate for the version of ICU library
585 * currently in use, or false when it can't be determined.
586 *
587 * @since 1.21
588 * @return string|false
589 */
590 static function getUnicodeVersionForICU() {
591 $icuVersion = IcuCollation::getICUVersion();
592 if ( !$icuVersion ) {
593 return false;
594 }
595
596 $versionPrefix = substr( $icuVersion, 0, 3 );
597 // Source: http://site.icu-project.org/download
598 $map = array(
599 '50.' => '6.2',
600 '49.' => '6.1',
601 '4.8' => '6.0',
602 '4.6' => '6.0',
603 '4.4' => '5.2',
604 '4.2' => '5.1',
605 '4.0' => '5.1',
606 '3.8' => '5.0',
607 '3.6' => '5.0',
608 '3.4' => '4.1',
609 );
610
611 if ( isset( $map[$versionPrefix] ) ) {
612 return $map[$versionPrefix];
613 } else {
614 return false;
615 }
616 }
617 }