Follow-up I0b781c11 (2a55449): use User::getAutomaticGroups().
[lhc/web/wiklou.git] / maintenance / language / generateCollationData.php
1 <?php
2 /**
3 * Maintenance script to generate first letter data files for Collation.php.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @ingroup Maintenance
21 * @file
22 */
23
24 require_once( dirname( __FILE__ ) .'/../Maintenance.php' );
25
26 /**
27 * Generate first letter data files for Collation.php
28 */
29 class GenerateCollationData extends Maintenance {
30 /** The directory with source data files in it */
31 var $dataDir;
32
33 /** The primary weights, indexed by codepoint */
34 var $weights;
35
36 /**
37 * A hashtable keyed by codepoint, where presence indicates that a character
38 * has a decomposition mapping. This makes it non-preferred for group header
39 * selection.
40 */
41 var $mappedChars;
42
43 var $debugOutFile;
44
45 /**
46 * Important tertiary weights from UTS #10 section 7.2
47 */
48 const NORMAL_UPPERCASE = 0x08;
49 const NORMAL_HIRAGANA = 0X0E;
50
51 public function __construct() {
52 parent::__construct();
53 $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
54 'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
55 false, true );
56 $this->addOption( 'debug-output', 'Filename for sending debug output to',
57 false, true );
58 }
59
60 public function execute() {
61 $this->dataDir = $this->getOption( 'data-dir', '.' );
62 if ( !file_exists( "{$this->dataDir}/allkeys.txt" ) ) {
63 $this->error( "Unable to find allkeys.txt. Please download it from " .
64 "http://www.unicode.org/Public/UCA/latest/allkeys.txt and specify " .
65 "its location with --data-dir=<DIR>" );
66 exit( 1 );
67 }
68 if ( !file_exists( "{$this->dataDir}/ucd.all.grouped.xml" ) ) {
69 $this->error( "Unable to find ucd.all.grouped.xml. Please download it " .
70 "from http://www.unicode.org/Public/6.0.0/ucdxml/ucd.all.grouped.zip " .
71 "and specify its location with --data-dir=<DIR>" );
72 exit( 1 );
73 }
74 $debugOutFileName = $this->getOption( 'debug-output' );
75 if ( $debugOutFileName ) {
76 $this->debugOutFile = fopen( $debugOutFileName, 'w' );
77 if ( !$this->debugOutFile ) {
78 $this->error( "Unable to open debug output file for writing" );
79 exit( 1 );
80 }
81 }
82 $this->loadUcd();
83 $this->generateFirstChars();
84 }
85
86 function loadUcd() {
87 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
88 $uxr->readChars( array( $this, 'charCallback' ) );
89 }
90
91 function charCallback( $data ) {
92 // Skip non-printable characters,
93 // but do not skip a normal space (U+0020) since
94 // people like to use that as a fake no header symbol.
95 $category = substr( $data['gc'], 0, 1 );
96 if ( strpos( 'LNPS', $category ) === false
97 && $data['cp'] !== '0020' ) {
98 return;
99 }
100 $cp = hexdec( $data['cp'] );
101
102 // Skip the CJK ideograph blocks, as an optimisation measure.
103 // UCA doesn't sort them properly anyway, without tailoring.
104 if ( IcuCollation::isCjk( $cp ) ) {
105 return;
106 }
107
108 // Skip the composed Hangul syllables, we will use the bare Jamo
109 // as first letters
110 if ( $data['block'] == 'Hangul Syllables' ) {
111 return;
112 }
113
114 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
115 if ( $data['UIdeo'] === 'Y' ) {
116 if ( $data['block'] == 'CJK Unified Ideographs'
117 || $data['block'] == 'CJK Compatibility Ideographs' )
118 {
119 $base = 0xFB40;
120 } else {
121 $base = 0xFB80;
122 }
123 } else {
124 $base = 0xFBC0;
125 }
126 $a = $base + ( $cp >> 15 );
127 $b = ( $cp & 0x7fff ) | 0x8000;
128
129 $this->weights[$cp] = sprintf( ".%04X.%04X", $a, $b );
130
131 if ( $data['dm'] !== '#' ) {
132 $this->mappedChars[$cp] = true;
133 }
134
135 if ( $cp % 4096 == 0 ) {
136 print "{$data['cp']}\n";
137 }
138 }
139
140 function generateFirstChars() {
141 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
142 if ( !$file ) {
143 $this->error( "Unable to open allkeys.txt" );
144 exit( 1 );
145 }
146 global $IP;
147 $outFile = fopen( "$IP/serialized/first-letters-root.ser", 'w' );
148 if ( !$outFile ) {
149 $this->error( "Unable to open output file first-letters-root.ser" );
150 exit( 1 );
151 }
152
153 $goodTertiaryChars = array();
154
155 // For each character with an entry in allkeys.txt, overwrite the implicit
156 // entry in $this->weights that came from the UCD.
157 // Also gather a list of tertiary weights, for use in selecting the group header
158 while ( false !== ( $line = fgets( $file ) ) ) {
159 // We're only interested in single-character weights, pick them out with a regex
160 $line = trim( $line );
161 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
162 continue;
163 }
164
165 $cp = hexdec( $m[1] );
166 $allWeights = trim( $m[2] );
167 $primary = '';
168 $tertiary = '';
169
170 if ( !isset( $this->weights[$cp] ) ) {
171 // Non-printable, ignore
172 continue;
173 }
174 foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
175 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
176 if ( !empty( $m[1] ) ) {
177 if ( $m[1][0] !== '0000' ) {
178 $primary .= '.' . $m[1][0];
179 }
180 if ( $m[1][2] !== '0000' ) {
181 $tertiary .= '.' . $m[1][2];
182 }
183 }
184 }
185 $this->weights[$cp] = $primary;
186 if ( $tertiary === '.0008'
187 || $tertiary === '.000E' )
188 {
189 $goodTertiaryChars[$cp] = true;
190 }
191 }
192 fclose( $file );
193
194 // Identify groups of characters with the same primary weight
195 $this->groups = array();
196 asort( $this->weights, SORT_STRING );
197 $prevWeight = reset( $this->weights );
198 $group = array();
199 foreach ( $this->weights as $cp => $weight ) {
200 if ( $weight !== $prevWeight ) {
201 $this->groups[$prevWeight] = $group;
202 $prevWeight = $weight;
203 if ( isset( $this->groups[$weight] ) ) {
204 $group = $this->groups[$weight];
205 } else {
206 $group = array();
207 }
208 }
209 $group[] = $cp;
210 }
211 if ( $group ) {
212 $this->groups[$prevWeight] = $group;
213 }
214
215 // If one character has a given primary weight sequence, and a second
216 // character has a longer primary weight sequence with an initial
217 // portion equal to the first character, then remove the second
218 // character. This avoids having characters like U+A732 (double A)
219 // polluting the basic latin sort area.
220
221 foreach ( $this->groups as $weight => $group ) {
222 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
223 if ( isset( $this->groups[$m[1]] ) ) {
224 unset( $this->groups[$weight] );
225 }
226 }
227 }
228
229 ksort( $this->groups, SORT_STRING );
230
231 // Identify the header character in each group
232 $headerChars = array();
233 $prevChar = "\000";
234 $tertiaryCollator = new Collator( 'root' );
235 $primaryCollator = new Collator( 'root' );
236 $primaryCollator->setStrength( Collator::PRIMARY );
237 $numOutOfOrder = 0;
238 foreach ( $this->groups as $weight => $group ) {
239 $uncomposedChars = array();
240 $goodChars = array();
241 foreach ( $group as $cp ) {
242 if ( isset( $goodTertiaryChars[$cp] ) ) {
243 $goodChars[] = $cp;
244 }
245 if ( !isset( $this->mappedChars[$cp] ) ) {
246 $uncomposedChars[] = $cp;
247 }
248 }
249 $x = array_intersect( $goodChars, $uncomposedChars );
250 if ( !$x ) {
251 $x = $uncomposedChars;
252 if ( !$x ) {
253 $x = $group;
254 }
255 }
256
257 // Use ICU to pick the lowest sorting character in the selection
258 $tertiaryCollator->sort( $x );
259 $cp = $x[0];
260
261 $char = codepointToUtf8( $cp );
262 $headerChars[] = $char;
263 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
264 $numOutOfOrder ++;
265 /*
266 printf( "Out of order: U+%05X > U+%05X\n",
267 utf8ToCodepoint( $prevChar ),
268 utf8ToCodepoint( $char ) );
269 */
270 }
271 $prevChar = $char;
272
273 if ( $this->debugOutFile ) {
274 fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
275 implode( ' ', array_map( 'codepointToUtf8', $group ) ) ) );
276 }
277 }
278
279 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
280
281 fwrite( $outFile, serialize( $headerChars ) );
282 }
283 }
284
285 class UcdXmlReader {
286 var $fileName;
287 var $callback;
288 var $groupAttrs;
289 var $xml;
290 var $blocks = array();
291 var $currentBlock;
292
293 function __construct( $fileName ) {
294 $this->fileName = $fileName;
295 }
296
297 public function readChars( $callback ) {
298 $this->getBlocks();
299 $this->currentBlock = reset( $this->blocks );
300 $xml = $this->open();
301 $this->callback = $callback;
302
303 while ( $xml->name !== 'repertoire' && $xml->next() );
304
305 while ( $xml->read() ) {
306 if ( $xml->nodeType == XMLReader::ELEMENT ) {
307 if ( $xml->name === 'group' ) {
308 $this->groupAttrs = $this->readAttributes();
309 } elseif ( $xml->name === 'char' ) {
310 $this->handleChar();
311 }
312 } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
313 if ( $xml->name === 'group' ) {
314 $this->groupAttrs = array();
315 }
316 }
317 }
318 $xml->close();
319 }
320
321 protected function open() {
322 $this->xml = new XMLReader;
323 $this->xml->open( $this->fileName );
324 if ( !$this->xml ) {
325 throw new MWException( __METHOD__.": unable to open {$this->fileName}" );
326 }
327 while ( $this->xml->name !== 'ucd' && $this->xml->read() );
328 $this->xml->read();
329 return $this->xml;
330 }
331
332 /**
333 * Read the attributes of the current element node and return them
334 * as an array
335 * @return array
336 */
337 protected function readAttributes() {
338 $attrs = array();
339 while ( $this->xml->moveToNextAttribute() ) {
340 $attrs[$this->xml->name] = $this->xml->value;
341 }
342 return $attrs;
343 }
344
345 protected function handleChar() {
346 $attrs = $this->readAttributes() + $this->groupAttrs;
347 if ( isset( $attrs['cp'] ) ) {
348 $first = $last = hexdec( $attrs['cp'] );
349 } else {
350 $first = hexdec( $attrs['first-cp'] );
351 $last = hexdec( $attrs['last-cp'] );
352 unset( $attrs['first-cp'] );
353 unset( $attrs['last-cp'] );
354 }
355
356 for ( $cp = $first; $cp <= $last; $cp++ ) {
357 $hexCp = sprintf( "%04X", $cp );
358 foreach ( array( 'na', 'na1' ) as $nameProp ) {
359 if ( isset( $attrs[$nameProp] ) ) {
360 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
361 }
362 }
363
364 while ( $this->currentBlock ) {
365 if ( $cp < $this->currentBlock[0] ) {
366 break;
367 } elseif ( $cp <= $this->currentBlock[1] ) {
368 $attrs['block'] = key( $this->blocks );
369 break;
370 } else {
371 $this->currentBlock = next( $this->blocks );
372 }
373 }
374
375 $attrs['cp'] = $hexCp;
376 call_user_func( $this->callback, $attrs );
377 }
378 }
379
380 public function getBlocks() {
381 if ( $this->blocks ) {
382 return $this->blocks;
383 }
384
385 $xml = $this->open();
386 while ( $xml->name !== 'blocks' && $xml->read() );
387
388 while ( $xml->read() ) {
389 if ( $xml->nodeType == XMLReader::ELEMENT ) {
390 if ( $xml->name === 'block' ) {
391 $attrs = $this->readAttributes();
392 $first = hexdec( $attrs['first-cp'] );
393 $last = hexdec( $attrs['last-cp'] );
394 $this->blocks[$attrs['name']] = array( $first, $last );
395 }
396 }
397 }
398 $xml->close();
399 return $this->blocks;
400 }
401
402 }
403
404 $maintClass = 'GenerateCollationData';
405 require_once( RUN_MAINTENANCE_IF_MAIN );