Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / Collation.php
blob723b38e4b8d9aa273b337c3dec03a476e449559b
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 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 $collationName string
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 default:
51 $match = array();
52 if ( preg_match( '/^uca-([a-z-]+)$/', $collationName, $match ) ) {
53 return new IcuCollation( $match[1] );
56 # Provide a mechanism for extensions to hook in.
57 $collationObject = null;
58 wfRunHooks( 'Collation::factory', array( $collationName, &$collationObject ) );
60 if ( $collationObject instanceof Collation ) {
61 return $collationObject;
64 // If all else fails...
65 throw new MWException( __METHOD__ . ": unknown collation type \"$collationName\"" );
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).
77 * @param string $string UTF-8 string
78 * @return string Binary sortkey
80 abstract function getSortKey( $string );
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
91 * == A ==
92 * * [[Aardvark]]
94 * == a ==
95 * * [[antelope]]
97 * == A ==
98 * * [[Ape]]
100 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
102 * @param string $string UTF-8 string
103 * @return string UTF-8 string corresponding to the first letter of input
105 abstract function getFirstLetter( $string );
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' );
116 function getSortKey( $string ) {
117 return $this->lang->uc( $string );
120 function getFirstLetter( $string ) {
121 if ( $string[0] == "\0" ) {
122 $string = substr( $string, 1 );
124 return $this->lang->ucfirst( $this->lang->firstChar( $string ) );
129 * Collation class that's essentially a no-op.
131 * Does sorting based on binary value of the string.
132 * Like how things were pre 1.17.
134 class IdentityCollation extends Collation {
136 function getSortKey( $string ) {
137 return $string;
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 );
147 return $wgContLang->firstChar( $string );
151 class IcuCollation extends Collation {
152 const FIRST_LETTER_VERSION = 1;
154 var $primaryCollator, $mainCollator, $locale;
155 var $firstLetterData;
158 * Unified CJK blocks.
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.
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
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 '-').
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).
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.
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.
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.
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 'uk' => array( "Ґ", "Ь" ),
218 'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
219 // Not verified, but likely correct
220 'af' => array(),
221 'ast' => array( "Ch", "Ll", "Ñ" ),
222 'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
223 'bg' => array(),
224 'br' => array( "Ch", "C'h" ),
225 'bs' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
226 'ca' => array(),
227 'co' => array(),
228 'cs' => array( "Č", "Ch", "Ř", "Š", "Ž" ),
229 'cy' => array( "Ch", "Dd", "Ff", "Ng", "Ll", "Ph", "Rh", "Th" ),
230 'da' => array( "Æ", "Ø", "Å" ),
231 'de' => array(),
232 'dsb' => array( "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
233 'el' => array(),
234 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
235 'es' => array( "Ñ" ),
236 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ),
237 'eu' => array( "Ñ" ),
238 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
239 'fr' => array(),
240 'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
241 'fy' => array(),
242 'ga' => array(),
243 'gd' => array(),
244 'gl' => array( "Ch", "Ll", "Ñ" ),
245 'hr' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
246 'hsb' => array( "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ),
247 'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
248 'kk' => array( "Ү", "І" ),
249 'kl' => array( "Æ", "Ø", "Å" ),
250 'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
251 'ky' => array( "Ё" ),
252 'la' => array(),
253 'lb' => array(),
254 'lt' => array( "Č", "Š", "Ž" ),
255 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
256 'mk' => array(),
257 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
258 'mt' => array( "Ċ", "Ġ", "Għ", "Ħ", "Ż" ),
259 'nl' => array(),
260 'no' => array( "Æ", "Ø", "Å" ),
261 'oc' => array(),
262 'rm' => array(),
263 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
264 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
265 'sco' => array(),
266 'sk' => array( "Ä", "Č", "Ch", "Ô", "Š", "Ž" ),
267 'sl' => array( "Č", "Š", "Ž" ),
268 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
269 'sq' => array( "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ),
270 'sr' => array(),
271 'tk' => array( "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ),
272 'tl' => array( "Ñ", "Ng" ),
273 'tr' => array( "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ),
274 'tt' => array( "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ),
275 'uz' => array( "Ch", "G'", "Ng", "O'", "Sh" ),
278 const RECORD_LENGTH = 14;
280 function __construct( $locale ) {
281 if ( !extension_loaded( 'intl' ) ) {
282 throw new MWException( 'An ICU collation was requested, ' .
283 'but the intl extension is not available.' );
285 $this->locale = $locale;
286 $this->mainCollator = Collator::create( $locale );
287 if ( !$this->mainCollator ) {
288 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
291 $this->primaryCollator = Collator::create( $locale );
292 $this->primaryCollator->setStrength( Collator::PRIMARY );
295 function getSortKey( $string ) {
296 // intl extension produces non null-terminated
297 // strings. Appending '' fixes it so that it doesn't generate
298 // a warning on each access in debug php.
299 wfSuppressWarnings();
300 $key = $this->mainCollator->getSortKey( $string ) . '';
301 wfRestoreWarnings();
302 return $key;
305 function getPrimarySortKey( $string ) {
306 wfSuppressWarnings();
307 $key = $this->primaryCollator->getSortKey( $string ) . '';
308 wfRestoreWarnings();
309 return $key;
312 function getFirstLetter( $string ) {
313 $string = strval( $string );
314 if ( $string === '' ) {
315 return '';
318 // Check for CJK
319 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
320 if ( ord( $firstChar ) > 0x7f
321 && self::isCjk( utf8ToCodepoint( $firstChar ) ) )
323 return $firstChar;
326 $sortKey = $this->getPrimarySortKey( $string );
328 // Do a binary search to find the correct letter to sort under
329 $min = $this->findLowerBound(
330 array( $this, 'getSortKeyByLetterIndex' ),
331 $this->getFirstLetterCount(),
332 'strcmp',
333 $sortKey );
335 if ( $min === false ) {
336 // Before the first letter
337 return '';
339 return $this->getLetterByIndex( $min );
342 function getFirstLetterData() {
343 if ( $this->firstLetterData !== null ) {
344 return $this->firstLetterData;
347 $cache = wfGetCache( CACHE_ANYTHING );
348 $cacheKey = wfMemcKey( 'first-letters', $this->locale );
349 $cacheEntry = $cache->get( $cacheKey );
351 if ( $cacheEntry && isset( $cacheEntry['version'] )
352 && $cacheEntry['version'] == self::FIRST_LETTER_VERSION )
354 $this->firstLetterData = $cacheEntry;
355 return $this->firstLetterData;
358 // Generate data from serialized data file
360 if ( isset ( self::$tailoringFirstLetters[$this->locale] ) ) {
361 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
362 // Append additional characters
363 $letters = array_merge( $letters, self::$tailoringFirstLetters[$this->locale] );
364 // Remove unnecessary ones, if any
365 if ( isset( self::$tailoringFirstLetters['-' . $this->locale] ) ) {
366 $letters = array_diff( $letters, self::$tailoringFirstLetters['-' . $this->locale] );
368 } else {
369 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
370 if ( $letters === false ) {
371 throw new MWException( "MediaWiki does not support ICU locale " .
372 "\"{$this->locale}\"" );
376 // Sort the letters.
378 // It's impossible to have the precompiled data file properly sorted,
379 // because the sort order changes depending on ICU version. If the
380 // array is not properly sorted, the binary search will return random
381 // results.
383 // We also take this opportunity to remove primary collisions.
384 $letterMap = array();
385 foreach ( $letters as $letter ) {
386 $key = $this->getPrimarySortKey( $letter );
387 if ( isset( $letterMap[$key] ) ) {
388 // Primary collision
389 // Keep whichever one sorts first in the main collator
390 if ( $this->mainCollator->compare( $letter, $letterMap[$key] ) < 0 ) {
391 $letterMap[$key] = $letter;
393 } else {
394 $letterMap[$key] = $letter;
397 ksort( $letterMap, SORT_STRING );
398 // Remove duplicate prefixes. Basically if something has a sortkey
399 // which is a prefix of some other sortkey, then it is an
400 // expansion and probably should not be considered a section
401 // header.
403 // For example 'þ' is sometimes sorted as if it is the letters
404 // 'th'. Other times it is its own primary element. Another
405 // example is '₨'. Sometimes its a currency symbol. Sometimes it
406 // is an 'R' followed by an 's'.
408 // Additionally an expanded element should always sort directly
409 // after its first element due to they way sortkeys work.
411 // UCA sortkey elements are of variable length but no collation
412 // element should be a prefix of some other element, so I think
413 // this is safe. See:
414 // * https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
415 // * http://site.icu-project.org/design/collation/uca-weight-allocation
417 // Additionally, there is something called primary compression to
418 // worry about. Basically, if you have two primary elements that
419 // are more than one byte and both start with the same byte then
420 // the first byte is dropped on the second primary. Additionally
421 // either \x03 or \xFF may be added to mean that the next primary
422 // does not start with the first byte of the first primary.
424 // This shouldn't matter much, as the first primary is not
425 // changed, and that is what we are comparing against.
427 // tl;dr: This makes some assumptions about how icu implements
428 // collations. It seems incredibly unlikely these assumptions
429 // will change, but nonetheless they are assumptions.
431 $prev = false;
432 $duplicatePrefixes = array();
433 foreach( $letterMap as $key => $value ) {
434 // Remove terminator byte. Otherwise the prefix
435 // comparison will get hung up on that.
436 $trimmedKey = rtrim( $key, "\0" );
437 if ( $prev === false || $prev === '' ) {
438 $prev = $trimmedKey;
439 // We don't yet have a collation element
440 // to compare against, so continue.
441 continue;
444 // Due to the fact the array is sorted, we only have
445 // to compare with the element directly previous
446 // to the current element (skipping expansions).
447 // An element "X" will always sort directly
448 // before "XZ" (Unless we have "XY", but we
449 // do not update $prev in that case).
450 if ( substr( $trimmedKey, 0, strlen( $prev ) ) === $prev ) {
451 $duplicatePrefixes[] = $key;
452 // If this is an expansion, we don't want to
453 // compare the next element to this element,
454 // but to what is currently $prev
455 continue;
457 $prev = $trimmedKey;
459 foreach( $duplicatePrefixes as $badKey ) {
460 wfDebug( "Removing '{$letterMap[$badKey]}' from first letters." );
461 unset( $letterMap[$badKey] );
462 // This code assumes that unsetting does not change sort order.
464 $data = array(
465 'chars' => array_values( $letterMap ),
466 'keys' => array_keys( $letterMap ),
467 'version' => self::FIRST_LETTER_VERSION,
470 // Reduce memory usage before caching
471 unset( $letterMap );
473 // Save to cache
474 $this->firstLetterData = $data;
475 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
476 return $data;
479 function getLetterByIndex( $index ) {
480 if ( $this->firstLetterData === null ) {
481 $this->getFirstLetterData();
483 return $this->firstLetterData['chars'][$index];
486 function getSortKeyByLetterIndex( $index ) {
487 if ( $this->firstLetterData === null ) {
488 $this->getFirstLetterData();
490 return $this->firstLetterData['keys'][$index];
493 function getFirstLetterCount() {
494 if ( $this->firstLetterData === null ) {
495 $this->getFirstLetterData();
497 return count( $this->firstLetterData['chars'] );
501 * Do a binary search, and return the index of the largest item that sorts
502 * less than or equal to the target value.
504 * @param array $valueCallback A function to call to get the value with
505 * a given array index.
506 * @param int $valueCount The number of items accessible via $valueCallback,
507 * indexed from 0 to $valueCount - 1
508 * @param array $comparisonCallback A callback to compare two values, returning
509 * -1, 0 or 1 in the style of strcmp().
510 * @param string $target The target value to find.
512 * @return int|bool The item index of the lower bound, or false if the target value
513 * sorts before all items.
515 function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) {
516 if ( $valueCount === 0 ) {
517 return false;
520 $min = 0;
521 $max = $valueCount;
522 do {
523 $mid = $min + ( ( $max - $min ) >> 1 );
524 $item = call_user_func( $valueCallback, $mid );
525 $comparison = call_user_func( $comparisonCallback, $target, $item );
526 if ( $comparison > 0 ) {
527 $min = $mid;
528 } elseif ( $comparison == 0 ) {
529 $min = $mid;
530 break;
531 } else {
532 $max = $mid;
534 } while ( $min < $max - 1 );
536 if ( $min == 0 ) {
537 $item = call_user_func( $valueCallback, $min );
538 $comparison = call_user_func( $comparisonCallback, $target, $item );
539 if ( $comparison < 0 ) {
540 // Before the first item
541 return false;
544 return $min;
547 static function isCjk( $codepoint ) {
548 foreach ( self::$cjkBlocks as $block ) {
549 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
550 return true;
553 return false;
557 * Return the version of ICU library used by PHP's intl extension,
558 * or false when the extension is not installed of the version
559 * can't be determined.
561 * The constant INTL_ICU_VERSION this function refers to isn't really
562 * documented. It is available since PHP 5.3.7 (see PHP bug 54561).
563 * This function will return false on older PHPs.
565 * @since 1.21
566 * @return string|false
568 static function getICUVersion() {
569 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION : false;
573 * Return the version of Unicode appropriate for the version of ICU library
574 * currently in use, or false when it can't be determined.
576 * @since 1.21
577 * @return string|false
579 static function getUnicodeVersionForICU() {
580 $icuVersion = IcuCollation::getICUVersion();
581 if ( !$icuVersion ) {
582 return false;
585 $versionPrefix = substr( $icuVersion, 0, 3 );
586 // Source: http://site.icu-project.org/download
587 $map = array(
588 '50.' => '6.2',
589 '49.' => '6.1',
590 '4.8' => '6.0',
591 '4.6' => '6.0',
592 '4.4' => '5.2',
593 '4.2' => '5.1',
594 '4.0' => '5.1',
595 '3.8' => '5.0',
596 '3.6' => '5.0',
597 '3.4' => '4.1',
600 if ( isset( $map[$versionPrefix] ) ) {
601 return $map[$versionPrefix];
602 } else {
603 return false;