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
23 abstract class Collation
{
24 private static $instance;
29 static function singleton() {
30 if ( !self
::$instance ) {
31 global $wgCategoryCollation;
32 self
::$instance = self
::factory( $wgCategoryCollation );
34 return self
::$instance;
39 * @param string $collationName
42 static function factory( $collationName ) {
43 switch ( $collationName ) {
45 return new UppercaseCollation
;
47 return new IdentityCollation
;
49 return new IcuCollation( 'root' );
51 return new CollationCkb
;
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\"" );
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
79 * @param string $string UTF-8 string
80 * @return string Binary sortkey
82 abstract function getSortKey( $string );
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
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
{
113 function __construct() {
114 // Get a language object so that we can use the generic UTF-8 uppercase
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 ) {
143 function getFirstLetter( $string ) {
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;
158 private $primaryCollator;
161 private $mainCollator;
167 protected $digitTransformLanguage;
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 ,
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" ),
226 'fa' => array( "آ", "ء", "ه" ),
227 'fi' => array( "Å", "Ä", "Ö" ),
229 'hu' => array( "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ),
230 'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
232 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
233 'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
236 'sv' => array( "Å", "Ä", "Ö" ),
237 'sv@collation=standard' => array( "Å", "Ä", "Ö" ),
238 'uk' => array( "Ґ", "Ь" ),
239 'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
240 // Not verified, but likely correct
242 'ast' => array( "Ch", "Ll", "Ñ" ),
243 'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
245 'br' => array( "Ch", "C'h" ),
246 'bs' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
249 'cs' => array( "Č", "Ch", "Ř", "Š", "Ž" ),
250 'da' => array( "Æ", "Ø", "Å" ),
252 'dsb' => array( "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
254 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
255 'es' => array( "Ñ" ),
256 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ),
257 'eu' => array( "Ñ" ),
258 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
259 'fur' => 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( "Ё" ),
272 'lt' => array( "Č", "Š", "Ž" ),
274 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
275 'mt' => array( "Ċ", "Ġ", "Għ", "Ħ", "Ż" ),
277 'no' => array( "Æ", "Ø", "Å" ),
280 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
281 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
283 'sk' => array( "Ä", "Č", "Ch", "Ô", "Š", "Ž" ),
284 'sl' => array( "Č", "Š", "Ž" ),
285 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
286 'sq' => array( "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ),
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 ) . '';
327 function getPrimarySortKey( $string ) {
328 wfSuppressWarnings();
329 $key = $this->primaryCollator
->getSortKey( $string ) . '';
334 function getFirstLetter( $string ) {
335 $string = strval( $string );
336 if ( $string === '' ) {
341 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
342 if ( ord( $firstChar ) > 0x7f && self
::isCjk( utf8ToCodepoint( $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(),
355 if ( $min === false ) {
356 // Before the first letter
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(
371 $this->digitTransformLanguage
->getCode(),
372 self
::getICUVersion()
374 $cacheEntry = $cache->get( $cacheKey );
376 if ( $cacheEntry && isset( $cacheEntry['version'] )
377 && $cacheEntry['version'] == self
::FIRST_LETTER_VERSION
379 $this->firstLetterData
= $cacheEntry;
380 return $this->firstLetterData
;
383 // Generate data from serialized data file
385 if ( isset( self
::$tailoringFirstLetters[$this->locale
] ) ) {
386 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
387 // Append additional characters
388 $letters = array_merge( $letters, self
::$tailoringFirstLetters[$this->locale
] );
389 // Remove unnecessary ones, if any
390 if ( isset( self
::$tailoringFirstLetters['-' . $this->locale
] ) ) {
391 $letters = array_diff( $letters, self
::$tailoringFirstLetters['-' . $this->locale
] );
393 // Apply digit transforms
394 $digits = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' );
395 $letters = array_diff( $letters, $digits );
396 foreach ( $digits as $digit ) {
397 $letters[] = $this->digitTransformLanguage
->formatNum( $digit, true );
400 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
401 if ( $letters === false ) {
402 throw new MWException( "MediaWiki does not support ICU locale " .
403 "\"{$this->locale}\"" );
409 // It's impossible to have the precompiled data file properly sorted,
410 // because the sort order changes depending on ICU version. If the
411 // array is not properly sorted, the binary search will return random
414 // We also take this opportunity to remove primary collisions.
415 $letterMap = array();
416 foreach ( $letters as $letter ) {
417 $key = $this->getPrimarySortKey( $letter );
418 if ( isset( $letterMap[$key] ) ) {
420 // Keep whichever one sorts first in the main collator
421 if ( $this->mainCollator
->compare( $letter, $letterMap[$key] ) < 0 ) {
422 $letterMap[$key] = $letter;
425 $letterMap[$key] = $letter;
428 ksort( $letterMap, SORT_STRING
);
429 // Remove duplicate prefixes. Basically if something has a sortkey
430 // which is a prefix of some other sortkey, then it is an
431 // expansion and probably should not be considered a section
434 // For example 'þ' is sometimes sorted as if it is the letters
435 // 'th'. Other times it is its own primary element. Another
436 // example is '₨'. Sometimes its a currency symbol. Sometimes it
437 // is an 'R' followed by an 's'.
439 // Additionally an expanded element should always sort directly
440 // after its first element due to they way sortkeys work.
442 // UCA sortkey elements are of variable length but no collation
443 // element should be a prefix of some other element, so I think
444 // this is safe. See:
445 // * https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
446 // * http://site.icu-project.org/design/collation/uca-weight-allocation
448 // Additionally, there is something called primary compression to
449 // worry about. Basically, if you have two primary elements that
450 // are more than one byte and both start with the same byte then
451 // the first byte is dropped on the second primary. Additionally
452 // either \x03 or \xFF may be added to mean that the next primary
453 // does not start with the first byte of the first primary.
455 // This shouldn't matter much, as the first primary is not
456 // changed, and that is what we are comparing against.
458 // tl;dr: This makes some assumptions about how icu implements
459 // collations. It seems incredibly unlikely these assumptions
460 // will change, but nonetheless they are assumptions.
463 $duplicatePrefixes = array();
464 foreach ( $letterMap as $key => $value ) {
465 // Remove terminator byte. Otherwise the prefix
466 // comparison will get hung up on that.
467 $trimmedKey = rtrim( $key, "\0" );
468 if ( $prev === false ||
$prev === '' ) {
470 // We don't yet have a collation element
471 // to compare against, so continue.
475 // Due to the fact the array is sorted, we only have
476 // to compare with the element directly previous
477 // to the current element (skipping expansions).
478 // An element "X" will always sort directly
479 // before "XZ" (Unless we have "XY", but we
480 // do not update $prev in that case).
481 if ( substr( $trimmedKey, 0, strlen( $prev ) ) === $prev ) {
482 $duplicatePrefixes[] = $key;
483 // If this is an expansion, we don't want to
484 // compare the next element to this element,
485 // but to what is currently $prev
490 foreach ( $duplicatePrefixes as $badKey ) {
491 wfDebug( "Removing '{$letterMap[$badKey]}' from first letters.\n" );
492 unset( $letterMap[$badKey] );
493 // This code assumes that unsetting does not change sort order.
496 'chars' => array_values( $letterMap ),
497 'keys' => array_keys( $letterMap ),
498 'version' => self
::FIRST_LETTER_VERSION
,
501 // Reduce memory usage before caching
505 $this->firstLetterData
= $data;
506 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
510 function getLetterByIndex( $index ) {
511 if ( $this->firstLetterData
=== null ) {
512 $this->getFirstLetterData();
514 return $this->firstLetterData
['chars'][$index];
517 function getSortKeyByLetterIndex( $index ) {
518 if ( $this->firstLetterData
=== null ) {
519 $this->getFirstLetterData();
521 return $this->firstLetterData
['keys'][$index];
524 function getFirstLetterCount() {
525 if ( $this->firstLetterData
=== null ) {
526 $this->getFirstLetterData();
528 return count( $this->firstLetterData
['chars'] );
531 static function isCjk( $codepoint ) {
532 foreach ( self
::$cjkBlocks as $block ) {
533 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
541 * Return the version of ICU library used by PHP's intl extension,
542 * or false when the extension is not installed of the version
543 * can't be determined.
545 * The constant INTL_ICU_VERSION this function refers to isn't really
546 * documented. It is available since PHP 5.3.7 (see PHP bug 54561).
547 * This function will return false on older PHPs.
550 * @return string|bool
552 static function getICUVersion() {
553 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION
: false;
557 * Return the version of Unicode appropriate for the version of ICU library
558 * currently in use, or false when it can't be determined.
561 * @return string|bool
563 static function getUnicodeVersionForICU() {
564 $icuVersion = IcuCollation
::getICUVersion();
565 if ( !$icuVersion ) {
569 $versionPrefix = substr( $icuVersion, 0, 3 );
570 // Source: http://site.icu-project.org/download
584 if ( isset( $map[$versionPrefix] ) ) {
585 return $map[$versionPrefix];
593 * Workaround for the lack of support of Sorani Kurdish / Central Kurdish language ('ckb') in ICU.
595 * Uses the same collation rules as Persian / Farsi ('fa'), but different characters for digits.
597 class CollationCkb
extends IcuCollation
{
598 function __construct() {
599 // This will set $locale and collators, which affect the actual sorting order
600 parent
::__construct( 'fa' );
601 // Override the 'fa' language set by parent constructor, which affects #getFirstLetterData()
602 $this->digitTransformLanguage
= Language
::factory( 'ckb' );