You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

815 lines
27 KiB

  1. <?php
  2. //============================================================+
  3. // File name : tcpdf_parser.php
  4. // Version : 1.0.16
  5. // Begin : 2011-05-23
  6. // Last Update : 2015-04-28
  7. // Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
  8. // License : http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT GNU-LGPLv3
  9. // -------------------------------------------------------------------
  10. // Copyright (C) 2011-2015 Nicola Asuni - Tecnick.com LTD
  11. //
  12. // This file is part of TCPDF software library.
  13. //
  14. // TCPDF is free software: you can redistribute it and/or modify it
  15. // under the terms of the GNU Lesser General Public License as
  16. // published by the Free Software Foundation, either version 3 of the
  17. // License, or (at your option) any later version.
  18. //
  19. // TCPDF is distributed in the hope that it will be useful, but
  20. // WITHOUT ANY WARRANTY; without even the implied warranty of
  21. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  22. // See the GNU Lesser General Public License for more details.
  23. //
  24. // You should have received a copy of the License
  25. // along with TCPDF. If not, see
  26. // <http://www.tecnick.com/pagefiles/tcpdf/LICENSE.TXT>.
  27. //
  28. // See LICENSE.TXT file for more information.
  29. // -------------------------------------------------------------------
  30. //
  31. // Description : This is a PHP class for parsing PDF documents.
  32. //
  33. //============================================================+
  34. /**
  35. * @file
  36. * This is a PHP class for parsing PDF documents.<br>
  37. * @package com.tecnick.tcpdf
  38. * @author Nicola Asuni
  39. * @version 1.0.15
  40. */
  41. // include class for decoding filters
  42. require_once(dirname(__FILE__).'/include/tcpdf_filters.php');
  43. /**
  44. * @class TCPDF_PARSER
  45. * This is a PHP class for parsing PDF documents.<br>
  46. * @package com.tecnick.tcpdf
  47. * @brief This is a PHP class for parsing PDF documents..
  48. * @version 1.0.15
  49. * @author Nicola Asuni - info@tecnick.com
  50. */
  51. class TCPDF_PARSER {
  52. /**
  53. * Raw content of the PDF document.
  54. * @private
  55. */
  56. private $pdfdata = '';
  57. /**
  58. * XREF data.
  59. * @protected
  60. */
  61. protected $xref = array();
  62. /**
  63. * Array of PDF objects.
  64. * @protected
  65. */
  66. protected $objects = array();
  67. /**
  68. * Class object for decoding filters.
  69. * @private
  70. */
  71. private $FilterDecoders;
  72. /**
  73. * Array of configuration parameters.
  74. * @private
  75. */
  76. private $cfg = array(
  77. 'die_for_errors' => false,
  78. 'ignore_filter_decoding_errors' => true,
  79. 'ignore_missing_filter_decoders' => true,
  80. );
  81. // -----------------------------------------------------------------------------
  82. /**
  83. * Parse a PDF document an return an array of objects.
  84. * @param $data (string) PDF data to parse.
  85. * @param $cfg (array) Array of configuration parameters:
  86. * 'die_for_errors' : if true termitate the program execution in case of error, otherwise thows an exception;
  87. * 'ignore_filter_decoding_errors' : if true ignore filter decoding errors;
  88. * 'ignore_missing_filter_decoders' : if true ignore missing filter decoding errors.
  89. * @public
  90. * @since 1.0.000 (2011-05-24)
  91. */
  92. public function __construct($data, $cfg=array()) {
  93. if (empty($data)) {
  94. $this->Error('Empty PDF data.');
  95. }
  96. // find the pdf header starting position
  97. if (($trimpos = strpos($data, '%PDF-')) === FALSE) {
  98. $this->Error('Invalid PDF data: missing %PDF header.');
  99. }
  100. // get PDF content string
  101. $this->pdfdata = substr($data, $trimpos);
  102. // get length
  103. $pdflen = strlen($this->pdfdata);
  104. // set configuration parameters
  105. $this->setConfig($cfg);
  106. // get xref and trailer data
  107. $this->xref = $this->getXrefData();
  108. // parse all document objects
  109. $this->objects = array();
  110. foreach ($this->xref['xref'] as $obj => $offset) {
  111. if (!isset($this->objects[$obj]) AND ($offset > 0)) {
  112. // decode objects with positive offset
  113. $this->objects[$obj] = $this->getIndirectObject($obj, $offset, true);
  114. }
  115. }
  116. // release some memory
  117. unset($this->pdfdata);
  118. $this->pdfdata = '';
  119. }
  120. /**
  121. * Set the configuration parameters.
  122. * @param $cfg (array) Array of configuration parameters:
  123. * 'die_for_errors' : if true termitate the program execution in case of error, otherwise thows an exception;
  124. * 'ignore_filter_decoding_errors' : if true ignore filter decoding errors;
  125. * 'ignore_missing_filter_decoders' : if true ignore missing filter decoding errors.
  126. * @public
  127. */
  128. protected function setConfig($cfg) {
  129. if (isset($cfg['die_for_errors'])) {
  130. $this->cfg['die_for_errors'] = !!$cfg['die_for_errors'];
  131. }
  132. if (isset($cfg['ignore_filter_decoding_errors'])) {
  133. $this->cfg['ignore_filter_decoding_errors'] = !!$cfg['ignore_filter_decoding_errors'];
  134. }
  135. if (isset($cfg['ignore_missing_filter_decoders'])) {
  136. $this->cfg['ignore_missing_filter_decoders'] = !!$cfg['ignore_missing_filter_decoders'];
  137. }
  138. }
  139. /**
  140. * Return an array of parsed PDF document objects.
  141. * @return (array) Array of parsed PDF document objects.
  142. * @public
  143. * @since 1.0.000 (2011-06-26)
  144. */
  145. public function getParsedData() {
  146. return array($this->xref, $this->objects);
  147. }
  148. /**
  149. * Get Cross-Reference (xref) table and trailer data from PDF document data.
  150. * @param $offset (int) xref offset (if know).
  151. * @param $xref (array) previous xref array (if any).
  152. * @return Array containing xref and trailer data.
  153. * @protected
  154. * @since 1.0.000 (2011-05-24)
  155. */
  156. protected function getXrefData($offset=0, $xref=array()) {
  157. if ($offset == 0) {
  158. // find last startxref
  159. if (preg_match_all('/[\r\n]startxref[\s]*[\r\n]+([0-9]+)[\s]*[\r\n]+%%EOF/i', $this->pdfdata, $matches, PREG_SET_ORDER, $offset) == 0) {
  160. $this->Error('Unable to find startxref');
  161. }
  162. $matches = array_pop($matches);
  163. $startxref = $matches[1];
  164. } elseif (strpos($this->pdfdata, 'xref', $offset) == $offset) {
  165. // Already pointing at the xref table
  166. $startxref = $offset;
  167. } elseif (preg_match('/([0-9]+[\s][0-9]+[\s]obj)/i', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset)) {
  168. // Cross-Reference Stream object
  169. $startxref = $offset;
  170. } elseif (preg_match('/[\r\n]startxref[\s]*[\r\n]+([0-9]+)[\s]*[\r\n]+%%EOF/i', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset)) {
  171. // startxref found
  172. $startxref = $matches[1][0];
  173. } else {
  174. $this->Error('Unable to find startxref');
  175. }
  176. // check xref position
  177. if (strpos($this->pdfdata, 'xref', $startxref) == $startxref) {
  178. // Cross-Reference
  179. $xref = $this->decodeXref($startxref, $xref);
  180. } else {
  181. // Cross-Reference Stream
  182. $xref = $this->decodeXrefStream($startxref, $xref);
  183. }
  184. if (empty($xref)) {
  185. $this->Error('Unable to find xref');
  186. }
  187. return $xref;
  188. }
  189. /**
  190. * Decode the Cross-Reference section
  191. * @param $startxref (int) Offset at which the xref section starts (position of the 'xref' keyword).
  192. * @param $xref (array) Previous xref array (if any).
  193. * @return Array containing xref and trailer data.
  194. * @protected
  195. * @since 1.0.000 (2011-06-20)
  196. */
  197. protected function decodeXref($startxref, $xref=array()) {
  198. $startxref += 4; // 4 is the length of the word 'xref'
  199. // skip initial white space chars: \x00 null (NUL), \x09 horizontal tab (HT), \x0A line feed (LF), \x0C form feed (FF), \x0D carriage return (CR), \x20 space (SP)
  200. $offset = $startxref + strspn($this->pdfdata, "\x00\x09\x0a\x0c\x0d\x20", $startxref);
  201. // initialize object number
  202. $obj_num = 0;
  203. // search for cross-reference entries or subsection
  204. while (preg_match('/([0-9]+)[\x20]([0-9]+)[\x20]?([nf]?)(\r\n|[\x20]?[\r\n])/', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
  205. if ($matches[0][1] != $offset) {
  206. // we are on another section
  207. break;
  208. }
  209. $offset += strlen($matches[0][0]);
  210. if ($matches[3][0] == 'n') {
  211. // create unique object index: [object number]_[generation number]
  212. $index = $obj_num.'_'.intval($matches[2][0]);
  213. // check if object already exist
  214. if (!isset($xref['xref'][$index])) {
  215. // store object offset position
  216. $xref['xref'][$index] = intval($matches[1][0]);
  217. }
  218. ++$obj_num;
  219. } elseif ($matches[3][0] == 'f') {
  220. ++$obj_num;
  221. } else {
  222. // object number (index)
  223. $obj_num = intval($matches[1][0]);
  224. }
  225. }
  226. // get trailer data
  227. if (preg_match('/trailer[\s]*<<(.*)>>/isU', $this->pdfdata, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
  228. $trailer_data = $matches[1][0];
  229. if (!isset($xref['trailer']) OR empty($xref['trailer'])) {
  230. // get only the last updated version
  231. $xref['trailer'] = array();
  232. // parse trailer_data
  233. if (preg_match('/Size[\s]+([0-9]+)/i', $trailer_data, $matches) > 0) {
  234. $xref['trailer']['size'] = intval($matches[1]);
  235. }
  236. if (preg_match('/Root[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
  237. $xref['trailer']['root'] = intval($matches[1]).'_'.intval($matches[2]);
  238. }
  239. if (preg_match('/Encrypt[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
  240. $xref['trailer']['encrypt'] = intval($matches[1]).'_'.intval($matches[2]);
  241. }
  242. if (preg_match('/Info[\s]+([0-9]+)[\s]+([0-9]+)[\s]+R/i', $trailer_data, $matches) > 0) {
  243. $xref['trailer']['info'] = intval($matches[1]).'_'.intval($matches[2]);
  244. }
  245. if (preg_match('/ID[\s]*[\[][\s]*[<]([^>]*)[>][\s]*[<]([^>]*)[>]/i', $trailer_data, $matches) > 0) {
  246. $xref['trailer']['id'] = array();
  247. $xref['trailer']['id'][0] = $matches[1];
  248. $xref['trailer']['id'][1] = $matches[2];
  249. }
  250. }
  251. if (preg_match('/Prev[\s]+([0-9]+)/i', $trailer_data, $matches) > 0) {
  252. // get previous xref
  253. $xref = $this->getXrefData(intval($matches[1]), $xref);
  254. }
  255. } else {
  256. $this->Error('Unable to find trailer');
  257. }
  258. return $xref;
  259. }
  260. /**
  261. * Decode the Cross-Reference Stream section
  262. * @param $startxref (int) Offset at which the xref section starts.
  263. * @param $xref (array) Previous xref array (if any).
  264. * @return Array containing xref and trailer data.
  265. * @protected
  266. * @since 1.0.003 (2013-03-16)
  267. */
  268. protected function decodeXrefStream($startxref, $xref=array()) {
  269. // try to read Cross-Reference Stream
  270. $xrefobj = $this->getRawObject($startxref);
  271. $xrefcrs = $this->getIndirectObject($xrefobj[1], $startxref, true);
  272. if (!isset($xref['trailer']) OR empty($xref['trailer'])) {
  273. // get only the last updated version
  274. $xref['trailer'] = array();
  275. $filltrailer = true;
  276. } else {
  277. $filltrailer = false;
  278. }
  279. if (!isset($xref['xref'])) {
  280. $xref['xref'] = array();
  281. }
  282. $valid_crs = false;
  283. $columns = 0;
  284. $sarr = $xrefcrs[0][1];
  285. if (!is_array($sarr)) {
  286. $sarr = array();
  287. }
  288. foreach ($sarr as $k => $v) {
  289. if (($v[0] == '/') AND ($v[1] == 'Type') AND (isset($sarr[($k +1)]) AND ($sarr[($k +1)][0] == '/') AND ($sarr[($k +1)][1] == 'XRef'))) {
  290. $valid_crs = true;
  291. } elseif (($v[0] == '/') AND ($v[1] == 'Index') AND (isset($sarr[($k +1)]))) {
  292. // first object number in the subsection
  293. $index_first = intval($sarr[($k +1)][1][0][1]);
  294. // number of entries in the subsection
  295. $index_entries = intval($sarr[($k +1)][1][1][1]);
  296. } elseif (($v[0] == '/') AND ($v[1] == 'Prev') AND (isset($sarr[($k +1)]) AND ($sarr[($k +1)][0] == 'numeric'))) {
  297. // get previous xref offset
  298. $prevxref = intval($sarr[($k +1)][1]);
  299. } elseif (($v[0] == '/') AND ($v[1] == 'W') AND (isset($sarr[($k +1)]))) {
  300. // number of bytes (in the decoded stream) of the corresponding field
  301. $wb = array();
  302. $wb[0] = intval($sarr[($k +1)][1][0][1]);
  303. $wb[1] = intval($sarr[($k +1)][1][1][1]);
  304. $wb[2] = intval($sarr[($k +1)][1][2][1]);
  305. } elseif (($v[0] == '/') AND ($v[1] == 'DecodeParms') AND (isset($sarr[($k +1)][1]))) {
  306. $decpar = $sarr[($k +1)][1];
  307. foreach ($decpar as $kdc => $vdc) {
  308. if (($vdc[0] == '/') AND ($vdc[1] == 'Columns') AND (isset($decpar[($kdc +1)]) AND ($decpar[($kdc +1)][0] == 'numeric'))) {
  309. $columns = intval($decpar[($kdc +1)][1]);
  310. } elseif (($vdc[0] == '/') AND ($vdc[1] == 'Predictor') AND (isset($decpar[($kdc +1)]) AND ($decpar[($kdc +1)][0] == 'numeric'))) {
  311. $predictor = intval($decpar[($kdc +1)][1]);
  312. }
  313. }
  314. } elseif ($filltrailer) {
  315. if (($v[0] == '/') AND ($v[1] == 'Size') AND (isset($sarr[($k +1)]) AND ($sarr[($k +1)][0] == 'numeric'))) {
  316. $xref['trailer']['size'] = $sarr[($k +1)][1];
  317. } elseif (($v[0] == '/') AND ($v[1] == 'Root') AND (isset($sarr[($k +1)]) AND ($sarr[($k +1)][0] == 'objref'))) {
  318. $xref['trailer']['root'] = $sarr[($k +1)][1];
  319. } elseif (($v[0] == '/') AND ($v[1] == 'Info') AND (isset($sarr[($k +1)]) AND ($sarr[($k +1)][0] == 'objref'))) {
  320. $xref['trailer']['info'] = $sarr[($k +1)][1];
  321. } elseif (($v[0] == '/') AND ($v[1] == 'Encrypt') AND (isset($sarr[($k +1)]) AND ($sarr[($k +1)][0] == 'objref'))) {
  322. $xref['trailer']['encrypt'] = $sarr[($k +1)][1];
  323. } elseif (($v[0] == '/') AND ($v[1] == 'ID') AND (isset($sarr[($k +1)]))) {
  324. $xref['trailer']['id'] = array();
  325. $xref['trailer']['id'][0] = $sarr[($k +1)][1][0][1];
  326. $xref['trailer']['id'][1] = $sarr[($k +1)][1][1][1];
  327. }
  328. }
  329. }
  330. // decode data
  331. if ($valid_crs AND isset($xrefcrs[1][3][0])) {
  332. // number of bytes in a row
  333. $rowlen = ($columns + 1);
  334. // convert the stream into an array of integers
  335. $sdata = unpack('C*', $xrefcrs[1][3][0]);
  336. // split the rows
  337. $sdata = array_chunk($sdata, $rowlen);
  338. // initialize decoded array
  339. $ddata = array();
  340. // initialize first row with zeros
  341. $prev_row = array_fill (0, $rowlen, 0);
  342. // for each row apply PNG unpredictor
  343. foreach ($sdata as $k => $row) {
  344. // initialize new row
  345. $ddata[$k] = array();
  346. // get PNG predictor value
  347. $predictor = (10 + $row[0]);
  348. // for each byte on the row
  349. for ($i=1; $i<=$columns; ++$i) {
  350. // new index
  351. $j = ($i - 1);
  352. $row_up = $prev_row[$j];
  353. if ($i == 1) {
  354. $row_left = 0;
  355. $row_upleft = 0;
  356. } else {
  357. $row_left = $row[($i - 1)];
  358. $row_upleft = $prev_row[($j - 1)];
  359. }
  360. switch ($predictor) {
  361. case 10: { // PNG prediction (on encoding, PNG None on all rows)
  362. $ddata[$k][$j] = $row[$i];
  363. break;
  364. }
  365. case 11: { // PNG prediction (on encoding, PNG Sub on all rows)
  366. $ddata[$k][$j] = (($row[$i] + $row_left) & 0xff);
  367. break;
  368. }
  369. case 12: { // PNG prediction (on encoding, PNG Up on all rows)
  370. $ddata[$k][$j] = (($row[$i] + $row_up) & 0xff);
  371. break;
  372. }
  373. case 13: { // PNG prediction (on encoding, PNG Average on all rows)
  374. $ddata[$k][$j] = (($row[$i] + (($row_left + $row_up) / 2)) & 0xff);
  375. break;
  376. }
  377. case 14: { // PNG prediction (on encoding, PNG Paeth on all rows)
  378. // initial estimate
  379. $p = ($row_left + $row_up - $row_upleft);
  380. // distances
  381. $pa = abs($p - $row_left);
  382. $pb = abs($p - $row_up);
  383. $pc = abs($p - $row_upleft);
  384. $pmin = min($pa, $pb, $pc);
  385. // return minimum distance
  386. switch ($pmin) {
  387. case $pa: {
  388. $ddata[$k][$j] = (($row[$i] + $row_left) & 0xff);
  389. break;
  390. }
  391. case $pb: {
  392. $ddata[$k][$j] = (($row[$i] + $row_up) & 0xff);
  393. break;
  394. }
  395. case $pc: {
  396. $ddata[$k][$j] = (($row[$i] + $row_upleft) & 0xff);
  397. break;
  398. }
  399. }
  400. break;
  401. }
  402. default: { // PNG prediction (on encoding, PNG optimum)
  403. $this->Error('Unknown PNG predictor');
  404. break;
  405. }
  406. }
  407. }
  408. $prev_row = $ddata[$k];
  409. } // end for each row
  410. // complete decoding
  411. $sdata = array();
  412. // for every row
  413. foreach ($ddata as $k => $row) {
  414. // initialize new row
  415. $sdata[$k] = array(0, 0, 0);
  416. if ($wb[0] == 0) {
  417. // default type field
  418. $sdata[$k][0] = 1;
  419. }
  420. $i = 0; // count bytes in the row
  421. // for every column
  422. for ($c = 0; $c < 3; ++$c) {
  423. // for every byte on the column
  424. for ($b = 0; $b < $wb[$c]; ++$b) {
  425. if (isset($row[$i])) {
  426. $sdata[$k][$c] += ($row[$i] << (($wb[$c] - 1 - $b) * 8));
  427. }
  428. ++$i;
  429. }
  430. }
  431. }
  432. $ddata = array();
  433. // fill xref
  434. if (isset($index_first)) {
  435. $obj_num = $index_first;
  436. } else {
  437. $obj_num = 0;
  438. }
  439. foreach ($sdata as $k => $row) {
  440. switch ($row[0]) {
  441. case 0: { // (f) linked list of free objects
  442. break;
  443. }
  444. case 1: { // (n) objects that are in use but are not compressed
  445. // create unique object index: [object number]_[generation number]
  446. $index = $obj_num.'_'.$row[2];
  447. // check if object already exist
  448. if (!isset($xref['xref'][$index])) {
  449. // store object offset position
  450. $xref['xref'][$index] = $row[1];
  451. }
  452. break;
  453. }
  454. case 2: { // compressed objects
  455. // $row[1] = object number of the object stream in which this object is stored
  456. // $row[2] = index of this object within the object stream
  457. $index = $row[1].'_0_'.$row[2];
  458. $xref['xref'][$index] = -1;
  459. break;
  460. }
  461. default: { // null objects
  462. break;
  463. }
  464. }
  465. ++$obj_num;
  466. }
  467. } // end decoding data
  468. if (isset($prevxref)) {
  469. // get previous xref
  470. $xref = $this->getXrefData($prevxref, $xref);
  471. }
  472. return $xref;
  473. }
  474. /**
  475. * Get object type, raw value and offset to next object
  476. * @param $offset (int) Object offset.
  477. * @return array containing object type, raw value and offset to next object
  478. * @protected
  479. * @since 1.0.000 (2011-06-20)
  480. */
  481. protected function getRawObject($offset=0) {
  482. $objtype = ''; // object type to be returned
  483. $objval = ''; // object value to be returned
  484. // skip initial white space chars: \x00 null (NUL), \x09 horizontal tab (HT), \x0A line feed (LF), \x0C form feed (FF), \x0D carriage return (CR), \x20 space (SP)
  485. $offset += strspn($this->pdfdata, "\x00\x09\x0a\x0c\x0d\x20", $offset);
  486. // get first char
  487. $char = $this->pdfdata[$offset];
  488. // get object type
  489. switch ($char) {
  490. case '%': { // \x25 PERCENT SIGN
  491. // skip comment and search for next token
  492. $next = strcspn($this->pdfdata, "\r\n", $offset);
  493. if ($next > 0) {
  494. $offset += $next;
  495. return $this->getRawObject($offset);
  496. }
  497. break;
  498. }
  499. case '/': { // \x2F SOLIDUS
  500. // name object
  501. $objtype = $char;
  502. ++$offset;
  503. if (preg_match('/^([^\x00\x09\x0a\x0c\x0d\x20\s\x28\x29\x3c\x3e\x5b\x5d\x7b\x7d\x2f\x25]+)/', substr($this->pdfdata, $offset, 256), $matches) == 1) {
  504. $objval = $matches[1]; // unescaped value
  505. $offset += strlen($objval);
  506. }
  507. break;
  508. }
  509. case '(': // \x28 LEFT PARENTHESIS
  510. case ')': { // \x29 RIGHT PARENTHESIS
  511. // literal string object
  512. $objtype = $char;
  513. ++$offset;
  514. $strpos = $offset;
  515. if ($char == '(') {
  516. $open_bracket = 1;
  517. while ($open_bracket > 0) {
  518. if (!isset($this->pdfdata[$strpos])) {
  519. break;
  520. }
  521. $ch = $this->pdfdata[$strpos];
  522. switch ($ch) {
  523. case '\\': { // REVERSE SOLIDUS (5Ch) (Backslash)
  524. // skip next character
  525. ++$strpos;
  526. break;
  527. }
  528. case '(': { // LEFT PARENHESIS (28h)
  529. ++$open_bracket;
  530. break;
  531. }
  532. case ')': { // RIGHT PARENTHESIS (29h)
  533. --$open_bracket;
  534. break;
  535. }
  536. }
  537. ++$strpos;
  538. }
  539. $objval = substr($this->pdfdata, $offset, ($strpos - $offset - 1));
  540. $offset = $strpos;
  541. }
  542. break;
  543. }
  544. case '[': // \x5B LEFT SQUARE BRACKET
  545. case ']': { // \x5D RIGHT SQUARE BRACKET
  546. // array object
  547. $objtype = $char;
  548. ++$offset;
  549. if ($char == '[') {
  550. // get array content
  551. $objval = array();
  552. do {
  553. // get element
  554. $element = $this->getRawObject($offset);
  555. $offset = $element[2];
  556. $objval[] = $element;
  557. } while ($element[0] != ']');
  558. // remove closing delimiter
  559. array_pop($objval);
  560. }
  561. break;
  562. }
  563. case '<': // \x3C LESS-THAN SIGN
  564. case '>': { // \x3E GREATER-THAN SIGN
  565. if (isset($this->pdfdata[($offset + 1)]) AND ($this->pdfdata[($offset + 1)] == $char)) {
  566. // dictionary object
  567. $objtype = $char.$char;
  568. $offset += 2;
  569. if ($char == '<') {
  570. // get array content
  571. $objval = array();
  572. do {
  573. // get element
  574. $element = $this->getRawObject($offset);
  575. $offset = $element[2];
  576. $objval[] = $element;
  577. } while ($element[0] != '>>');
  578. // remove closing delimiter
  579. array_pop($objval);
  580. }
  581. } else {
  582. // hexadecimal string object
  583. $objtype = $char;
  584. ++$offset;
  585. if (($char == '<') AND (preg_match('/^([0-9A-Fa-f\x09\x0a\x0c\x0d\x20]+)>/iU', substr($this->pdfdata, $offset), $matches) == 1)) {
  586. // remove white space characters
  587. $objval = strtr($matches[1], "\x09\x0a\x0c\x0d\x20", '');
  588. $offset += strlen($matches[0]);
  589. } elseif (($endpos = strpos($this->pdfdata, '>', $offset)) !== FALSE) {
  590. $offset = $endpos + 1;
  591. }
  592. }
  593. break;
  594. }
  595. default: {
  596. if (substr($this->pdfdata, $offset, 6) == 'endobj') {
  597. // indirect object
  598. $objtype = 'endobj';
  599. $offset += 6;
  600. } elseif (substr($this->pdfdata, $offset, 4) == 'null') {
  601. // null object
  602. $objtype = 'null';
  603. $offset += 4;
  604. $objval = 'null';
  605. } elseif (substr($this->pdfdata, $offset, 4) == 'true') {
  606. // boolean true object
  607. $objtype = 'boolean';
  608. $offset += 4;
  609. $objval = 'true';
  610. } elseif (substr($this->pdfdata, $offset, 5) == 'false') {
  611. // boolean false object
  612. $objtype = 'boolean';
  613. $offset += 5;
  614. $objval = 'false';
  615. } elseif (substr($this->pdfdata, $offset, 6) == 'stream') {
  616. // start stream object
  617. $objtype = 'stream';
  618. $offset += 6;
  619. if (preg_match('/^([\r]?[\n])/isU', substr($this->pdfdata, $offset), $matches) == 1) {
  620. $offset += strlen($matches[0]);
  621. if (preg_match('/(endstream)[\x09\x0a\x0c\x0d\x20]/isU', substr($this->pdfdata, $offset), $matches, PREG_OFFSET_CAPTURE) == 1) {
  622. $objval = substr($this->pdfdata, $offset, $matches[0][1]);
  623. $offset += $matches[1][1];
  624. }
  625. }
  626. } elseif (substr($this->pdfdata, $offset, 9) == 'endstream') {
  627. // end stream object
  628. $objtype = 'endstream';
  629. $offset += 9;
  630. } elseif (preg_match('/^([0-9]+)[\s]+([0-9]+)[\s]+R/iU', substr($this->pdfdata, $offset, 33), $matches) == 1) {
  631. // indirect object reference
  632. $objtype = 'objref';
  633. $offset += strlen($matches[0]);
  634. $objval = intval($matches[1]).'_'.intval($matches[2]);
  635. } elseif (preg_match('/^([0-9]+)[\s]+([0-9]+)[\s]+obj/iU', substr($this->pdfdata, $offset, 33), $matches) == 1) {
  636. // object start
  637. $objtype = 'obj';
  638. $objval = intval($matches[1]).'_'.intval($matches[2]);
  639. $offset += strlen ($matches[0]);
  640. } elseif (($numlen = strspn($this->pdfdata, '+-.0123456789', $offset)) > 0) {
  641. // numeric object
  642. $objtype = 'numeric';
  643. $objval = substr($this->pdfdata, $offset, $numlen);
  644. $offset += $numlen;
  645. }
  646. break;
  647. }
  648. }
  649. return array($objtype, $objval, $offset);
  650. }
  651. /**
  652. * Get content of indirect object.
  653. * @param $obj_ref (string) Object number and generation number separated by underscore character.
  654. * @param $offset (int) Object offset.
  655. * @param $decoding (boolean) If true decode streams.
  656. * @return array containing object data.
  657. * @protected
  658. * @since 1.0.000 (2011-05-24)
  659. */
  660. protected function getIndirectObject($obj_ref, $offset=0, $decoding=true) {
  661. $obj = explode('_', $obj_ref);
  662. if (($obj === false) OR (count($obj) != 2)) {
  663. $this->Error('Invalid object reference: '.$obj);
  664. return;
  665. }
  666. $objref = $obj[0].' '.$obj[1].' obj';
  667. // ignore leading zeros
  668. $offset += strspn($this->pdfdata, '0', $offset);
  669. if (strpos($this->pdfdata, $objref, $offset) != $offset) {
  670. // an indirect reference to an undefined object shall be considered a reference to the null object
  671. return array('null', 'null', $offset);
  672. }
  673. // starting position of object content
  674. $offset += strlen($objref);
  675. // get array of object content
  676. $objdata = array();
  677. $i = 0; // object main index
  678. do {
  679. $oldoffset = $offset;
  680. // get element
  681. $element = $this->getRawObject($offset);
  682. $offset = $element[2];
  683. // decode stream using stream's dictionary information
  684. if ($decoding AND ($element[0] == 'stream') AND (isset($objdata[($i - 1)][0])) AND ($objdata[($i - 1)][0] == '<<')) {
  685. $element[3] = $this->decodeStream($objdata[($i - 1)][1], $element[1]);
  686. }
  687. $objdata[$i] = $element;
  688. ++$i;
  689. } while (($element[0] != 'endobj') AND ($offset != $oldoffset));
  690. // remove closing delimiter
  691. array_pop($objdata);
  692. // return raw object content
  693. return $objdata;
  694. }
  695. /**
  696. * Get the content of object, resolving indect object reference if necessary.
  697. * @param $obj (string) Object value.
  698. * @return array containing object data.
  699. * @protected
  700. * @since 1.0.000 (2011-06-26)
  701. */
  702. protected function getObjectVal($obj) {
  703. if ($obj[0] == 'objref') {
  704. // reference to indirect object
  705. if (isset($this->objects[$obj[1]])) {
  706. // this object has been already parsed
  707. return $this->objects[$obj[1]];
  708. } elseif (isset($this->xref[$obj[1]])) {
  709. // parse new object
  710. $this->objects[$obj[1]] = $this->getIndirectObject($obj[1], $this->xref[$obj[1]], false);
  711. return $this->objects[$obj[1]];
  712. }
  713. }
  714. return $obj;
  715. }
  716. /**
  717. * Decode the specified stream.
  718. * @param $sdic (array) Stream's dictionary array.
  719. * @param $stream (string) Stream to decode.
  720. * @return array containing decoded stream data and remaining filters.
  721. * @protected
  722. * @since 1.0.000 (2011-06-22)
  723. */
  724. protected function decodeStream($sdic, $stream) {
  725. // get stream length and filters
  726. $slength = strlen($stream);
  727. if ($slength <= 0) {
  728. return array('', array());
  729. }
  730. $filters = array();
  731. foreach ($sdic as $k => $v) {
  732. if ($v[0] == '/') {
  733. if (($v[1] == 'Length') AND (isset($sdic[($k + 1)])) AND ($sdic[($k + 1)][0] == 'numeric')) {
  734. // get declared stream length
  735. $declength = intval($sdic[($k + 1)][1]);
  736. if ($declength < $slength) {
  737. $stream = substr($stream, 0, $declength);
  738. $slength = $declength;
  739. }
  740. } elseif (($v[1] == 'Filter') AND (isset($sdic[($k + 1)]))) {
  741. // resolve indirect object
  742. $objval = $this->getObjectVal($sdic[($k + 1)]);
  743. if ($objval[0] == '/') {
  744. // single filter
  745. $filters[] = $objval[1];
  746. } elseif ($objval[0] == '[') {
  747. // array of filters
  748. foreach ($objval[1] as $flt) {
  749. if ($flt[0] == '/') {
  750. $filters[] = $flt[1];
  751. }
  752. }
  753. }
  754. }
  755. }
  756. }
  757. // decode the stream
  758. $remaining_filters = array();
  759. foreach ($filters as $filter) {
  760. if (in_array($filter, TCPDF_FILTERS::getAvailableFilters())) {
  761. try {
  762. $stream = TCPDF_FILTERS::decodeFilter($filter, $stream);
  763. } catch (Exception $e) {
  764. $emsg = $e->getMessage();
  765. if ((($emsg[0] == '~') AND !$this->cfg['ignore_missing_filter_decoders'])
  766. OR (($emsg[0] != '~') AND !$this->cfg['ignore_filter_decoding_errors'])) {
  767. $this->Error($e->getMessage());
  768. }
  769. }
  770. } else {
  771. // add missing filter to array
  772. $remaining_filters[] = $filter;
  773. }
  774. }
  775. return array($stream, $remaining_filters);
  776. }
  777. /**
  778. * Throw an exception or print an error message and die if the K_TCPDF_PARSER_THROW_EXCEPTION_ERROR constant is set to true.
  779. * @param $msg (string) The error message
  780. * @public
  781. * @since 1.0.000 (2011-05-23)
  782. */
  783. public function Error($msg) {
  784. if ($this->cfg['die_for_errors']) {
  785. die('<strong>TCPDF_PARSER ERROR: </strong>'.$msg);
  786. } else {
  787. throw new Exception('TCPDF_PARSER ERROR: '.$msg);
  788. }
  789. }
  790. } // END OF TCPDF_PARSER CLASS
  791. //============================================================+
  792. // END OF FILE
  793. //============================================================+