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 IcuCollation( 'root' );
29 # Provide a mechanism for extensions to hook in.
31 $collationObject = null;
32 wfRunHooks( 'Collation::factory', array( $collationName, &$collationObject ) );
34 if ( $collationObject instanceof Collation
) {
35 return $collationObject;
38 // If all else fails...
39 throw new MWException( __METHOD__
.": unknown collation type \"$collationName\"" );
44 * Given a string, convert it to a (hopefully short) key that can be used
45 * for efficient sorting. A binary sort according to the sortkeys
46 * corresponds to a logical sort of the corresponding strings. Current
47 * code expects that a line feed character should sort before all others, but
48 * has no other particular expectations (and that one can be changed if
51 * @param string $string UTF-8 string
52 * @return string Binary sortkey
54 abstract function getSortKey( $string );
57 * Given a string, return the logical "first letter" to be used for
58 * grouping on category pages and so on. This has to be coordinated
59 * carefully with convertToSortkey(), or else the sorted list might jump
60 * back and forth between the same "initial letters" or other pathological
61 * behavior. For instance, if you just return the first character, but "a"
62 * sorts the same as "A" based on getSortKey(), then you might get a
74 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
76 * @param string $string UTF-8 string
77 * @return string UTF-8 string corresponding to the first letter of input
79 abstract function getFirstLetter( $string );
82 class UppercaseCollation
extends Collation
{
84 function __construct() {
85 // Get a language object so that we can use the generic UTF-8 uppercase
87 $this->lang
= Language
::factory( 'en' );
90 function getSortKey( $string ) {
91 return $this->lang
->uc( $string );
94 function getFirstLetter( $string ) {
95 if ( $string[0] == "\0" ) {
96 $string = substr( $string, 1 );
98 return $this->lang
->ucfirst( $this->lang
->firstChar( $string ) );
102 class IcuCollation
extends Collation
{
103 var $primaryCollator, $mainCollator, $locale;
104 var $firstLetterData;
107 * Unified CJK blocks.
109 * The same definition of a CJK block must be used for both Collation and
110 * generateCollationData.php. These blocks are omitted from the first
111 * letter data, as an optimisation measure and because the default UCA table
112 * is pretty useless for sorting Chinese text anyway. Japanese and Korean
113 * blocks are not included here, because they are smaller and more useful.
115 static $cjkBlocks = array(
116 array( 0x2E80, 0x2EFF ), // CJK Radicals Supplement
117 array( 0x2F00, 0x2FDF ), // Kangxi Radicals
118 array( 0x2FF0, 0x2FFF ), // Ideographic Description Characters
119 array( 0x3000, 0x303F ), // CJK Symbols and Punctuation
120 array( 0x31C0, 0x31EF ), // CJK Strokes
121 array( 0x3200, 0x32FF ), // Enclosed CJK Letters and Months
122 array( 0x3300, 0x33FF ), // CJK Compatibility
123 array( 0x3400, 0x4DBF ), // CJK Unified Ideographs Extension A
124 array( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
125 array( 0xF900, 0xFAFF ), // CJK Compatibility Ideographs
126 array( 0xFE30, 0xFE4F ), // CJK Compatibility Forms
127 array( 0x20000, 0x2A6DF ), // CJK Unified Ideographs Extension B
128 array( 0x2A700, 0x2B73F ), // CJK Unified Ideographs Extension C
129 array( 0x2B740, 0x2B81F ), // CJK Unified Ideographs Extension D
130 array( 0x2F800, 0x2FA1F ), // CJK Compatibility Ideographs Supplement
133 const RECORD_LENGTH
= 14;
135 function __construct( $locale ) {
136 if ( !extension_loaded( 'intl' ) ) {
137 throw new MWException( 'An ICU collation was requested, ' .
138 'but the intl extension is not available.' );
140 $this->locale
= $locale;
141 $this->mainCollator
= Collator
::create( $locale );
142 if ( !$this->mainCollator
) {
143 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
146 $this->primaryCollator
= Collator
::create( $locale );
147 $this->primaryCollator
->setStrength( Collator
::PRIMARY
);
150 function getSortKey( $string ) {
151 // intl extension produces non null-terminated
152 // strings. Appending '' fixes it so that it doesn't generate
153 // a warning on each access in debug php.
154 wfSuppressWarnings();
155 $key = $this->mainCollator
->getSortKey( $string ) . '';
160 function getPrimarySortKey( $string ) {
161 wfSuppressWarnings();
162 $key = $this->primaryCollator
->getSortKey( $string ) . '';
167 function getFirstLetter( $string ) {
168 $string = strval( $string );
169 if ( $string === '' ) {
174 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
175 if ( ord( $firstChar ) > 0x7f
176 && self
::isCjk( utf8ToCodepoint( $firstChar ) ) )
181 $sortKey = $this->getPrimarySortKey( $string );
183 // Do a binary search to find the correct letter to sort under
184 $min = $this->findLowerBound(
185 array( $this, 'getSortKeyByLetterIndex' ),
186 $this->getFirstLetterCount(),
190 if ( $min === false ) {
191 // Before the first letter
194 return $this->getLetterByIndex( $min );
197 function getFirstLetterData() {
198 if ( $this->firstLetterData
!== null ) {
199 return $this->firstLetterData
;
202 $cache = wfGetCache( CACHE_ANYTHING
);
203 $cacheKey = wfMemcKey( 'first-letters', $this->locale
);
204 $cacheEntry = $cache->get( $cacheKey );
207 $this->firstLetterData
= $cacheEntry;
208 return $this->firstLetterData
;
211 // Generate data from serialized data file
213 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
214 if ( $letters === false ) {
215 throw new MWException( "MediaWiki does not support ICU locale " .
216 "\"{$this->locale}\"" );
221 // It's impossible to have the precompiled data file properly sorted,
222 // because the sort order changes depending on ICU version. If the
223 // array is not properly sorted, the binary search will return random
226 // We also take this opportunity to remove primary collisions.
227 $letterMap = array();
228 foreach ( $letters as $letter ) {
229 $key = $this->getPrimarySortKey( $letter );
230 if ( isset( $letterMap[$key] ) ) {
232 // Keep whichever one sorts first in the main collator
233 if ( $this->mainCollator
->compare( $letter, $letterMap[$key] ) < 0 ) {
234 $letterMap[$key] = $letter;
237 $letterMap[$key] = $letter;
240 ksort( $letterMap, SORT_STRING
);
242 'chars' => array_values( $letterMap ),
243 'keys' => array_keys( $letterMap )
246 // Reduce memory usage before caching
250 $this->firstLetterData
= $data;
251 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
255 function getLetterByIndex( $index ) {
256 if ( $this->firstLetterData
=== null ) {
257 $this->getFirstLetterData();
259 return $this->firstLetterData
['chars'][$index];
262 function getSortKeyByLetterIndex( $index ) {
263 if ( $this->firstLetterData
=== null ) {
264 $this->getFirstLetterData();
266 return $this->firstLetterData
['keys'][$index];
269 function getFirstLetterCount() {
270 if ( $this->firstLetterData
=== null ) {
271 $this->getFirstLetterData();
273 return count( $this->firstLetterData
['chars'] );
277 * Do a binary search, and return the index of the largest item that sorts
278 * less than or equal to the target value.
280 * @param $valueCallback array A function to call to get the value with
281 * a given array index.
282 * @param $valueCount int The number of items accessible via $valueCallback,
283 * indexed from 0 to $valueCount - 1
284 * @param $comparisonCallback array A callback to compare two values, returning
285 * -1, 0 or 1 in the style of strcmp().
286 * @param $target string The target value to find.
288 * @return The item index of the lower bound, or false if the target value
289 * sorts before all items.
291 function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) {
293 $max = $valueCount - 1;
295 $mid = $min +
( ( $max - $min ) >> 1 );
296 $item = call_user_func( $valueCallback, $mid );
297 $comparison = call_user_func( $comparisonCallback, $target, $item );
298 if ( $comparison > 0 ) {
300 } elseif ( $comparison == 0 ) {
306 } while ( $min < $max - 1 );
308 if ( $min == 0 && $max == 0 && $comparison > 0 ) {
309 // Before the first item
316 static function isCjk( $codepoint ) {
317 foreach ( self
::$cjkBlocks as $block ) {
318 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {