ppub.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. class Asset {
  3. public $path = "";
  4. public $mimetype = "";
  5. public $start_location = 0;
  6. public $end_location = 0;
  7. public $flags = array();
  8. public function __construct($path, $mimetype, $slocation, $elocation, $flags) {
  9. $this->path = $path;
  10. $this->mimetype = $mimetype;
  11. $this->start_location = $slocation;
  12. $this->end_location = $elocation;
  13. $this->flags = $flags;
  14. }
  15. }
  16. class Ppub {
  17. public $metadata = array();
  18. public $asset_index = array();
  19. public $asset_list = array();
  20. public $default_asset = null;
  21. private $handle = null;
  22. private $blob_start = 0;
  23. public function read_file($file_path) {
  24. $handle = fopen($file_path, "rb");
  25. if(fread($handle, 5) != "ppub\n"){
  26. throw new Exception("File did not start with magic number", 1);
  27. }
  28. $head_size_string = "";
  29. $next_char = '';
  30. while($next_char != "\n"){
  31. $head_size_string .= $next_char;
  32. $next_char = fread($handle, 1);
  33. }
  34. $index_length = intval($head_size_string);
  35. $index_data = fread($handle, $index_length);
  36. $this->handle = $handle;
  37. $this->blob_start = strlen($head_size_string) + $index_length + 6;
  38. $this->build_asset_list($index_data);
  39. $this->build_metadata($this->read_asset($this->asset_list[0]));
  40. }
  41. public function read_asset($asset) {
  42. $start_location = $asset->start_location + $this->blob_start;
  43. $length = $asset->end_location - $asset->start_location;
  44. fseek($this->handle, $start_location);
  45. $data = fread($this->handle, $length);
  46. if(in_array("gzip", $asset->flags)) {
  47. $data = gzdecode($data);
  48. }
  49. return $data;
  50. }
  51. private function build_asset_list($data) {
  52. $asset_list = array();
  53. $lines = explode("\n", $data);
  54. for ($i=0; $i < sizeof($lines); $i++) {
  55. if(trim($lines[$i]) == ''){
  56. continue;
  57. }
  58. $keyval = explode(": ", $lines[$i], 2);
  59. $vals = explode(" ", $keyval[1]);
  60. $asset = new Asset($keyval[0], $vals[0], intval($vals[1]), intval($vals[2]), array_slice($vals, 3));
  61. array_push($asset_list, $asset);
  62. $this->asset_index[$asset->path] = $asset;
  63. }
  64. $this->asset_list = $asset_list;
  65. }
  66. private function build_metadata($data) {
  67. $data_list = array();
  68. $lines = explode("\n", $data);
  69. for ($i=0; $i < sizeof($lines); $i++) {
  70. if(trim($lines[$i]) == ''){
  71. continue;
  72. }
  73. $keyval = explode(": ", $lines[$i], 2);
  74. $data_list[$keyval[0]] = $keyval[1];
  75. }
  76. $this->metadata = $data_list;
  77. }
  78. }
  79. ?>