Use Xml::element instead of Html::element for empty elements
[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 private 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 string $collationName
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 case 'xx-uca-ckb':
51 return new CollationCkb;
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 private $lang;
112
113 function __construct() {
114 // Get a language object so that we can use the generic UTF-8 uppercase
115 // function there
116 $this->lang = Language::factory( 'en' );
117 }
118
119 function getSortKey( $string ) {
120 return $this->lang->uc( $string );
121 }
122
123 function getFirstLetter( $string ) {
124 if ( $string[0] == "\0" ) {
125 $string = substr( $string, 1 );
126 }
127 return $this->lang->ucfirst( $this->lang->firstChar( $string ) );
128 }
129 }
130
131 /**
132 * Collation class that's essentially a no-op.
133 *
134 * Does sorting based on binary value of the string.
135 * Like how things were pre 1.17.
136 */
137 class IdentityCollation extends Collation {
138
139 function getSortKey( $string ) {
140 return $string;
141 }
142
143 function getFirstLetter( $string ) {
144 global $wgContLang;
145 // Copied from UppercaseCollation.
146 // I'm kind of unclear on when this could happen...
147 if ( $string[0] == "\0" ) {
148 $string = substr( $string, 1 );
149 }
150 return $wgContLang->firstChar( $string );
151 }
152 }
153
154 class IcuCollation extends Collation {
155 const FIRST_LETTER_VERSION = 2;
156
157 /** @var Collator */
158 private $primaryCollator;
159
160 /** @var Collator */
161 private $mainCollator;
162
163 /** @var */
164 private $locale;
165
166 /** @var Language */
167 protected $digitTransformLanguage;
168
169 /** @var array */
170 private $firstLetterData;
171
172 /**
173 * Unified CJK blocks.
174 *
175 * The same definition of a CJK block must be used for both Collation and
176 * generateCollationData.php. These blocks are omitted from the first
177 * letter data, as an optimisation measure and because the default UCA table
178 * is pretty useless for sorting Chinese text anyway. Japanese and Korean
179 * blocks are not included here, because they are smaller and more useful.
180 */
181 private static $cjkBlocks = array(
182 array( 0x2E80, 0x2EFF ), // CJK Radicals Supplement
183 array( 0x2F00, 0x2FDF ), // Kangxi Radicals
184 array( 0x2FF0, 0x2FFF ), // Ideographic Description Characters
185 array( 0x3000, 0x303F ), // CJK Symbols and Punctuation
186 array( 0x31C0, 0x31EF ), // CJK Strokes
187 array( 0x3200, 0x32FF ), // Enclosed CJK Letters and Months
188 array( 0x3300, 0x33FF ), // CJK Compatibility
189 array( 0x3400, 0x4DBF ), // CJK Unified Ideographs Extension A
190 array( 0x4E00, 0x9FFF ), // CJK Unified Ideographs
191 array( 0xF900, 0xFAFF ), // CJK Compatibility Ideographs
192 array( 0xFE30, 0xFE4F ), // CJK Compatibility Forms
193 array( 0x20000, 0x2A6DF ), // CJK Unified Ideographs Extension B
194 array( 0x2A700, 0x2B73F ), // CJK Unified Ideographs Extension C
195 array( 0x2B740, 0x2B81F ), // CJK Unified Ideographs Extension D
196 array( 0x2F800, 0x2FA1F ), // CJK Compatibility Ideographs Supplement
197 );
198
199 /**
200 * Additional characters (or character groups) to be considered separate
201 * letters for given languages, or to be removed from the list of such
202 * letters (denoted by keys starting with '-').
203 *
204 * These are additions to (or subtractions from) the data stored in the
205 * first-letters-root.ser file (which among others includes full basic latin,
206 * cyrillic and greek alphabets).
207 *
208 * "Separate letter" is a letter that would have a separate heading/section
209 * for it in a dictionary or a phone book in this language. This data isn't
210 * used for sorting (the ICU library handles that), only for deciding which
211 * characters (or character groups) to use as headings.
212 *
213 * Initially generated based on the primary level of Unicode collation
214 * tailorings available at http://developer.mimer.com/charts/tailorings.htm ,
215 * later modified.
216 *
217 * Empty arrays are intended; this signifies that the data for the language is
218 * available and that there are, in fact, no additional letters to consider.
219 */
220 private static $tailoringFirstLetters = array(
221 // Verified by native speakers
222 'be' => array( "Ё" ),
223 'be-tarask' => array( "Ё" ),
224 'cy' => array( "Ch", "Dd", "Ff", "Ng", "Ll", "Ph", "Rh", "Th" ),
225 'en' => array(),
226 'fa' => array( "آ", "ء", "ه" ),
227 'fi' => array( "Å", "Ä", "Ö" ),
228 'fr' => array(),
229 'hu' => array( "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ),
230 'is' => array( "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ),
231 'it' => array(),
232 'lv' => array( "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ),
233 'pl' => array( "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ),
234 'pt' => array(),
235 'ru' => array(),
236 'sv' => array( "Å", "Ä", "Ö" ),
237 'sv@collation=standard' => array( "Å", "Ä", "Ö" ),
238 'uk' => array( "Ґ", "Ь" ),
239 'vi' => array( "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ),
240 // Not verified, but likely correct
241 'af' => array(),
242 'ast' => array( "Ch", "Ll", "Ñ" ),
243 'az' => array( "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ),
244 'bg' => array(),
245 'br' => array( "Ch", "C'h" ),
246 'bs' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
247 'ca' => array(),
248 'co' => array(),
249 'cs' => array( "Č", "Ch", "Ř", "Š", "Ž" ),
250 'da' => array( "Æ", "Ø", "Å" ),
251 'de' => array(),
252 'dsb' => array( "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ),
253 'el' => array(),
254 'eo' => array( "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ),
255 'es' => array( "Ñ" ),
256 'et' => array( "Š", "Ž", "Õ", "Ä", "Ö", "Ü" ),
257 'eu' => array( "Ñ" ),
258 'fo' => array( "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ),
259 'fur' => array( "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ),
260 'fy' => array(),
261 'ga' => array(),
262 'gd' => array(),
263 'gl' => array( "Ch", "Ll", "Ñ" ),
264 'hr' => array( "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ),
265 'hsb' => array( "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ),
266 'kk' => array( "Ү", "І" ),
267 'kl' => array( "Æ", "Ø", "Å" ),
268 'ku' => array( "Ç", "Ê", "Î", "Ş", "Û" ),
269 'ky' => array( "Ё" ),
270 'la' => array(),
271 'lb' => array(),
272 'lt' => array( "Č", "Š", "Ž" ),
273 'mk' => array(),
274 'mo' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
275 'mt' => array( "Ċ", "Ġ", "Għ", "Ħ", "Ż" ),
276 'nl' => array(),
277 'no' => array( "Æ", "Ø", "Å" ),
278 'oc' => array(),
279 'rm' => array(),
280 'ro' => array( "Ă", "Â", "Î", "Ş", "Ţ" ),
281 'rup' => array( "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ),
282 'sco' => array(),
283 'sk' => array( "Ä", "Č", "Ch", "Ô", "Š", "Ž" ),
284 'sl' => array( "Č", "Š", "Ž" ),
285 'smn' => array( "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ),
286 'sq' => array( "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ),
287 'sr' => array(),
288 'tk' => array( "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ),
289 'tl' => array( "Ñ", "Ng" ),
290 'tr' => array( "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ),
291 'tt' => array( "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ),
292 'uz' => array( "Ch", "G'", "Ng", "O'", "Sh" ),
293 );
294
295 const RECORD_LENGTH = 14;
296
297 function __construct( $locale ) {
298 if ( !extension_loaded( 'intl' ) ) {
299 throw new MWException( 'An ICU collation was requested, ' .
300 'but the intl extension is not available.' );
301 }
302
303 $this->locale = $locale;
304 // Drop everything after the '@' in locale's name
305 $localeParts = explode( '@', $locale );
306 $this->digitTransformLanguage = Language::factory( $locale === 'root' ? 'en' : $localeParts[0] );
307
308 $this->mainCollator = Collator::create( $locale );
309 if ( !$this->mainCollator ) {
310 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
311 }
312
313 $this->primaryCollator = Collator::create( $locale );
314 $this->primaryCollator->setStrength( Collator::PRIMARY );
315 }
316
317 function getSortKey( $string ) {
318 // intl extension produces non null-terminated
319 // strings. Appending '' fixes it so that it doesn't generate
320 // a warning on each access in debug php.
321 wfSuppressWarnings();
322 $key = $this->mainCollator->getSortKey( $string ) . '';
323 wfRestoreWarnings();
324 return $key;
325 }
326
327 function getPrimarySortKey( $string ) {
328 wfSuppressWarnings();
329 $key = $this->primaryCollator->getSortKey( $string ) . '';
330 wfRestoreWarnings();
331 return $key;
332 }
333
334 function getFirstLetter( $string ) {
335 $string = strval( $string );
336 if ( $string === '' ) {
337 return '';
338 }
339
340 // Check for CJK
341 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
342 if ( ord( $firstChar ) > 0x7f && self::isCjk( utf8ToCodepoint( $firstChar ) ) ) {
343 return $firstChar;
344 }
345
346 $sortKey = $this->getPrimarySortKey( $string );
347
348 // Do a binary search to find the correct letter to sort under
349 $min = ArrayUtils::findLowerBound(
350 array( $this, 'getSortKeyByLetterIndex' ),
351 $this->getFirstLetterCount(),
352 'strcmp',
353 $sortKey );
354
355 if ( $min === false ) {
356 // Before the first letter
357 return '';
358 }
359 return $this->getLetterByIndex( $min );
360 }
361
362 function getFirstLetterData() {
363 if ( $this->firstLetterData !== null ) {
364 return $this->firstLetterData;
365 }
366
367 $cache = wfGetCache( CACHE_ANYTHING );
368 $cacheKey = wfMemcKey( 'first-letters', $this->locale, $this->digitTransformLanguage->getCode() );
369 $cacheEntry = $cache->get( $cacheKey );
370
371 if ( $cacheEntry && isset( $cacheEntry['version'] )
372 && $cacheEntry['version'] == self::FIRST_LETTER_VERSION
373 ) {
374 $this->firstLetterData = $cacheEntry;
375 return $this->firstLetterData;
376 }
377
378 // Generate data from serialized data file
379
380 if ( isset( self::$tailoringFirstLetters[$this->locale] ) ) {
381 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
382 // Append additional characters
383 $letters = array_merge( $letters, self::$tailoringFirstLetters[$this->locale] );
384 // Remove unnecessary ones, if any
385 if ( isset( self::$tailoringFirstLetters['-' . $this->locale] ) ) {
386 $letters = array_diff( $letters, self::$tailoringFirstLetters['-' . $this->locale] );
387 }
388 // Apply digit transforms
389 $digits = array( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' );
390 $letters = array_diff( $letters, $digits );
391 foreach ( $digits as $digit ) {
392 $letters[] = $this->digitTransformLanguage->formatNum( $digit, true );
393 }
394 } else {
395 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
396 if ( $letters === false ) {
397 throw new MWException( "MediaWiki does not support ICU locale " .
398 "\"{$this->locale}\"" );
399 }
400 }
401
402 // Sort the letters.
403 //
404 // It's impossible to have the precompiled data file properly sorted,
405 // because the sort order changes depending on ICU version. If the
406 // array is not properly sorted, the binary search will return random
407 // results.
408 //
409 // We also take this opportunity to remove primary collisions.
410 $letterMap = array();
411 foreach ( $letters as $letter ) {
412 $key = $this->getPrimarySortKey( $letter );
413 if ( isset( $letterMap[$key] ) ) {
414 // Primary collision
415 // Keep whichever one sorts first in the main collator
416 if ( $this->mainCollator->compare( $letter, $letterMap[$key] ) < 0 ) {
417 $letterMap[$key] = $letter;
418 }
419 } else {
420 $letterMap[$key] = $letter;
421 }
422 }
423 ksort( $letterMap, SORT_STRING );
424 // Remove duplicate prefixes. Basically if something has a sortkey
425 // which is a prefix of some other sortkey, then it is an
426 // expansion and probably should not be considered a section
427 // header.
428 //
429 // For example 'þ' is sometimes sorted as if it is the letters
430 // 'th'. Other times it is its own primary element. Another
431 // example is '₨'. Sometimes its a currency symbol. Sometimes it
432 // is an 'R' followed by an 's'.
433 //
434 // Additionally an expanded element should always sort directly
435 // after its first element due to they way sortkeys work.
436 //
437 // UCA sortkey elements are of variable length but no collation
438 // element should be a prefix of some other element, so I think
439 // this is safe. See:
440 // * https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
441 // * http://site.icu-project.org/design/collation/uca-weight-allocation
442 //
443 // Additionally, there is something called primary compression to
444 // worry about. Basically, if you have two primary elements that
445 // are more than one byte and both start with the same byte then
446 // the first byte is dropped on the second primary. Additionally
447 // either \x03 or \xFF may be added to mean that the next primary
448 // does not start with the first byte of the first primary.
449 //
450 // This shouldn't matter much, as the first primary is not
451 // changed, and that is what we are comparing against.
452 //
453 // tl;dr: This makes some assumptions about how icu implements
454 // collations. It seems incredibly unlikely these assumptions
455 // will change, but nonetheless they are assumptions.
456
457 $prev = false;
458 $duplicatePrefixes = array();
459 foreach ( $letterMap as $key => $value ) {
460 // Remove terminator byte. Otherwise the prefix
461 // comparison will get hung up on that.
462 $trimmedKey = rtrim( $key, "\0" );
463 if ( $prev === false || $prev === '' ) {
464 $prev = $trimmedKey;
465 // We don't yet have a collation element
466 // to compare against, so continue.
467 continue;
468 }
469
470 // Due to the fact the array is sorted, we only have
471 // to compare with the element directly previous
472 // to the current element (skipping expansions).
473 // An element "X" will always sort directly
474 // before "XZ" (Unless we have "XY", but we
475 // do not update $prev in that case).
476 if ( substr( $trimmedKey, 0, strlen( $prev ) ) === $prev ) {
477 $duplicatePrefixes[] = $key;
478 // If this is an expansion, we don't want to
479 // compare the next element to this element,
480 // but to what is currently $prev
481 continue;
482 }
483 $prev = $trimmedKey;
484 }
485 foreach ( $duplicatePrefixes as $badKey ) {
486 wfDebug( "Removing '{$letterMap[$badKey]}' from first letters.\n" );
487 unset( $letterMap[$badKey] );
488 // This code assumes that unsetting does not change sort order.
489 }
490 $data = array(
491 'chars' => array_values( $letterMap ),
492 'keys' => array_keys( $letterMap ),
493 'version' => self::FIRST_LETTER_VERSION,
494 );
495
496 // Reduce memory usage before caching
497 unset( $letterMap );
498
499 // Save to cache
500 $this->firstLetterData = $data;
501 $cache->set( $cacheKey, $data, 86400 * 7 /* 1 week */ );
502 return $data;
503 }
504
505 function getLetterByIndex( $index ) {
506 if ( $this->firstLetterData === null ) {
507 $this->getFirstLetterData();
508 }
509 return $this->firstLetterData['chars'][$index];
510 }
511
512 function getSortKeyByLetterIndex( $index ) {
513 if ( $this->firstLetterData === null ) {
514 $this->getFirstLetterData();
515 }
516 return $this->firstLetterData['keys'][$index];
517 }
518
519 function getFirstLetterCount() {
520 if ( $this->firstLetterData === null ) {
521 $this->getFirstLetterData();
522 }
523 return count( $this->firstLetterData['chars'] );
524 }
525
526 static function isCjk( $codepoint ) {
527 foreach ( self::$cjkBlocks as $block ) {
528 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
529 return true;
530 }
531 }
532 return false;
533 }
534
535 /**
536 * Return the version of ICU library used by PHP's intl extension,
537 * or false when the extension is not installed of the version
538 * can't be determined.
539 *
540 * The constant INTL_ICU_VERSION this function refers to isn't really
541 * documented. It is available since PHP 5.3.7 (see PHP bug 54561).
542 * This function will return false on older PHPs.
543 *
544 * @since 1.21
545 * @return string|bool
546 */
547 static function getICUVersion() {
548 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION : false;
549 }
550
551 /**
552 * Return the version of Unicode appropriate for the version of ICU library
553 * currently in use, or false when it can't be determined.
554 *
555 * @since 1.21
556 * @return string|bool
557 */
558 static function getUnicodeVersionForICU() {
559 $icuVersion = IcuCollation::getICUVersion();
560 if ( !$icuVersion ) {
561 return false;
562 }
563
564 $versionPrefix = substr( $icuVersion, 0, 3 );
565 // Source: http://site.icu-project.org/download
566 $map = array(
567 '50.' => '6.2',
568 '49.' => '6.1',
569 '4.8' => '6.0',
570 '4.6' => '6.0',
571 '4.4' => '5.2',
572 '4.2' => '5.1',
573 '4.0' => '5.1',
574 '3.8' => '5.0',
575 '3.6' => '5.0',
576 '3.4' => '4.1',
577 );
578
579 if ( isset( $map[$versionPrefix] ) ) {
580 return $map[$versionPrefix];
581 } else {
582 return false;
583 }
584 }
585 }
586
587 /**
588 * Workaround for the lack of support of Sorani Kurdish / Central Kurdish language ('ckb') in ICU.
589 *
590 * Uses the same collation rules as Persian / Farsi ('fa'), but different characters for digits.
591 */
592 class CollationCkb extends IcuCollation {
593 function __construct() {
594 // This will set $locale and collators, which affect the actual sorting order
595 parent::__construct( 'fa' );
596 // Override the 'fa' language set by parent constructor, which affects #getFirstLetterData()
597 $this->digitTransformLanguage = Language::factory( 'ckb' );
598 }
599 }