Merge "CologneBlue rewrite: kill mWatchLinkNum, watchThisPage() is only called once...
[lhc/web/wiklou.git] / includes / Collation.php
1 <?php
2 /**
3 * Database row sorting.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 abstract class Collation {
24 static $instance;
25
26 /**
27 * @return Collation
28 */
29 static function singleton() {
30 if ( !self::$instance ) {
31 global $wgCategoryCollation;
32 self::$instance = self::factory( $wgCategoryCollation );
33 }
34 return self::$instance;
35 }
36
37 /**
38 * @throws MWException
39 * @param $collationName string
40 * @return Collation
41 */
42 static function factory( $collationName ) {
43 switch( $collationName ) {
44 case 'uppercase':
45 return new UppercaseCollation;
46 case 'identity':
47 return new IdentityCollation;
48 case 'uca-default':
49 return new IcuCollation( 'root' );
50 default:
51 # Provide a mechanism for extensions to hook in.
52
53 $collationObject = null;
54 wfRunHooks( 'Collation::factory', array( $collationName, &$collationObject ) );
55
56 if ( $collationObject instanceof Collation ) {
57 return $collationObject;
58 }
59
60 // If all else fails...
61 throw new MWException( __METHOD__.": unknown collation type \"$collationName\"" );
62 }
63 }
64
65 /**
66 * Given a string, convert it to a (hopefully short) key that can be used
67 * for efficient sorting. A binary sort according to the sortkeys
68 * corresponds to a logical sort of the corresponding strings. Current
69 * code expects that a line feed character should sort before all others, but
70 * has no other particular expectations (and that one can be changed if
71 * necessary).
72 *
73 * @param string $string UTF-8 string
74 * @return string Binary sortkey
75 */
76 abstract function getSortKey( $string );
77
78 /**
79 * Given a string, return the logical "first letter" to be used for
80 * grouping on category pages and so on. This has to be coordinated
81 * carefully with convertToSortkey(), or else the sorted list might jump
82 * back and forth between the same "initial letters" or other pathological
83 * behavior. For instance, if you just return the first character, but "a"
84 * sorts the same as "A" based on getSortKey(), then you might get a
85 * list like
86 *
87 * == A ==
88 * * [[Aardvark]]
89 *
90 * == a ==
91 * * [[antelope]]
92 *
93 * == A ==
94 * * [[Ape]]
95 *
96 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
97 *
98 * @param string $string UTF-8 string
99 * @return string UTF-8 string corresponding to the first letter of input
100 */
101 abstract function getFirstLetter( $string );
102 }
103
104 class UppercaseCollation extends Collation {
105 var $lang;
106 function __construct() {
107 // Get a language object so that we can use the generic UTF-8 uppercase
108 // function there
109 $this->lang = Language::factory( 'en' );
110 }
111
112 function getSortKey( $string ) {
113 return $this->lang->uc( $string );
114 }
115
116 function getFirstLetter( $string ) {
117 if ( $string[0] == "\0" ) {
118 $string = substr( $string, 1 );
119 }
120 return $this->lang->ucfirst( $this->lang->firstChar( $string ) );
121 }
122 }
123
124 /**
125 * Collation class that's essentially a no-op.
126 *
127 * Does sorting based on binary value of the string.
128 * Like how things were pre 1.17.
129 */
130 class IdentityCollation extends Collation {
131
132 function getSortKey( $string ) {
133 return $string;
134 }
135
136 function getFirstLetter( $string ) {
137 global $wgContLang;
138 // Copied from UppercaseCollation.
139 // I'm kind of unclear on when this could happen...
140 if ( $string[0] == "\0" ) {
141 $string = substr( $string, 1 );
142 }
143 return $wgContLang->firstChar( $string );
144 }
145 }
146
147
148 class IcuCollation extends Collation {
149 var $primaryCollator, $mainCollator, $locale;
150 var $firstLetterData;
151
152 /**
153 * Unified CJK blocks.
154 *
155 * The same definition of a CJK block must be used for both Collation and
156 * generateCollationData.php. These blocks are omitted from the first
157 * letter data, as an optimisation measure and because the default UCA table
158 * is pretty useless for sorting Chinese text anyway. Japanese and Korean
159 * blocks are not included here, because they are smaller and more useful.
160 */
161 static $cjkBlocks = array(
162 array( 0x2E80, 0x2EFF ), // CJK Radicals Supplement
163 array( 0x2F00, 0x2FDF ), // Kangxi Radicals
164 array( 0x2FF0, 0x2FFF ), // Ideographic Description Characters
165 array( 0x3000, 0x303F ), // CJK Symbols and Punctuation
166 array( 0x31C0, 0x31EF ), // CJK Strokes
167 array( 0x3200, 0x32FF ), // Enclosed CJK Letters and Months
168 array( 0x3300, 0x33FF ), // CJK Compatibility
169 array( 0x3400, 0x4DBF ), // CJK Unified Ideographs Extension A
170 array( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
171 array( 0xF900, 0xFAFF ), // CJK Compatibility Ideographs
172 array( 0xFE30, 0xFE4F ), // CJK Compatibility Forms
173 array( 0x20000, 0x2A6DF ), // CJK Unified Ideographs Extension B
174 array( 0x2A700, 0x2B73F ), // CJK Unified Ideographs Extension C
175 array( 0x2B740, 0x2B81F ), // CJK Unified Ideographs Extension D
176 array( 0x2F800, 0x2FA1F ), // CJK Compatibility Ideographs Supplement
177 );
178
179 const RECORD_LENGTH = 14;
180
181 function __construct( $locale ) {
182 if ( !extension_loaded( 'intl' ) ) {
183 throw new MWException( 'An ICU collation was requested, ' .
184 'but the intl extension is not available.' );
185 }
186 $this->locale = $locale;
187 $this->mainCollator = Collator::create( $locale );
188 if ( !$this->mainCollator ) {
189 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
190 }
191
192 $this->primaryCollator = Collator::create( $locale );
193 $this->primaryCollator->setStrength( Collator::PRIMARY );
194 }
195
196 function getSortKey( $string ) {
197 // intl extension produces non null-terminated
198 // strings. Appending '' fixes it so that it doesn't generate
199 // a warning on each access in debug php.
200 wfSuppressWarnings();
201 $key = $this->mainCollator->getSortKey( $string ) . '';
202 wfRestoreWarnings();
203 return $key;
204 }
205
206 function getPrimarySortKey( $string ) {
207 wfSuppressWarnings();
208 $key = $this->primaryCollator->getSortKey( $string ) . '';
209 wfRestoreWarnings();
210 return $key;
211 }
212
213 function getFirstLetter( $string ) {
214 $string = strval( $string );
215 if ( $string === '' ) {
216 return '';
217 }
218
219 // Check for CJK
220 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
221 if ( ord( $firstChar ) > 0x7f
222 && self::isCjk( utf8ToCodepoint( $firstChar ) ) )
223 {
224 return $firstChar;
225 }
226
227 $sortKey = $this->getPrimarySortKey( $string );
228
229 // Do a binary search to find the correct letter to sort under
230 $min = $this->findLowerBound(
231 array( $this, 'getSortKeyByLetterIndex' ),
232 $this->getFirstLetterCount(),
233 'strcmp',
234 $sortKey );
235
236 if ( $min === false ) {
237 // Before the first letter
238 return '';
239 }
240 return $this->getLetterByIndex( $min );
241 }
242
243 function getFirstLetterData() {
244 if ( $this->firstLetterData !== null ) {
245 return $this->firstLetterData;
246 }
247
248 $cache = wfGetCache( CACHE_ANYTHING );
249 $cacheKey = wfMemcKey( 'first-letters', $this->locale );
250 $cacheEntry = $cache->get( $cacheKey );
251
252 if ( $cacheEntry ) {
253 $this->firstLetterData = $cacheEntry;
254 return $this->firstLetterData;
255 }
256
257 // Generate data from serialized data file
258
259 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
260 if ( $letters === false ) {
261 throw new MWException( "MediaWiki does not support ICU locale " .
262 "\"{$this->locale}\"" );
263 }
264
265 // Sort the letters.
266 //
267 // It's impossible to have the precompiled data file properly sorted,
268 // because the sort order changes depending on ICU version. If the
269 // array is not properly sorted, the binary search will return random
270 // results.
271 //
272 // We also take this opportunity to remove primary collisions.
273 $letterMap = array();
274 foreach ( $letters as $letter ) {
275 $key = $this->getPrimarySortKey( $letter );
276 if ( isset( $letterMap[$key] ) ) {
277 // Primary collision
278 // Keep whichever one sorts first in the main collator
279 if ( $this->mainCollator->compare( $letter, $letterMap[$key] ) < 0 ) {
280 $letterMap[$key] = $letter;
281 }
282 } else {
283 $letterMap[$key] = $letter;
284 }
285 }
286 ksort( $letterMap, SORT_STRING );
287 $data = array(
288 'chars' => array_values( $letterMap ),
289 'keys' => array_keys( $letterMap )
290 );
291
292 // Reduce memory usage before caching
293 unset( $letterMap );
294
295 // Save to cache
296 $this->firstLetterData = $data;
297 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
298 return $data;
299 }
300
301 function getLetterByIndex( $index ) {
302 if ( $this->firstLetterData === null ) {
303 $this->getFirstLetterData();
304 }
305 return $this->firstLetterData['chars'][$index];
306 }
307
308 function getSortKeyByLetterIndex( $index ) {
309 if ( $this->firstLetterData === null ) {
310 $this->getFirstLetterData();
311 }
312 return $this->firstLetterData['keys'][$index];
313 }
314
315 function getFirstLetterCount() {
316 if ( $this->firstLetterData === null ) {
317 $this->getFirstLetterData();
318 }
319 return count( $this->firstLetterData['chars'] );
320 }
321
322 /**
323 * Do a binary search, and return the index of the largest item that sorts
324 * less than or equal to the target value.
325 *
326 * @param $valueCallback array A function to call to get the value with
327 * a given array index.
328 * @param $valueCount int The number of items accessible via $valueCallback,
329 * indexed from 0 to $valueCount - 1
330 * @param $comparisonCallback array A callback to compare two values, returning
331 * -1, 0 or 1 in the style of strcmp().
332 * @param $target string The target value to find.
333 *
334 * @return int|bool The item index of the lower bound, or false if the target value
335 * sorts before all items.
336 */
337 function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) {
338 $min = 0;
339 $max = $valueCount - 1;
340 do {
341 $mid = $min + ( ( $max - $min ) >> 1 );
342 $item = call_user_func( $valueCallback, $mid );
343 $comparison = call_user_func( $comparisonCallback, $target, $item );
344 if ( $comparison > 0 ) {
345 $min = $mid;
346 } elseif ( $comparison == 0 ) {
347 $min = $mid;
348 break;
349 } else {
350 $max = $mid;
351 }
352 } while ( $min < $max - 1 );
353
354 if ( $min == 0 && $max == 0 && $comparison > 0 ) {
355 // Before the first item
356 return false;
357 } else {
358 return $min;
359 }
360 }
361
362 static function isCjk( $codepoint ) {
363 foreach ( self::$cjkBlocks as $block ) {
364 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
365 return true;
366 }
367 }
368 return false;
369 }
370 }
371