PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/dompdf/dompdf/include/functions.inc.php

https://github.com/TechGemIN/DomPDF-Boilerplate
PHP | 1054 lines | 720 code | 132 blank | 202 comment | 155 complexity | 12b77963b0ecd7dedad02e5825820323 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 (!extension_loaded('mbstring')) {
  293. def('MB_OVERLOAD_MAIL', 1);
  294. def('MB_OVERLOAD_STRING', 2);
  295. def('MB_OVERLOAD_REGEX', 4);
  296. def('MB_CASE_UPPER', 0);
  297. def('MB_CASE_LOWER', 1);
  298. def('MB_CASE_TITLE', 2);
  299. if (!function_exists('mb_convert_encoding')) {
  300. function mb_convert_encoding($data, $to_encoding, $from_encoding = 'UTF-8') {
  301. if (str_replace('-', '', strtolower($to_encoding)) === 'utf8') {
  302. return utf8_encode($data);
  303. }
  304. return utf8_decode($data);
  305. }
  306. }
  307. if (!function_exists('mb_detect_encoding')) {
  308. function mb_detect_encoding($data, $encoding_list = array('iso-8859-1'), $strict = false) {
  309. return 'iso-8859-1';
  310. }
  311. }
  312. if (!function_exists('mb_detect_order')) {
  313. function mb_detect_order($encoding_list = array('iso-8859-1')) {
  314. return 'iso-8859-1';
  315. }
  316. }
  317. if (!function_exists('mb_internal_encoding')) {
  318. function mb_internal_encoding($encoding = null) {
  319. if (isset($encoding)) {
  320. return true;
  321. }
  322. return 'iso-8859-1';
  323. }
  324. }
  325. if (!function_exists('mb_strlen')) {
  326. function mb_strlen($str, $encoding = 'iso-8859-1') {
  327. switch (str_replace('-', '', strtolower($encoding))) {
  328. case "utf8": return strlen(utf8_encode($str));
  329. case "8bit": return strlen($str);
  330. default: return strlen(utf8_decode($str));
  331. }
  332. }
  333. }
  334. if (!function_exists('mb_strpos')) {
  335. function mb_strpos($haystack, $needle, $offset = 0) {
  336. return strpos($haystack, $needle, $offset);
  337. }
  338. }
  339. if (!function_exists('mb_strrpos')) {
  340. function mb_strrpos($haystack, $needle, $offset = 0) {
  341. return strrpos($haystack, $needle, $offset);
  342. }
  343. }
  344. if (!function_exists('mb_strtolower')) {
  345. function mb_strtolower( $str ) {
  346. return strtolower($str);
  347. }
  348. }
  349. if (!function_exists('mb_strtoupper')) {
  350. function mb_strtoupper( $str ) {
  351. return strtoupper($str);
  352. }
  353. }
  354. if (!function_exists('mb_substr')) {
  355. function mb_substr($string, $start, $length = null, $encoding = 'iso-8859-1') {
  356. if ( is_null($length) ) {
  357. return substr($string, $start);
  358. }
  359. return substr($string, $start, $length);
  360. }
  361. }
  362. if (!function_exists('mb_substr_count')) {
  363. function mb_substr_count($haystack, $needle, $encoding = 'iso-8859-1') {
  364. return substr_count($haystack, $needle);
  365. }
  366. }
  367. if (!function_exists('mb_encode_numericentity')) {
  368. function mb_encode_numericentity($str, $convmap, $encoding) {
  369. return htmlspecialchars($str);
  370. }
  371. }
  372. if (!function_exists('mb_convert_case')) {
  373. function mb_convert_case($str, $mode = MB_CASE_UPPER, $encoding = array()) {
  374. switch($mode) {
  375. case MB_CASE_UPPER: return mb_strtoupper($str);
  376. case MB_CASE_LOWER: return mb_strtolower($str);
  377. case MB_CASE_TITLE: return ucwords(mb_strtolower($str));
  378. default: return $str;
  379. }
  380. }
  381. }
  382. if (!function_exists('mb_list_encodings')) {
  383. function mb_list_encodings() {
  384. return array(
  385. "ISO-8859-1",
  386. "UTF-8",
  387. "8bit",
  388. );
  389. }
  390. }
  391. }
  392. /**
  393. * Decoder for RLE8 compression in windows bitmaps
  394. * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp
  395. *
  396. * @param string $str Data to decode
  397. * @param integer $width Image width
  398. *
  399. * @return string
  400. */
  401. function rle8_decode ($str, $width){
  402. $lineWidth = $width + (3 - ($width-1) % 4);
  403. $out = '';
  404. $cnt = strlen($str);
  405. for ($i = 0; $i <$cnt; $i++) {
  406. $o = ord($str[$i]);
  407. switch ($o){
  408. case 0: # ESCAPE
  409. $i++;
  410. switch (ord($str[$i])){
  411. case 0: # NEW LINE
  412. $padCnt = $lineWidth - strlen($out)%$lineWidth;
  413. if ($padCnt<$lineWidth) $out .= str_repeat(chr(0), $padCnt); # pad line
  414. break;
  415. case 1: # END OF FILE
  416. $padCnt = $lineWidth - strlen($out)%$lineWidth;
  417. if ($padCnt<$lineWidth) $out .= str_repeat(chr(0), $padCnt); # pad line
  418. break 3;
  419. case 2: # DELTA
  420. $i += 2;
  421. break;
  422. default: # ABSOLUTE MODE
  423. $num = ord($str[$i]);
  424. for ($j = 0; $j < $num; $j++)
  425. $out .= $str[++$i];
  426. if ($num % 2) $i++;
  427. }
  428. break;
  429. default:
  430. $out .= str_repeat($str[++$i], $o);
  431. }
  432. }
  433. return $out;
  434. }
  435. /**
  436. * Decoder for RLE4 compression in windows bitmaps
  437. * see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp
  438. *
  439. * @param string $str Data to decode
  440. * @param integer $width Image width
  441. *
  442. * @return string
  443. */
  444. function rle4_decode ($str, $width) {
  445. $w = floor($width/2) + ($width % 2);
  446. $lineWidth = $w + (3 - ( ($width-1) / 2) % 4);
  447. $pixels = array();
  448. $cnt = strlen($str);
  449. $c = 0;
  450. for ($i = 0; $i < $cnt; $i++) {
  451. $o = ord($str[$i]);
  452. switch ($o) {
  453. case 0: # ESCAPE
  454. $i++;
  455. switch (ord($str[$i])){
  456. case 0: # NEW LINE
  457. while (count($pixels)%$lineWidth != 0) {
  458. $pixels[] = 0;
  459. }
  460. break;
  461. case 1: # END OF FILE
  462. while (count($pixels)%$lineWidth != 0) {
  463. $pixels[] = 0;
  464. }
  465. break 3;
  466. case 2: # DELTA
  467. $i += 2;
  468. break;
  469. default: # ABSOLUTE MODE
  470. $num = ord($str[$i]);
  471. for ($j = 0; $j < $num; $j++) {
  472. if ($j%2 == 0) {
  473. $c = ord($str[++$i]);
  474. $pixels[] = ($c & 240)>>4;
  475. }
  476. else {
  477. $pixels[] = $c & 15;
  478. }
  479. }
  480. if ($num % 2 == 0) {
  481. $i++;
  482. }
  483. }
  484. break;
  485. default:
  486. $c = ord($str[++$i]);
  487. for ($j = 0; $j < $o; $j++) {
  488. $pixels[] = ($j%2==0 ? ($c & 240)>>4 : $c & 15);
  489. }
  490. }
  491. }
  492. $out = '';
  493. if (count($pixels)%2) {
  494. $pixels[] = 0;
  495. }
  496. $cnt = count($pixels)/2;
  497. for ($i = 0; $i < $cnt; $i++) {
  498. $out .= chr(16*$pixels[2*$i] + $pixels[2*$i+1]);
  499. }
  500. return $out;
  501. }
  502. if ( !function_exists("imagecreatefrombmp") ) {
  503. /**
  504. * Credit goes to mgutt
  505. * http://www.programmierer-forum.de/function-imagecreatefrombmp-welche-variante-laeuft-t143137.htm
  506. * Modified by Fabien Menager to support RGB555 BMP format
  507. */
  508. function imagecreatefrombmp($filename) {
  509. if (!function_exists("imagecreatetruecolor")) {
  510. trigger_error("The PHP GD extension is required, but is not installed.", E_ERROR);
  511. return false;
  512. }
  513. // version 1.00
  514. if (!($fh = fopen($filename, 'rb'))) {
  515. trigger_error('imagecreatefrombmp: Can not open ' . $filename, E_USER_WARNING);
  516. return false;
  517. }
  518. $bytes_read = 0;
  519. // read file header
  520. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
  521. // check for bitmap
  522. if ($meta['type'] != 19778) {
  523. trigger_error('imagecreatefrombmp: ' . $filename . ' is not a bitmap!', E_USER_WARNING);
  524. return false;
  525. }
  526. // read image header
  527. $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
  528. $bytes_read += 40;
  529. // read additional bitfield header
  530. if ($meta['compression'] == 3) {
  531. $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
  532. $bytes_read += 12;
  533. }
  534. // set bytes and padding
  535. $meta['bytes'] = $meta['bits'] / 8;
  536. $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4)- floor($meta['width'] * $meta['bytes'] / 4)));
  537. if ($meta['decal'] == 4) {
  538. $meta['decal'] = 0;
  539. }
  540. // obtain imagesize
  541. if ($meta['imagesize'] < 1) {
  542. $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
  543. // in rare cases filesize is equal to offset so we need to read physical size
  544. if ($meta['imagesize'] < 1) {
  545. $meta['imagesize'] = @filesize($filename) - $meta['offset'];
  546. if ($meta['imagesize'] < 1) {
  547. trigger_error('imagecreatefrombmp: Can not obtain filesize of ' . $filename . '!', E_USER_WARNING);
  548. return false;
  549. }
  550. }
  551. }
  552. // calculate colors
  553. $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
  554. // read color palette
  555. $palette = array();
  556. if ($meta['bits'] < 16) {
  557. $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
  558. // in rare cases the color value is signed
  559. if ($palette[1] < 0) {
  560. foreach ($palette as $i => $color) {
  561. $palette[$i] = $color + 16777216;
  562. }
  563. }
  564. }
  565. // ignore extra bitmap headers
  566. if ($meta['headersize'] > $bytes_read) {
  567. fread($fh, $meta['headersize'] - $bytes_read);
  568. }
  569. // create gd image
  570. $im = imagecreatetruecolor($meta['width'], $meta['height']);
  571. $data = fread($fh, $meta['imagesize']);
  572. // uncompress data
  573. switch ($meta['compression']) {
  574. case 1: $data = rle8_decode($data, $meta['width']); break;
  575. case 2: $data = rle4_decode($data, $meta['width']); break;
  576. }
  577. $p = 0;
  578. $vide = chr(0);
  579. $y = $meta['height'] - 1;
  580. $error = 'imagecreatefrombmp: ' . $filename . ' has not enough data!';
  581. // loop through the image data beginning with the lower left corner
  582. while ($y >= 0) {
  583. $x = 0;
  584. while ($x < $meta['width']) {
  585. switch ($meta['bits']) {
  586. case 32:
  587. case 24:
  588. if (!($part = substr($data, $p, 3 /*$meta['bytes']*/))) {
  589. trigger_error($error, E_USER_WARNING);
  590. return $im;
  591. }
  592. $color = unpack('V', $part . $vide);
  593. break;
  594. case 16:
  595. if (!($part = substr($data, $p, 2 /*$meta['bytes']*/))) {
  596. trigger_error($error, E_USER_WARNING);
  597. return $im;
  598. }
  599. $color = unpack('v', $part);
  600. if (empty($meta['rMask']) || $meta['rMask'] != 0xf800) {
  601. $color[1] = (($color[1] & 0x7c00) >> 7) * 65536 + (($color[1] & 0x03e0) >> 2) * 256 + (($color[1] & 0x001f) << 3); // 555
  602. }
  603. else {
  604. $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3); // 565
  605. }
  606. break;
  607. case 8:
  608. $color = unpack('n', $vide . substr($data, $p, 1));
  609. $color[1] = $palette[ $color[1] + 1 ];
  610. break;
  611. case 4:
  612. $color = unpack('n', $vide . substr($data, floor($p), 1));
  613. $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
  614. $color[1] = $palette[ $color[1] + 1 ];
  615. break;
  616. case 1:
  617. $color = unpack('n', $vide . substr($data, floor($p), 1));
  618. switch (($p * 8) % 8) {
  619. case 0: $color[1] = $color[1] >> 7; break;
  620. case 1: $color[1] = ($color[1] & 0x40) >> 6; break;
  621. case 2: $color[1] = ($color[1] & 0x20) >> 5; break;
  622. case 3: $color[1] = ($color[1] & 0x10) >> 4; break;
  623. case 4: $color[1] = ($color[1] & 0x8 ) >> 3; break;
  624. case 5: $color[1] = ($color[1] & 0x4 ) >> 2; break;
  625. case 6: $color[1] = ($color[1] & 0x2 ) >> 1; break;
  626. case 7: $color[1] = ($color[1] & 0x1 ); break;
  627. }
  628. $color[1] = $palette[ $color[1] + 1 ];
  629. break;
  630. default:
  631. trigger_error('imagecreatefrombmp: ' . $filename . ' has ' . $meta['bits'] . ' bits and this is not supported!', E_USER_WARNING);
  632. return false;
  633. }
  634. imagesetpixel($im, $x, $y, $color[1]);
  635. $x++;
  636. $p += $meta['bytes'];
  637. }
  638. $y--;
  639. $p += $meta['decal'];
  640. }
  641. fclose($fh);
  642. return $im;
  643. }
  644. }
  645. /**
  646. * getimagesize doesn't give a good size for 32bit BMP image v5
  647. *
  648. * @param string $filename
  649. * @return array The same format as getimagesize($filename)
  650. */
  651. function dompdf_getimagesize($filename) {
  652. static $cache = array();
  653. if ( isset($cache[$filename]) ) {
  654. return $cache[$filename];
  655. }
  656. list($width, $height, $type) = getimagesize($filename);
  657. if ( $width == null || $height == null ) {
  658. $data = file_get_contents($filename, null, null, 0, 26);
  659. if ( substr($data, 0, 2) === "BM" ) {
  660. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset/Vheadersize/Vwidth/Vheight', $data);
  661. $width = (int)$meta['width'];
  662. $height = (int)$meta['height'];
  663. $type = IMAGETYPE_BMP;
  664. }
  665. }
  666. return $cache[$filename] = array($width, $height, $type);
  667. }
  668. /**
  669. * Converts a CMYK color to RGB
  670. *
  671. * @param float|float[] $c
  672. * @param float $m
  673. * @param float $y
  674. * @param float $k
  675. *
  676. * @return float[]
  677. */
  678. function cmyk_to_rgb($c, $m = null, $y = null, $k = null) {
  679. if (is_array($c)) {
  680. list($c, $m, $y, $k) = $c;
  681. }
  682. $c *= 255;
  683. $m *= 255;
  684. $y *= 255;
  685. $k *= 255;
  686. $r = (1 - round(2.55 * ($c+$k))) ;
  687. $g = (1 - round(2.55 * ($m+$k))) ;
  688. $b = (1 - round(2.55 * ($y+$k))) ;
  689. if ($r < 0) $r = 0;
  690. if ($g < 0) $g = 0;
  691. if ($b < 0) $b = 0;
  692. return array(
  693. $r, $g, $b,
  694. "r" => $r, "g" => $g, "b" => $b
  695. );
  696. }
  697. function unichr($c) {
  698. if ($c <= 0x7F) {
  699. return chr($c);
  700. }
  701. else if ($c <= 0x7FF) {
  702. return chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F);
  703. }
  704. else if ($c <= 0xFFFF) {
  705. return chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F)
  706. . chr(0x80 | $c & 0x3F);
  707. }
  708. else if ($c <= 0x10FFFF) {
  709. return chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F)
  710. . chr(0x80 | $c >> 6 & 0x3F)
  711. . chr(0x80 | $c & 0x3F);
  712. }
  713. return false;
  714. }
  715. if ( !function_exists("date_default_timezone_get") ) {
  716. function date_default_timezone_get() {
  717. return "";
  718. }
  719. function date_default_timezone_set($timezone_identifier) {
  720. return true;
  721. }
  722. }
  723. /**
  724. * Stores warnings in an array for display later
  725. * This function allows warnings generated by the DomDocument parser
  726. * and CSS loader ({@link Stylesheet}) to be captured and displayed
  727. * later. Without this function, errors are displayed immediately and
  728. * PDF streaming is impossible.
  729. * @see http://www.php.net/manual/en/function.set-error_handler.php
  730. *
  731. * @param int $errno
  732. * @param string $errstr
  733. * @param string $errfile
  734. * @param string $errline
  735. *
  736. * @throws DOMPDF_Exception
  737. */
  738. function record_warnings($errno, $errstr, $errfile, $errline) {
  739. // Not a warning or notice
  740. if ( !($errno & (E_WARNING | E_NOTICE | E_USER_NOTICE | E_USER_WARNING )) ) {
  741. throw new DOMPDF_Exception($errstr . " $errno");
  742. }
  743. global $_dompdf_warnings;
  744. global $_dompdf_show_warnings;
  745. if ( $_dompdf_show_warnings ) {
  746. echo $errstr . "\n";
  747. }
  748. $_dompdf_warnings[] = $errstr;
  749. }
  750. /**
  751. * Print a useful backtrace
  752. */
  753. function bt() {
  754. if ( php_sapi_name() !== "cli") {
  755. echo "<pre>";
  756. }
  757. $bt = debug_backtrace();
  758. array_shift($bt); // remove actual bt() call
  759. echo "\n";
  760. $i = 0;
  761. foreach ($bt as $call) {
  762. $file = basename($call["file"]) . " (" . $call["line"] . ")";
  763. if ( isset($call["class"]) ) {
  764. $func = $call["class"] . "->" . $call["function"] . "()";
  765. }
  766. else {
  767. $func = $call["function"] . "()";
  768. }
  769. echo "#" . str_pad($i, 2, " ", STR_PAD_RIGHT) . ": " . str_pad($file.":", 42) . " $func\n";
  770. $i++;
  771. }
  772. echo "\n";
  773. if ( php_sapi_name() !== "cli") {
  774. echo "</pre>";
  775. }
  776. }
  777. /**
  778. * Print debug messages
  779. *
  780. * @param string $type The type of debug messages to print
  781. * @param string $msg The message to show
  782. */
  783. function dompdf_debug($type, $msg) {
  784. global $_DOMPDF_DEBUG_TYPES, $_dompdf_show_warnings, $_dompdf_debug;
  785. if ( isset($_DOMPDF_DEBUG_TYPES[$type]) && ($_dompdf_show_warnings || $_dompdf_debug) ) {
  786. $arr = debug_backtrace();
  787. echo basename($arr[0]["file"]) . " (" . $arr[0]["line"] ."): " . $arr[1]["function"] . ": ";
  788. pre_r($msg);
  789. }
  790. }
  791. if ( !function_exists("print_memusage") ) {
  792. /**
  793. * Dump memory usage
  794. */
  795. function print_memusage() {
  796. global $memusage;
  797. echo "Memory Usage\n";
  798. $prev = 0;
  799. $initial = reset($memusage);
  800. echo str_pad("Initial:", 40) . $initial . "\n\n";
  801. foreach ($memusage as $key=>$mem) {
  802. $mem -= $initial;
  803. echo str_pad("$key:" , 40);
  804. echo str_pad("$mem", 12) . "(diff: " . ($mem - $prev) . ")\n";
  805. $prev = $mem;
  806. }
  807. echo "\n" . str_pad("Total:", 40) . memory_get_usage() . "\n";
  808. }
  809. }
  810. if ( !function_exists("enable_mem_profile") ) {
  811. /**
  812. * Initialize memory profiling code
  813. */
  814. function enable_mem_profile() {
  815. global $memusage;
  816. $memusage = array("Startup" => memory_get_usage());
  817. register_shutdown_function("print_memusage");
  818. }
  819. }
  820. if ( !function_exists("mark_memusage") ) {
  821. /**
  822. * Record the current memory usage
  823. *
  824. * @param string $location a meaningful location
  825. */
  826. function mark_memusage($location) {
  827. global $memusage;
  828. if ( isset($memusage) ) {
  829. $memusage[$location] = memory_get_usage();
  830. }
  831. }
  832. }
  833. if ( !function_exists('sys_get_temp_dir')) {
  834. /**
  835. * Find the current system temporary directory
  836. *
  837. * @link http://us.php.net/manual/en/function.sys-get-temp-dir.php#85261
  838. */
  839. function sys_get_temp_dir() {
  840. if (!empty($_ENV['TMP'])) {
  841. return realpath($_ENV['TMP']);
  842. }
  843. if (!empty($_ENV['TMPDIR'])) {
  844. return realpath( $_ENV['TMPDIR']);
  845. }
  846. if (!empty($_ENV['TEMP'])) {
  847. return realpath( $_ENV['TEMP']);
  848. }
  849. $tempfile=tempnam(uniqid(rand(), true), '');
  850. if (file_exists($tempfile)) {
  851. unlink($tempfile);
  852. return realpath(dirname($tempfile));
  853. }
  854. }
  855. }
  856. if ( function_exists("memory_get_peak_usage") ) {
  857. function DOMPDF_memory_usage(){
  858. return memory_get_peak_usage(true);
  859. }
  860. }
  861. else if ( function_exists("memory_get_usage") ) {
  862. function DOMPDF_memory_usage(){
  863. return memory_get_usage(true);
  864. }
  865. }
  866. else {
  867. function DOMPDF_memory_usage(){
  868. return "N/A";
  869. }
  870. }
  871. if ( function_exists("curl_init") ) {
  872. function DOMPDF_fetch_url($url, &$headers = null) {
  873. $ch = curl_init($url);
  874. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  875. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  876. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  877. curl_setopt($ch, CURLOPT_HEADER, true);
  878. $data = curl_exec($ch);
  879. $raw_headers = substr($data, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
  880. $headers = preg_split("/[\n\r]+/", trim($raw_headers));
  881. $data = substr($data, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
  882. curl_close($ch);
  883. return $data;
  884. }
  885. }
  886. else {
  887. function DOMPDF_fetch_url($url, &$headers = null) {
  888. $data = file_get_contents($url);
  889. $headers = $http_response_header;
  890. return $data;
  891. }
  892. }
  893. /**
  894. * Affect null to the unused objects
  895. * @param mixed $object
  896. */
  897. if ( PHP_VERSION_ID < 50300 ) {
  898. function clear_object(&$object) {
  899. if ( is_object($object) ) {
  900. foreach ($object as &$value) {
  901. clear_object($value);
  902. }
  903. }
  904. $object = null;
  905. unset($object);
  906. }
  907. }
  908. else {
  909. function clear_object(&$object) {
  910. // void
  911. }
  912. }