3 * Maintenance script to generate first letter data files for Collation.php.
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.
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.
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
21 * @ingroup MaintenanceLanguage
24 require_once( __DIR__
. '/../Maintenance.php' );
27 * Generate first letter data files for Collation.php
29 * @ingroup MaintenanceLanguage
31 class GenerateCollationData
extends Maintenance
{
32 /** The directory with source data files in it */
35 /** The primary weights, indexed by codepoint */
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
48 * Important tertiary weights from UTS #10 section 7.2
50 const NORMAL_UPPERCASE
= 0x08;
51 const NORMAL_HIRAGANA
= 0X0E;
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',
58 $this->addOption( 'debug-output', 'Filename for sending debug output to',
62 public function execute() {
63 $this->dataDir
= $this->getOption( 'data-dir', '.' );
65 $allkeysPresent = file_exists( "{$this->dataDir}/allkeys.txt" );
66 $ucdallPresent = file_exists( "{$this->dataDir}/ucd.all.grouped.xml" );
68 // As of January 2013, these links work for all versions of Unicode
69 // between 5.1 and 6.2, inclusive.
70 $allkeysURL = "http://www.unicode.org/Public/UCA/<Unicode version>/allkeys.txt";
71 $ucdallURL = "http://www.unicode.org/Public/<Unicode version>/ucdxml/ucd.all.grouped.zip";
73 if ( !$allkeysPresent ||
!$ucdallPresent ) {
74 $icuVersion = IcuCollation
::getICUVersion();
75 $unicodeVersion = IcuCollation
::getUnicodeVersionForICU();
79 if ( !$allkeysPresent ) {
80 $error .= "Unable to find allkeys.txt. "
81 . "Download it and specify its location with --data-dir=<DIR>. "
84 if ( !$ucdallPresent ) {
85 $error .= "Unable to find ucd.all.grouped.xml. "
86 . "Download it, unzip, and specify its location with --data-dir=<DIR>. "
90 $versionKnown = false;
92 // Unknown version - either very old intl,
93 // or PHP < 5.3.7 which does not expose this information
94 $error .= "As MediaWiki could not determine the version of ICU library used by your PHP's "
95 . "intl extension it can't suggest which file version to download. "
96 . "This can be caused by running a very old version of intl or PHP < 5.3.7. "
97 . "If you are sure everything is all right, find out the ICU version "
98 . "by running phpinfo(), check what is the Unicode version it is using "
99 . "at http://site.icu-project.org/download, then try finding appropriate data file(s) at:";
100 } elseif ( version_compare( $icuVersion, "4.0", "<" ) ) {
102 $error .= "You are using outdated version of ICU ($icuVersion), intended for "
103 . ( $unicodeVersion ?
"Unicode $unicodeVersion" : "an unknown version of Unicode" )
104 . "; this file might not be avalaible for it, and it's not supported by MediaWiki. "
105 . " You are on your own; consider upgrading PHP's intl extension or try "
106 . "one of the files available at:";
107 } elseif ( version_compare( $icuVersion, "51.0", ">=" ) ) {
108 // Extra recent version
109 $error .= "You are using ICU $icuVersion, released after this script was last updated. "
110 . "Check what is the Unicode version it is using at http://site.icu-project.org/download . "
111 . "It can't be guaranteed everything will work, but appropriate file(s) should "
112 . "be available at:";
115 $versionKnown = true;
116 $error .= "You are using ICU $icuVersion, intended for "
117 . ( $unicodeVersion ?
"Unicode $unicodeVersion" : "an unknown version of Unicode" )
118 . ". Appropriate file(s) should be available at:";
122 if ( $versionKnown && $unicodeVersion ) {
123 $allkeysURL = str_replace( "<Unicode version>", "$unicodeVersion.0", $allkeysURL );
124 $ucdallURL = str_replace( "<Unicode version>", "$unicodeVersion.0", $ucdallURL );
127 if ( !$allkeysPresent ) {
128 $error .= "* $allkeysURL\n";
130 if ( !$ucdallPresent ) {
131 $error .= "* $ucdallURL\n";
134 $this->error( $error );
138 $debugOutFileName = $this->getOption( 'debug-output' );
139 if ( $debugOutFileName ) {
140 $this->debugOutFile
= fopen( $debugOutFileName, 'w' );
141 if ( !$this->debugOutFile
) {
142 $this->error( "Unable to open debug output file for writing" );
147 $this->generateFirstChars();
151 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
152 $uxr->readChars( array( $this, 'charCallback' ) );
155 function charCallback( $data ) {
156 // Skip non-printable characters,
157 // but do not skip a normal space (U+0020) since
158 // people like to use that as a fake no header symbol.
159 $category = substr( $data['gc'], 0, 1 );
160 if ( strpos( 'LNPS', $category ) === false
161 && $data['cp'] !== '0020' ) {
164 $cp = hexdec( $data['cp'] );
166 // Skip the CJK ideograph blocks, as an optimisation measure.
167 // UCA doesn't sort them properly anyway, without tailoring.
168 if ( IcuCollation
::isCjk( $cp ) ) {
172 // Skip the composed Hangul syllables, we will use the bare Jamo
174 if ( $data['block'] == 'Hangul Syllables' ) {
178 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
179 if ( $data['UIdeo'] === 'Y' ) {
180 if ( $data['block'] == 'CJK Unified Ideographs'
181 ||
$data['block'] == 'CJK Compatibility Ideographs' )
190 $a = $base +
( $cp >> 15 );
191 $b = ( $cp & 0x7fff ) |
0x8000;
193 $this->weights
[$cp] = sprintf( ".%04X.%04X", $a, $b );
195 if ( $data['dm'] !== '#' ) {
196 $this->mappedChars
[$cp] = true;
199 if ( $cp %
4096 == 0 ) {
200 print "{$data['cp']}\n";
204 function generateFirstChars() {
205 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
207 $this->error( "Unable to open allkeys.txt" );
211 $outFile = fopen( "$IP/serialized/first-letters-root.ser", 'w' );
213 $this->error( "Unable to open output file first-letters-root.ser" );
217 $goodTertiaryChars = array();
219 // For each character with an entry in allkeys.txt, overwrite the implicit
220 // entry in $this->weights that came from the UCD.
221 // Also gather a list of tertiary weights, for use in selecting the group header
222 while ( false !== ( $line = fgets( $file ) ) ) {
223 // We're only interested in single-character weights, pick them out with a regex
224 $line = trim( $line );
225 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
229 $cp = hexdec( $m[1] );
230 $allWeights = trim( $m[2] );
234 if ( !isset( $this->weights
[$cp] ) ) {
235 // Non-printable, ignore
238 foreach ( StringUtils
::explode( '[', $allWeights ) as $weightStr ) {
239 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
240 if ( !empty( $m[1] ) ) {
241 if ( $m[1][0] !== '0000' ) {
242 $primary .= '.' . $m[1][0];
244 if ( $m[1][2] !== '0000' ) {
245 $tertiary .= '.' . $m[1][2];
249 $this->weights
[$cp] = $primary;
250 if ( $tertiary === '.0008'
251 ||
$tertiary === '.000E' )
253 $goodTertiaryChars[$cp] = true;
258 // Identify groups of characters with the same primary weight
259 $this->groups
= array();
260 asort( $this->weights
, SORT_STRING
);
261 $prevWeight = reset( $this->weights
);
263 foreach ( $this->weights
as $cp => $weight ) {
264 if ( $weight !== $prevWeight ) {
265 $this->groups
[$prevWeight] = $group;
266 $prevWeight = $weight;
267 if ( isset( $this->groups
[$weight] ) ) {
268 $group = $this->groups
[$weight];
276 $this->groups
[$prevWeight] = $group;
279 // If one character has a given primary weight sequence, and a second
280 // character has a longer primary weight sequence with an initial
281 // portion equal to the first character, then remove the second
282 // character. This avoids having characters like U+A732 (double A)
283 // polluting the basic latin sort area.
285 foreach ( $this->groups
as $weight => $group ) {
286 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
287 if ( isset( $this->groups
[$m[1]] ) ) {
288 unset( $this->groups
[$weight] );
293 ksort( $this->groups
, SORT_STRING
);
295 // Identify the header character in each group
296 $headerChars = array();
298 $tertiaryCollator = new Collator( 'root' );
299 $primaryCollator = new Collator( 'root' );
300 $primaryCollator->setStrength( Collator
::PRIMARY
);
302 foreach ( $this->groups
as $weight => $group ) {
303 $uncomposedChars = array();
304 $goodChars = array();
305 foreach ( $group as $cp ) {
306 if ( isset( $goodTertiaryChars[$cp] ) ) {
309 if ( !isset( $this->mappedChars
[$cp] ) ) {
310 $uncomposedChars[] = $cp;
313 $x = array_intersect( $goodChars, $uncomposedChars );
315 $x = $uncomposedChars;
321 // Use ICU to pick the lowest sorting character in the selection
322 $tertiaryCollator->sort( $x );
325 $char = codepointToUtf8( $cp );
326 $headerChars[] = $char;
327 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
330 printf( "Out of order: U+%05X > U+%05X\n",
331 utf8ToCodepoint( $prevChar ),
332 utf8ToCodepoint( $char ) );
337 if ( $this->debugOutFile
) {
338 fwrite( $this->debugOutFile
, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
339 implode( ' ', array_map( 'codepointToUtf8', $group ) ) ) );
343 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
345 fwrite( $outFile, serialize( $headerChars ) );
354 public $blocks = array();
355 public $currentBlock;
357 function __construct( $fileName ) {
358 $this->fileName
= $fileName;
361 public function readChars( $callback ) {
363 $this->currentBlock
= reset( $this->blocks
);
364 $xml = $this->open();
365 $this->callback
= $callback;
367 while ( $xml->name
!== 'repertoire' && $xml->next() );
369 while ( $xml->read() ) {
370 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
371 if ( $xml->name
=== 'group' ) {
372 $this->groupAttrs
= $this->readAttributes();
373 } elseif ( $xml->name
=== 'char' ) {
376 } elseif ( $xml->nodeType
=== XMLReader
::END_ELEMENT
) {
377 if ( $xml->name
=== 'group' ) {
378 $this->groupAttrs
= array();
385 protected function open() {
386 $this->xml
= new XMLReader
;
387 $this->xml
->open( $this->fileName
);
389 throw new MWException( __METHOD__
. ": unable to open {$this->fileName}" );
391 while ( $this->xml
->name
!== 'ucd' && $this->xml
->read() );
397 * Read the attributes of the current element node and return them
401 protected function readAttributes() {
403 while ( $this->xml
->moveToNextAttribute() ) {
404 $attrs[$this->xml
->name
] = $this->xml
->value
;
409 protected function handleChar() {
410 $attrs = $this->readAttributes() +
$this->groupAttrs
;
411 if ( isset( $attrs['cp'] ) ) {
412 $first = $last = hexdec( $attrs['cp'] );
414 $first = hexdec( $attrs['first-cp'] );
415 $last = hexdec( $attrs['last-cp'] );
416 unset( $attrs['first-cp'] );
417 unset( $attrs['last-cp'] );
420 for ( $cp = $first; $cp <= $last; $cp++
) {
421 $hexCp = sprintf( "%04X", $cp );
422 foreach ( array( 'na', 'na1' ) as $nameProp ) {
423 if ( isset( $attrs[$nameProp] ) ) {
424 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
428 while ( $this->currentBlock
) {
429 if ( $cp < $this->currentBlock
[0] ) {
431 } elseif ( $cp <= $this->currentBlock
[1] ) {
432 $attrs['block'] = key( $this->blocks
);
435 $this->currentBlock
= next( $this->blocks
);
439 $attrs['cp'] = $hexCp;
440 call_user_func( $this->callback
, $attrs );
444 public function getBlocks() {
445 if ( $this->blocks
) {
446 return $this->blocks
;
449 $xml = $this->open();
450 while ( $xml->name
!== 'blocks' && $xml->read() );
452 while ( $xml->read() ) {
453 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
454 if ( $xml->name
=== 'block' ) {
455 $attrs = $this->readAttributes();
456 $first = hexdec( $attrs['first-cp'] );
457 $last = hexdec( $attrs['last-cp'] );
458 $this->blocks
[$attrs['name']] = array( $first, $last );
463 return $this->blocks
;
468 $maintClass = 'GenerateCollationData';
469 require_once( RUN_MAINTENANCE_IF_MAIN
);