3 abstract class Collation
{
9 static function singleton() {
10 if ( !self
::$instance ) {
11 global $wgCategoryCollation;
12 self
::$instance = self
::factory( $wgCategoryCollation );
14 return self
::$instance;
19 * @param $collationName string
22 static function factory( $collationName ) {
23 switch( $collationName ) {
25 return new UppercaseCollation
;
27 return new IdentityCollation
;
29 return new IcuCollation( 'root' );
31 # Provide a mechanism for extensions to hook in.
33 $collationObject = null;
34 wfRunHooks( 'Collation::factory', array( $collationName, &$collationObject ) );
36 if ( $collationObject instanceof Collation
) {
37 return $collationObject;
40 // If all else fails...
41 throw new MWException( __METHOD__
.": unknown collation type \"$collationName\"" );
46 * Given a string, convert it to a (hopefully short) key that can be used
47 * for efficient sorting. A binary sort according to the sortkeys
48 * corresponds to a logical sort of the corresponding strings. Current
49 * code expects that a line feed character should sort before all others, but
50 * has no other particular expectations (and that one can be changed if
53 * @param string $string UTF-8 string
54 * @return string Binary sortkey
56 abstract function getSortKey( $string );
59 * Given a string, return the logical "first letter" to be used for
60 * grouping on category pages and so on. This has to be coordinated
61 * carefully with convertToSortkey(), or else the sorted list might jump
62 * back and forth between the same "initial letters" or other pathological
63 * behavior. For instance, if you just return the first character, but "a"
64 * sorts the same as "A" based on getSortKey(), then you might get a
76 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
78 * @param string $string UTF-8 string
79 * @return string UTF-8 string corresponding to the first letter of input
81 abstract function getFirstLetter( $string );
84 class UppercaseCollation
extends Collation
{
86 function __construct() {
87 // Get a language object so that we can use the generic UTF-8 uppercase
89 $this->lang
= Language
::factory( 'en' );
92 function getSortKey( $string ) {
93 return $this->lang
->uc( $string );
96 function getFirstLetter( $string ) {
97 if ( $string[0] == "\0" ) {
98 $string = substr( $string, 1 );
100 return $this->lang
->ucfirst( $this->lang
->firstChar( $string ) );
105 * Collation class that's essentially a no-op.
107 * Does sorting based on binary value of the string.
108 * Like how things were pre 1.17.
110 class IdentityCollation
extends Collation
{
112 function getSortKey( $string ) {
116 function getFirstLetter( $string ) {
118 // Copied from UppercaseCollation.
119 // I'm kind of unclear on when this could happen...
120 if ( $string[0] == "\0" ) {
121 $string = substr( $string, 1 );
123 return $wgContLang->firstChar( $string );
128 class IcuCollation
extends Collation
{
129 var $primaryCollator, $mainCollator, $locale;
130 var $firstLetterData;
133 * Unified CJK blocks.
135 * The same definition of a CJK block must be used for both Collation and
136 * generateCollationData.php. These blocks are omitted from the first
137 * letter data, as an optimisation measure and because the default UCA table
138 * is pretty useless for sorting Chinese text anyway. Japanese and Korean
139 * blocks are not included here, because they are smaller and more useful.
141 static $cjkBlocks = array(
142 array( 0x2E80, 0x2EFF ), // CJK Radicals Supplement
143 array( 0x2F00, 0x2FDF ), // Kangxi Radicals
144 array( 0x2FF0, 0x2FFF ), // Ideographic Description Characters
145 array( 0x3000, 0x303F ), // CJK Symbols and Punctuation
146 array( 0x31C0, 0x31EF ), // CJK Strokes
147 array( 0x3200, 0x32FF ), // Enclosed CJK Letters and Months
148 array( 0x3300, 0x33FF ), // CJK Compatibility
149 array( 0x3400, 0x4DBF ), // CJK Unified Ideographs Extension A
150 array( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
151 array( 0xF900, 0xFAFF ), // CJK Compatibility Ideographs
152 array( 0xFE30, 0xFE4F ), // CJK Compatibility Forms
153 array( 0x20000, 0x2A6DF ), // CJK Unified Ideographs Extension B
154 array( 0x2A700, 0x2B73F ), // CJK Unified Ideographs Extension C
155 array( 0x2B740, 0x2B81F ), // CJK Unified Ideographs Extension D
156 array( 0x2F800, 0x2FA1F ), // CJK Compatibility Ideographs Supplement
159 const RECORD_LENGTH
= 14;
161 function __construct( $locale ) {
162 if ( !extension_loaded( 'intl' ) ) {
163 throw new MWException( 'An ICU collation was requested, ' .
164 'but the intl extension is not available.' );
166 $this->locale
= $locale;
167 $this->mainCollator
= Collator
::create( $locale );
168 if ( !$this->mainCollator
) {
169 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
172 $this->primaryCollator
= Collator
::create( $locale );
173 $this->primaryCollator
->setStrength( Collator
::PRIMARY
);
176 function getSortKey( $string ) {
177 // intl extension produces non null-terminated
178 // strings. Appending '' fixes it so that it doesn't generate
179 // a warning on each access in debug php.
180 wfSuppressWarnings();
181 $key = $this->mainCollator
->getSortKey( $string ) . '';
186 function getPrimarySortKey( $string ) {
187 wfSuppressWarnings();
188 $key = $this->primaryCollator
->getSortKey( $string ) . '';
193 function getFirstLetter( $string ) {
194 $string = strval( $string );
195 if ( $string === '' ) {
200 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
201 if ( ord( $firstChar ) > 0x7f
202 && self
::isCjk( utf8ToCodepoint( $firstChar ) ) )
207 $sortKey = $this->getPrimarySortKey( $string );
209 // Do a binary search to find the correct letter to sort under
210 $min = $this->findLowerBound(
211 array( $this, 'getSortKeyByLetterIndex' ),
212 $this->getFirstLetterCount(),
216 if ( $min === false ) {
217 // Before the first letter
220 return $this->getLetterByIndex( $min );
223 function getFirstLetterData() {
224 if ( $this->firstLetterData
!== null ) {
225 return $this->firstLetterData
;
228 $cache = wfGetCache( CACHE_ANYTHING
);
229 $cacheKey = wfMemcKey( 'first-letters', $this->locale
);
230 $cacheEntry = $cache->get( $cacheKey );
233 $this->firstLetterData
= $cacheEntry;
234 return $this->firstLetterData
;
237 // Generate data from serialized data file
239 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
240 if ( $letters === false ) {
241 throw new MWException( "MediaWiki does not support ICU locale " .
242 "\"{$this->locale}\"" );
247 // It's impossible to have the precompiled data file properly sorted,
248 // because the sort order changes depending on ICU version. If the
249 // array is not properly sorted, the binary search will return random
252 // We also take this opportunity to remove primary collisions.
253 $letterMap = array();
254 foreach ( $letters as $letter ) {
255 $key = $this->getPrimarySortKey( $letter );
256 if ( isset( $letterMap[$key] ) ) {
258 // Keep whichever one sorts first in the main collator
259 if ( $this->mainCollator
->compare( $letter, $letterMap[$key] ) < 0 ) {
260 $letterMap[$key] = $letter;
263 $letterMap[$key] = $letter;
266 ksort( $letterMap, SORT_STRING
);
268 'chars' => array_values( $letterMap ),
269 'keys' => array_keys( $letterMap )
272 // Reduce memory usage before caching
276 $this->firstLetterData
= $data;
277 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
281 function getLetterByIndex( $index ) {
282 if ( $this->firstLetterData
=== null ) {
283 $this->getFirstLetterData();
285 return $this->firstLetterData
['chars'][$index];
288 function getSortKeyByLetterIndex( $index ) {
289 if ( $this->firstLetterData
=== null ) {
290 $this->getFirstLetterData();
292 return $this->firstLetterData
['keys'][$index];
295 function getFirstLetterCount() {
296 if ( $this->firstLetterData
=== null ) {
297 $this->getFirstLetterData();
299 return count( $this->firstLetterData
['chars'] );
303 * Do a binary search, and return the index of the largest item that sorts
304 * less than or equal to the target value.
306 * @param $valueCallback array A function to call to get the value with
307 * a given array index.
308 * @param $valueCount int The number of items accessible via $valueCallback,
309 * indexed from 0 to $valueCount - 1
310 * @param $comparisonCallback array A callback to compare two values, returning
311 * -1, 0 or 1 in the style of strcmp().
312 * @param $target string The target value to find.
314 * @return int|bool The item index of the lower bound, or false if the target value
315 * sorts before all items.
317 function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) {
319 $max = $valueCount - 1;
321 $mid = $min +
( ( $max - $min ) >> 1 );
322 $item = call_user_func( $valueCallback, $mid );
323 $comparison = call_user_func( $comparisonCallback, $target, $item );
324 if ( $comparison > 0 ) {
326 } elseif ( $comparison == 0 ) {
332 } while ( $min < $max - 1 );
334 if ( $min == 0 && $max == 0 && $comparison > 0 ) {
335 // Before the first item
342 static function isCjk( $codepoint ) {
343 foreach ( self
::$cjkBlocks as $block ) {
344 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {