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