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