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';
26 use Wikimedia\StaticArrayWriter
;
29 * Generate first letter data files for Collation.php
31 * @ingroup MaintenanceLanguage
33 class GenerateCollationData
extends Maintenance
{
34 /** The directory with source data files in it */
37 /** The primary weights, indexed by codepoint */
41 * A hashtable keyed by codepoint, where presence indicates that a character
42 * has a decomposition mapping. This makes it non-preferred for group header
50 * Important tertiary weights from UTS #10 section 7.2
52 const NORMAL_UPPERCASE
= 0x08;
53 const NORMAL_HIRAGANA
= 0x0E;
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',
60 $this->addOption( 'debug-output', 'Filename for sending debug output to',
64 public function execute() {
65 $this->dataDir
= $this->getOption( 'data-dir', '.' );
67 $allkeysPresent = file_exists( "{$this->dataDir}/allkeys.txt" );
68 $ucdallPresent = file_exists( "{$this->dataDir}/ucd.all.grouped.xml" );
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";
75 if ( !$allkeysPresent ||
!$ucdallPresent ) {
76 $icuVersion = INTL_ICU_VERSION
;
77 $unicodeVersion = IcuCollation
::getUnicodeVersionForICU();
81 if ( !$allkeysPresent ) {
82 $error .= "Unable to find allkeys.txt. "
83 . "Download it and specify its location with --data-dir=<DIR>. "
86 if ( !$ucdallPresent ) {
87 $error .= "Unable to find ucd.all.grouped.xml. "
88 . "Download it, unzip, and specify its location with --data-dir=<DIR>. "
92 $versionKnown = false;
93 if ( version_compare( $icuVersion, "4.0", "<" ) ) {
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 avalaible 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:";
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:";
115 if ( $versionKnown && $unicodeVersion ) {
116 $allkeysURL = str_replace( "<Unicode version>", "$unicodeVersion.0", $allkeysURL );
117 $ucdallURL = str_replace( "<Unicode version>", "$unicodeVersion.0", $ucdallURL );
120 if ( !$allkeysPresent ) {
121 $error .= "* $allkeysURL\n";
123 if ( !$ucdallPresent ) {
124 $error .= "* $ucdallURL\n";
127 $this->fatalError( $error );
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" );
138 $this->generateFirstChars();
142 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
143 $uxr->readChars( [ $this, 'charCallback' ] );
146 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'
156 $cp = hexdec( $data['cp'] );
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 ) ) {
164 // Skip the composed Hangul syllables, we will use the bare Jamo
166 if ( $data['block'] == 'Hangul Syllables' ) {
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'
182 $a = $base +
( $cp >> 15 );
183 $b = ( $cp & 0x7fff ) |
0x8000;
185 $this->weights
[$cp] = sprintf( ".%04X.%04X", $a, $b );
187 if ( $data['dm'] !== '#' ) {
188 $this->mappedChars
[$cp] = true;
191 if ( $cp %
4096 == 0 ) {
192 print "{$data['cp']}\n";
196 function generateFirstChars() {
197 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
199 $this->fatalError( "Unable to open allkeys.txt" );
202 $goodTertiaryChars = [];
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 ) ) {
214 $cp = hexdec( $m[1] );
215 $allWeights = trim( $m[2] );
219 if ( !isset( $this->weights
[$cp] ) ) {
220 // Non-printable, ignore
223 foreach ( StringUtils
::explode( '[', $allWeights ) as $weightStr ) {
224 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
225 if ( !empty( $m[1] ) ) {
226 if ( $m[1][0] !== '0000' ) {
227 $primary .= '.' . $m[1][0];
229 if ( $m[1][2] !== '0000' ) {
230 $tertiary .= '.' . $m[1][2];
234 $this->weights
[$cp] = $primary;
235 if ( $tertiary === '.0008'
236 ||
$tertiary === '.000E'
238 $goodTertiaryChars[$cp] = true;
243 // Identify groups of characters with the same primary weight
245 asort( $this->weights
, SORT_STRING
);
246 $prevWeight = reset( $this->weights
);
248 foreach ( $this->weights
as $cp => $weight ) {
249 if ( $weight !== $prevWeight ) {
250 $this->groups
[$prevWeight] = $group;
251 $prevWeight = $weight;
252 $group = $this->groups
[$weight] ??
[];
257 $this->groups
[$prevWeight] = $group;
260 // If one character has a given primary weight sequence, and a second
261 // character has a longer primary weight sequence with an initial
262 // portion equal to the first character, then remove the second
263 // character. This avoids having characters like U+A732 (double A)
264 // polluting the basic Latin sort area.
266 foreach ( $this->groups
as $weight => $group ) {
267 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
268 if ( isset( $this->groups
[$m[1]] ) ) {
269 unset( $this->groups
[$weight] );
274 ksort( $this->groups
, SORT_STRING
);
276 // Identify the header character in each group
279 $tertiaryCollator = new Collator( 'root' );
280 $primaryCollator = new Collator( 'root' );
281 $primaryCollator->setStrength( Collator
::PRIMARY
);
283 foreach ( $this->groups
as $weight => $group ) {
284 $uncomposedChars = [];
286 foreach ( $group as $cp ) {
287 if ( isset( $goodTertiaryChars[$cp] ) ) {
290 if ( !isset( $this->mappedChars
[$cp] ) ) {
291 $uncomposedChars[] = $cp;
294 $x = array_intersect( $goodChars, $uncomposedChars );
296 $x = $uncomposedChars;
302 // Use ICU to pick the lowest sorting character in the selection
303 $tertiaryCollator->sort( $x );
306 $char = UtfNormal\Utils
::codepointToUtf8( $cp );
307 $headerChars[] = $char;
308 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
313 if ( $this->debugOutFile
) {
314 fwrite( $this->debugOutFile
, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
315 implode( ' ', array_map( 'UtfNormal\Utils::codepointToUtf8', $group ) ) ) );
319 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
322 $writer = new StaticArrayWriter();
324 "$IP/includes/collation/data/first-letters-root.php",
325 $writer->create( $headerChars, 'File created by generateCollationData.php' )
327 echo "first-letters-root: file written.\n";
337 public $currentBlock;
339 function __construct( $fileName ) {
340 $this->fileName
= $fileName;
343 public function readChars( $callback ) {
345 $this->currentBlock
= reset( $this->blocks
);
346 $xml = $this->open();
347 $this->callback
= $callback;
349 while ( $xml->name
!== 'repertoire' && $xml->next() );
351 while ( $xml->read() ) {
352 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
353 if ( $xml->name
=== 'group' ) {
354 $this->groupAttrs
= $this->readAttributes();
355 } elseif ( $xml->name
=== 'char' ) {
358 } elseif ( $xml->nodeType
=== XMLReader
::END_ELEMENT
) {
359 if ( $xml->name
=== 'group' ) {
360 $this->groupAttrs
= [];
367 protected function open() {
368 $this->xml
= new XMLReader
;
369 $this->xml
->open( $this->fileName
);
371 throw new MWException( __METHOD__
. ": unable to open {$this->fileName}" );
373 while ( $this->xml
->name
!== 'ucd' && $this->xml
->read() );
380 * Read the attributes of the current element node and return them
384 protected function readAttributes() {
386 while ( $this->xml
->moveToNextAttribute() ) {
387 $attrs[$this->xml
->name
] = $this->xml
->value
;
393 protected function handleChar() {
394 $attrs = $this->readAttributes() +
$this->groupAttrs
;
395 if ( isset( $attrs['cp'] ) ) {
396 $first = $last = hexdec( $attrs['cp'] );
398 $first = hexdec( $attrs['first-cp'] );
399 $last = hexdec( $attrs['last-cp'] );
400 unset( $attrs['first-cp'] );
401 unset( $attrs['last-cp'] );
404 for ( $cp = $first; $cp <= $last; $cp++
) {
405 $hexCp = sprintf( "%04X", $cp );
406 foreach ( [ 'na', 'na1' ] as $nameProp ) {
407 if ( isset( $attrs[$nameProp] ) ) {
408 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
412 while ( $this->currentBlock
) {
413 if ( $cp < $this->currentBlock
[0] ) {
415 } elseif ( $cp <= $this->currentBlock
[1] ) {
416 $attrs['block'] = key( $this->blocks
);
419 $this->currentBlock
= next( $this->blocks
);
423 $attrs['cp'] = $hexCp;
424 call_user_func( $this->callback
, $attrs );
428 public function getBlocks() {
429 if ( $this->blocks
) {
430 return $this->blocks
;
433 $xml = $this->open();
434 while ( $xml->name
!== 'blocks' && $xml->read() );
436 while ( $xml->read() ) {
437 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
438 if ( $xml->name
=== 'block' ) {
439 $attrs = $this->readAttributes();
440 $first = hexdec( $attrs['first-cp'] );
441 $last = hexdec( $attrs['last-cp'] );
442 $this->blocks
[$attrs['name']] = [ $first, $last ];
448 return $this->blocks
;
452 $maintClass = GenerateCollationData
::class;
453 require_once RUN_MAINTENANCE_IF_MAIN
;