generateCollationData.php 14 KB

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