Merge "(bug 44921) API should properly handle OPTIONS"
[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 'uppercase-sv':
47 return new UppercaseSvCollation;
48 case 'identity':
49 return new IdentityCollation;
50 case 'uca-default':
51 return new IcuCollation( 'root' );
52 default:
53 $match = array();
54 if ( preg_match( '/^uca-([a-z-]+)$/', $collationName, $match ) ) {
55 return new IcuCollation( $match[1] );
56 }
57
58 # Provide a mechanism for extensions to hook in.
59 $collationObject = null;
60 wfRunHooks( 'Collation::factory', array( $collationName, &$collationObject ) );
61
62 if ( $collationObject instanceof Collation ) {
63 return $collationObject;
64 }
65
66 // If all else fails...
67 throw new MWException( __METHOD__.": unknown collation type \"$collationName\"" );
68 }
69 }
70
71 /**
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
77 * necessary).
78 *
79 * @param string $string UTF-8 string
80 * @return string Binary sortkey
81 */
82 abstract function getSortKey( $string );
83
84 /**
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
91 * list like
92 *
93 * == A ==
94 * * [[Aardvark]]
95 *
96 * == a ==
97 * * [[antelope]]
98 *
99 * == A ==
100 * * [[Ape]]
101 *
102 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
103 *
104 * @param string $string UTF-8 string
105 * @return string UTF-8 string corresponding to the first letter of input
106 */
107 abstract function getFirstLetter( $string );
108 }
109
110 class UppercaseCollation extends Collation {
111 var $lang;
112 function __construct() {
113 // Get a language object so that we can use the generic UTF-8 uppercase
114 // function there
115 $this->lang = Language::factory( 'en' );
116 }
117
118 function getSortKey( $string ) {
119 return $this->lang->uc( $string );
120 }
121
122 function getFirstLetter( $string ) {
123 if ( $string[0] == "\0" ) {
124 $string = substr( $string, 1 );
125 }
126 return $this->lang->ucfirst( $this->lang->firstChar( $string ) );
127 }
128 }
129
130 /**
131 * Like UppercaseCollation but swaps Ä and Æ.
132 *
133 * This provides an ordering suitable for Swedish.
134 * @author Lejonel
135 */
136 class UppercaseSvCollation extends UppercaseCollation {
137
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( 'Ä' => 'Æ', 'Æ' => 'Ä' ) );
143 }
144 }
145
146 /**
147 * Collation class that's essentially a no-op.
148 *
149 * Does sorting based on binary value of the string.
150 * Like how things were pre 1.17.
151 */
152 class IdentityCollation extends Collation {
153
154 function getSortKey( $string ) {
155 return $string;
156 }
157
158 function getFirstLetter( $string ) {
159 global $wgContLang;
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 );
164 }
165 return $wgContLang->firstChar( $string );
166 }
167 }
168
169
170 class IcuCollation extends Collation {
171 var $primaryCollator, $mainCollator, $locale;
172 var $firstLetterData;
173
174 /**
175 * Unified CJK blocks.
176 *
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.
182 */
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
199 );
200
201 /**
202 * Additional characters (or character groups) to be considered first-letters
203 *
204 * Generated based on the primary level of Unicode collation tailorings
205 * available at http://developer.mimer.com/charts/tailorings.htm .
206 *
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.
209 */
210 static $tailoringFirstLetters = array(
211 // Verified by native speakers
212 'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
213 'fi' => array( "Å", "Ä", "Ö" ),
214 // Not verified, but likely correct
215 'af' => array(),
216 'ast' => array( "CH", "LL", "Ñ" ),
217 'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
218 'be' => array( "Ё" ),
219 'bg' => array(),
220 'br' => array( "CH", "C'H" ),
221 'bs' => array( "Č", "Ć", "DŽ", "Đ", "LJ", "NJ", "Š", "Ž" ),
222 'ca' => array(),
223 'co' => array(),
224 'cs' => array( "Č", "CH", "Ř", "Š", "Ž" ),
225 'cy' => array( "CH", "DD", "FF", "NG", "LL", "PH", "RH", "TH" ),
226 'da' => array( "Æ", "Ø", "Å" ),
227 'de' => array(),
228 'dsb' => array( "Č", "Ć", "DŹ", "Ě", "CH", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
229 'el' => array(),
230 'en' => array(),
231 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
232 'es' => array( "Ñ" ),
233 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ),
234 'eu' => array( "Ñ" ),
235 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
236 'fr' => array(),
237 'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
238 'fy' => array(),
239 'ga' => array(),
240 'gd' => 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( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
246 'it' => array(),
247 'kk' => array( "Ү", "І" ),
248 'kl' => array( "Æ", "Ø", "Å" ),
249 'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
250 'ky' => array( "Ё" ),
251 'la' => array(),
252 'lb' => array(),
253 'lt' => array( "Č", "Š", "Ž" ),
254 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
255 'mk' => array(),
256 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
257 'mt' => array( "Ċ", "Ġ", "GĦ", "Ħ", "Ż" ),
258 'nl' => array(),
259 'no' => array( "Æ", "Ø", "Å" ),
260 'oc' => array(),
261 'pt' => array(),
262 'rm' => array(),
263 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
264 'ru' => array(),
265 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
266 'sco' => array(),
267 'sk' => array( "Ä", "Č", "CH", "Ô", "Š", "Ž" ),
268 'sl' => array( "Č", "Š", "Ž" ),
269 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
270 'sq' => array( "Ç", "DH", "Ë", "GJ", "LL", "NJ", "RR", "SH", "TH", "XH", "ZH" ),
271 'sr' => array(),
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( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
280 );
281
282 const RECORD_LENGTH = 14;
283
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.' );
288 }
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" );
293 }
294
295 $this->primaryCollator = Collator::create( $locale );
296 $this->primaryCollator->setStrength( Collator::PRIMARY );
297 }
298
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 ) . '';
305 wfRestoreWarnings();
306 return $key;
307 }
308
309 function getPrimarySortKey( $string ) {
310 wfSuppressWarnings();
311 $key = $this->primaryCollator->getSortKey( $string ) . '';
312 wfRestoreWarnings();
313 return $key;
314 }
315
316 function getFirstLetter( $string ) {
317 $string = strval( $string );
318 if ( $string === '' ) {
319 return '';
320 }
321
322 // Check for CJK
323 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
324 if ( ord( $firstChar ) > 0x7f
325 && self::isCjk( utf8ToCodepoint( $firstChar ) ) )
326 {
327 return $firstChar;
328 }
329
330 $sortKey = $this->getPrimarySortKey( $string );
331
332 // Do a binary search to find the correct letter to sort under
333 $min = $this->findLowerBound(
334 array( $this, 'getSortKeyByLetterIndex' ),
335 $this->getFirstLetterCount(),
336 'strcmp',
337 $sortKey );
338
339 if ( $min === false ) {
340 // Before the first letter
341 return '';
342 }
343 return $this->getLetterByIndex( $min );
344 }
345
346 function getFirstLetterData() {
347 if ( $this->firstLetterData !== null ) {
348 return $this->firstLetterData;
349 }
350
351 $cache = wfGetCache( CACHE_ANYTHING );
352 $cacheKey = wfMemcKey( 'first-letters', $this->locale );
353 $cacheEntry = $cache->get( $cacheKey );
354
355 if ( $cacheEntry ) {
356 $this->firstLetterData = $cacheEntry;
357 return $this->firstLetterData;
358 }
359
360 // Generate data from serialized data file
361
362 if ( isset ( self::$tailoringFirstLetters[$this->locale] ) ) {
363 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
364 $letters = array_merge( $letters, self::$tailoringFirstLetters[$this->locale] );
365 } else {
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}\"" );
370 }
371 }
372
373 // Sort the letters.
374 //
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
378 // results.
379 //
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] ) ) {
385 // Primary collision
386 // Keep whichever one sorts first in the main collator
387 if ( $this->mainCollator->compare( $letter, $letterMap[$key] ) < 0 ) {
388 $letterMap[$key] = $letter;
389 }
390 } else {
391 $letterMap[$key] = $letter;
392 }
393 }
394 ksort( $letterMap, SORT_STRING );
395 $data = array(
396 'chars' => array_values( $letterMap ),
397 'keys' => array_keys( $letterMap )
398 );
399
400 // Reduce memory usage before caching
401 unset( $letterMap );
402
403 // Save to cache
404 $this->firstLetterData = $data;
405 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
406 return $data;
407 }
408
409 function getLetterByIndex( $index ) {
410 if ( $this->firstLetterData === null ) {
411 $this->getFirstLetterData();
412 }
413 return $this->firstLetterData['chars'][$index];
414 }
415
416 function getSortKeyByLetterIndex( $index ) {
417 if ( $this->firstLetterData === null ) {
418 $this->getFirstLetterData();
419 }
420 return $this->firstLetterData['keys'][$index];
421 }
422
423 function getFirstLetterCount() {
424 if ( $this->firstLetterData === null ) {
425 $this->getFirstLetterData();
426 }
427 return count( $this->firstLetterData['chars'] );
428 }
429
430 /**
431 * Do a binary search, and return the index of the largest item that sorts
432 * less than or equal to the target value.
433 *
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.
441 *
442 * @return int|bool The item index of the lower bound, or false if the target value
443 * sorts before all items.
444 */
445 function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) {
446 if ( $valueCount === 0 ) {
447 return false;
448 }
449
450 $min = 0;
451 $max = $valueCount;
452 do {
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 ) {
457 $min = $mid;
458 } elseif ( $comparison == 0 ) {
459 $min = $mid;
460 break;
461 } else {
462 $max = $mid;
463 }
464 } while ( $min < $max - 1 );
465
466 if ( $min == 0 ) {
467 $item = call_user_func( $valueCallback, $min );
468 $comparison = call_user_func( $comparisonCallback, $target, $item );
469 if ( $comparison < 0 ) {
470 // Before the first item
471 return false;
472 }
473 }
474 return $min;
475 }
476
477 static function isCjk( $codepoint ) {
478 foreach ( self::$cjkBlocks as $block ) {
479 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
480 return true;
481 }
482 }
483 return false;
484 }
485
486 /**
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.
490 *
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.
494 *
495 * @since 1.21
496 * @return string|false
497 */
498 static function getICUVersion() {
499 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION : false;
500 }
501
502 /**
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.
505 *
506 * @since 1.21
507 * @return string|false
508 */
509 static function getUnicodeVersionForICU() {
510 $icuVersion = IcuCollation::getICUVersion();
511 if ( !$icuVersion ) {
512 return false;
513 }
514
515 $versionPrefix = substr( $icuVersion, 0, 3 );
516 // Source: http://site.icu-project.org/download
517 $map = array(
518 '50.' => '6.2',
519 '49.' => '6.1',
520 '4.8' => '6.0',
521 '4.6' => '6.0',
522 '4.4' => '5.2',
523 '4.2' => '5.1',
524 '4.0' => '5.1',
525 '3.8' => '5.0',
526 '3.6' => '5.0',
527 '3.4' => '4.1',
528 );
529
530 if ( isset( $map[$versionPrefix] ) ) {
531 return $map[$versionPrefix];
532 } else {
533 return false;
534 }
535 }
536 }