MediaWiki master
generateCollationData.php
Go to the documentation of this file.
1<?php
24require_once __DIR__ . '/../Maintenance.php';
25
27
35 public $dataDir;
36
38 public $weights;
39
46
48
49 private $groups;
50
51 public function __construct() {
52 parent::__construct();
53 $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
54 'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
55 false, true );
56 $this->addOption( 'debug-output', 'Filename for sending debug output to',
57 false, true );
58 }
59
60 public function execute() {
61 $this->dataDir = $this->getOption( 'data-dir', '.' );
62
63 $allkeysPresent = file_exists( "{$this->dataDir}/allkeys.txt" );
64 $ucdallPresent = file_exists( "{$this->dataDir}/ucd.all.grouped.xml" );
65
66 if ( !$allkeysPresent || !$ucdallPresent ) {
67 $icuVersion = INTL_ICU_VERSION;
68 $unicodeVersion = implode( '.', array_slice( IntlChar::getUnicodeVersion(), 0, 3 ) );
69
70 $error = "";
71
72 if ( !$allkeysPresent ) {
73 $error .= "Unable to find allkeys.txt. "
74 . "Download it and specify its location with --data-dir=<DIR>. "
75 . "\n\n";
76 }
77 if ( !$ucdallPresent ) {
78 $error .= "Unable to find ucd.all.grouped.xml. "
79 . "Download it, unzip, and specify its location with --data-dir=<DIR>. "
80 . "\n\n";
81 }
82
83 $error .= "You are using ICU $icuVersion, intended for Unicode $unicodeVersion. "
84 . "Appropriate file(s) should be available at:\n";
85
86 $allkeysURL = "https://www.unicode.org/Public/UCA/$unicodeVersion/allkeys.txt";
87 $ucdallURL = "https://www.unicode.org/Public/$unicodeVersion/ucdxml/ucd.all.grouped.zip";
88
89 if ( !$allkeysPresent ) {
90 $error .= "* $allkeysURL\n";
91 }
92 if ( !$ucdallPresent ) {
93 $error .= "* $ucdallURL\n";
94 }
95
96 $this->fatalError( $error );
97 }
98
99 $debugOutFileName = $this->getOption( 'debug-output' );
100 if ( $debugOutFileName ) {
101 $this->debugOutFile = fopen( $debugOutFileName, 'w' );
102 if ( !$this->debugOutFile ) {
103 $this->fatalError( "Unable to open debug output file for writing" );
104 }
105 }
106 $this->loadUcd();
107 $this->generateFirstChars();
108 }
109
110 private function loadUcd() {
111 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
112 $uxr->readChars( [ $this, 'charCallback' ] );
113 }
114
115 private function charCallback( $data ) {
116 // Skip non-printable characters,
117 // but do not skip a normal space (U+0020) since
118 // people like to use that as a fake no header symbol.
119 $category = substr( $data['gc'], 0, 1 );
120 if ( strpos( 'LNPS', $category ) === false
121 && $data['cp'] !== '0020'
122 ) {
123 return;
124 }
125 $cp = hexdec( $data['cp'] );
126
127 // Skip the CJK ideograph blocks, as an optimisation measure.
128 // UCA doesn't sort them properly anyway, without tailoring.
129 if ( IcuCollation::isCjk( $cp ) ) {
130 return;
131 }
132
133 // Skip the composed Hangul syllables, we will use the bare Jamo
134 // as first letters
135 if ( $data['block'] == 'Hangul Syllables' ) {
136 return;
137 }
138
139 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
140 if ( $data['UIdeo'] === 'Y' ) {
141 if ( $data['block'] == 'CJK Unified Ideographs'
142 || $data['block'] == 'CJK Compatibility Ideographs'
143 ) {
144 $base = 0xFB40;
145 } else {
146 $base = 0xFB80;
147 }
148 } else {
149 $base = 0xFBC0;
150 }
151 $a = $base + ( $cp >> 15 );
152 $b = ( $cp & 0x7fff ) | 0x8000;
153
154 $this->weights[$cp] = sprintf( ".%04X.%04X", $a, $b );
155
156 if ( $data['dm'] !== '#' ) {
157 $this->mappedChars[$cp] = true;
158 }
159
160 if ( $cp % 4096 == 0 ) {
161 print "{$data['cp']}\n";
162 }
163 }
164
165 private function generateFirstChars() {
166 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
167 if ( !$file ) {
168 $this->fatalError( "Unable to open allkeys.txt" );
169 }
170
171 $goodTertiaryChars = [];
172
173 // For each character with an entry in allkeys.txt, overwrite the implicit
174 // entry in $this->weights that came from the UCD.
175 // Also gather a list of tertiary weights, for use in selecting the group header
176 while ( ( $line = fgets( $file ) ) !== false ) {
177 // We're only interested in single-character weights, pick them out with a regex
178 $line = trim( $line );
179 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
180 continue;
181 }
182
183 $cp = hexdec( $m[1] );
184 $allWeights = trim( $m[2] );
185 $primary = '';
186 $tertiary = '';
187
188 if ( !isset( $this->weights[$cp] ) ) {
189 // Non-printable, ignore
190 continue;
191 }
192 foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
193 if ( preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m ) ) {
194 if ( $m[1][0] !== '0000' ) {
195 $primary .= '.' . $m[1][0];
196 }
197 if ( $m[1][2] !== '0000' ) {
198 $tertiary .= '.' . $m[1][2];
199 }
200 }
201 }
202 $this->weights[$cp] = $primary;
203 if ( $tertiary === '.0008'
204 || $tertiary === '.000E'
205 ) {
206 $goodTertiaryChars[$cp] = true;
207 }
208 }
209 fclose( $file );
210
211 // Identify groups of characters with the same primary weight
212 $this->groups = [];
213 asort( $this->weights, SORT_STRING );
214 $prevWeight = reset( $this->weights );
215 $group = [];
216 foreach ( $this->weights as $cp => $weight ) {
217 if ( $weight !== $prevWeight ) {
218 $this->groups[$prevWeight] = $group;
219 $prevWeight = $weight;
220 $group = $this->groups[$weight] ?? [];
221 }
222 $group[] = $cp;
223 }
224 if ( $group ) {
225 $this->groups[$prevWeight] = $group;
226 }
227
228 // If one character has a given primary weight sequence, and a second
229 // character has a longer primary weight sequence with an initial
230 // portion equal to the first character, then remove the second
231 // character. This avoids having characters like U+A732 (double A)
232 // polluting the basic Latin sort area.
233
234 foreach ( $this->groups as $weight => $group ) {
235 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
236 if ( isset( $this->groups[$m[1]] ) ) {
237 unset( $this->groups[$weight] );
238 }
239 }
240 }
241
242 ksort( $this->groups, SORT_STRING );
243
244 // Identify the header character in each group
245 $headerChars = [];
246 $prevChar = "\000";
247 $tertiaryCollator = new Collator( 'root' );
248 $primaryCollator = new Collator( 'root' );
249 $primaryCollator->setStrength( Collator::PRIMARY );
250 $numOutOfOrder = 0;
251 foreach ( $this->groups as $weight => $group ) {
252 $uncomposedChars = [];
253 $goodChars = [];
254 foreach ( $group as $cp ) {
255 if ( isset( $goodTertiaryChars[$cp] ) ) {
256 $goodChars[] = $cp;
257 }
258 if ( !isset( $this->mappedChars[$cp] ) ) {
259 $uncomposedChars[] = $cp;
260 }
261 }
262 $x = array_intersect( $goodChars, $uncomposedChars );
263 if ( !$x ) {
264 $x = $uncomposedChars;
265 if ( !$x ) {
266 $x = $group;
267 }
268 }
269
270 // Use ICU to pick the lowest sorting character in the selection
271 $tertiaryCollator->sort( $x );
272 $cp = $x[0];
273
274 $char = UtfNormal\Utils::codepointToUtf8( $cp );
275 $headerChars[] = $char;
276 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
277 $numOutOfOrder++;
278 }
279 $prevChar = $char;
280
281 if ( $this->debugOutFile ) {
282 fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
283 implode( ' ', array_map( [ UtfNormal\Utils::class, 'codepointToUtf8' ], $group ) ) ) );
284 }
285 }
286
287 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
288
289 global $IP;
290 $writer = new StaticArrayWriter();
291 file_put_contents(
292 "$IP/includes/collation/data/first-letters-root.php",
293 $writer->create( $headerChars, 'File created by generateCollationData.php' )
294 );
295 echo "first-letters-root: file written.\n";
296 }
297}
298
300 public $fileName;
301 public $callback;
303 public $xml;
304 public $blocks = [];
306
307 public function __construct( $fileName ) {
308 $this->fileName = $fileName;
309 }
310
311 public function readChars( $callback ) {
312 $this->getBlocks();
313 $this->currentBlock = reset( $this->blocks );
314 $xml = $this->open();
315 $this->callback = $callback;
316
317 while ( $xml->name !== 'repertoire' && $xml->next() );
318
319 while ( $xml->read() ) {
320 if ( $xml->nodeType == XMLReader::ELEMENT ) {
321 if ( $xml->name === 'group' ) {
322 $this->groupAttrs = $this->readAttributes();
323 } elseif ( $xml->name === 'char' ) {
324 $this->handleChar();
325 }
326 } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
327 if ( $xml->name === 'group' ) {
328 $this->groupAttrs = [];
329 }
330 }
331 }
332 $xml->close();
333 }
334
335 protected function open() {
336 $this->xml = new XMLReader;
337 if ( !$this->xml->open( $this->fileName ) ) {
338 throw new RuntimeException( __METHOD__ . ": unable to open {$this->fileName}" );
339 }
340 while ( $this->xml->name !== 'ucd' && $this->xml->read() );
341 $this->xml->read();
342
343 return $this->xml;
344 }
345
351 protected function readAttributes() {
352 $attrs = [];
353 while ( $this->xml->moveToNextAttribute() ) {
354 $attrs[$this->xml->name] = $this->xml->value;
355 }
356
357 return $attrs;
358 }
359
360 protected function handleChar() {
361 $attrs = $this->readAttributes() + $this->groupAttrs;
362 if ( isset( $attrs['cp'] ) ) {
363 $first = $last = hexdec( $attrs['cp'] );
364 } else {
365 $first = hexdec( $attrs['first-cp'] );
366 $last = hexdec( $attrs['last-cp'] );
367 unset( $attrs['first-cp'] );
368 unset( $attrs['last-cp'] );
369 }
370
371 for ( $cp = $first; $cp <= $last; $cp++ ) {
372 $hexCp = sprintf( "%04X", $cp );
373 foreach ( [ 'na', 'na1' ] as $nameProp ) {
374 if ( isset( $attrs[$nameProp] ) ) {
375 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
376 }
377 }
378
379 while ( $this->currentBlock ) {
380 if ( $cp < $this->currentBlock[0] ) {
381 break;
382 } elseif ( $cp <= $this->currentBlock[1] ) {
383 $attrs['block'] = key( $this->blocks );
384 break;
385 } else {
386 $this->currentBlock = next( $this->blocks );
387 }
388 }
389
390 $attrs['cp'] = $hexCp;
391 call_user_func( $this->callback, $attrs );
392 }
393 }
394
395 public function getBlocks() {
396 if ( $this->blocks ) {
397 return $this->blocks;
398 }
399
400 $xml = $this->open();
401 while ( $xml->name !== 'blocks' && $xml->read() );
402
403 while ( $xml->read() ) {
404 if ( $xml->nodeType == XMLReader::ELEMENT ) {
405 if ( $xml->name === 'block' ) {
406 $attrs = $this->readAttributes();
407 $first = hexdec( $attrs['first-cp'] );
408 $last = hexdec( $attrs['last-cp'] );
409 $this->blocks[$attrs['name']] = [ $first, $last ];
410 }
411 }
412 }
413 $xml->close();
414
415 return $this->blocks;
416 }
417}
418
419$maintClass = GenerateCollationData::class;
420require_once RUN_MAINTENANCE_IF_MAIN;
if(!defined( 'MEDIAWIKI')) if(ini_get('mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:98
Generate first letter data files for Collation.php.
__construct()
Default constructor.
$weights
The primary weights, indexed by codepoint.
execute()
Do the actual work.
$dataDir
The directory with source data files in it.
$mappedChars
A hashtable keyed by codepoint, where presence indicates that a character has a decomposition mapping...
static isCjk( $codepoint)
Test if a code point is a CJK (Chinese, Japanese, Korean) character.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
readAttributes()
Read the attributes of the current element node and return them as an array.
Format a static PHP array to be written to a file.