]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - maintenance/language/generateCollationData.php
MediaWiki 1.17.0
[autoinstalls/mediawiki.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                 $category = substr( $data['gc'], 0, 1 );
73                 if ( strpos( 'LNPS', $category ) === false ) {
74                         return;
75                 }
76                 $cp = hexdec( $data['cp'] );
77
78                 // Skip the CJK ideograph blocks, as an optimisation measure.
79                 // UCA doesn't sort them properly anyway, without tailoring.
80                 if ( IcuCollation::isCjk( $cp ) ) {
81                         return;
82                 }
83
84                 // Skip the composed Hangul syllables, we will use the bare Jamo 
85                 // as first letters
86                 if ( $data['block'] == 'Hangul Syllables' ) {
87                         return;
88                 }
89
90                 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
91                 if ( $data['UIdeo'] === 'Y' ) {
92                         if ( $data['block'] == 'CJK Unified Ideographs'
93                                 || $data['block'] == 'CJK Compatibility Ideographs' )
94                         {
95                                 $base = 0xFB40;
96                         } else {
97                                 $base = 0xFB80;
98                         }
99                 } else {
100                         $base = 0xFBC0;
101                 }
102                 $a = $base + ( $cp >> 15 );
103                 $b = ( $cp & 0x7fff ) | 0x8000;
104
105                 $this->weights[$cp] = sprintf( ".%04X.%04X", $a, $b );
106
107                 if ( $data['dm'] !== '#' ) {
108                         $this->mappedChars[$cp] = true;
109                 }
110
111                 if ( $cp % 4096 == 0 ) {
112                         print "{$data['cp']}\n";
113                 }
114         }
115
116         function generateFirstChars() {
117                 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
118                 if ( !$file ) {
119                         $this->error( "Unable to open allkeys.txt" );
120                         exit( 1 );
121                 }
122                 global $IP;
123                 $outFile = fopen( "$IP/serialized/first-letters-root.ser", 'w' );
124                 if ( !$outFile ) {
125                         $this->error( "Unable to open output file first-letters-root.ser" );
126                         exit( 1 );
127                 }
128
129                 $goodTertiaryChars = array();
130
131                 // For each character with an entry in allkeys.txt, overwrite the implicit
132                 // entry in $this->weights that came from the UCD.
133                 // Also gather a list of tertiary weights, for use in selecting the group header
134                 while ( false !== ( $line = fgets( $file ) ) ) {
135                         // We're only interested in single-character weights, pick them out with a regex
136                         $line = trim( $line );
137                         if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
138                                 continue;
139                         }
140
141                         $cp = hexdec( $m[1] );
142                         $allWeights = trim( $m[2] );
143                         $primary = '';
144                         $tertiary = '';
145
146                         if ( !isset( $this->weights[$cp] ) ) {
147                                 // Non-printable, ignore
148                                 continue;
149                         }
150                         foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
151                                 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
152                                 if ( !empty( $m[1] ) ) {
153                                         if ( $m[1][0] !== '0000' ) {
154                                                 $primary .= '.' . $m[1][0];
155                                         }
156                                         if ( $m[1][2] !== '0000' ) {
157                                                 $tertiary .= '.' . $m[1][2];
158                                         }
159                                 }
160                         }
161                         $this->weights[$cp] = $primary;
162                         if ( $tertiary === '.0008'
163                                 || $tertiary === '.000E' ) 
164                         {
165                                 $goodTertiaryChars[$cp] = true;
166                         }
167                 }
168                 fclose( $file );
169
170                 // Identify groups of characters with the same primary weight
171                 $this->groups = array();
172                 asort( $this->weights, SORT_STRING );
173                 $prevWeight = reset( $this->weights );
174                 $group = array();
175                 foreach ( $this->weights as $cp => $weight ) {
176                         if ( $weight !== $prevWeight ) {
177                                 $this->groups[$prevWeight] = $group;
178                                 $prevWeight = $weight;
179                                 if ( isset( $this->groups[$weight] ) ) {
180                                         $group = $this->groups[$weight];
181                                 } else {
182                                         $group = array();
183                                 }
184                         }
185                         $group[] = $cp;
186                 }
187                 if ( $group ) {
188                         $this->groups[$prevWeight] = $group;
189                 }
190
191                 // If one character has a given primary weight sequence, and a second
192                 // character has a longer primary weight sequence with an initial 
193                 // portion equal to the first character, then remove the second 
194                 // character. This avoids having characters like U+A732 (double A)
195                 // polluting the basic latin sort area.
196                 $prevWeights = array();
197                 foreach ( $this->groups as $weight => $group ) {
198                         if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
199                                 if ( isset( $this->groups[$m[1]] ) ) {
200                                         unset( $this->groups[$weight] );
201                                 }
202                         }
203                 }
204
205                 ksort( $this->groups, SORT_STRING );
206
207                 // Identify the header character in each group
208                 $headerChars = array();
209                 $prevChar = "\000";
210                 $tertiaryCollator = new Collator( 'root' );
211                 $primaryCollator = new Collator( 'root' );
212                 $primaryCollator->setStrength( Collator::PRIMARY );
213                 $numOutOfOrder = 0;
214                 foreach ( $this->groups as $weight => $group ) {
215                         $uncomposedChars = array();
216                         $goodChars = array();
217                         foreach ( $group as $cp ) {
218                                 if ( isset( $goodTertiaryChars[$cp] ) ) {
219                                         $goodChars[] = $cp;
220                                 }
221                                 if ( !isset( $this->mappedChars[$cp] ) ) {
222                                         $uncomposedChars[] = $cp;
223                                 }
224                         }
225                         $x = array_intersect( $goodChars, $uncomposedChars );
226                         if ( !$x ) {
227                                 $x = $uncomposedChars;
228                                 if ( !$x ) {
229                                         $x = $group;
230                                 }
231                         }
232
233                         // Use ICU to pick the lowest sorting character in the selection
234                         $tertiaryCollator->sort( $x );
235                         $cp = $x[0];
236
237                         $char = codepointToUtf8( $cp );
238                         $headerChars[] = $char;
239                         if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
240                                 $numOutOfOrder ++;
241                                 /*
242                                 printf( "Out of order: U+%05X > U+%05X\n",
243                                         utf8ToCodepoint( $prevChar ),
244                                         utf8ToCodepoint( $char ) );
245                                  */
246                         }
247                         $prevChar = $char;
248
249                         if ( $this->debugOutFile ) {
250                                 fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
251                                         implode( ' ', array_map( 'codepointToUtf8', $group ) ) ) );
252                         }
253                 }
254
255                 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
256
257                 fwrite( $outFile, serialize( $headerChars ) );
258         }
259 }
260
261 class UcdXmlReader {
262         var $fileName;
263         var $callback;
264         var $groupAttrs;
265         var $xml;
266         var $blocks = array();
267         var $currentBlock;
268
269         function __construct( $fileName ) {
270                 $this->fileName = $fileName;
271         }
272
273         public function readChars( $callback ) {
274                 $this->getBlocks();
275                 $this->currentBlock = reset( $this->blocks );
276                 $xml = $this->open();
277                 $this->callback = $callback;
278
279                 while ( $xml->name !== 'repertoire' && $xml->next() );
280
281                 while ( $xml->read() ) {
282                         if ( $xml->nodeType == XMLReader::ELEMENT ) {
283                                 if ( $xml->name === 'group' ) {
284                                         $this->groupAttrs = $this->readAttributes();
285                                 } elseif ( $xml->name === 'char' ) {
286                                         $this->handleChar();
287                                 }
288                         } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
289                                 if ( $xml->name === 'group' ) {
290                                         $this->groupAttrs = array();
291                                 }
292                         }
293                 }
294                 $xml->close();
295         }
296
297         protected function open() {
298                 $this->xml = new XMLReader;
299                 $this->xml->open( $this->fileName );
300                 if ( !$this->xml ) {
301                         throw new MWException( __METHOD__.": unable to open {$this->fileName}" );
302                 }
303                 while ( $this->xml->name !== 'ucd' && $this->xml->read() );
304                 $this->xml->read();
305                 return $this->xml;
306         }       
307
308         /**
309          * Read the attributes of the current element node and return them 
310          * as an array
311          */
312         protected function readAttributes() {
313                 $attrs = array();
314                 while ( $this->xml->moveToNextAttribute() ) {
315                         $attrs[$this->xml->name] = $this->xml->value;
316                 }
317                 return $attrs;
318         }
319
320         protected function handleChar() {
321                 $attrs = $this->readAttributes() + $this->groupAttrs;
322                 if ( isset( $attrs['cp'] ) ) {
323                         $first = $last = hexdec( $attrs['cp'] );
324                 } else {
325                         $first = hexdec( $attrs['first-cp'] );
326                         $last = hexdec( $attrs['last-cp'] );
327                         unset( $attrs['first-cp'] );
328                         unset( $attrs['last-cp'] );
329                 }
330
331                 for ( $cp = $first; $cp <= $last; $cp++ ) {
332                         $hexCp = sprintf( "%04X", $cp );
333                         foreach ( array( 'na', 'na1' ) as $nameProp ) {
334                                 if ( isset( $attrs[$nameProp] ) ) {
335                                         $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
336                                 }
337                         }
338
339                         while ( $this->currentBlock ) {
340                                 if ( $cp < $this->currentBlock[0] ) {
341                                         break;
342                                 } elseif ( $cp <= $this->currentBlock[1] ) {
343                                         $attrs['block'] = key( $this->blocks );
344                                         break;
345                                 } else {
346                                         $this->currentBlock = next( $this->blocks );
347                                 }
348                         }
349
350                         $attrs['cp'] = $hexCp;
351                         call_user_func( $this->callback, $attrs );
352                 }
353         }
354
355         public function getBlocks() {
356                 if ( $this->blocks ) {
357                         return $this->blocks;
358                 }
359
360                 $xml = $this->open();
361                 while ( $xml->name !== 'blocks' && $xml->read() );
362
363                 while ( $xml->read() ) {
364                         if ( $xml->nodeType == XMLReader::ELEMENT ) {
365                                 if ( $xml->name === 'block' ) {
366                                         $attrs = $this->readAttributes();
367                                         $first = hexdec( $attrs['first-cp'] );
368                                         $last = hexdec( $attrs['last-cp'] );
369                                         $this->blocks[$attrs['name']] = array( $first, $last );
370                                 }
371                         }
372                 }
373                 $xml->close();
374                 return $this->blocks;
375         }
376
377 }
378
379 $maintClass = 'GenerateCollationData';
380 require_once( DO_MAINTENANCE );
381