Fix newline issues in tests.
[htmlpurifier/darkodev.git] / maintenance / generate-entity-file.php
blob81872887fb993f4e50aa40e4d4e2172a793e005e
1 #!/usr/bin/php
2 <?php
4 chdir(dirname(__FILE__));
5 require_once 'common.php';
6 assertCli();
8 /**
9 * @file
10 * Parses *.ent files into an entity lookup table, and then serializes and
11 * writes the whole kaboodle to a file. The resulting file is cached so
12 * that this script does not need to be run. This script should rarely,
13 * if ever, be run, since HTML's entities are fairly immutable.
16 // here's where the entity files are located, assuming working directory
17 // is the same as the location of this PHP file. Needs trailing slash.
18 $entity_dir = '../docs/entities/';
20 // defines the output file for the serialized content.
21 $output_file = '../library/HTMLPurifier/EntityLookup/entities.ser';
23 // courtesy of a PHP manual comment
24 function unichr($dec) {
25 if ($dec < 128) {
26 $utf = chr($dec);
27 } else if ($dec < 2048) {
28 $utf = chr(192 + (($dec - ($dec % 64)) / 64));
29 $utf .= chr(128 + ($dec % 64));
30 } else {
31 $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
32 $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
33 $utf .= chr(128 + ($dec % 64));
35 return $utf;
38 if ( !is_dir($entity_dir) ) exit("Fatal Error: Can't find entity directory.\n");
39 if ( file_exists($output_file) ) exit("Fatal Error: entity-lookup.txt already exists.\n");
41 $dh = @opendir($entity_dir);
42 if ( !$dh ) exit("Fatal Error: Cannot read entity directory.\n");
44 $entity_files = array();
45 while (($file = readdir($dh)) !== false) {
46 if (@$file[0] === '.') continue;
47 if (substr(strrchr($file, "."), 1) !== 'ent') continue;
48 $entity_files[] = $file;
50 closedir($dh);
52 if ( !$entity_files ) exit("Fatal Error: No entity files to parse.\n");
54 $entity_table = array();
55 $regexp = '/<!ENTITY\s+([A-Za-z]+)\s+"&#(?:38;#)?([0-9]+);">/';
57 foreach ( $entity_files as $file ) {
58 $contents = file_get_contents($entity_dir . $file);
59 $matches = array();
60 preg_match_all($regexp, $contents, $matches, PREG_SET_ORDER);
61 foreach ($matches as $match) {
62 $entity_table[$match[1]] = unichr($match[2]);
66 $output = serialize($entity_table);
68 $fh = fopen($output_file, 'w');
69 fwrite($fh, $output);
70 fclose($fh);
72 echo "Completed successfully.";