Teknik is a suite of services with attractive and functional interfaces. https://www.teknik.io/
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.

tcpdf_parser.php 26KB

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