generate-entity-file.php 2.2KB

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