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