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 IdentityCollation
;
49 return new IcuCollation( 'root' );
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\"" );
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
77 * @param string $string UTF-8 string
78 * @return string Binary sortkey
80 abstract function getSortKey( $string );
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
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
{
110 function __construct() {
111 // Get a language object so that we can use the generic UTF-8 uppercase
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 ) {
140 function getFirstLetter( $string ) {
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 var $primaryCollator, $mainCollator, $locale;
153 var $firstLetterData;
156 * Unified CJK blocks.
158 * The same definition of a CJK block must be used for both Collation and
159 * generateCollationData.php. These blocks are omitted from the first
160 * letter data, as an optimisation measure and because the default UCA table
161 * is pretty useless for sorting Chinese text anyway. Japanese and Korean
162 * blocks are not included here, because they are smaller and more useful.
164 static $cjkBlocks = array(
165 array( 0x2E80, 0x2EFF ), // CJK Radicals Supplement
166 array( 0x2F00, 0x2FDF ), // Kangxi Radicals
167 array( 0x2FF0, 0x2FFF ), // Ideographic Description Characters
168 array( 0x3000, 0x303F ), // CJK Symbols and Punctuation
169 array( 0x31C0, 0x31EF ), // CJK Strokes
170 array( 0x3200, 0x32FF ), // Enclosed CJK Letters and Months
171 array( 0x3300, 0x33FF ), // CJK Compatibility
172 array( 0x3400, 0x4DBF ), // CJK Unified Ideographs Extension A
173 array( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
174 array( 0xF900, 0xFAFF ), // CJK Compatibility Ideographs
175 array( 0xFE30, 0xFE4F ), // CJK Compatibility Forms
176 array( 0x20000, 0x2A6DF ), // CJK Unified Ideographs Extension B
177 array( 0x2A700, 0x2B73F ), // CJK Unified Ideographs Extension C
178 array( 0x2B740, 0x2B81F ), // CJK Unified Ideographs Extension D
179 array( 0x2F800, 0x2FA1F ), // CJK Compatibility Ideographs Supplement
183 * Additional characters (or character groups) to be considered separate
184 * letters for given languages, or to be removed from the list of such
185 * letters (denoted by keys starting with '-').
187 * These are additions to (or subtractions from) the data stored in the
188 * first-letters-root.ser file (which among others includes full basic latin,
189 * cyrillic and greek alphabets).
191 * "Separate letter" is a letter that would have a separate heading/section
192 * for it in a dictionary or a phone book in this language. This data isn't
193 * used for sorting (the ICU library handles that), only for deciding which
194 * characters (or character groups) to use as headings.
196 * Initially generated based on the primary level of Unicode collation
197 * tailorings available at http://developer.mimer.com/charts/tailorings.htm ,
200 * Empty arrays are intended; this signifies that the data for the language is
201 * available and that there are, in fact, no additional letters to consider.
203 static $tailoringFirstLetters = array(
204 // Verified by native speakers
205 'be' => array( "Ё" ),
206 'be-tarask' => array( "Ё" ),
208 'fi' => array( "Å", "Ä", "Ö" ),
209 'hu' => array( "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ),
211 'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
214 'uk' => array( "Ґ", "Ь" ),
215 // Not verified, but likely correct
217 'ast' => array( "Ch", "Ll", "Ñ" ),
218 'az' => 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", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
230 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
231 'es' => array( "Ñ" ),
232 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ),
233 'eu' => array( "Ñ" ),
234 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
236 'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
240 'gl' => array( "Ch", "Ll", "Ñ" ),
241 'hr' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
242 'hsb' => array( "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ),
243 'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
244 'kk' => array( "Ү", "І" ),
245 'kl' => array( "Æ", "Ø", "Å" ),
246 'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
247 'ky' => array( "Ё" ),
250 'lt' => array( "Č", "Š", "Ž" ),
251 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
253 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
254 'mt' => array( "Ċ", "Ġ", "Għ", "Ħ", "Ż" ),
256 'no' => array( "Æ", "Ø", "Å" ),
259 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
260 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
262 'sk' => array( "Ä", "Č", "Ch", "Ô", "Š", "Ž" ),
263 'sl' => array( "Č", "Š", "Ž" ),
264 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
265 'sq' => array( "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ),
267 'sv' => array( "Å", "Ä", "Ö" ),
268 '-sv' => array( "Þ" ), // sorted as "th" in Swedish, causing unexpected output - bug 45446
269 'tk' => array( "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ),
270 'tl' => array( "Ñ", "Ng" ),
271 'tr' => array( "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ),
272 'tt' => array( "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ),
273 'uz' => array( "Ch", "G'", "Ng", "O'", "Sh" ),
274 'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
277 const RECORD_LENGTH
= 14;
279 function __construct( $locale ) {
280 if ( !extension_loaded( 'intl' ) ) {
281 throw new MWException( 'An ICU collation was requested, ' .
282 'but the intl extension is not available.' );
284 $this->locale
= $locale;
285 $this->mainCollator
= Collator
::create( $locale );
286 if ( !$this->mainCollator
) {
287 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
290 $this->primaryCollator
= Collator
::create( $locale );
291 $this->primaryCollator
->setStrength( Collator
::PRIMARY
);
294 function getSortKey( $string ) {
295 // intl extension produces non null-terminated
296 // strings. Appending '' fixes it so that it doesn't generate
297 // a warning on each access in debug php.
298 wfSuppressWarnings();
299 $key = $this->mainCollator
->getSortKey( $string ) . '';
304 function getPrimarySortKey( $string ) {
305 wfSuppressWarnings();
306 $key = $this->primaryCollator
->getSortKey( $string ) . '';
311 function getFirstLetter( $string ) {
312 $string = strval( $string );
313 if ( $string === '' ) {
318 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
319 if ( ord( $firstChar ) > 0x7f
320 && self
::isCjk( utf8ToCodepoint( $firstChar ) ) )
325 $sortKey = $this->getPrimarySortKey( $string );
327 // Do a binary search to find the correct letter to sort under
328 $min = $this->findLowerBound(
329 array( $this, 'getSortKeyByLetterIndex' ),
330 $this->getFirstLetterCount(),
334 if ( $min === false ) {
335 // Before the first letter
338 return $this->getLetterByIndex( $min );
341 function getFirstLetterData() {
342 if ( $this->firstLetterData
!== null ) {
343 return $this->firstLetterData
;
346 $cache = wfGetCache( CACHE_ANYTHING
);
347 $cacheKey = wfMemcKey( 'first-letters', $this->locale
);
348 $cacheEntry = $cache->get( $cacheKey );
351 $this->firstLetterData
= $cacheEntry;
352 return $this->firstLetterData
;
355 // Generate data from serialized data file
357 if ( isset ( self
::$tailoringFirstLetters[$this->locale
] ) ) {
358 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
359 // Append additional characters
360 $letters = array_merge( $letters, self
::$tailoringFirstLetters[$this->locale
] );
361 // Remove unnecessary ones, if any
362 if ( isset( self
::$tailoringFirstLetters[ '-' . $this->locale
] ) ) {
363 $letters = array_diff( $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 array $valueCallback A function to call to get the value with
435 * a given array index.
436 * @param int $valueCount The number of items accessible via $valueCallback,
437 * indexed from 0 to $valueCount - 1
438 * @param array $comparisonCallback A callback to compare two values, returning
439 * -1, 0 or 1 in the style of strcmp().
440 * @param string $target 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];