Merge "Make sure Parsoid doesn't get snobbish and treat non-html5 tags badly."
[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 $match = array();
52 if ( preg_match( '/^uca-([a-z-]+)$/', $collationName, $match ) ) {
53 return new IcuCollation( $match[1] );
54 }
55
56 # Provide a mechanism for extensions to hook in.
57 $collationObject = null;
58 wfRunHooks( 'Collation::factory', array( $collationName, &$collationObject ) );
59
60 if ( $collationObject instanceof Collation ) {
61 return $collationObject;
62 }
63
64 // If all else fails...
65 throw new MWException( __METHOD__.": unknown collation type \"$collationName\"" );
66 }
67 }
68
69 /**
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
75 * necessary).
76 *
77 * @param string $string UTF-8 string
78 * @return string Binary sortkey
79 */
80 abstract function getSortKey( $string );
81
82 /**
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
89 * list like
90 *
91 * == A ==
92 * * [[Aardvark]]
93 *
94 * == a ==
95 * * [[antelope]]
96 *
97 * == A ==
98 * * [[Ape]]
99 *
100 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
101 *
102 * @param string $string UTF-8 string
103 * @return string UTF-8 string corresponding to the first letter of input
104 */
105 abstract function getFirstLetter( $string );
106 }
107
108 class UppercaseCollation extends Collation {
109 var $lang;
110 function __construct() {
111 // Get a language object so that we can use the generic UTF-8 uppercase
112 // function there
113 $this->lang = Language::factory( 'en' );
114 }
115
116 function getSortKey( $string ) {
117 return $this->lang->uc( $string );
118 }
119
120 function getFirstLetter( $string ) {
121 if ( $string[0] == "\0" ) {
122 $string = substr( $string, 1 );
123 }
124 return $this->lang->ucfirst( $this->lang->firstChar( $string ) );
125 }
126 }
127
128 /**
129 * Collation class that's essentially a no-op.
130 *
131 * Does sorting based on binary value of the string.
132 * Like how things were pre 1.17.
133 */
134 class IdentityCollation extends Collation {
135
136 function getSortKey( $string ) {
137 return $string;
138 }
139
140 function getFirstLetter( $string ) {
141 global $wgContLang;
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 );
146 }
147 return $wgContLang->firstChar( $string );
148 }
149 }
150
151 class IcuCollation extends Collation {
152 var $primaryCollator, $mainCollator, $locale;
153 var $firstLetterData;
154
155 /**
156 * Unified CJK blocks.
157 *
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.
163 */
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
180 );
181
182 /**
183 * Additional characters (or character groups) to be considered separate
184 * letters for given languages, compared to the data stored in the
185 * first-letters-root.ser file (which among others includes full basic latin,
186 * cyrillic and greek alphabets).
187 *
188 * "Separate letter" is a letter that would have a separate heading/section
189 * for it in a dictionary or a phone book in this language. This data isn't
190 * used for sorting (the ICU library handles that), only for deciding which
191 * characters (or character groups) to use as headings.
192 *
193 * Initially generated based on the primary level of Unicode collation
194 * tailorings available at http://developer.mimer.com/charts/tailorings.htm ,
195 * later modified.
196 *
197 * Empty arrays are intended; this signifies that the data for the language is
198 * available and that there are, in fact, no additional letters to consider.
199 */
200 static $tailoringFirstLetters = array(
201 // Verified by native speakers
202 'be' => array( "Ё" ),
203 'be-tarask' => array( "Ё" ),
204 'en' => array(),
205 'fi' => array( "Å", "Ä", "Ö" ),
206 'hu' => array( "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ),
207 'it' => array(),
208 'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
209 'pt' => array(),
210 'ru' => array(),
211 'uk' => array( "Ґ", "Ь" ),
212 // Not verified, but likely correct
213 'af' => array(),
214 'ast' => array( "Ch", "Ll", "Ñ" ),
215 'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
216 'bg' => array(),
217 'br' => array( "Ch", "C'h" ),
218 'bs' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
219 'ca' => array(),
220 'co' => array(),
221 'cs' => array( "Č", "Ch", "Ř", "Š", "Ž" ),
222 'cy' => array( "Ch", "Dd", "Ff", "Ng", "Ll", "Ph", "Rh", "Th" ),
223 'da' => array( "Æ", "Ø", "Å" ),
224 'de' => array(),
225 'dsb' => array( "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
226 'el' => array(),
227 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
228 'es' => array( "Ñ" ),
229 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ),
230 'eu' => array( "Ñ" ),
231 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
232 'fr' => array(),
233 'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
234 'fy' => array(),
235 'ga' => array(),
236 'gd' => array(),
237 'gl' => array( "Ch", "Ll", "Ñ" ),
238 'hr' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
239 'hsb' => array( "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ),
240 'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
241 'kk' => array( "Ү", "І" ),
242 'kl' => array( "Æ", "Ø", "Å" ),
243 'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
244 'ky' => array( "Ё" ),
245 'la' => array(),
246 'lb' => array(),
247 'lt' => array( "Č", "Š", "Ž" ),
248 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
249 'mk' => array(),
250 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
251 'mt' => array( "Ċ", "Ġ", "Għ", "Ħ", "Ż" ),
252 'nl' => array(),
253 'no' => array( "Æ", "Ø", "Å" ),
254 'oc' => array(),
255 'rm' => array(),
256 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
257 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
258 'sco' => array(),
259 'sk' => array( "Ä", "Č", "Ch", "Ô", "Š", "Ž" ),
260 'sl' => array( "Č", "Š", "Ž" ),
261 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
262 'sq' => array( "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ),
263 'sr' => array(),
264 'sv' => array( "Å", "Ä", "Ö" ),
265 'tk' => array( "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ),
266 'tl' => array( "Ñ", "Ng" ),
267 'tr' => array( "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ),
268 'tt' => array( "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ),
269 'uz' => array( "Ch", "G'", "Ng", "O'", "Sh" ),
270 'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
271 );
272
273 const RECORD_LENGTH = 14;
274
275 function __construct( $locale ) {
276 if ( !extension_loaded( 'intl' ) ) {
277 throw new MWException( 'An ICU collation was requested, ' .
278 'but the intl extension is not available.' );
279 }
280 $this->locale = $locale;
281 $this->mainCollator = Collator::create( $locale );
282 if ( !$this->mainCollator ) {
283 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
284 }
285
286 $this->primaryCollator = Collator::create( $locale );
287 $this->primaryCollator->setStrength( Collator::PRIMARY );
288 }
289
290 function getSortKey( $string ) {
291 // intl extension produces non null-terminated
292 // strings. Appending '' fixes it so that it doesn't generate
293 // a warning on each access in debug php.
294 wfSuppressWarnings();
295 $key = $this->mainCollator->getSortKey( $string ) . '';
296 wfRestoreWarnings();
297 return $key;
298 }
299
300 function getPrimarySortKey( $string ) {
301 wfSuppressWarnings();
302 $key = $this->primaryCollator->getSortKey( $string ) . '';
303 wfRestoreWarnings();
304 return $key;
305 }
306
307 function getFirstLetter( $string ) {
308 $string = strval( $string );
309 if ( $string === '' ) {
310 return '';
311 }
312
313 // Check for CJK
314 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
315 if ( ord( $firstChar ) > 0x7f
316 && self::isCjk( utf8ToCodepoint( $firstChar ) ) )
317 {
318 return $firstChar;
319 }
320
321 $sortKey = $this->getPrimarySortKey( $string );
322
323 // Do a binary search to find the correct letter to sort under
324 $min = $this->findLowerBound(
325 array( $this, 'getSortKeyByLetterIndex' ),
326 $this->getFirstLetterCount(),
327 'strcmp',
328 $sortKey );
329
330 if ( $min === false ) {
331 // Before the first letter
332 return '';
333 }
334 return $this->getLetterByIndex( $min );
335 }
336
337 function getFirstLetterData() {
338 if ( $this->firstLetterData !== null ) {
339 return $this->firstLetterData;
340 }
341
342 $cache = wfGetCache( CACHE_ANYTHING );
343 $cacheKey = wfMemcKey( 'first-letters', $this->locale );
344 $cacheEntry = $cache->get( $cacheKey );
345
346 if ( $cacheEntry ) {
347 $this->firstLetterData = $cacheEntry;
348 return $this->firstLetterData;
349 }
350
351 // Generate data from serialized data file
352
353 if ( isset ( self::$tailoringFirstLetters[$this->locale] ) ) {
354 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
355 $letters = array_merge( $letters, self::$tailoringFirstLetters[$this->locale] );
356 } else {
357 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
358 if ( $letters === false ) {
359 throw new MWException( "MediaWiki does not support ICU locale " .
360 "\"{$this->locale}\"" );
361 }
362 }
363
364 // Sort the letters.
365 //
366 // It's impossible to have the precompiled data file properly sorted,
367 // because the sort order changes depending on ICU version. If the
368 // array is not properly sorted, the binary search will return random
369 // results.
370 //
371 // We also take this opportunity to remove primary collisions.
372 $letterMap = array();
373 foreach ( $letters as $letter ) {
374 $key = $this->getPrimarySortKey( $letter );
375 if ( isset( $letterMap[$key] ) ) {
376 // Primary collision
377 // Keep whichever one sorts first in the main collator
378 if ( $this->mainCollator->compare( $letter, $letterMap[$key] ) < 0 ) {
379 $letterMap[$key] = $letter;
380 }
381 } else {
382 $letterMap[$key] = $letter;
383 }
384 }
385 ksort( $letterMap, SORT_STRING );
386 $data = array(
387 'chars' => array_values( $letterMap ),
388 'keys' => array_keys( $letterMap )
389 );
390
391 // Reduce memory usage before caching
392 unset( $letterMap );
393
394 // Save to cache
395 $this->firstLetterData = $data;
396 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
397 return $data;
398 }
399
400 function getLetterByIndex( $index ) {
401 if ( $this->firstLetterData === null ) {
402 $this->getFirstLetterData();
403 }
404 return $this->firstLetterData['chars'][$index];
405 }
406
407 function getSortKeyByLetterIndex( $index ) {
408 if ( $this->firstLetterData === null ) {
409 $this->getFirstLetterData();
410 }
411 return $this->firstLetterData['keys'][$index];
412 }
413
414 function getFirstLetterCount() {
415 if ( $this->firstLetterData === null ) {
416 $this->getFirstLetterData();
417 }
418 return count( $this->firstLetterData['chars'] );
419 }
420
421 /**
422 * Do a binary search, and return the index of the largest item that sorts
423 * less than or equal to the target value.
424 *
425 * @param $valueCallback array A function to call to get the value with
426 * a given array index.
427 * @param $valueCount int The number of items accessible via $valueCallback,
428 * indexed from 0 to $valueCount - 1
429 * @param $comparisonCallback array A callback to compare two values, returning
430 * -1, 0 or 1 in the style of strcmp().
431 * @param $target string The target value to find.
432 *
433 * @return int|bool The item index of the lower bound, or false if the target value
434 * sorts before all items.
435 */
436 function findLowerBound( $valueCallback, $valueCount, $comparisonCallback, $target ) {
437 if ( $valueCount === 0 ) {
438 return false;
439 }
440
441 $min = 0;
442 $max = $valueCount;
443 do {
444 $mid = $min + ( ( $max - $min ) >> 1 );
445 $item = call_user_func( $valueCallback, $mid );
446 $comparison = call_user_func( $comparisonCallback, $target, $item );
447 if ( $comparison > 0 ) {
448 $min = $mid;
449 } elseif ( $comparison == 0 ) {
450 $min = $mid;
451 break;
452 } else {
453 $max = $mid;
454 }
455 } while ( $min < $max - 1 );
456
457 if ( $min == 0 ) {
458 $item = call_user_func( $valueCallback, $min );
459 $comparison = call_user_func( $comparisonCallback, $target, $item );
460 if ( $comparison < 0 ) {
461 // Before the first item
462 return false;
463 }
464 }
465 return $min;
466 }
467
468 static function isCjk( $codepoint ) {
469 foreach ( self::$cjkBlocks as $block ) {
470 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
471 return true;
472 }
473 }
474 return false;
475 }
476
477 /**
478 * Return the version of ICU library used by PHP's intl extension,
479 * or false when the extension is not installed of the version
480 * can't be determined.
481 *
482 * The constant INTL_ICU_VERSION this function refers to isn't really
483 * documented. It is available since PHP 5.3.7 (see PHP bug 54561).
484 * This function will return false on older PHPs.
485 *
486 * @since 1.21
487 * @return string|false
488 */
489 static function getICUVersion() {
490 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION : false;
491 }
492
493 /**
494 * Return the version of Unicode appropriate for the version of ICU library
495 * currently in use, or false when it can't be determined.
496 *
497 * @since 1.21
498 * @return string|false
499 */
500 static function getUnicodeVersionForICU() {
501 $icuVersion = IcuCollation::getICUVersion();
502 if ( !$icuVersion ) {
503 return false;
504 }
505
506 $versionPrefix = substr( $icuVersion, 0, 3 );
507 // Source: http://site.icu-project.org/download
508 $map = array(
509 '50.' => '6.2',
510 '49.' => '6.1',
511 '4.8' => '6.0',
512 '4.6' => '6.0',
513 '4.4' => '5.2',
514 '4.2' => '5.1',
515 '4.0' => '5.1',
516 '3.8' => '5.0',
517 '3.6' => '5.0',
518 '3.4' => '4.1',
519 );
520
521 if ( isset( $map[$versionPrefix] ) ) {
522 return $map[$versionPrefix];
523 } else {
524 return false;
525 }
526 }
527 }