PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/include/functions.inc.php

https://github.com/dwagner2301/dompdf
PHP | 1026 lines | 692 code | 132 blank | 202 comment | 141 complexity | bb9321811874ef62b5b16ae24aa428f6 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * @package dompdf
  4. * @link http://dompdf.github.com/
  5. * @author Benj Carson <benjcarson@digitaljunkies.ca>
  6. * @author Helmut Tischer <htischer@weihenstephan.org>
  7. * @author Fabien MĂŠnager <fabien.menager@gmail.com>
  8. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  9. */
  10. if ( !defined('PHP_VERSION_ID') ) {
  11. $version = explode('.', PHP_VERSION);
  12. define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
  13. }
  14. /**
  15. * Defined a constant if not already defined
  16. *
  17. * @param string $name The constant name
  18. * @param mixed $value The value
  19. */
  20. function def($name, $value = true) {
  21. if ( !defined($name) ) {
  22. define($name, $value);
  23. }
  24. }
  25. if ( !function_exists("pre_r") ) {
  26. /**
  27. * print_r wrapper for html/cli output
  28. *
  29. * Wraps print_r() output in < pre > tags if the current sapi is not 'cli'.
  30. * Returns the output string instead of displaying it if $return is true.
  31. *
  32. * @param mixed $mixed variable or expression to display
  33. * @param bool $return
  34. *
  35. * @return string
  36. */
  37. function pre_r($mixed, $return = false) {
  38. if ( $return ) {
  39. return "<pre>" . print_r($mixed, true) . "</pre>";
  40. }
  41. if ( php_sapi_name() !== "cli" ) {
  42. echo "<pre>";
  43. }
  44. print_r($mixed);
  45. if ( php_sapi_name() !== "cli" ) {
  46. echo "</pre>";
  47. }
  48. else {
  49. echo "\n";
  50. }
  51. flush();
  52. }
  53. }
  54. if ( !function_exists("pre_var_dump") ) {
  55. /**
  56. * var_dump wrapper for html/cli output
  57. *
  58. * Wraps var_dump() output in < pre > tags if the current sapi is not 'cli'.
  59. *
  60. * @param mixed $mixed variable or expression to display.
  61. */
  62. function pre_var_dump($mixed) {
  63. if ( php_sapi_name() !== "cli" ) {
  64. echo "<pre>";
  65. }
  66. var_dump($mixed);
  67. if ( php_sapi_name() !== "cli" ) {
  68. echo "</pre>";
  69. }
  70. }
  71. }
  72. if ( !function_exists("d") ) {
  73. /**
  74. * generic debug function
  75. *
  76. * Takes everything and does its best to give a good debug output
  77. *
  78. * @param mixed $mixed variable or expression to display.
  79. */
  80. function d($mixed) {
  81. if ( php_sapi_name() !== "cli" ) {
  82. echo "<pre>";
  83. }
  84. // line
  85. if ( $mixed instanceof Line_Box ) {
  86. echo $mixed;
  87. }
  88. // other
  89. else {
  90. var_export($mixed);
  91. }
  92. if ( php_sapi_name() !== "cli" ) {
  93. echo "</pre>";
  94. }
  95. }
  96. }
  97. /**
  98. * builds a full url given a protocol, hostname, base path and url
  99. *
  100. * @param string $protocol
  101. * @param string $host
  102. * @param string $base_path
  103. * @param string $url
  104. * @return string
  105. *
  106. * Initially the trailing slash of $base_path was optional, and conditionally appended.
  107. * However on dynamically created sites, where the page is given as url parameter,
  108. * the base path might not end with an url.
  109. * Therefore do not append a slash, and **require** the $base_url to ending in a slash
  110. * when needed.
  111. * Vice versa, on using the local file system path of a file, make sure that the slash
  112. * is appended (o.k. also for Windows)
  113. */
  114. function build_url($protocol, $host, $base_path, $url) {
  115. if ( strlen($url) == 0 ) {
  116. //return $protocol . $host . rtrim($base_path, "/\\") . "/";
  117. return $protocol . $host . $base_path;
  118. }
  119. // Is the url already fully qualified or a Data URI?
  120. if ( mb_strpos($url, "://") !== false || mb_strpos($url, "data:") === 0 ) {
  121. return $url;
  122. }
  123. $ret = $protocol;
  124. if ( !in_array(mb_strtolower($protocol), array("http://", "https://", "ftp://", "ftps://")) ) {
  125. //On Windows local file, an abs path can begin also with a '\' or a drive letter and colon
  126. //drive: followed by a relative path would be a drive specific default folder.
  127. //not known in php app code, treat as abs path
  128. //($url[1] !== ':' || ($url[2]!=='\\' && $url[2]!=='/'))
  129. if ( $url[0] !== '/' && (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' || ($url[0] !== '\\' && $url[1] !== ':')) ) {
  130. // For rel path and local acess we ignore the host, and run the path through realpath()
  131. $ret .= realpath($base_path).'/';
  132. }
  133. $ret .= $url;
  134. $ret = preg_replace('/\?(.*)$/', "", $ret);
  135. return $ret;
  136. }
  137. //remote urls with backslash in html/css are not really correct, but lets be genereous
  138. if ( $url[0] === '/' || $url[0] === '\\' ) {
  139. // Absolute path
  140. $ret .= $host . $url;
  141. }
  142. else {
  143. // Relative path
  144. //$base_path = $base_path !== "" ? rtrim($base_path, "/\\") . "/" : "";
  145. $ret .= $host . $base_path . $url;
  146. }
  147. return $ret;
  148. }
  149. /**
  150. * parse a full url or pathname and return an array(protocol, host, path,
  151. * file + query + fragment)
  152. *
  153. * @param string $url
  154. * @return array
  155. */
  156. function explode_url($url) {
  157. $protocol = "";
  158. $host = "";
  159. $path = "";
  160. $file = "";
  161. $arr = parse_url($url);
  162. // Exclude windows drive letters...
  163. if ( isset($arr["scheme"]) && $arr["scheme"] !== "file" && strlen($arr["scheme"]) > 1 ) {
  164. $protocol = $arr["scheme"] . "://";
  165. if ( isset($arr["user"]) ) {
  166. $host .= $arr["user"];
  167. if ( isset($arr["pass"]) ) {
  168. $host .= ":" . $arr["pass"];
  169. }
  170. $host .= "@";
  171. }
  172. if ( isset($arr["host"]) ) {
  173. $host .= $arr["host"];
  174. }
  175. if ( isset($arr["port"]) ) {
  176. $host .= ":" . $arr["port"];
  177. }
  178. if ( isset($arr["path"]) && $arr["path"] !== "" ) {
  179. // Do we have a trailing slash?
  180. if ( $arr["path"][ mb_strlen($arr["path"]) - 1 ] === "/" ) {
  181. $path = $arr["path"];
  182. $file = "";
  183. }
  184. else {
  185. $path = rtrim(dirname($arr["path"]), '/\\') . "/";
  186. $file = basename($arr["path"]);
  187. }
  188. }
  189. if ( isset($arr["query"]) ) {
  190. $file .= "?" . $arr["query"];
  191. }
  192. if ( isset($arr["fragment"]) ) {
  193. $file .= "#" . $arr["fragment"];
  194. }
  195. }
  196. else {
  197. $i = mb_strpos($url, "file://");
  198. if ( $i !== false ) {
  199. $url = mb_substr($url, $i + 7);
  200. }
  201. $protocol = ""; // "file://"; ? why doesn't this work... It's because of
  202. // network filenames like //COMPU/SHARENAME
  203. $host = ""; // localhost, really
  204. $file = basename($url);
  205. $path = dirname($url);
  206. // Check that the path exists
  207. if ( $path !== false ) {
  208. $path .= '/';
  209. }
  210. else {
  211. // generate a url to access the file if no real path found.
  212. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
  213. $host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : php_uname("n");
  214. if ( substr($arr["path"], 0, 1) === '/' ) {
  215. $path = dirname($arr["path"]);
  216. }
  217. else {
  218. $path = '/' . rtrim(dirname($_SERVER["SCRIPT_NAME"]), '/') . '/' . $arr["path"];
  219. }
  220. }
  221. }
  222. $ret = array($protocol, $host, $path, $file,
  223. "protocol" => $protocol,
  224. "host" => $host,
  225. "path" => $path,
  226. "file" => $file);
  227. return $ret;
  228. }
  229. /**
  230. * Converts decimal numbers to roman numerals
  231. *
  232. * @param int $num
  233. *
  234. * @throws DOMPDF_Exception
  235. * @return string
  236. */
  237. function dec2roman($num) {
  238. static $ones = array("", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix");
  239. static $tens = array("", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc");
  240. static $hund = array("", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm");
  241. static $thou = array("", "m", "mm", "mmm");
  242. if ( !is_numeric($num) ) {
  243. throw new DOMPDF_Exception("dec2roman() requires a numeric argument.");
  244. }
  245. if ( $num > 4000 || $num < 0 ) {
  246. return "(out of range)";
  247. }
  248. $num = strrev((string)$num);
  249. $ret = "";
  250. switch (mb_strlen($num)) {
  251. case 4: $ret .= $thou[$num[3]];
  252. case 3: $ret .= $hund[$num[2]];
  253. case 2: $ret .= $tens[$num[1]];
  254. case 1: $ret .= $ones[$num[0]];
  255. default: break;
  256. }
  257. return $ret;
  258. }
  259. /**
  260. * Determines whether $value is a percentage or not
  261. *
  262. * @param float $value
  263. *
  264. * @return bool
  265. */
  266. function is_percent($value) {
  267. return false !== mb_strpos($value, "%");
  268. }
  269. /**
  270. * Parses a data URI scheme
  271. * http://en.wikipedia.org/wiki/Data_URI_scheme
  272. *
  273. * @param string $data_uri The data URI to parse
  274. *
  275. * @return array The result with charset, mime type and decoded data
  276. */
  277. function parse_data_uri($data_uri) {
  278. if (!preg_match('/^data:(?P<mime>[a-z0-9\/+-.]+)(;charset=(?P<charset>[a-z0-9-])+)?(?P<base64>;base64)?\,(?P<data>.*)?/i', $data_uri, $match)) {
  279. return false;
  280. }
  281. $match['data'] = rawurldecode($match['data']);
  282. $result = array(
  283. 'charset' => $match['charset'] ? $match['charset'] : 'US-ASCII',
  284. 'mime' => $match['mime'] ? $match['mime'] : 'text/plain',
  285. 'data' => $match['base64'] ? base64_decode($match['data']) : $match['data'],
  286. );
  287. return $result;
  288. }
  289. /**
  290. * mb_string compatibility
  291. */
  292. if ( !function_exists("mb_strlen") ) {
  293. define('MB_OVERLOAD_MAIL', 1);
  294. define('MB_OVERLOAD_STRING', 2);
  295. define('MB_OVERLOAD_REGEX', 4);
  296. define('MB_CASE_UPPER', 0);
  297. define('MB_CASE_LOWER', 1);
  298. define('MB_CASE_TITLE', 2);
  299. function mb_convert_encoding($data, $to_encoding, $from_encoding = 'UTF-8') {
  300. if (str_replace('-', '', strtolower($to_encoding)) === 'utf8') {
  301. return utf8_encode($data);
  302. }
  303. return utf8_decode($data);
  304. }
  305. function mb_detect_encoding($data, $encoding_list = array('iso-8859-1'), $strict = false) {
  306. return 'iso-8859-1';
  307. }
  308. function mb_detect_order($encoding_list = array('iso-8859-1')) {
  309. return 'iso-8859-1';
  310. }
  311. function mb_internal_encoding($encoding = null) {
  312. if (isset($encoding)) {
  313. return true;
  314. }
  315. return 'iso-8859-1';
  316. }
  317. function mb_strlen($str, $encoding = 'iso-8859-1') {
  318. switch (str_replace('-', '', strtolower($encoding))) {
  319. case "utf8": return strlen(utf8_encode($str));
  320. case "8bit": return strlen($str);
  321. default: return strlen(utf8_decode($str));
  322. }
  323. }
  324. function mb_strpos($haystack, $needle, $offset = 0) {
  325. return strpos($haystack, $needle, $offset);
  326. }
  327. function mb_strrpos($haystack, $needle, $offset = 0) {
  328. return strrpos($haystack, $needle, $offset);
  329. }
  330. function mb_strtolower( $str ) {
  331. return strtolower($str);
  332. }
  333. function mb_strtoupper( $str ) {
  334. return strtoupper($str);
  335. }
  336. function mb_substr($string, $start, $length = null, $encoding = 'iso-8859-1') {
  337. if ( is_null($length) ) {
  338. return substr($string, $start);
  339. }
  340. return substr($string, $start, $length);
  341. }
  342. function mb_substr_count($haystack, $needle, $encoding = 'iso-8859-1') {
  343. return substr_count($haystack, $needle);
  344. }
  345. function mb_encode_numericentity($str, $convmap, $encoding) {
  346. return htmlspecialchars($str);
  347. }
  348. function mb_convert_case($str, $mode = MB_CASE_UPPER, $encoding = array()) {
  349. switch($mode) {
  350. case MB_CASE_UPPER: return mb_strtoupper($str);
  351. case MB_CASE_LOWER: return mb_strtolower($str);
  352. case MB_CASE_TITLE: return ucwords(mb_strtolower($str));
  353. default: return $str;
  354. }
  355. }
  356. function mb_list_encodings() {
  357. return array(
  358. "ISO-8859-1",
  359. "UTF-8",
  360. "8bit",
  361. );
  362. }
  363. }
  364. /**
  365. * Decoder for RLE8 compression in windows bitmaps
  366. * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp
  367. *
  368. * @param string $str Data to decode
  369. * @param integer $width Image width
  370. *
  371. * @return string
  372. */
  373. function rle8_decode ($str, $width){
  374. $lineWidth = $width + (3 - ($width-1) % 4);
  375. $out = '';
  376. $cnt = strlen($str);
  377. for ($i = 0; $i <$cnt; $i++) {
  378. $o = ord($str[$i]);
  379. switch ($o){
  380. case 0: # ESCAPE
  381. $i++;
  382. switch (ord($str[$i])){
  383. case 0: # NEW LINE
  384. $padCnt = $lineWidth - strlen($out)%$lineWidth;
  385. if ($padCnt<$lineWidth) $out .= str_repeat(chr(0), $padCnt); # pad line
  386. break;
  387. case 1: # END OF FILE
  388. $padCnt = $lineWidth - strlen($out)%$lineWidth;
  389. if ($padCnt<$lineWidth) $out .= str_repeat(chr(0), $padCnt); # pad line
  390. break 3;
  391. case 2: # DELTA
  392. $i += 2;
  393. break;
  394. default: # ABSOLUTE MODE
  395. $num = ord($str[$i]);
  396. for ($j = 0; $j < $num; $j++)
  397. $out .= $str[++$i];
  398. if ($num % 2) $i++;
  399. }
  400. break;
  401. default:
  402. $out .= str_repeat($str[++$i], $o);
  403. }
  404. }
  405. return $out;
  406. }
  407. /**
  408. * Decoder for RLE4 compression in windows bitmaps
  409. * see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp
  410. *
  411. * @param string $str Data to decode
  412. * @param integer $width Image width
  413. *
  414. * @return string
  415. */
  416. function rle4_decode ($str, $width) {
  417. $w = floor($width/2) + ($width % 2);
  418. $lineWidth = $w + (3 - ( ($width-1) / 2) % 4);
  419. $pixels = array();
  420. $cnt = strlen($str);
  421. $c = 0;
  422. for ($i = 0; $i < $cnt; $i++) {
  423. $o = ord($str[$i]);
  424. switch ($o) {
  425. case 0: # ESCAPE
  426. $i++;
  427. switch (ord($str[$i])){
  428. case 0: # NEW LINE
  429. while (count($pixels)%$lineWidth != 0) {
  430. $pixels[] = 0;
  431. }
  432. break;
  433. case 1: # END OF FILE
  434. while (count($pixels)%$lineWidth != 0) {
  435. $pixels[] = 0;
  436. }
  437. break 3;
  438. case 2: # DELTA
  439. $i += 2;
  440. break;
  441. default: # ABSOLUTE MODE
  442. $num = ord($str[$i]);
  443. for ($j = 0; $j < $num; $j++) {
  444. if ($j%2 == 0) {
  445. $c = ord($str[++$i]);
  446. $pixels[] = ($c & 240)>>4;
  447. }
  448. else {
  449. $pixels[] = $c & 15;
  450. }
  451. }
  452. if ($num % 2 == 0) {
  453. $i++;
  454. }
  455. }
  456. break;
  457. default:
  458. $c = ord($str[++$i]);
  459. for ($j = 0; $j < $o; $j++) {
  460. $pixels[] = ($j%2==0 ? ($c & 240)>>4 : $c & 15);
  461. }
  462. }
  463. }
  464. $out = '';
  465. if (count($pixels)%2) {
  466. $pixels[] = 0;
  467. }
  468. $cnt = count($pixels)/2;
  469. for ($i = 0; $i < $cnt; $i++) {
  470. $out .= chr(16*$pixels[2*$i] + $pixels[2*$i+1]);
  471. }
  472. return $out;
  473. }
  474. if ( !function_exists("imagecreatefrombmp") ) {
  475. /**
  476. * Credit goes to mgutt
  477. * http://www.programmierer-forum.de/function-imagecreatefrombmp-welche-variante-laeuft-t143137.htm
  478. * Modified by Fabien Menager to support RGB555 BMP format
  479. */
  480. function imagecreatefrombmp($filename) {
  481. if (!function_exists("imagecreatetruecolor")) {
  482. trigger_error("The PHP GD extension is required, but is not installed.", E_ERROR);
  483. return false;
  484. }
  485. // version 1.00
  486. if (!($fh = fopen($filename, 'rb'))) {
  487. trigger_error('imagecreatefrombmp: Can not open ' . $filename, E_USER_WARNING);
  488. return false;
  489. }
  490. $bytes_read = 0;
  491. // read file header
  492. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
  493. // check for bitmap
  494. if ($meta['type'] != 19778) {
  495. trigger_error('imagecreatefrombmp: ' . $filename . ' is not a bitmap!', E_USER_WARNING);
  496. return false;
  497. }
  498. // read image header
  499. $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
  500. $bytes_read += 40;
  501. // read additional bitfield header
  502. if ($meta['compression'] == 3) {
  503. $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
  504. $bytes_read += 12;
  505. }
  506. // set bytes and padding
  507. $meta['bytes'] = $meta['bits'] / 8;
  508. $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4)- floor($meta['width'] * $meta['bytes'] / 4)));
  509. if ($meta['decal'] == 4) {
  510. $meta['decal'] = 0;
  511. }
  512. // obtain imagesize
  513. if ($meta['imagesize'] < 1) {
  514. $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
  515. // in rare cases filesize is equal to offset so we need to read physical size
  516. if ($meta['imagesize'] < 1) {
  517. $meta['imagesize'] = @filesize($filename) - $meta['offset'];
  518. if ($meta['imagesize'] < 1) {
  519. trigger_error('imagecreatefrombmp: Can not obtain filesize of ' . $filename . '!', E_USER_WARNING);
  520. return false;
  521. }
  522. }
  523. }
  524. // calculate colors
  525. $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
  526. // read color palette
  527. $palette = array();
  528. if ($meta['bits'] < 16) {
  529. $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
  530. // in rare cases the color value is signed
  531. if ($palette[1] < 0) {
  532. foreach ($palette as $i => $color) {
  533. $palette[$i] = $color + 16777216;
  534. }
  535. }
  536. }
  537. // ignore extra bitmap headers
  538. if ($meta['headersize'] > $bytes_read) {
  539. fread($fh, $meta['headersize'] - $bytes_read);
  540. }
  541. // create gd image
  542. $im = imagecreatetruecolor($meta['width'], $meta['height']);
  543. $data = fread($fh, $meta['imagesize']);
  544. // uncompress data
  545. switch ($meta['compression']) {
  546. case 1: $data = rle8_decode($data, $meta['width']); break;
  547. case 2: $data = rle4_decode($data, $meta['width']); break;
  548. }
  549. $p = 0;
  550. $vide = chr(0);
  551. $y = $meta['height'] - 1;
  552. $error = 'imagecreatefrombmp: ' . $filename . ' has not enough data!';
  553. // loop through the image data beginning with the lower left corner
  554. while ($y >= 0) {
  555. $x = 0;
  556. while ($x < $meta['width']) {
  557. switch ($meta['bits']) {
  558. case 32:
  559. case 24:
  560. if (!($part = substr($data, $p, 3 /*$meta['bytes']*/))) {
  561. trigger_error($error, E_USER_WARNING);
  562. return $im;
  563. }
  564. $color = unpack('V', $part . $vide);
  565. break;
  566. case 16:
  567. if (!($part = substr($data, $p, 2 /*$meta['bytes']*/))) {
  568. trigger_error($error, E_USER_WARNING);
  569. return $im;
  570. }
  571. $color = unpack('v', $part);
  572. if (empty($meta['rMask']) || $meta['rMask'] != 0xf800) {
  573. $color[1] = (($color[1] & 0x7c00) >> 7) * 65536 + (($color[1] & 0x03e0) >> 2) * 256 + (($color[1] & 0x001f) << 3); // 555
  574. }
  575. else {
  576. $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3); // 565
  577. }
  578. break;
  579. case 8:
  580. $color = unpack('n', $vide . substr($data, $p, 1));
  581. $color[1] = $palette[ $color[1] + 1 ];
  582. break;
  583. case 4:
  584. $color = unpack('n', $vide . substr($data, floor($p), 1));
  585. $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
  586. $color[1] = $palette[ $color[1] + 1 ];
  587. break;
  588. case 1:
  589. $color = unpack('n', $vide . substr($data, floor($p), 1));
  590. switch (($p * 8) % 8) {
  591. case 0: $color[1] = $color[1] >> 7; break;
  592. case 1: $color[1] = ($color[1] & 0x40) >> 6; break;
  593. case 2: $color[1] = ($color[1] & 0x20) >> 5; break;
  594. case 3: $color[1] = ($color[1] & 0x10) >> 4; break;
  595. case 4: $color[1] = ($color[1] & 0x8 ) >> 3; break;
  596. case 5: $color[1] = ($color[1] & 0x4 ) >> 2; break;
  597. case 6: $color[1] = ($color[1] & 0x2 ) >> 1; break;
  598. case 7: $color[1] = ($color[1] & 0x1 ); break;
  599. }
  600. $color[1] = $palette[ $color[1] + 1 ];
  601. break;
  602. default:
  603. trigger_error('imagecreatefrombmp: ' . $filename . ' has ' . $meta['bits'] . ' bits and this is not supported!', E_USER_WARNING);
  604. return false;
  605. }
  606. imagesetpixel($im, $x, $y, $color[1]);
  607. $x++;
  608. $p += $meta['bytes'];
  609. }
  610. $y--;
  611. $p += $meta['decal'];
  612. }
  613. fclose($fh);
  614. return $im;
  615. }
  616. }
  617. /**
  618. * getimagesize doesn't give a good size for 32bit BMP image v5
  619. *
  620. * @param string $filename
  621. * @return array The same format as getimagesize($filename)
  622. */
  623. function dompdf_getimagesize($filename) {
  624. static $cache = array();
  625. if ( isset($cache[$filename]) ) {
  626. return $cache[$filename];
  627. }
  628. list($width, $height, $type) = getimagesize($filename);
  629. if ( $width == null || $height == null ) {
  630. $data = file_get_contents($filename, null, null, 0, 26);
  631. if ( substr($data, 0, 2) === "BM" ) {
  632. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset/Vheadersize/Vwidth/Vheight', $data);
  633. $width = (int)$meta['width'];
  634. $height = (int)$meta['height'];
  635. $type = IMAGETYPE_BMP;
  636. }
  637. }
  638. return $cache[$filename] = array($width, $height, $type);
  639. }
  640. /**
  641. * Converts a CMYK color to RGB
  642. *
  643. * @param float|float[] $c
  644. * @param float $m
  645. * @param float $y
  646. * @param float $k
  647. *
  648. * @return float[]
  649. */
  650. function cmyk_to_rgb($c, $m = null, $y = null, $k = null) {
  651. if (is_array($c)) {
  652. list($c, $m, $y, $k) = $c;
  653. }
  654. $c *= 255;
  655. $m *= 255;
  656. $y *= 255;
  657. $k *= 255;
  658. $r = (1 - round(2.55 * ($c+$k))) ;
  659. $g = (1 - round(2.55 * ($m+$k))) ;
  660. $b = (1 - round(2.55 * ($y+$k))) ;
  661. if ($r < 0) $r = 0;
  662. if ($g < 0) $g = 0;
  663. if ($b < 0) $b = 0;
  664. return array(
  665. $r, $g, $b,
  666. "r" => $r, "g" => $g, "b" => $b
  667. );
  668. }
  669. function unichr($c) {
  670. if ($c <= 0x7F) {
  671. return chr($c);
  672. }
  673. else if ($c <= 0x7FF) {
  674. return chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F);
  675. }
  676. else if ($c <= 0xFFFF) {
  677. return chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F)
  678. . chr(0x80 | $c & 0x3F);
  679. }
  680. else if ($c <= 0x10FFFF) {
  681. return chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F)
  682. . chr(0x80 | $c >> 6 & 0x3F)
  683. . chr(0x80 | $c & 0x3F);
  684. }
  685. return false;
  686. }
  687. if ( !function_exists("date_default_timezone_get") ) {
  688. function date_default_timezone_get() {
  689. return "";
  690. }
  691. function date_default_timezone_set($timezone_identifier) {
  692. return true;
  693. }
  694. }
  695. /**
  696. * Stores warnings in an array for display later
  697. * This function allows warnings generated by the DomDocument parser
  698. * and CSS loader ({@link Stylesheet}) to be captured and displayed
  699. * later. Without this function, errors are displayed immediately and
  700. * PDF streaming is impossible.
  701. * @see http://www.php.net/manual/en/function.set-error_handler.php
  702. *
  703. * @param int $errno
  704. * @param string $errstr
  705. * @param string $errfile
  706. * @param string $errline
  707. *
  708. * @throws DOMPDF_Exception
  709. */
  710. function record_warnings($errno, $errstr, $errfile, $errline) {
  711. // Not a warning or notice
  712. if ( !($errno & (E_WARNING | E_NOTICE | E_USER_NOTICE | E_USER_WARNING )) ) {
  713. throw new DOMPDF_Exception($errstr . " $errno");
  714. }
  715. global $_dompdf_warnings;
  716. global $_dompdf_show_warnings;
  717. if ( $_dompdf_show_warnings ) {
  718. echo $errstr . "\n";
  719. }
  720. $_dompdf_warnings[] = $errstr;
  721. }
  722. /**
  723. * Print a useful backtrace
  724. */
  725. function bt() {
  726. if ( php_sapi_name() !== "cli") {
  727. echo "<pre>";
  728. }
  729. $bt = debug_backtrace();
  730. array_shift($bt); // remove actual bt() call
  731. echo "\n";
  732. $i = 0;
  733. foreach ($bt as $call) {
  734. $file = basename($call["file"]) . " (" . $call["line"] . ")";
  735. if ( isset($call["class"]) ) {
  736. $func = $call["class"] . "->" . $call["function"] . "()";
  737. }
  738. else {
  739. $func = $call["function"] . "()";
  740. }
  741. echo "#" . str_pad($i, 2, " ", STR_PAD_RIGHT) . ": " . str_pad($file.":", 42) . " $func\n";
  742. $i++;
  743. }
  744. echo "\n";
  745. if ( php_sapi_name() !== "cli") {
  746. echo "</pre>";
  747. }
  748. }
  749. /**
  750. * Print debug messages
  751. *
  752. * @param string $type The type of debug messages to print
  753. * @param string $msg The message to show
  754. */
  755. function dompdf_debug($type, $msg) {
  756. global $_DOMPDF_DEBUG_TYPES, $_dompdf_show_warnings, $_dompdf_debug;
  757. if ( isset($_DOMPDF_DEBUG_TYPES[$type]) && ($_dompdf_show_warnings || $_dompdf_debug) ) {
  758. $arr = debug_backtrace();
  759. echo basename($arr[0]["file"]) . " (" . $arr[0]["line"] ."): " . $arr[1]["function"] . ": ";
  760. pre_r($msg);
  761. }
  762. }
  763. if ( !function_exists("print_memusage") ) {
  764. /**
  765. * Dump memory usage
  766. */
  767. function print_memusage() {
  768. global $memusage;
  769. echo "Memory Usage\n";
  770. $prev = 0;
  771. $initial = reset($memusage);
  772. echo str_pad("Initial:", 40) . $initial . "\n\n";
  773. foreach ($memusage as $key=>$mem) {
  774. $mem -= $initial;
  775. echo str_pad("$key:" , 40);
  776. echo str_pad("$mem", 12) . "(diff: " . ($mem - $prev) . ")\n";
  777. $prev = $mem;
  778. }
  779. echo "\n" . str_pad("Total:", 40) . memory_get_usage() . "\n";
  780. }
  781. }
  782. if ( !function_exists("enable_mem_profile") ) {
  783. /**
  784. * Initialize memory profiling code
  785. */
  786. function enable_mem_profile() {
  787. global $memusage;
  788. $memusage = array("Startup" => memory_get_usage());
  789. register_shutdown_function("print_memusage");
  790. }
  791. }
  792. if ( !function_exists("mark_memusage") ) {
  793. /**
  794. * Record the current memory usage
  795. *
  796. * @param string $location a meaningful location
  797. */
  798. function mark_memusage($location) {
  799. global $memusage;
  800. if ( isset($memusage) ) {
  801. $memusage[$location] = memory_get_usage();
  802. }
  803. }
  804. }
  805. if ( !function_exists('sys_get_temp_dir')) {
  806. /**
  807. * Find the current system temporary directory
  808. *
  809. * @link http://us.php.net/manual/en/function.sys-get-temp-dir.php#85261
  810. */
  811. function sys_get_temp_dir() {
  812. if (!empty($_ENV['TMP'])) {
  813. return realpath($_ENV['TMP']);
  814. }
  815. if (!empty($_ENV['TMPDIR'])) {
  816. return realpath( $_ENV['TMPDIR']);
  817. }
  818. if (!empty($_ENV['TEMP'])) {
  819. return realpath( $_ENV['TEMP']);
  820. }
  821. $tempfile=tempnam(uniqid(rand(), true), '');
  822. if (file_exists($tempfile)) {
  823. unlink($tempfile);
  824. return realpath(dirname($tempfile));
  825. }
  826. }
  827. }
  828. if ( function_exists("memory_get_peak_usage") ) {
  829. function DOMPDF_memory_usage(){
  830. return memory_get_peak_usage(true);
  831. }
  832. }
  833. else if ( function_exists("memory_get_usage") ) {
  834. function DOMPDF_memory_usage(){
  835. return memory_get_usage(true);
  836. }
  837. }
  838. else {
  839. function DOMPDF_memory_usage(){
  840. return "N/A";
  841. }
  842. }
  843. if ( function_exists("curl_init") ) {
  844. function DOMPDF_fetch_url($url, &$headers = null) {
  845. $ch = curl_init($url);
  846. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  847. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  848. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  849. curl_setopt($ch, CURLOPT_HEADER, true);
  850. $data = curl_exec($ch);
  851. $raw_headers = substr($data, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
  852. $headers = preg_split("/[\n\r]+/", trim($raw_headers));
  853. $data = substr($data, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
  854. curl_close($ch);
  855. return $data;
  856. }
  857. }
  858. else {
  859. function DOMPDF_fetch_url($url, &$headers = null) {
  860. $data = file_get_contents($url);
  861. $headers = $http_response_header;
  862. return $data;
  863. }
  864. }
  865. /**
  866. * Affect null to the unused objects
  867. * @param mixed $object
  868. */
  869. if ( PHP_VERSION_ID < 50300 ) {
  870. function clear_object(&$object) {
  871. if ( is_object($object) ) {
  872. foreach ($object as &$value) {
  873. clear_object($value);
  874. }
  875. }
  876. $object = null;
  877. unset($object);
  878. }
  879. }
  880. else {
  881. function clear_object(&$object) {
  882. // void
  883. }
  884. }