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