pdf_parser.php 19 KB

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