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