pdf_parser.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. <?php
  2. //
  3. // FPDI - Version 1.2
  4. //
  5. // Copyright 2004-2007 Setasign - Jan Slabon
  6. //
  7. // Licensed under the Apache License, Version 2.0 (the "License");
  8. // you may not use this file except in compliance with the License.
  9. // You may obtain a copy of the License at
  10. //
  11. // http://www.apache.org/licenses/LICENSE-2.0
  12. //
  13. // Unless required by applicable law or agreed to in writing, software
  14. // distributed under the License is distributed on an "AS IS" BASIS,
  15. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. // See the License for the specific language governing permissions and
  17. // limitations under the License.
  18. //
  19. if (!defined ('PDF_TYPE_NULL'))
  20. define ('PDF_TYPE_NULL', 0);
  21. if (!defined ('PDF_TYPE_NUMERIC'))
  22. define ('PDF_TYPE_NUMERIC', 1);
  23. if (!defined ('PDF_TYPE_TOKEN'))
  24. define ('PDF_TYPE_TOKEN', 2);
  25. if (!defined ('PDF_TYPE_HEX'))
  26. define ('PDF_TYPE_HEX', 3);
  27. if (!defined ('PDF_TYPE_STRING'))
  28. define ('PDF_TYPE_STRING', 4);
  29. if (!defined ('PDF_TYPE_DICTIONARY'))
  30. define ('PDF_TYPE_DICTIONARY', 5);
  31. if (!defined ('PDF_TYPE_ARRAY'))
  32. define ('PDF_TYPE_ARRAY', 6);
  33. if (!defined ('PDF_TYPE_OBJDEC'))
  34. define ('PDF_TYPE_OBJDEC', 7);
  35. if (!defined ('PDF_TYPE_OBJREF'))
  36. define ('PDF_TYPE_OBJREF', 8);
  37. if (!defined ('PDF_TYPE_OBJECT'))
  38. define ('PDF_TYPE_OBJECT', 9);
  39. if (!defined ('PDF_TYPE_STREAM'))
  40. define ('PDF_TYPE_STREAM', 10);
  41. require_once("pdf_context.php");
  42. require_once("wrapper_functions.php");
  43. class pdf_parser {
  44. /**
  45. * Filename
  46. * @var string
  47. */
  48. var $filename;
  49. /**
  50. * File resource
  51. * @var resource
  52. */
  53. var $f;
  54. /**
  55. * PDF Context
  56. * @var object pdf_context-Instance
  57. */
  58. var $c;
  59. /**
  60. * xref-Data
  61. * @var array
  62. */
  63. var $xref;
  64. /**
  65. * root-Object
  66. * @var array
  67. */
  68. var $root;
  69. /**
  70. * Constructor
  71. *
  72. * @param string $filename Source-Filename
  73. */
  74. function pdf_parser($filename) {
  75. $this->filename = $filename;
  76. $this->f = @fopen($this->filename, "rb");
  77. if (!$this->f)
  78. $this->error(sprintf("Cannot open %s !", $filename));
  79. $this->getPDFVersion();
  80. $this->c =& new pdf_context($this->f);
  81. // Read xref-Data
  82. $this->pdf_read_xref($this->xref, $this->pdf_find_xref());
  83. // Check for Encryption
  84. $this->getEncryption();
  85. // Read root
  86. $this->pdf_read_root();
  87. }
  88. /**
  89. * Close the opened file
  90. */
  91. function closeFile() {
  92. if (isset($this->f)) {
  93. fclose($this->f);
  94. unset($this->f);
  95. }
  96. }
  97. /**
  98. * Print Error and die
  99. *
  100. * @param string $msg Error-Message
  101. */
  102. function error($msg) {
  103. die("<b>PDF-Parser Error:</b> ".$msg);
  104. }
  105. /**
  106. * Check Trailer for Encryption
  107. */
  108. function getEncryption() {
  109. if (isset($this->xref['trailer'][1]['/Encrypt'])) {
  110. $this->error("File is encrypted!");
  111. }
  112. }
  113. /**
  114. * Find/Return /Root
  115. *
  116. * @return array
  117. */
  118. function pdf_find_root() {
  119. if ($this->xref['trailer'][1]['/Root'][0] != PDF_TYPE_OBJREF) {
  120. $this->error("Wrong Type of Root-Element! Must be an indirect reference");
  121. }
  122. return $this->xref['trailer'][1]['/Root'];
  123. }
  124. /**
  125. * Read the /Root
  126. */
  127. function pdf_read_root() {
  128. // read root
  129. $this->root = $this->pdf_resolve_object($this->c, $this->pdf_find_root());
  130. }
  131. /**
  132. * Get PDF-Version
  133. *
  134. * And reset the PDF Version used in FPDI if needed
  135. */
  136. function getPDFVersion() {
  137. fseek($this->f, 0);
  138. preg_match("/\d\.\d/",fread($this->f,16),$m);
  139. $this->pdfVersion = $m[0];
  140. }
  141. /**
  142. * Find the xref-Table
  143. */
  144. function pdf_find_xref() {
  145. fseek ($this->f, -min(filesize($this->filename),1500), SEEK_END);
  146. $data = fread($this->f, 1500);
  147. $pos = strlen($data) - strpos(strrev($data), strrev('startxref'));
  148. $data = substr($data, $pos);
  149. if (!preg_match('/\s*(\d+).*$/s', $data, $matches)) {
  150. $this->error("Unable to find pointer to xref table");
  151. }
  152. return (int) $matches[1];
  153. }
  154. /**
  155. * Read xref-table
  156. *
  157. * @param array $result Array of xref-table
  158. * @param integer $offset of xref-table
  159. * @param integer $start start-position in xref-table
  160. * @param integer $end end-position in xref-table
  161. */
  162. function pdf_read_xref(&$result, $offset, $start = null, $end = null) {
  163. if (is_null ($start) || is_null ($end)) {
  164. fseek($this->f, $o_pos = $offset);
  165. $data = trim(fgets($this->f,1024));
  166. if (strlen($data) == 0)
  167. $data = trim(fgets($this->f,1024));
  168. if ($data !== 'xref') {
  169. fseek($this->f, $o_pos);
  170. $data = trim(_fgets($this->f, true));
  171. if ($data !== 'xref') {
  172. if (preg_match('/(.*xref)(.*)/m', $data, $m)) { // xref 0 128 - in one line
  173. fseek($this->f, $o_pos+strlen($m[1]));
  174. } elseif (preg_match('/(x|r|e|f)+/', $data, $m)) { // correct invalid xref-pointer
  175. $tmpOffset = $offset-4+strlen($m[0]);
  176. $this->pdf_read_xref($result, $tmpOffset, $start, $end);
  177. return;
  178. } else {
  179. $this->error("Unable to find xref table - Maybe a Problem with 'auto_detect_line_endings'");
  180. }
  181. }
  182. }
  183. $o_pos = ftell($this->f);
  184. $data = explode(' ', trim(fgets($this->f,1024)));
  185. if (count($data) != 2) {
  186. fseek($this->f, $o_pos);
  187. $data = explode(' ', trim(_fgets($this->f, true)));
  188. if (count($data) != 2) {
  189. if (count($data) > 2) { // no lineending
  190. $n_pos = $o_pos+strlen($data[0])+strlen($data[1])+2;
  191. fseek($this->f, $n_pos);
  192. } else {
  193. $this->error("Unexpected header in xref table");
  194. }
  195. }
  196. }
  197. $start = $data[0];
  198. $end = $start + $data[1];
  199. }
  200. if (!isset($result['xref_location'])) {
  201. $result['xref_location'] = $offset;
  202. }
  203. if (!isset($result['max_object']) || $end > $result['max_object']) {
  204. $result['max_object'] = $end;
  205. }
  206. for (; $start < $end; $start++) {
  207. $data = ltrim(fread($this->f, 20)); // Spezifications says: 20 bytes including newlines
  208. $offset = substr($data, 0, 10);
  209. $generation = substr($data, 11, 5);
  210. if (!isset ($result['xref'][$start][(int) $generation])) {
  211. $result['xref'][$start][(int) $generation] = (int) $offset;
  212. }
  213. }
  214. $o_pos = ftell($this->f);
  215. $data = fgets($this->f,1024);
  216. if (strlen(trim($data)) == 0)
  217. $data = fgets($this->f, 1024);
  218. if (preg_match("/trailer/",$data)) {
  219. if (preg_match("/(.*trailer[ \n\r]*)/",$data,$m)) {
  220. fseek($this->f, $o_pos+strlen($m[1]));
  221. }
  222. $c =& new pdf_context($this->f);
  223. $trailer = $this->pdf_read_value($c);
  224. if (isset($trailer[1]['/Prev'])) {
  225. $this->pdf_read_xref($result, $trailer[1]['/Prev'][1]);
  226. $result['trailer'][1] = array_merge($result['trailer'][1], $trailer[1]);
  227. } else {
  228. $result['trailer'] = $trailer;
  229. }
  230. } else {
  231. $data = explode(' ', trim($data));
  232. if (count($data) != 2) {
  233. fseek($this->f, $o_pos);
  234. $data = explode(' ', trim (_fgets ($this->f, true)));
  235. if (count($data) != 2) {
  236. $this->error("Unexpected data in xref table");
  237. }
  238. }
  239. $this->pdf_read_xref($result, null, (int) $data[0], (int) $data[0] + (int) $data[1]);
  240. }
  241. }
  242. /**
  243. * Reads an Value
  244. *
  245. * @param object $c pdf_context
  246. * @param string $token a Token
  247. * @return mixed
  248. */
  249. function pdf_read_value(&$c, $token = null) {
  250. if (is_null($token)) {
  251. $token = $this->pdf_read_token($c);
  252. }
  253. if ($token === false) {
  254. return false;
  255. }
  256. switch ($token) {
  257. case '<':
  258. // This is a hex string.
  259. // Read the value, then the terminator
  260. $pos = $c->offset;
  261. while(1) {
  262. $match = strpos ($c->buffer, '>', $pos);
  263. // If you can't find it, try
  264. // reading more data from the stream
  265. if ($match === false) {
  266. if (!$c->increase_length()) {
  267. return false;
  268. } else {
  269. continue;
  270. }
  271. }
  272. $result = substr ($c->buffer, $c->offset, $match - $c->offset);
  273. $c->offset = $match+1;
  274. return array (PDF_TYPE_HEX, $result);
  275. }
  276. break;
  277. case '<<':
  278. // This is a dictionary.
  279. $result = array();
  280. // Recurse into this function until we reach
  281. // the end of the dictionary.
  282. while (($key = $this->pdf_read_token($c)) !== '>>') {
  283. if ($key === false) {
  284. return false;
  285. }
  286. if (($value = $this->pdf_read_value($c)) === false) {
  287. return false;
  288. }
  289. $result[$key] = $value;
  290. }
  291. return array (PDF_TYPE_DICTIONARY, $result);
  292. case '[':
  293. // This is an array.
  294. $result = array();
  295. // Recurse into this function until we reach
  296. // the end of the array.
  297. while (($token = $this->pdf_read_token($c)) !== ']') {
  298. if ($token === false) {
  299. return false;
  300. }
  301. if (($value = $this->pdf_read_value($c, $token)) === false) {
  302. return false;
  303. }
  304. $result[] = $value;
  305. }
  306. return array (PDF_TYPE_ARRAY, $result);
  307. case '(' :
  308. // This is a string
  309. $pos = $c->offset;
  310. while(1) {
  311. // Start by finding the next closed
  312. // parenthesis
  313. $match = strpos ($c->buffer, ')', $pos);
  314. // If you can't find it, try
  315. // reading more data from the stream
  316. if ($match === false) {
  317. if (!$c->increase_length()) {
  318. return false;
  319. } else {
  320. continue;
  321. }
  322. }
  323. // Make sure that there is no backslash
  324. // before the parenthesis. If there is,
  325. // move on. Otherwise, return the string.
  326. $esc = preg_match('/([\\\\]+)$/', $tmpresult = substr($c->buffer, $c->offset, $match - $c->offset), $m);
  327. if ($esc === 0 || strlen($m[1]) % 2 == 0) {
  328. $result = $tmpresult;
  329. $c->offset = $match + 1;
  330. return array (PDF_TYPE_STRING, $result);
  331. } else {
  332. $pos = $match + 1;
  333. if ($pos > $c->offset + $c->length) {
  334. $c->increase_length();
  335. }
  336. }
  337. }
  338. case "stream":
  339. $o_pos = ftell($c->file)-strlen($c->buffer);
  340. $o_offset = $c->offset;
  341. $c->reset($startpos = $o_pos + $o_offset);
  342. $e = 0; // ensure line breaks in front of the stream
  343. if ($c->buffer[0] == chr(10) || $c->buffer[0] == chr(13))
  344. $e++;
  345. if ($c->buffer[1] == chr(10) && $c->buffer[0] != chr(10))
  346. $e++;
  347. if ($this->actual_obj[1][1]['/Length'][0] == PDF_TYPE_OBJREF) {
  348. $tmp_c =& new pdf_context($this->f);
  349. $tmp_length = $this->pdf_resolve_object($tmp_c,$this->actual_obj[1][1]['/Length']);
  350. $length = $tmp_length[1][1];
  351. } else {
  352. $length = $this->actual_obj[1][1]['/Length'][1];
  353. }
  354. if ($length > 0) {
  355. $c->reset($startpos+$e,$length);
  356. $v = $c->buffer;
  357. } else {
  358. $v = '';
  359. }
  360. $c->reset($startpos+$e+$length+9); // 9 = strlen("endstream")
  361. return array(PDF_TYPE_STREAM, $v);
  362. default :
  363. if (is_numeric ($token)) {
  364. // A numeric token. Make sure that
  365. // it is not part of something else.
  366. if (($tok2 = $this->pdf_read_token ($c)) !== false) {
  367. if (is_numeric ($tok2)) {
  368. // Two numeric tokens in a row.
  369. // In this case, we're probably in
  370. // front of either an object reference
  371. // or an object specification.
  372. // Determine the case and return the data
  373. if (($tok3 = $this->pdf_read_token ($c)) !== false) {
  374. switch ($tok3) {
  375. case 'obj' :
  376. return array (PDF_TYPE_OBJDEC, (int) $token, (int) $tok2);
  377. case 'R' :
  378. return array (PDF_TYPE_OBJREF, (int) $token, (int) $tok2);
  379. }
  380. // If we get to this point, that numeric value up
  381. // there was just a numeric value. Push the extra
  382. // tokens back into the stack and return the value.
  383. array_push ($c->stack, $tok3);
  384. }
  385. }
  386. array_push ($c->stack, $tok2);
  387. }
  388. return array (PDF_TYPE_NUMERIC, $token);
  389. } else {
  390. // Just a token. Return it.
  391. return array (PDF_TYPE_TOKEN, $token);
  392. }
  393. }
  394. }
  395. /**
  396. * Resolve an object
  397. *
  398. * @param object $c pdf_context
  399. * @param array $obj_spec The object-data
  400. * @param boolean $encapsulate Must set to true, cause the parsing and fpdi use this method only without this para
  401. */
  402. function pdf_resolve_object(&$c, $obj_spec, $encapsulate = true) {
  403. // Exit if we get invalid data
  404. if (!is_array($obj_spec)) {
  405. return false;
  406. }
  407. if ($obj_spec[0] == PDF_TYPE_OBJREF) {
  408. // This is a reference, resolve it
  409. if (isset($this->xref['xref'][$obj_spec[1]][$obj_spec[2]])) {
  410. // Save current file position
  411. // This is needed if you want to resolve
  412. // references while you're reading another object
  413. // (e.g.: if you need to determine the length
  414. // of a stream)
  415. $old_pos = ftell($c->file);
  416. // Reposition the file pointer and
  417. // load the object header.
  418. $c->reset($this->xref['xref'][$obj_spec[1]][$obj_spec[2]]);
  419. $header = $this->pdf_read_value($c,null,true);
  420. if ($header[0] != PDF_TYPE_OBJDEC || $header[1] != $obj_spec[1] || $header[2] != $obj_spec[2]) {
  421. $this->error("Unable to find object ({$obj_spec[1]}, {$obj_spec[2]}) at expected location");
  422. }
  423. // If we're being asked to store all the information
  424. // about the object, we add the object ID and generation
  425. // number for later use
  426. $this->actual_obj =& $result;
  427. if ($encapsulate) {
  428. $result = array (
  429. PDF_TYPE_OBJECT,
  430. 'obj' => $obj_spec[1],
  431. 'gen' => $obj_spec[2]
  432. );
  433. } else {
  434. $result = array();
  435. }
  436. // Now simply read the object data until
  437. // we encounter an end-of-object marker
  438. while(1) {
  439. $value = $this->pdf_read_value($c);
  440. if ($value === false || count($result) > 4) {
  441. // in this case the parser coudn't find an endobj so we break here
  442. break;
  443. }
  444. if ($value[0] == PDF_TYPE_TOKEN && $value[1] === 'endobj') {
  445. break;
  446. }
  447. $result[] = $value;
  448. }
  449. $c->reset($old_pos);
  450. if (isset($result[2][0]) && $result[2][0] == PDF_TYPE_STREAM) {
  451. $result[0] = PDF_TYPE_STREAM;
  452. }
  453. return $result;
  454. }
  455. } else {
  456. return $obj_spec;
  457. }
  458. }
  459. /**
  460. * Reads a token from the file
  461. *
  462. * @param object $c pdf_context
  463. * @return mixed
  464. */
  465. function pdf_read_token(&$c)
  466. {
  467. // If there is a token available
  468. // on the stack, pop it out and
  469. // return it.
  470. if (count($c->stack)) {
  471. return array_pop($c->stack);
  472. }
  473. // Strip away any whitespace
  474. do {
  475. if (!$c->ensure_content()) {
  476. return false;
  477. }
  478. $c->offset += _strspn($c->buffer, " \n\r\t", $c->offset);
  479. } while ($c->offset >= $c->length - 1);
  480. // Get the first character in the stream
  481. $char = $c->buffer[$c->offset++];
  482. switch ($char) {
  483. case '[' :
  484. case ']' :
  485. case '(' :
  486. case ')' :
  487. // This is either an array or literal string
  488. // delimiter, Return it
  489. return $char;
  490. case '<' :
  491. case '>' :
  492. // This could either be a hex string or
  493. // dictionary delimiter. Determine the
  494. // appropriate case and return the token
  495. if ($c->buffer[$c->offset] == $char) {
  496. if (!$c->ensure_content()) {
  497. return false;
  498. }
  499. $c->offset++;
  500. return $char . $char;
  501. } else {
  502. return $char;
  503. }
  504. default :
  505. // This is "another" type of token (probably
  506. // a dictionary entry or a numeric value)
  507. // Find the end and return it.
  508. if (!$c->ensure_content()) {
  509. return false;
  510. }
  511. while(1) {
  512. // Determine the length of the token
  513. $pos = _strcspn($c->buffer, " []<>()\r\n\t/", $c->offset);
  514. if ($c->offset + $pos <= $c->length - 1) {
  515. break;
  516. } else {
  517. // If the script reaches this point,
  518. // the token may span beyond the end
  519. // of the current buffer. Therefore,
  520. // we increase the size of the buffer
  521. // and try again--just to be safe.
  522. $c->increase_length();
  523. }
  524. }
  525. $result = substr($c->buffer, $c->offset - 1, $pos + 1);
  526. $c->offset += $pos;
  527. return $result;
  528. }
  529. }
  530. }
  531. ?>