Merge "Reset relevant DB tables before the first test of a suite."
[lhc/web/wiklou.git] / maintenance / language / generateCollationData.php
1 <?php
2 /**
3 * Maintenance script to generate first letter data files for Collation.php.
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 * @ingroup MaintenanceLanguage
22 */
23
24 require_once __DIR__ . '/../Maintenance.php';
25
26 /**
27 * Generate first letter data files for Collation.php
28 *
29 * @ingroup MaintenanceLanguage
30 */
31 class GenerateCollationData extends Maintenance {
32 /** The directory with source data files in it */
33 public $dataDir;
34
35 /** The primary weights, indexed by codepoint */
36 public $weights;
37
38 /**
39 * A hashtable keyed by codepoint, where presence indicates that a character
40 * has a decomposition mapping. This makes it non-preferred for group header
41 * selection.
42 */
43 public $mappedChars;
44
45 public $debugOutFile;
46
47 /**
48 * Important tertiary weights from UTS #10 section 7.2
49 */
50 const NORMAL_UPPERCASE = 0x08;
51 const NORMAL_HIRAGANA = 0x0E;
52
53 public function __construct() {
54 parent::__construct();
55 $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
56 'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
57 false, true );
58 $this->addOption( 'debug-output', 'Filename for sending debug output to',
59 false, true );
60 }
61
62 public function execute() {
63 $this->dataDir = $this->getOption( 'data-dir', '.' );
64
65 $allkeysPresent = file_exists( "{$this->dataDir}/allkeys.txt" );
66 $ucdallPresent = file_exists( "{$this->dataDir}/ucd.all.grouped.xml" );
67
68 // As of January 2013, these links work for all versions of Unicode
69 // between 5.1 and 6.2, inclusive.
70 $allkeysURL = "https://www.unicode.org/Public/UCA/<Unicode version>/allkeys.txt";
71 $ucdallURL = "https://www.unicode.org/Public/<Unicode version>/ucdxml/ucd.all.grouped.zip";
72
73 if ( !$allkeysPresent || !$ucdallPresent ) {
74 $icuVersion = INTL_ICU_VERSION;
75 $unicodeVersion = IcuCollation::getUnicodeVersionForICU();
76
77 $error = "";
78
79 if ( !$allkeysPresent ) {
80 $error .= "Unable to find allkeys.txt. "
81 . "Download it and specify its location with --data-dir=<DIR>. "
82 . "\n\n";
83 }
84 if ( !$ucdallPresent ) {
85 $error .= "Unable to find ucd.all.grouped.xml. "
86 . "Download it, unzip, and specify its location with --data-dir=<DIR>. "
87 . "\n\n";
88 }
89
90 $versionKnown = false;
91 if ( version_compare( $icuVersion, "4.0", "<" ) ) {
92 // Extra old version
93 $error .= "You are using outdated version of ICU ($icuVersion), intended for "
94 . ( $unicodeVersion ? "Unicode $unicodeVersion" : "an unknown version of Unicode" )
95 . "; this file might not be avalaible for it, and it's not supported by MediaWiki. "
96 . " You are on your own; consider upgrading PHP's intl extension or try "
97 . "one of the files available at:";
98 } elseif ( version_compare( $icuVersion, "51.0", ">=" ) ) {
99 // Extra recent version
100 $error .= "You are using ICU $icuVersion, released after this script was last updated. "
101 . "Check what is the Unicode version it is using at http://site.icu-project.org/download . "
102 . "It can't be guaranteed everything will work, but appropriate file(s) should "
103 . "be available at:";
104 } else {
105 // ICU 4.0 to 50.x
106 $versionKnown = true;
107 $error .= "You are using ICU $icuVersion, intended for "
108 . ( $unicodeVersion ? "Unicode $unicodeVersion" : "an unknown version of Unicode" )
109 . ". Appropriate file(s) should be available at:";
110 }
111 $error .= "\n";
112
113 if ( $versionKnown && $unicodeVersion ) {
114 $allkeysURL = str_replace( "<Unicode version>", "$unicodeVersion.0", $allkeysURL );
115 $ucdallURL = str_replace( "<Unicode version>", "$unicodeVersion.0", $ucdallURL );
116 }
117
118 if ( !$allkeysPresent ) {
119 $error .= "* $allkeysURL\n";
120 }
121 if ( !$ucdallPresent ) {
122 $error .= "* $ucdallURL\n";
123 }
124
125 $this->fatalError( $error );
126 }
127
128 $debugOutFileName = $this->getOption( 'debug-output' );
129 if ( $debugOutFileName ) {
130 $this->debugOutFile = fopen( $debugOutFileName, 'w' );
131 if ( !$this->debugOutFile ) {
132 $this->fatalError( "Unable to open debug output file for writing" );
133 }
134 }
135 $this->loadUcd();
136 $this->generateFirstChars();
137 }
138
139 function loadUcd() {
140 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
141 $uxr->readChars( [ $this, 'charCallback' ] );
142 }
143
144 function charCallback( $data ) {
145 // Skip non-printable characters,
146 // but do not skip a normal space (U+0020) since
147 // people like to use that as a fake no header symbol.
148 $category = substr( $data['gc'], 0, 1 );
149 if ( strpos( 'LNPS', $category ) === false
150 && $data['cp'] !== '0020'
151 ) {
152 return;
153 }
154 $cp = hexdec( $data['cp'] );
155
156 // Skip the CJK ideograph blocks, as an optimisation measure.
157 // UCA doesn't sort them properly anyway, without tailoring.
158 if ( IcuCollation::isCjk( $cp ) ) {
159 return;
160 }
161
162 // Skip the composed Hangul syllables, we will use the bare Jamo
163 // as first letters
164 if ( $data['block'] == 'Hangul Syllables' ) {
165 return;
166 }
167
168 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
169 if ( $data['UIdeo'] === 'Y' ) {
170 if ( $data['block'] == 'CJK Unified Ideographs'
171 || $data['block'] == 'CJK Compatibility Ideographs'
172 ) {
173 $base = 0xFB40;
174 } else {
175 $base = 0xFB80;
176 }
177 } else {
178 $base = 0xFBC0;
179 }
180 $a = $base + ( $cp >> 15 );
181 $b = ( $cp & 0x7fff ) | 0x8000;
182
183 $this->weights[$cp] = sprintf( ".%04X.%04X", $a, $b );
184
185 if ( $data['dm'] !== '#' ) {
186 $this->mappedChars[$cp] = true;
187 }
188
189 if ( $cp % 4096 == 0 ) {
190 print "{$data['cp']}\n";
191 }
192 }
193
194 function generateFirstChars() {
195 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
196 if ( !$file ) {
197 $this->fatalError( "Unable to open allkeys.txt" );
198 }
199 global $IP;
200 $outFile = fopen( "$IP/serialized/first-letters-root.ser", 'w' );
201 if ( !$outFile ) {
202 $this->fatalError( "Unable to open output file first-letters-root.ser" );
203 }
204
205 $goodTertiaryChars = [];
206
207 // For each character with an entry in allkeys.txt, overwrite the implicit
208 // entry in $this->weights that came from the UCD.
209 // Also gather a list of tertiary weights, for use in selecting the group header
210 while ( false !== ( $line = fgets( $file ) ) ) {
211 // We're only interested in single-character weights, pick them out with a regex
212 $line = trim( $line );
213 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
214 continue;
215 }
216
217 $cp = hexdec( $m[1] );
218 $allWeights = trim( $m[2] );
219 $primary = '';
220 $tertiary = '';
221
222 if ( !isset( $this->weights[$cp] ) ) {
223 // Non-printable, ignore
224 continue;
225 }
226 foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
227 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
228 if ( !empty( $m[1] ) ) {
229 if ( $m[1][0] !== '0000' ) {
230 $primary .= '.' . $m[1][0];
231 }
232 if ( $m[1][2] !== '0000' ) {
233 $tertiary .= '.' . $m[1][2];
234 }
235 }
236 }
237 $this->weights[$cp] = $primary;
238 if ( $tertiary === '.0008'
239 || $tertiary === '.000E'
240 ) {
241 $goodTertiaryChars[$cp] = true;
242 }
243 }
244 fclose( $file );
245
246 // Identify groups of characters with the same primary weight
247 $this->groups = [];
248 asort( $this->weights, SORT_STRING );
249 $prevWeight = reset( $this->weights );
250 $group = [];
251 foreach ( $this->weights as $cp => $weight ) {
252 if ( $weight !== $prevWeight ) {
253 $this->groups[$prevWeight] = $group;
254 $prevWeight = $weight;
255 if ( isset( $this->groups[$weight] ) ) {
256 $group = $this->groups[$weight];
257 } else {
258 $group = [];
259 }
260 }
261 $group[] = $cp;
262 }
263 if ( $group ) {
264 $this->groups[$prevWeight] = $group;
265 }
266
267 // If one character has a given primary weight sequence, and a second
268 // character has a longer primary weight sequence with an initial
269 // portion equal to the first character, then remove the second
270 // character. This avoids having characters like U+A732 (double A)
271 // polluting the basic latin sort area.
272
273 foreach ( $this->groups as $weight => $group ) {
274 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
275 if ( isset( $this->groups[$m[1]] ) ) {
276 unset( $this->groups[$weight] );
277 }
278 }
279 }
280
281 ksort( $this->groups, SORT_STRING );
282
283 // Identify the header character in each group
284 $headerChars = [];
285 $prevChar = "\000";
286 $tertiaryCollator = new Collator( 'root' );
287 $primaryCollator = new Collator( 'root' );
288 $primaryCollator->setStrength( Collator::PRIMARY );
289 $numOutOfOrder = 0;
290 foreach ( $this->groups as $weight => $group ) {
291 $uncomposedChars = [];
292 $goodChars = [];
293 foreach ( $group as $cp ) {
294 if ( isset( $goodTertiaryChars[$cp] ) ) {
295 $goodChars[] = $cp;
296 }
297 if ( !isset( $this->mappedChars[$cp] ) ) {
298 $uncomposedChars[] = $cp;
299 }
300 }
301 $x = array_intersect( $goodChars, $uncomposedChars );
302 if ( !$x ) {
303 $x = $uncomposedChars;
304 if ( !$x ) {
305 $x = $group;
306 }
307 }
308
309 // Use ICU to pick the lowest sorting character in the selection
310 $tertiaryCollator->sort( $x );
311 $cp = $x[0];
312
313 $char = UtfNormal\Utils::codepointToUtf8( $cp );
314 $headerChars[] = $char;
315 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
316 $numOutOfOrder++;
317 }
318 $prevChar = $char;
319
320 if ( $this->debugOutFile ) {
321 fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
322 implode( ' ', array_map( 'UtfNormal\Utils::codepointToUtf8', $group ) ) ) );
323 }
324 }
325
326 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
327
328 fwrite( $outFile, serialize( $headerChars ) );
329 }
330 }
331
332 class UcdXmlReader {
333 public $fileName;
334 public $callback;
335 public $groupAttrs;
336 public $xml;
337 public $blocks = [];
338 public $currentBlock;
339
340 function __construct( $fileName ) {
341 $this->fileName = $fileName;
342 }
343
344 public function readChars( $callback ) {
345 $this->getBlocks();
346 $this->currentBlock = reset( $this->blocks );
347 $xml = $this->open();
348 $this->callback = $callback;
349
350 while ( $xml->name !== 'repertoire' && $xml->next() );
351
352 while ( $xml->read() ) {
353 if ( $xml->nodeType == XMLReader::ELEMENT ) {
354 if ( $xml->name === 'group' ) {
355 $this->groupAttrs = $this->readAttributes();
356 } elseif ( $xml->name === 'char' ) {
357 $this->handleChar();
358 }
359 } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
360 if ( $xml->name === 'group' ) {
361 $this->groupAttrs = [];
362 }
363 }
364 }
365 $xml->close();
366 }
367
368 protected function open() {
369 $this->xml = new XMLReader;
370 $this->xml->open( $this->fileName );
371 if ( !$this->xml ) {
372 throw new MWException( __METHOD__ . ": unable to open {$this->fileName}" );
373 }
374 while ( $this->xml->name !== 'ucd' && $this->xml->read() );
375 $this->xml->read();
376
377 return $this->xml;
378 }
379
380 /**
381 * Read the attributes of the current element node and return them
382 * as an array
383 * @return array
384 */
385 protected function readAttributes() {
386 $attrs = [];
387 while ( $this->xml->moveToNextAttribute() ) {
388 $attrs[$this->xml->name] = $this->xml->value;
389 }
390
391 return $attrs;
392 }
393
394 protected function handleChar() {
395 $attrs = $this->readAttributes() + $this->groupAttrs;
396 if ( isset( $attrs['cp'] ) ) {
397 $first = $last = hexdec( $attrs['cp'] );
398 } else {
399 $first = hexdec( $attrs['first-cp'] );
400 $last = hexdec( $attrs['last-cp'] );
401 unset( $attrs['first-cp'] );
402 unset( $attrs['last-cp'] );
403 }
404
405 for ( $cp = $first; $cp <= $last; $cp++ ) {
406 $hexCp = sprintf( "%04X", $cp );
407 foreach ( [ 'na', 'na1' ] as $nameProp ) {
408 if ( isset( $attrs[$nameProp] ) ) {
409 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
410 }
411 }
412
413 while ( $this->currentBlock ) {
414 if ( $cp < $this->currentBlock[0] ) {
415 break;
416 } elseif ( $cp <= $this->currentBlock[1] ) {
417 $attrs['block'] = key( $this->blocks );
418 break;
419 } else {
420 $this->currentBlock = next( $this->blocks );
421 }
422 }
423
424 $attrs['cp'] = $hexCp;
425 call_user_func( $this->callback, $attrs );
426 }
427 }
428
429 public function getBlocks() {
430 if ( $this->blocks ) {
431 return $this->blocks;
432 }
433
434 $xml = $this->open();
435 while ( $xml->name !== 'blocks' && $xml->read() );
436
437 while ( $xml->read() ) {
438 if ( $xml->nodeType == XMLReader::ELEMENT ) {
439 if ( $xml->name === 'block' ) {
440 $attrs = $this->readAttributes();
441 $first = hexdec( $attrs['first-cp'] );
442 $last = hexdec( $attrs['last-cp'] );
443 $this->blocks[$attrs['name']] = [ $first, $last ];
444 }
445 }
446 }
447 $xml->close();
448
449 return $this->blocks;
450 }
451 }
452
453 $maintClass = GenerateCollationData::class;
454 require_once RUN_MAINTENANCE_IF_MAIN;