PageRenderTime 72ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/include/PHPExcel/Writer/PDF/include/functions.inc.php

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