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