Split Collation.php
[lhc/web/wiklou.git] / includes / collation / IcuCollation.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 class IcuCollation extends Collation {
22 const FIRST_LETTER_VERSION = 2;
23
24 /** @var Collator */
25 private $primaryCollator;
26
27 /** @var Collator */
28 private $mainCollator;
29
30 /** @var string */
31 private $locale;
32
33 /** @var Language */
34 protected $digitTransformLanguage;
35
36 /** @var array */
37 private $firstLetterData;
38
39 /**
40 * Unified CJK blocks.
41 *
42 * The same definition of a CJK block must be used for both Collation and
43 * generateCollationData.php. These blocks are omitted from the first
44 * letter data, as an optimisation measure and because the default UCA table
45 * is pretty useless for sorting Chinese text anyway. Japanese and Korean
46 * blocks are not included here, because they are smaller and more useful.
47 */
48 private static $cjkBlocks = [
49 [ 0x2E80, 0x2EFF ], // CJK Radicals Supplement
50 [ 0x2F00, 0x2FDF ], // Kangxi Radicals
51 [ 0x2FF0, 0x2FFF ], // Ideographic Description Characters
52 [ 0x3000, 0x303F ], // CJK Symbols and Punctuation
53 [ 0x31C0, 0x31EF ], // CJK Strokes
54 [ 0x3200, 0x32FF ], // Enclosed CJK Letters and Months
55 [ 0x3300, 0x33FF ], // CJK Compatibility
56 [ 0x3400, 0x4DBF ], // CJK Unified Ideographs Extension A
57 [ 0x4E00, 0x9FFF ], // CJK Unified Ideographs
58 [ 0xF900, 0xFAFF ], // CJK Compatibility Ideographs
59 [ 0xFE30, 0xFE4F ], // CJK Compatibility Forms
60 [ 0x20000, 0x2A6DF ], // CJK Unified Ideographs Extension B
61 [ 0x2A700, 0x2B73F ], // CJK Unified Ideographs Extension C
62 [ 0x2B740, 0x2B81F ], // CJK Unified Ideographs Extension D
63 [ 0x2F800, 0x2FA1F ], // CJK Compatibility Ideographs Supplement
64 ];
65
66 /**
67 * Additional characters (or character groups) to be considered separate
68 * letters for given languages, or to be removed from the list of such
69 * letters (denoted by keys starting with '-').
70 *
71 * These are additions to (or subtractions from) the data stored in the
72 * first-letters-root.ser file (which among others includes full basic latin,
73 * cyrillic and greek alphabets).
74 *
75 * "Separate letter" is a letter that would have a separate heading/section
76 * for it in a dictionary or a phone book in this language. This data isn't
77 * used for sorting (the ICU library handles that), only for deciding which
78 * characters (or character groups) to use as headings.
79 *
80 * Initially generated based on the primary level of Unicode collation
81 * tailorings available at http://developer.mimer.com/charts/tailorings.htm ,
82 * later modified.
83 *
84 * Empty arrays are intended; this signifies that the data for the language is
85 * available and that there are, in fact, no additional letters to consider.
86 */
87 private static $tailoringFirstLetters = [
88 // Verified by native speakers
89 'be' => [ "Ё" ],
90 'be-tarask' => [ "Ё" ],
91 'cy' => [ "Ch", "Dd", "Ff", "Ng", "Ll", "Ph", "Rh", "Th" ],
92 'en' => [],
93 'fa' => [ "آ", "ء", "ه" ],
94 'fi' => [ "Å", "Ä", "Ö" ],
95 'fr' => [],
96 'hu' => [ "Cs", "Dz", "Dzs", "Gy", "Ly", "Ny", "Ö", "Sz", "Ty", "Ü", "Zs" ],
97 'is' => [ "Á", "Ð", "É", "Í", "Ó", "Ú", "Ý", "Þ", "Æ", "Ö", "Å" ],
98 'it' => [],
99 'lv' => [ "Č", "Ģ", "Ķ", "Ļ", "Ņ", "Š", "Ž" ],
100 'pl' => [ "Ą", "Ć", "Ę", "Ł", "Ń", "Ó", "Ś", "Ź", "Ż" ],
101 'pt' => [],
102 'ru' => [],
103 'sv' => [ "Å", "Ä", "Ö" ],
104 'sv@collation=standard' => [ "Å", "Ä", "Ö" ],
105 'uk' => [ "Ґ", "Ь" ],
106 'vi' => [ "Ă", "Â", "Đ", "Ê", "Ô", "Ơ", "Ư" ],
107 // Not verified, but likely correct
108 'af' => [],
109 'ast' => [ "Ch", "Ll", "Ñ" ],
110 'az' => [ "Ç", "Ə", "Ğ", "İ", "Ö", "Ş", "Ü" ],
111 'bg' => [],
112 'br' => [ "Ch", "C'h" ],
113 'bs' => [ "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ],
114 'ca' => [],
115 'co' => [],
116 'cs' => [ "Č", "Ch", "Ř", "Š", "Ž" ],
117 'da' => [ "Æ", "Ø", "Å" ],
118 'de' => [],
119 'dsb' => [ "Č", "Ć", "Dź", "Ě", "Ch", "Ł", "Ń", "Ŕ", "Š", "Ś", "Ž", "Ź" ],
120 'el' => [],
121 'eo' => [ "Ĉ", "Ĝ", "Ĥ", "Ĵ", "Ŝ", "Ŭ" ],
122 'es' => [ "Ñ" ],
123 'et' => [ "Š", "Ž", "Õ", "Ä", "Ö", "Ü", "W" ], // added W for CollationEt (xx-uca-et)
124 'eu' => [ "Ñ" ],
125 'fo' => [ "Á", "Ð", "Í", "Ó", "Ú", "Ý", "Æ", "Ø", "Å" ],
126 'fur' => [ "À", "Á", "Â", "È", "Ì", "Ò", "Ù" ],
127 'fy' => [],
128 'ga' => [],
129 'gd' => [],
130 'gl' => [ "Ch", "Ll", "Ñ" ],
131 'hr' => [ "Č", "Ć", "Dž", "Đ", "Lj", "Nj", "Š", "Ž" ],
132 'hsb' => [ "Č", "Dź", "Ě", "Ch", "Ł", "Ń", "Ř", "Š", "Ć", "Ž" ],
133 'kk' => [ "Ү", "І" ],
134 'kl' => [ "Æ", "Ø", "Å" ],
135 'ku' => [ "Ç", "Ê", "Î", "Ş", "Û" ],
136 'ky' => [ "Ё" ],
137 'la' => [],
138 'lb' => [],
139 'lt' => [ "Č", "Š", "Ž" ],
140 'mk' => [],
141 'mo' => [ "Ă", "Â", "Î", "Ş", "Ţ" ],
142 'mt' => [ "Ċ", "Ġ", "Għ", "Ħ", "Ż" ],
143 'nl' => [],
144 'no' => [ "Æ", "Ø", "Å" ],
145 'oc' => [],
146 'rm' => [],
147 'ro' => [ "Ă", "Â", "Î", "Ş", "Ţ" ],
148 'rup' => [ "Ă", "Â", "Î", "Ľ", "Ń", "Ş", "Ţ" ],
149 'sco' => [],
150 'sk' => [ "Ä", "Č", "Ch", "Ô", "Š", "Ž" ],
151 'sl' => [ "Č", "Š", "Ž" ],
152 'smn' => [ "Á", "Č", "Đ", "Ŋ", "Š", "Ŧ", "Ž", "Æ", "Ø", "Å", "Ä", "Ö" ],
153 'sq' => [ "Ç", "Dh", "Ë", "Gj", "Ll", "Nj", "Rr", "Sh", "Th", "Xh", "Zh" ],
154 'sr' => [],
155 'tk' => [ "Ç", "Ä", "Ž", "Ň", "Ö", "Ş", "Ü", "Ý" ],
156 'tl' => [ "Ñ", "Ng" ],
157 'tr' => [ "Ç", "Ğ", "İ", "Ö", "Ş", "Ü" ],
158 'tt' => [ "Ә", "Ө", "Ү", "Җ", "Ң", "Һ" ],
159 'uz' => [ "Ch", "G'", "Ng", "O'", "Sh" ],
160 ];
161
162 const RECORD_LENGTH = 14;
163
164 public function __construct( $locale ) {
165 if ( !extension_loaded( 'intl' ) ) {
166 throw new MWException( 'An ICU collation was requested, ' .
167 'but the intl extension is not available.' );
168 }
169
170 $this->locale = $locale;
171 // Drop everything after the '@' in locale's name
172 $localeParts = explode( '@', $locale );
173 $this->digitTransformLanguage = Language::factory( $locale === 'root' ? 'en' : $localeParts[0] );
174
175 $this->mainCollator = Collator::create( $locale );
176 if ( !$this->mainCollator ) {
177 throw new MWException( "Invalid ICU locale specified for collation: $locale" );
178 }
179
180 $this->primaryCollator = Collator::create( $locale );
181 $this->primaryCollator->setStrength( Collator::PRIMARY );
182 }
183
184 public function getSortKey( $string ) {
185 // intl extension produces non null-terminated
186 // strings. Appending '' fixes it so that it doesn't generate
187 // a warning on each access in debug php.
188 MediaWiki\suppressWarnings();
189 $key = $this->mainCollator->getSortKey( $string ) . '';
190 MediaWiki\restoreWarnings();
191 return $key;
192 }
193
194 public function getPrimarySortKey( $string ) {
195 MediaWiki\suppressWarnings();
196 $key = $this->primaryCollator->getSortKey( $string ) . '';
197 MediaWiki\restoreWarnings();
198 return $key;
199 }
200
201 public function getFirstLetter( $string ) {
202 $string = strval( $string );
203 if ( $string === '' ) {
204 return '';
205 }
206
207 // Check for CJK
208 $firstChar = mb_substr( $string, 0, 1, 'UTF-8' );
209 if ( ord( $firstChar ) > 0x7f && self::isCjk( UtfNormal\Utils::utf8ToCodepoint( $firstChar ) ) ) {
210 return $firstChar;
211 }
212
213 $sortKey = $this->getPrimarySortKey( $string );
214
215 // Do a binary search to find the correct letter to sort under
216 $min = ArrayUtils::findLowerBound(
217 [ $this, 'getSortKeyByLetterIndex' ],
218 $this->getFirstLetterCount(),
219 'strcmp',
220 $sortKey );
221
222 if ( $min === false ) {
223 // Before the first letter
224 return '';
225 }
226 return $this->getLetterByIndex( $min );
227 }
228
229 public function getFirstLetterData() {
230 if ( $this->firstLetterData !== null ) {
231 return $this->firstLetterData;
232 }
233
234 $cache = wfGetCache( CACHE_ANYTHING );
235 $cacheKey = wfMemcKey(
236 'first-letters',
237 $this->locale,
238 $this->digitTransformLanguage->getCode(),
239 self::getICUVersion()
240 );
241 $cacheEntry = $cache->get( $cacheKey );
242
243 if ( $cacheEntry && isset( $cacheEntry['version'] )
244 && $cacheEntry['version'] == self::FIRST_LETTER_VERSION
245 ) {
246 $this->firstLetterData = $cacheEntry;
247 return $this->firstLetterData;
248 }
249
250 // Generate data from serialized data file
251
252 if ( isset( self::$tailoringFirstLetters[$this->locale] ) ) {
253 $letters = wfGetPrecompiledData( "first-letters-root.ser" );
254 // Append additional characters
255 $letters = array_merge( $letters, self::$tailoringFirstLetters[$this->locale] );
256 // Remove unnecessary ones, if any
257 if ( isset( self::$tailoringFirstLetters['-' . $this->locale] ) ) {
258 $letters = array_diff( $letters, self::$tailoringFirstLetters['-' . $this->locale] );
259 }
260 // Apply digit transforms
261 $digits = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ];
262 $letters = array_diff( $letters, $digits );
263 foreach ( $digits as $digit ) {
264 $letters[] = $this->digitTransformLanguage->formatNum( $digit, true );
265 }
266 } else {
267 $letters = wfGetPrecompiledData( "first-letters-{$this->locale}.ser" );
268 if ( $letters === false ) {
269 throw new MWException( "MediaWiki does not support ICU locale " .
270 "\"{$this->locale}\"" );
271 }
272 }
273
274 /* Sort the letters.
275 *
276 * It's impossible to have the precompiled data file properly sorted,
277 * because the sort order changes depending on ICU version. If the
278 * array is not properly sorted, the binary search will return random
279 * results.
280 *
281 * We also take this opportunity to remove primary collisions.
282 */
283 $letterMap = [];
284 foreach ( $letters as $letter ) {
285 $key = $this->getPrimarySortKey( $letter );
286 if ( isset( $letterMap[$key] ) ) {
287 // Primary collision
288 // Keep whichever one sorts first in the main collator
289 if ( $this->mainCollator->compare( $letter, $letterMap[$key] ) < 0 ) {
290 $letterMap[$key] = $letter;
291 }
292 } else {
293 $letterMap[$key] = $letter;
294 }
295 }
296 ksort( $letterMap, SORT_STRING );
297
298 /* Remove duplicate prefixes. Basically if something has a sortkey
299 * which is a prefix of some other sortkey, then it is an
300 * expansion and probably should not be considered a section
301 * header.
302 *
303 * For example 'þ' is sometimes sorted as if it is the letters
304 * 'th'. Other times it is its own primary element. Another
305 * example is '₨'. Sometimes its a currency symbol. Sometimes it
306 * is an 'R' followed by an 's'.
307 *
308 * Additionally an expanded element should always sort directly
309 * after its first element due to they way sortkeys work.
310 *
311 * UCA sortkey elements are of variable length but no collation
312 * element should be a prefix of some other element, so I think
313 * this is safe. See:
314 * - https://ssl.icu-project.org/repos/icu/icuhtml/trunk/design/collation/ICU_collation_design.htm
315 * - http://site.icu-project.org/design/collation/uca-weight-allocation
316 *
317 * Additionally, there is something called primary compression to
318 * worry about. Basically, if you have two primary elements that
319 * are more than one byte and both start with the same byte then
320 * the first byte is dropped on the second primary. Additionally
321 * either \x03 or \xFF may be added to mean that the next primary
322 * does not start with the first byte of the first primary.
323 *
324 * This shouldn't matter much, as the first primary is not
325 * changed, and that is what we are comparing against.
326 *
327 * tl;dr: This makes some assumptions about how icu implements
328 * collations. It seems incredibly unlikely these assumptions
329 * will change, but nonetheless they are assumptions.
330 */
331
332 $prev = false;
333 $duplicatePrefixes = [];
334 foreach ( $letterMap as $key => $value ) {
335 // Remove terminator byte. Otherwise the prefix
336 // comparison will get hung up on that.
337 $trimmedKey = rtrim( $key, "\0" );
338 if ( $prev === false || $prev === '' ) {
339 $prev = $trimmedKey;
340 // We don't yet have a collation element
341 // to compare against, so continue.
342 continue;
343 }
344
345 // Due to the fact the array is sorted, we only have
346 // to compare with the element directly previous
347 // to the current element (skipping expansions).
348 // An element "X" will always sort directly
349 // before "XZ" (Unless we have "XY", but we
350 // do not update $prev in that case).
351 if ( substr( $trimmedKey, 0, strlen( $prev ) ) === $prev ) {
352 $duplicatePrefixes[] = $key;
353 // If this is an expansion, we don't want to
354 // compare the next element to this element,
355 // but to what is currently $prev
356 continue;
357 }
358 $prev = $trimmedKey;
359 }
360 foreach ( $duplicatePrefixes as $badKey ) {
361 wfDebug( "Removing '{$letterMap[$badKey]}' from first letters.\n" );
362 unset( $letterMap[$badKey] );
363 // This code assumes that unsetting does not change sort order.
364 }
365 $data = [
366 'chars' => array_values( $letterMap ),
367 'keys' => array_keys( $letterMap ),
368 'version' => self::FIRST_LETTER_VERSION,
369 ];
370
371 // Reduce memory usage before caching
372 unset( $letterMap );
373
374 // Save to cache
375 $this->firstLetterData = $data;
376 $cache->set( $cacheKey, $data, $cache::TTL_WEEK );
377 return $data;
378 }
379
380 public function getLetterByIndex( $index ) {
381 if ( $this->firstLetterData === null ) {
382 $this->getFirstLetterData();
383 }
384 return $this->firstLetterData['chars'][$index];
385 }
386
387 public function getSortKeyByLetterIndex( $index ) {
388 if ( $this->firstLetterData === null ) {
389 $this->getFirstLetterData();
390 }
391 return $this->firstLetterData['keys'][$index];
392 }
393
394 public function getFirstLetterCount() {
395 if ( $this->firstLetterData === null ) {
396 $this->getFirstLetterData();
397 }
398 return count( $this->firstLetterData['chars'] );
399 }
400
401 static function isCjk( $codepoint ) {
402 foreach ( self::$cjkBlocks as $block ) {
403 if ( $codepoint >= $block[0] && $codepoint <= $block[1] ) {
404 return true;
405 }
406 }
407 return false;
408 }
409
410 /**
411 * Return the version of ICU library used by PHP's intl extension,
412 * or false when the extension is not installed of the version
413 * can't be determined.
414 *
415 * The constant INTL_ICU_VERSION this function refers to isn't really
416 * documented. It is available since PHP 5.3.7 (see PHP bug 54561).
417 * This function will return false on older PHPs.
418 *
419 * @since 1.21
420 * @return string|bool
421 */
422 static function getICUVersion() {
423 return defined( 'INTL_ICU_VERSION' ) ? INTL_ICU_VERSION : false;
424 }
425
426 /**
427 * Return the version of Unicode appropriate for the version of ICU library
428 * currently in use, or false when it can't be determined.
429 *
430 * @since 1.21
431 * @return string|bool
432 */
433 static function getUnicodeVersionForICU() {
434 $icuVersion = IcuCollation::getICUVersion();
435 if ( !$icuVersion ) {
436 return false;
437 }
438
439 $versionPrefix = substr( $icuVersion, 0, 3 );
440 // Source: http://site.icu-project.org/download
441 $map = [
442 '50.' => '6.2',
443 '49.' => '6.1',
444 '4.8' => '6.0',
445 '4.6' => '6.0',
446 '4.4' => '5.2',
447 '4.2' => '5.1',
448 '4.0' => '5.1',
449 '3.8' => '5.0',
450 '3.6' => '5.0',
451 '3.4' => '4.1',
452 ];
453
454 if ( isset( $map[$versionPrefix] ) ) {
455 return $map[$versionPrefix];
456 } else {
457 return false;
458 }
459 }
460 }