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
;
53 return new CollationEt
;
56 if ( preg_match( '/^uca-([a-z@=-]+)$/', $collationName, $match ) ) {
57 return new IcuCollation( $match[1] );
60 # Provide a mechanism for extensions to hook in.
61 $collationObject = null;
62 Hooks
::run( 'Collation::factory', array( $collationName, &$collationObject ) );
64 if ( $collationObject instanceof Collation
) {
65 return $collationObject;
68 // If all else fails...
69 throw new MWException( __METHOD__
. ": unknown collation type \"$collationName\"" );
74 * Given a string, convert it to a (hopefully short) key that can be used
75 * for efficient sorting. A binary sort according to the sortkeys
76 * corresponds to a logical sort of the corresponding strings. Current
77 * code expects that a line feed character should sort before all others, but
78 * has no other particular expectations (and that one can be changed if
81 * @param string $string UTF-8 string
82 * @return string Binary sortkey
84 abstract function getSortKey( $string );
87 * Given a string, return the logical "first letter" to be used for
88 * grouping on category pages and so on. This has to be coordinated
89 * carefully with convertToSortkey(), or else the sorted list might jump
90 * back and forth between the same "initial letters" or other pathological
91 * behavior. For instance, if you just return the first character, but "a"
92 * sorts the same as "A" based on getSortKey(), then you might get a
104 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
106 * @param string $string UTF-8 string
107 * @return string UTF-8 string corresponding to the first letter of input
109 abstract function getFirstLetter( $string );
112 class UppercaseCollation
extends Collation
{
115 function __construct() {
116 // Get a language object so that we can use the generic UTF-8 uppercase
118 $this->lang
= Language
::factory( 'en' );
121 function getSortKey( $string ) {
122 return $this->lang
->uc( $string );
125 function getFirstLetter( $string ) {
126 if ( $string[0] == "\0" ) {
127 $string = substr( $string, 1 );
129 return $this->lang
->ucfirst( $this->lang
->firstChar( $string ) );
134 * Collation class that's essentially a no-op.
136 * Does sorting based on binary value of the string.
137 * Like how things were pre 1.17.
139 class IdentityCollation
extends Collation
{
141 function getSortKey( $string ) {
145 function getFirstLetter( $string ) {
147 // Copied from UppercaseCollation.
148 // I'm kind of unclear on when this could happen...
149 if ( $string[0] == "\0" ) {
150 $string = substr( $string, 1 );
152 return $wgContLang->firstChar( $string );
156 class IcuCollation
extends Collation
{
157 const FIRST_LETTER_VERSION
= 2;
160 private $primaryCollator;
163 private $mainCollator;
169 protected $digitTransformLanguage;
172 private $firstLetterData;
175 * Unified CJK blocks.
177 * The same definition of a CJK block must be used for both Collation and
178 * generateCollationData.php. These blocks are omitted from the first
179 * letter data, as an optimisation measure and because the default UCA table
180 * is pretty useless for sorting Chinese text anyway. Japanese and Korean
181 * blocks are not included here, because they are smaller and more useful.
183 private static $cjkBlocks = array(
184 array( 0x2E80, 0x2EFF ), // CJK Radicals Supplement
185 array( 0x2F00, 0x2FDF ), // Kangxi Radicals
186 array( 0x2FF0, 0x2FFF ), // Ideographic Description Characters
187 array( 0x3000, 0x303F ), // CJK Symbols and Punctuation
188 array( 0x31C0, 0x31EF ), // CJK Strokes
189 array( 0x3200, 0x32FF ), // Enclosed CJK Letters and Months
190 array( 0x3300, 0x33FF ), // CJK Compatibility
191 array( 0x3400, 0x4DBF ), // CJK Unified Ideographs Extension A
192 array( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
193 array( 0xF900, 0xFAFF ), // CJK Compatibility Ideographs
194 array( 0xFE30, 0xFE4F ), // CJK Compatibility Forms
195 array( 0x20000, 0x2A6DF ), // CJK Unified Ideographs Extension B
196 array( 0x2A700, 0x2B73F ), // CJK Unified Ideographs Extension C
197 array( 0x2B740, 0x2B81F ), // CJK Unified Ideographs Extension D
198 array( 0x2F800, 0x2FA1F ), // CJK Compatibility Ideographs Supplement
202 * Additional characters (or character groups) to be considered separate
203 * letters for given languages, or to be removed from the list of such
204 * letters (denoted by keys starting with '-').
206 * These are additions to (or subtractions from) the data stored in the
207 * first-letters-root.ser file (which among others includes full basic latin,
208 * cyrillic and greek alphabets).
210 * "Separate letter" is a letter that would have a separate heading/section
211 * for it in a dictionary or a phone book in this language. This data isn't
212 * used for sorting (the ICU library handles that), only for deciding which
213 * characters (or character groups) to use as headings.
215 * Initially generated based on the primary level of Unicode collation
216 * tailorings available at http://developer.mimer.com/charts/tailorings.htm ,
219 * Empty arrays are intended; this signifies that the data for the language is
220 * available and that there are, in fact, no additional letters to consider.
222 private static $tailoringFirstLetters = array(
223 // Verified by native speakers
224 'be' => array( "Ё" ),
225 'be-tarask' => array( "Ё" ),
226 'cy' => array( "Ch", "Dd", "Ff", "Ng", "Ll", "Ph", "Rh", "Th" ),
228 'fa' => array( "آ", "ء", "ه" ),
229 'fi' => array( "Å", "Ä", "Ö" ),
231 'hu' => array( "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ),
232 'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
234 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
235 'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
238 'sv' => array( "Å", "Ä", "Ö" ),
239 'sv@collation=standard' => array( "Å", "Ä", "Ö" ),
240 'uk' => array( "Ґ", "Ь" ),
241 'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
242 // Not verified, but likely correct
244 'ast' => array( "Ch", "Ll", "Ñ" ),
245 'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
247 'br' => array( "Ch", "C'h" ),
248 'bs' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
251 'cs' => array( "Č", "Ch", "Ř", "Š", "Ž" ),
252 'da' => array( "Æ", "Ø", "Å" ),
254 'dsb' => array( "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
256 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
257 'es' => array( "Ñ" ),
258 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü", "W" ), // added W for CollationEt (xx-uca-et)
259 'eu' => array( "Ñ" ),
260 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
261 'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
265 'gl' => array( "Ch", "Ll", "Ñ" ),
266 'hr' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
267 'hsb' => array( "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ),
268 'kk' => array( "Ү", "І" ),
269 'kl' => array( "Æ", "Ø", "Å" ),
270 'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
271 'ky' => array( "Ё" ),
274 'lt' => array( "Č", "Š", "Ž" ),
276 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
277 'mt' => array( "Ċ", "Ġ", "Għ", "Ħ", "Ż" ),
279 'no' => array( "Æ", "Ø", "Å" ),
282 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
283 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
285 'sk' => array( "Ä", "Č", "Ch", "Ô", "Š", "Ž" ),
286 'sl' => array( "Č", "Š", "Ž" ),
287 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
288 'sq' => array( "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ),
290 'tk' => array( "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ),
291 'tl' => array( "Ñ", "Ng" ),
292 'tr' => array( "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ),
293 'tt' => array( "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ),
294 'uz' => array( "Ch", "G'", "Ng", "O'", "Sh" ),
297 const RECORD_LENGTH
= 14;
299 function __construct( $locale ) {
300 if ( !extension_loaded( 'intl' ) ) {
301 throw new MWException( 'An ICU collation was requested, ' .
302 'but the intl extension is not available.' );
305 $this->locale
= $locale;
306 // Drop everything after the '@' in locale's name
307 $localeParts = explode( '@', $locale );
308 $this->digitTransformLanguage
= Language
::factory( $locale === 'root' ?
'en' : $localeParts[0] );
310 $this->mainCollator
= Collator
::create( $locale );
311 if ( !$this->mainCollator
) {
312 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
315 $this->primaryCollator
= Collator
::create( $locale );
316 $this->primaryCollator
->setStrength( Collator
::PRIMARY
);
319 function getSortKey( $string ) {
320 // intl extension produces non null-terminated
321 // strings. Appending '' fixes it so that it doesn't generate
322 // a warning on each access in debug php.
323 MediaWiki\
suppressWarnings();
324 $key = $this->mainCollator
->getSortKey( $string ) . '';
325 MediaWiki\restoreWarnings
();
329 function getPrimarySortKey( $string ) {
330 MediaWiki\
suppressWarnings();
331 $key = $this->primaryCollator
->getSortKey( $string ) . '';
332 MediaWiki\restoreWarnings
();
336 function getFirstLetter( $string ) {
337 $string = strval( $string );
338 if ( $string === '' ) {
343 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
344 if ( ord( $firstChar ) > 0x7f && self
::isCjk( UtfNormal\Utils
::utf8ToCodepoint( $firstChar ) ) ) {
348 $sortKey = $this->getPrimarySortKey( $string );
350 // Do a binary search to find the correct letter to sort under
351 $min = ArrayUtils
::findLowerBound(
352 array( $this, 'getSortKeyByLetterIndex' ),
353 $this->getFirstLetterCount(),
357 if ( $min === false ) {
358 // Before the first letter
361 return $this->getLetterByIndex( $min );
364 function getFirstLetterData() {
365 if ( $this->firstLetterData
!== null ) {
366 return $this->firstLetterData
;
369 $cache = wfGetCache( CACHE_ANYTHING
);
370 $cacheKey = wfMemcKey(
373 $this->digitTransformLanguage
->getCode(),
374 self
::getICUVersion()
376 $cacheEntry = $cache->get( $cacheKey );
378 if ( $cacheEntry && isset( $cacheEntry['version'] )
379 && $cacheEntry['version'] == self
::FIRST_LETTER_VERSION
381 $this->firstLetterData
= $cacheEntry;
382 return $this->firstLetterData
;
385 // Generate data from serialized data file
387 if ( isset( self
::$tailoringFirstLetters[$this->locale
] ) ) {
388 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
389 // Append additional characters
390 $letters = array_merge( $letters, self
::$tailoringFirstLetters[$this->locale
] );
391 // Remove unnecessary ones, if any
392 if ( isset( self
::$tailoringFirstLetters['-' . $this->locale
] ) ) {
393 $letters = array_diff( $letters, self
::$tailoringFirstLetters['-' . $this->locale
] );
395 // Apply digit transforms
396 $digits = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' );
397 $letters = array_diff( $letters, $digits );
398 foreach ( $digits as $digit ) {
399 $letters[] = $this->digitTransformLanguage
->formatNum( $digit, true );
402 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
403 if ( $letters === false ) {
404 throw new MWException( "MediaWiki does not support ICU locale " .
405 "\"{$this->locale}\"" );
411 * It's impossible to have the precompiled data file properly sorted,
412 * because the sort order changes depending on ICU version. If the
413 * array is not properly sorted, the binary search will return random
416 * We also take this opportunity to remove primary collisions.
418 $letterMap = array();
419 foreach ( $letters as $letter ) {
420 $key = $this->getPrimarySortKey( $letter );
421 if ( isset( $letterMap[$key] ) ) {
423 // Keep whichever one sorts first in the main collator
424 if ( $this->mainCollator
->compare( $letter, $letterMap[$key] ) < 0 ) {
425 $letterMap[$key] = $letter;
428 $letterMap[$key] = $letter;
431 ksort( $letterMap, SORT_STRING
);
433 /* Remove duplicate prefixes. Basically if something has a sortkey
434 * which is a prefix of some other sortkey, then it is an
435 * expansion and probably should not be considered a section
438 * For example 'þ' is sometimes sorted as if it is the letters
439 * 'th'. Other times it is its own primary element. Another
440 * example is '₨'. Sometimes its a currency symbol. Sometimes it
441 * is an 'R' followed by an 's'.
443 * Additionally an expanded element should always sort directly
444 * after its first element due to they way sortkeys work.
446 * UCA sortkey elements are of variable length but no collation
447 * element should be a prefix of some other element, so I think
449 * - https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
450 * - http://site.icu-project.org/design/collation/uca-weight-allocation
452 * Additionally, there is something called primary compression to
453 * worry about. Basically, if you have two primary elements that
454 * are more than one byte and both start with the same byte then
455 * the first byte is dropped on the second primary. Additionally
456 * either \x03 or \xFF may be added to mean that the next primary
457 * does not start with the first byte of the first primary.
459 * This shouldn't matter much, as the first primary is not
460 * changed, and that is what we are comparing against.
462 * tl;dr: This makes some assumptions about how icu implements
463 * collations. It seems incredibly unlikely these assumptions
464 * will change, but nonetheless they are assumptions.
468 $duplicatePrefixes = array();
469 foreach ( $letterMap as $key => $value ) {
470 // Remove terminator byte. Otherwise the prefix
471 // comparison will get hung up on that.
472 $trimmedKey = rtrim( $key, "\0" );
473 if ( $prev === false ||
$prev === '' ) {
475 // We don't yet have a collation element
476 // to compare against, so continue.
480 // Due to the fact the array is sorted, we only have
481 // to compare with the element directly previous
482 // to the current element (skipping expansions).
483 // An element "X" will always sort directly
484 // before "XZ" (Unless we have "XY", but we
485 // do not update $prev in that case).
486 if ( substr( $trimmedKey, 0, strlen( $prev ) ) === $prev ) {
487 $duplicatePrefixes[] = $key;
488 // If this is an expansion, we don't want to
489 // compare the next element to this element,
490 // but to what is currently $prev
495 foreach ( $duplicatePrefixes as $badKey ) {
496 wfDebug( "Removing '{$letterMap[$badKey]}' from first letters.\n" );
497 unset( $letterMap[$badKey] );
498 // This code assumes that unsetting does not change sort order.
501 'chars' => array_values( $letterMap ),
502 'keys' => array_keys( $letterMap ),
503 'version' => self
::FIRST_LETTER_VERSION
,
506 // Reduce memory usage before caching
510 $this->firstLetterData
= $data;
511 $cache->set( $cacheKey, $data, $cache::TTL_WEEK
);
515 function getLetterByIndex( $index ) {
516 if ( $this->firstLetterData
=== null ) {
517 $this->getFirstLetterData();
519 return $this->firstLetterData
['chars'][$index];
522 function getSortKeyByLetterIndex( $index ) {
523 if ( $this->firstLetterData
=== null ) {
524 $this->getFirstLetterData();
526 return $this->firstLetterData
['keys'][$index];
529 function getFirstLetterCount() {
530 if ( $this->firstLetterData
=== null ) {
531 $this->getFirstLetterData();
533 return count( $this->firstLetterData
['chars'] );
536 static function isCjk( $codepoint ) {
537 foreach ( self
::$cjkBlocks as $block ) {
538 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
546 * Return the version of ICU library used by PHP's intl extension,
547 * or false when the extension is not installed of the version
548 * can't be determined.
550 * The constant INTL_ICU_VERSION this function refers to isn't really
551 * documented. It is available since PHP 5.3.7 (see PHP bug 54561).
552 * This function will return false on older PHPs.
555 * @return string|bool
557 static function getICUVersion() {
558 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION
: false;
562 * Return the version of Unicode appropriate for the version of ICU library
563 * currently in use, or false when it can't be determined.
566 * @return string|bool
568 static function getUnicodeVersionForICU() {
569 $icuVersion = IcuCollation
::getICUVersion();
570 if ( !$icuVersion ) {
574 $versionPrefix = substr( $icuVersion, 0, 3 );
575 // Source: http://site.icu-project.org/download
589 if ( isset( $map[$versionPrefix] ) ) {
590 return $map[$versionPrefix];
598 * Workaround for the lack of support of Sorani Kurdish / Central Kurdish language ('ckb') in ICU.
600 * Uses the same collation rules as Persian / Farsi ('fa'), but different characters for digits.
602 class CollationCkb
extends IcuCollation
{
603 function __construct() {
604 // This will set $locale and collators, which affect the actual sorting order
605 parent
::__construct( 'fa' );
606 // Override the 'fa' language set by parent constructor, which affects #getFirstLetterData()
607 $this->digitTransformLanguage
= Language
::factory( 'ckb' );
612 * Workaround for incorrect collation of Estonian language ('et') in ICU (bug 54168).
614 * 'W' and 'V' should not be considered the same letter for the purposes of collation in modern
615 * Estonian. We work around this by replacing 'W' and 'w' with 'ᴡ' U+1D21 'LATIN LETTER SMALL
616 * CAPITAL W' for sortkey generation, which is collated like 'W' and is not tailored to have the
617 * same primary weight as 'V' in Estonian.
619 class CollationEt
extends IcuCollation
{
620 function __construct() {
621 parent
::__construct( 'et' );
624 private static function mangle( $string ) {
627 'ᴡ', // U+1D21 'LATIN LETTER SMALL CAPITAL W'
632 private static function unmangle( $string ) {
633 // Casing data is lost…
635 'ᴡ', // U+1D21 'LATIN LETTER SMALL CAPITAL W'
641 function getSortKey( $string ) {
642 return parent
::getSortKey( self
::mangle( $string ) );
645 function getFirstLetter( $string ) {
646 return self
::unmangle( parent
::getFirstLetter( self
::mangle( $string ) ) );