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
{
29 static function singleton() {
30 if ( !self
::$instance ) {
31 global $wgCategoryCollation;
32 self
::$instance = self
::factory( $wgCategoryCollation );
34 return self
::$instance;
39 * @param $collationName string
42 static function factory( $collationName ) {
43 switch( $collationName ) {
45 return new UppercaseCollation
;
47 return new UppercaseSvCollation
;
49 return new IdentityCollation
;
51 return new IcuCollation( 'root' );
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
{
112 function __construct() {
113 // Get a language object so that we can use the generic UTF-8 uppercase
115 $this->lang
= Language
::factory( 'en' );
118 function getSortKey( $string ) {
119 return $this->lang
->uc( $string );
122 function getFirstLetter( $string ) {
123 if ( $string[0] == "\0" ) {
124 $string = substr( $string, 1 );
126 return $this->lang
->ucfirst( $this->lang
->firstChar( $string ) );
131 * Like UppercaseCollation but swaps Ä and Æ.
133 * This provides an ordering suitable for Swedish.
136 class UppercaseSvCollation
extends UppercaseCollation
{
138 /* Unicode code point order is ÄÅÆÖ, Swedish order is ÅÄÖ and Æ is often sorted as Ä.
139 * Replacing Ä for Æ should give a better collation. */
140 function getSortKey( $string ) {
141 $uppercase = $this->lang
->uc( $string );
142 return strtr( $uppercase, array( 'Ä' => 'Æ', 'Æ' => 'Ä' ) );
147 * Collation class that's essentially a no-op.
149 * Does sorting based on binary value of the string.
150 * Like how things were pre 1.17.
152 class IdentityCollation
extends Collation
{
154 function getSortKey( $string ) {
158 function getFirstLetter( $string ) {
160 // Copied from UppercaseCollation.
161 // I'm kind of unclear on when this could happen...
162 if ( $string[0] == "\0" ) {
163 $string = substr( $string, 1 );
165 return $wgContLang->firstChar( $string );
170 class IcuCollation
extends Collation
{
171 var $primaryCollator, $mainCollator, $locale;
172 var $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 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 first-letters
204 * Generated based on the primary level of Unicode collation tailorings
205 * available at http://developer.mimer.com/charts/tailorings.htm .
207 * Empty arrays are intended; this signifies that the data for the language is
208 * available and that there are, in fact, no additional letters to consider.
210 static $tailoringFirstLetters = array(
211 // Verified by native speakers
212 'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
213 'fi' => array( "Å", "Ä", "Ö" ),
214 // Not verified, but likely correct
216 'ast' => array( "CH", "LL", "Ñ" ),
217 'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
218 'be' => array( "Ё" ),
220 'br' => array( "CH", "C'H" ),
221 'bs' => array( "Č", "Ć", "DŽ", "Đ", "LJ", "NJ", "Š", "Ž" ),
224 'cs' => array( "Č", "CH", "Ř", "Š", "Ž" ),
225 'cy' => array( "CH", "DD", "FF", "NG", "LL", "PH", "RH", "TH" ),
226 'da' => array( "Æ", "Ø", "Å" ),
228 'dsb' => array( "Č", "Ć", "DŹ", "Ě", "CH", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
231 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
232 'es' => array( "Ñ" ),
233 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ),
234 'eu' => array( "Ñ" ),
235 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
237 'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
241 'gl' => array( "CH", "LL", "Ñ" ),
242 'hr' => array( "Č", "Ć", "DŽ", "Đ", "LJ", "NJ", "Š", "Ž" ),
243 'hsb' => array( "Č", "DŹ", "Ě", "CH", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ),
244 'hu' => array( "CS", "DZ", "DZS", "GY", "LY", "NY", "Ö", "SZ", "TY", "Ü", "ZS" ),
245 'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
247 'kk' => array( "Ү", "І" ),
248 'kl' => array( "Æ", "Ø", "Å" ),
249 'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
250 'ky' => array( "Ё" ),
253 'lt' => array( "Č", "Š", "Ž" ),
254 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
256 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
257 'mt' => array( "Ċ", "Ġ", "GĦ", "Ħ", "Ż" ),
259 'no' => array( "Æ", "Ø", "Å" ),
263 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
265 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
267 'sk' => array( "Ä", "Č", "CH", "Ô", "Š", "Ž" ),
268 'sl' => array( "Č", "Š", "Ž" ),
269 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
270 'sq' => array( "Ç", "DH", "Ë", "GJ", "LL", "NJ", "RR", "SH", "TH", "XH", "ZH" ),
272 'sv' => array( "Å", "Ä", "Ö" ),
273 'tk' => array( "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ),
274 'tl' => array( "Ñ", "NG" ), /* 'fil' in the data source */
275 'tr' => array( "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ),
276 'tt' => array( "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ),
277 'uk' => array( "Ґ", "Ь" ),
278 'uz' => array( "CH", "G'", "NG", "O'", "SH" ),
279 'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
282 const RECORD_LENGTH
= 14;
284 function __construct( $locale ) {
285 if ( !extension_loaded( 'intl' ) ) {
286 throw new MWException( 'An ICU collation was requested, ' .
287 'but the intl extension is not available.' );
289 $this->locale
= $locale;
290 $this->mainCollator
= Collator
::create( $locale );
291 if ( !$this->mainCollator
) {
292 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
295 $this->primaryCollator
= Collator
::create( $locale );
296 $this->primaryCollator
->setStrength( Collator
::PRIMARY
);
299 function getSortKey( $string ) {
300 // intl extension produces non null-terminated
301 // strings. Appending '' fixes it so that it doesn't generate
302 // a warning on each access in debug php.
303 wfSuppressWarnings();
304 $key = $this->mainCollator
->getSortKey( $string ) . '';
309 function getPrimarySortKey( $string ) {
310 wfSuppressWarnings();
311 $key = $this->primaryCollator
->getSortKey( $string ) . '';
316 function getFirstLetter( $string ) {
317 $string = strval( $string );
318 if ( $string === '' ) {
323 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
324 if ( ord( $firstChar ) > 0x7f
325 && self
::isCjk( utf8ToCodepoint( $firstChar ) ) )
330 $sortKey = $this->getPrimarySortKey( $string );
332 // Do a binary search to find the correct letter to sort under
333 $min = $this->findLowerBound(
334 array( $this, 'getSortKeyByLetterIndex' ),
335 $this->getFirstLetterCount(),
339 if ( $min === false ) {
340 // Before the first letter
343 return $this->getLetterByIndex( $min );
346 function getFirstLetterData() {
347 if ( $this->firstLetterData
!== null ) {
348 return $this->firstLetterData
;
351 $cache = wfGetCache( CACHE_ANYTHING
);
352 $cacheKey = wfMemcKey( 'first-letters', $this->locale
);
353 $cacheEntry = $cache->get( $cacheKey );
356 $this->firstLetterData
= $cacheEntry;
357 return $this->firstLetterData
;
360 // Generate data from serialized data file
362 if ( isset ( self
::$tailoringFirstLetters[$this->locale
] ) ) {
363 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
364 $letters = array_merge( $letters, self
::$tailoringFirstLetters[$this->locale
] );
366 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
367 if ( $letters === false ) {
368 throw new MWException( "MediaWiki does not support ICU locale " .
369 "\"{$this->locale}\"" );
375 // It's impossible to have the precompiled data file properly sorted,
376 // because the sort order changes depending on ICU version. If the
377 // array is not properly sorted, the binary search will return random
380 // We also take this opportunity to remove primary collisions.
381 $letterMap = array();
382 foreach ( $letters as $letter ) {
383 $key = $this->getPrimarySortKey( $letter );
384 if ( isset( $letterMap[$key] ) ) {
386 // Keep whichever one sorts first in the main collator
387 if ( $this->mainCollator
->compare( $letter, $letterMap[$key] ) < 0 ) {
388 $letterMap[$key] = $letter;
391 $letterMap[$key] = $letter;
394 ksort( $letterMap, SORT_STRING
);
396 'chars' => array_values( $letterMap ),
397 'keys' => array_keys( $letterMap )
400 // Reduce memory usage before caching
404 $this->firstLetterData
= $data;
405 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
409 function getLetterByIndex( $index ) {
410 if ( $this->firstLetterData
=== null ) {
411 $this->getFirstLetterData();
413 return $this->firstLetterData
['chars'][$index];
416 function getSortKeyByLetterIndex( $index ) {
417 if ( $this->firstLetterData
=== null ) {
418 $this->getFirstLetterData();
420 return $this->firstLetterData
['keys'][$index];
423 function getFirstLetterCount() {
424 if ( $this->firstLetterData
=== null ) {
425 $this->getFirstLetterData();
427 return count( $this->firstLetterData
['chars'] );
431 * Do a binary search, and return the index of the largest item that sorts
432 * less than or equal to the target value.
434 * @param $valueCallback array A function to call to get the value with
435 * a given array index.
436 * @param $valueCount int The number of items accessible via $valueCallback,
437 * indexed from 0 to $valueCount - 1
438 * @param $comparisonCallback array A callback to compare two values, returning
439 * -1, 0 or 1 in the style of strcmp().
440 * @param $target string The target value to find.
442 * @return int|bool The item index of the lower bound, or false if the target value
443 * sorts before all items.
445 function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) {
446 if ( $valueCount === 0 ) {
453 $mid = $min +
( ( $max - $min ) >> 1 );
454 $item = call_user_func( $valueCallback, $mid );
455 $comparison = call_user_func( $comparisonCallback, $target, $item );
456 if ( $comparison > 0 ) {
458 } elseif ( $comparison == 0 ) {
464 } while ( $min < $max - 1 );
467 $item = call_user_func( $valueCallback, $min );
468 $comparison = call_user_func( $comparisonCallback, $target, $item );
469 if ( $comparison < 0 ) {
470 // Before the first item
477 static function isCjk( $codepoint ) {
478 foreach ( self
::$cjkBlocks as $block ) {
479 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
487 * Return the version of ICU library used by PHP's intl extension,
488 * or false when the extension is not installed of the version
489 * can't be determined.
491 * The constant INTL_ICU_VERSION this function refers to isn't really
492 * documented. It is available since PHP 5.3.7 (see PHP bug 54561).
493 * This function will return false on older PHPs.
496 * @return string|false
498 static function getICUVersion() {
499 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION
: false;
503 * Return the version of Unicode appropriate for the version of ICU library
504 * currently in use, or false when it can't be determined.
507 * @return string|false
509 static function getUnicodeVersionForICU() {
510 $icuVersion = IcuCollation
::getICUVersion();
511 if ( !$icuVersion ) {
515 $versionPrefix = substr( $icuVersion, 0, 3 );
516 // Source: http://site.icu-project.org/download
530 if ( isset( $map[$versionPrefix] ) ) {
531 return $map[$versionPrefix];