MediaWiki  1.32.0
generateCollationData.php
Go to the documentation of this file.
1 <?php
24 require_once __DIR__ . '/../Maintenance.php';
25 
33  public $dataDir;
34 
36  public $weights;
37 
43  public $mappedChars;
44 
45  public $debugOutFile;
46 
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 
200  $goodTertiaryChars = [];
201 
202  // For each character with an entry in allkeys.txt, overwrite the implicit
203  // entry in $this->weights that came from the UCD.
204  // Also gather a list of tertiary weights, for use in selecting the group header
205  while ( false !== ( $line = fgets( $file ) ) ) {
206  // We're only interested in single-character weights, pick them out with a regex
207  $line = trim( $line );
208  if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
209  continue;
210  }
211 
212  $cp = hexdec( $m[1] );
213  $allWeights = trim( $m[2] );
214  $primary = '';
215  $tertiary = '';
216 
217  if ( !isset( $this->weights[$cp] ) ) {
218  // Non-printable, ignore
219  continue;
220  }
221  foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
222  preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
223  if ( !empty( $m[1] ) ) {
224  if ( $m[1][0] !== '0000' ) {
225  $primary .= '.' . $m[1][0];
226  }
227  if ( $m[1][2] !== '0000' ) {
228  $tertiary .= '.' . $m[1][2];
229  }
230  }
231  }
232  $this->weights[$cp] = $primary;
233  if ( $tertiary === '.0008'
234  || $tertiary === '.000E'
235  ) {
236  $goodTertiaryChars[$cp] = true;
237  }
238  }
239  fclose( $file );
240 
241  // Identify groups of characters with the same primary weight
242  $this->groups = [];
243  asort( $this->weights, SORT_STRING );
244  $prevWeight = reset( $this->weights );
245  $group = [];
246  foreach ( $this->weights as $cp => $weight ) {
247  if ( $weight !== $prevWeight ) {
248  $this->groups[$prevWeight] = $group;
249  $prevWeight = $weight;
250  if ( isset( $this->groups[$weight] ) ) {
251  $group = $this->groups[$weight];
252  } else {
253  $group = [];
254  }
255  }
256  $group[] = $cp;
257  }
258  if ( $group ) {
259  $this->groups[$prevWeight] = $group;
260  }
261 
262  // If one character has a given primary weight sequence, and a second
263  // character has a longer primary weight sequence with an initial
264  // portion equal to the first character, then remove the second
265  // character. This avoids having characters like U+A732 (double A)
266  // polluting the basic Latin sort area.
267 
268  foreach ( $this->groups as $weight => $group ) {
269  if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
270  if ( isset( $this->groups[$m[1]] ) ) {
271  unset( $this->groups[$weight] );
272  }
273  }
274  }
275 
276  ksort( $this->groups, SORT_STRING );
277 
278  // Identify the header character in each group
279  $headerChars = [];
280  $prevChar = "\000";
281  $tertiaryCollator = new Collator( 'root' );
282  $primaryCollator = new Collator( 'root' );
283  $primaryCollator->setStrength( Collator::PRIMARY );
284  $numOutOfOrder = 0;
285  foreach ( $this->groups as $weight => $group ) {
286  $uncomposedChars = [];
287  $goodChars = [];
288  foreach ( $group as $cp ) {
289  if ( isset( $goodTertiaryChars[$cp] ) ) {
290  $goodChars[] = $cp;
291  }
292  if ( !isset( $this->mappedChars[$cp] ) ) {
293  $uncomposedChars[] = $cp;
294  }
295  }
296  $x = array_intersect( $goodChars, $uncomposedChars );
297  if ( !$x ) {
298  $x = $uncomposedChars;
299  if ( !$x ) {
300  $x = $group;
301  }
302  }
303 
304  // Use ICU to pick the lowest sorting character in the selection
305  $tertiaryCollator->sort( $x );
306  $cp = $x[0];
307 
308  $char = UtfNormal\Utils::codepointToUtf8( $cp );
309  $headerChars[] = $char;
310  if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
311  $numOutOfOrder++;
312  }
313  $prevChar = $char;
314 
315  if ( $this->debugOutFile ) {
316  fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
317  implode( ' ', array_map( 'UtfNormal\Utils::codepointToUtf8', $group ) ) ) );
318  }
319  }
320 
321  print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
322 
323  global $IP;
324  $writer = new StaticArrayWriter();
325  file_put_contents(
326  "$IP/includes/collation/data/first-letters-root.php",
327  $writer->create( $headerChars, 'File created by generateCollationData.php' )
328  );
329  echo "first-letters-root: file written.\n";
330  }
331 }
332 
334  public $fileName;
335  public $callback;
336  public $groupAttrs;
337  public $xml;
338  public $blocks = [];
340 
341  function __construct( $fileName ) {
342  $this->fileName = $fileName;
343  }
344 
345  public function readChars( $callback ) {
346  $this->getBlocks();
347  $this->currentBlock = reset( $this->blocks );
348  $xml = $this->open();
349  $this->callback = $callback;
350 
351  while ( $xml->name !== 'repertoire' && $xml->next() );
352 
353  while ( $xml->read() ) {
354  if ( $xml->nodeType == XMLReader::ELEMENT ) {
355  if ( $xml->name === 'group' ) {
356  $this->groupAttrs = $this->readAttributes();
357  } elseif ( $xml->name === 'char' ) {
358  $this->handleChar();
359  }
360  } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
361  if ( $xml->name === 'group' ) {
362  $this->groupAttrs = [];
363  }
364  }
365  }
366  $xml->close();
367  }
368 
369  protected function open() {
370  $this->xml = new XMLReader;
371  $this->xml->open( $this->fileName );
372  if ( !$this->xml ) {
373  throw new MWException( __METHOD__ . ": unable to open {$this->fileName}" );
374  }
375  while ( $this->xml->name !== 'ucd' && $this->xml->read() );
376  $this->xml->read();
377 
378  return $this->xml;
379  }
380 
386  protected function readAttributes() {
387  $attrs = [];
388  while ( $this->xml->moveToNextAttribute() ) {
389  $attrs[$this->xml->name] = $this->xml->value;
390  }
391 
392  return $attrs;
393  }
394 
395  protected function handleChar() {
396  $attrs = $this->readAttributes() + $this->groupAttrs;
397  if ( isset( $attrs['cp'] ) ) {
398  $first = $last = hexdec( $attrs['cp'] );
399  } else {
400  $first = hexdec( $attrs['first-cp'] );
401  $last = hexdec( $attrs['last-cp'] );
402  unset( $attrs['first-cp'] );
403  unset( $attrs['last-cp'] );
404  }
405 
406  for ( $cp = $first; $cp <= $last; $cp++ ) {
407  $hexCp = sprintf( "%04X", $cp );
408  foreach ( [ 'na', 'na1' ] as $nameProp ) {
409  if ( isset( $attrs[$nameProp] ) ) {
410  $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
411  }
412  }
413 
414  while ( $this->currentBlock ) {
415  if ( $cp < $this->currentBlock[0] ) {
416  break;
417  } elseif ( $cp <= $this->currentBlock[1] ) {
418  $attrs['block'] = key( $this->blocks );
419  break;
420  } else {
421  $this->currentBlock = next( $this->blocks );
422  }
423  }
424 
425  $attrs['cp'] = $hexCp;
426  call_user_func( $this->callback, $attrs );
427  }
428  }
429 
430  public function getBlocks() {
431  if ( $this->blocks ) {
432  return $this->blocks;
433  }
434 
435  $xml = $this->open();
436  while ( $xml->name !== 'blocks' && $xml->read() );
437 
438  while ( $xml->read() ) {
439  if ( $xml->nodeType == XMLReader::ELEMENT ) {
440  if ( $xml->name === 'block' ) {
441  $attrs = $this->readAttributes();
442  $first = hexdec( $attrs['first-cp'] );
443  $last = hexdec( $attrs['last-cp'] );
444  $this->blocks[$attrs['name']] = [ $first, $last ];
445  }
446  }
447  }
448  $xml->close();
449 
450  return $this->blocks;
451  }
452 }
453 
455 require_once RUN_MAINTENANCE_IF_MAIN;
GenerateCollationData\generateFirstChars
generateFirstChars()
Definition: generateCollationData.php:194
UcdXmlReader\$groupAttrs
$groupAttrs
Definition: generateCollationData.php:336
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:465
UcdXmlReader\$xml
$xml
Definition: generateCollationData.php:337
captcha-old.count
count
Definition: captcha-old.py:249
$last
$last
Definition: profileinfo.php:419
$maintClass
$maintClass
Definition: generateCollationData.php:454
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
UcdXmlReader\readAttributes
readAttributes()
Read the attributes of the current element node and return them as an array.
Definition: generateCollationData.php:386
$base
$base
Definition: generateLocalAutoload.php:11
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
MWException
MediaWiki exception.
Definition: MWException.php:26
UcdXmlReader\getBlocks
getBlocks()
Definition: generateCollationData.php:430
UcdXmlReader\$fileName
$fileName
Definition: generateCollationData.php:334
UcdXmlReader\$callback
$callback
Definition: generateCollationData.php:335
UcdXmlReader\$blocks
$blocks
Definition: generateCollationData.php:338
StringUtils\explode
static explode( $separator, $subject)
Workalike for explode() with limited memory usage.
Definition: StringUtils.php:336
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:236
$IP
$IP
Definition: update.php:3
IcuCollation\isCjk
static isCjk( $codepoint)
Test if a code point is a CJK (Chinese, Japanese, Korean) character.
Definition: IcuCollation.php:521
UcdXmlReader\$currentBlock
$currentBlock
Definition: generateCollationData.php:339
UcdXmlReader\__construct
__construct( $fileName)
Definition: generateCollationData.php:341
GenerateCollationData\$dataDir
$dataDir
The directory with source data files in it.
Definition: generateCollationData.php:33
UcdXmlReader\handleChar
handleChar()
Definition: generateCollationData.php:395
GenerateCollationData\$debugOutFile
$debugOutFile
Definition: generateCollationData.php:45
key
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message key
Definition: hooks.txt:2205
$line
$line
Definition: cdb.php:59
GenerateCollationData\execute
execute()
Do the actual work.
Definition: generateCollationData.php:62
groups
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing groups(accessed through $special->getFilterGroup)
UcdXmlReader\readChars
readChars( $callback)
Definition: generateCollationData.php:345
IcuCollation\getUnicodeVersionForICU
static getUnicodeVersionForICU()
Return the version of Unicode appropriate for the version of ICU library currently in use,...
Definition: IcuCollation.php:554
GenerateCollationData\$mappedChars
$mappedChars
A hashtable keyed by codepoint, where presence indicates that a character has a decomposition mapping...
Definition: generateCollationData.php:43
GenerateCollationData\$weights
$weights
The primary weights, indexed by codepoint.
Definition: generateCollationData.php:36
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:271
UcdXmlReader\open
open()
Definition: generateCollationData.php:369
GenerateCollationData\charCallback
charCallback( $data)
Definition: generateCollationData.php:144
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
GenerateCollationData\NORMAL_HIRAGANA
const NORMAL_HIRAGANA
Definition: generateCollationData.php:51
GenerateCollationData\loadUcd
loadUcd()
Definition: generateCollationData.php:139
GenerateCollationData\NORMAL_UPPERCASE
const NORMAL_UPPERCASE
Important tertiary weights from UTS #10 section 7.2.
Definition: generateCollationData.php:50
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
GenerateCollationData\__construct
__construct()
Default constructor.
Definition: generateCollationData.php:53
UcdXmlReader
Definition: generateCollationData.php:333
GenerateCollationData
Generate first letter data files for Collation.php.
Definition: generateCollationData.php:31