functions.inc.php 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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. // version 1.00
  482. if (!($fh = fopen($filename, 'rb'))) {
  483. trigger_error('imagecreatefrombmp: Can not open ' . $filename, E_USER_WARNING);
  484. return false;
  485. }
  486. $bytes_read = 0;
  487. // read file header
  488. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
  489. // check for bitmap
  490. if ($meta['type'] != 19778) {
  491. trigger_error('imagecreatefrombmp: ' . $filename . ' is not a bitmap!', E_USER_WARNING);
  492. return false;
  493. }
  494. // read image header
  495. $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
  496. $bytes_read += 40;
  497. // read additional bitfield header
  498. if ($meta['compression'] == 3) {
  499. $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
  500. $bytes_read += 12;
  501. }
  502. // set bytes and padding
  503. $meta['bytes'] = $meta['bits'] / 8;
  504. $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4)- floor($meta['width'] * $meta['bytes'] / 4)));
  505. if ($meta['decal'] == 4) {
  506. $meta['decal'] = 0;
  507. }
  508. // obtain imagesize
  509. if ($meta['imagesize'] < 1) {
  510. $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
  511. // in rare cases filesize is equal to offset so we need to read physical size
  512. if ($meta['imagesize'] < 1) {
  513. $meta['imagesize'] = @filesize($filename) - $meta['offset'];
  514. if ($meta['imagesize'] < 1) {
  515. trigger_error('imagecreatefrombmp: Can not obtain filesize of ' . $filename . '!', E_USER_WARNING);
  516. return false;
  517. }
  518. }
  519. }
  520. // calculate colors
  521. $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
  522. // read color palette
  523. $palette = array();
  524. if ($meta['bits'] < 16) {
  525. $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
  526. // in rare cases the color value is signed
  527. if ($palette[1] < 0) {
  528. foreach ($palette as $i => $color) {
  529. $palette[$i] = $color + 16777216;
  530. }
  531. }
  532. }
  533. // ignore extra bitmap headers
  534. if ($meta['headersize'] > $bytes_read) {
  535. fread($fh, $meta['headersize'] - $bytes_read);
  536. }
  537. // create gd image
  538. $im = imagecreatetruecolor($meta['width'], $meta['height']);
  539. $data = fread($fh, $meta['imagesize']);
  540. // uncompress data
  541. switch ($meta['compression']) {
  542. case 1: $data = rle8_decode($data, $meta['width']); break;
  543. case 2: $data = rle4_decode($data, $meta['width']); break;
  544. }
  545. $p = 0;
  546. $vide = chr(0);
  547. $y = $meta['height'] - 1;
  548. $error = 'imagecreatefrombmp: ' . $filename . ' has not enough data!';
  549. // loop through the image data beginning with the lower left corner
  550. while ($y >= 0) {
  551. $x = 0;
  552. while ($x < $meta['width']) {
  553. switch ($meta['bits']) {
  554. case 32:
  555. case 24:
  556. if (!($part = substr($data, $p, 3 /*$meta['bytes']*/))) {
  557. trigger_error($error, E_USER_WARNING);
  558. return $im;
  559. }
  560. $color = unpack('V', $part . $vide);
  561. break;
  562. case 16:
  563. if (!($part = substr($data, $p, 2 /*$meta['bytes']*/))) {
  564. trigger_error($error, E_USER_WARNING);
  565. return $im;
  566. }
  567. $color = unpack('v', $part);
  568. if (empty($meta['rMask']) || $meta['rMask'] != 0xf800) {
  569. $color[1] = (($color[1] & 0x7c00) >> 7) * 65536 + (($color[1] & 0x03e0) >> 2) * 256 + (($color[1] & 0x001f) << 3); // 555
  570. }
  571. else {
  572. $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3); // 565
  573. }
  574. break;
  575. case 8:
  576. $color = unpack('n', $vide . substr($data, $p, 1));
  577. $color[1] = $palette[ $color[1] + 1 ];
  578. break;
  579. case 4:
  580. $color = unpack('n', $vide . substr($data, floor($p), 1));
  581. $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
  582. $color[1] = $palette[ $color[1] + 1 ];
  583. break;
  584. case 1:
  585. $color = unpack('n', $vide . substr($data, floor($p), 1));
  586. switch (($p * 8) % 8) {
  587. case 0: $color[1] = $color[1] >> 7; break;
  588. case 1: $color[1] = ($color[1] & 0x40) >> 6; break;
  589. case 2: $color[1] = ($color[1] & 0x20) >> 5; break;
  590. case 3: $color[1] = ($color[1] & 0x10) >> 4; break;
  591. case 4: $color[1] = ($color[1] & 0x8 ) >> 3; break;
  592. case 5: $color[1] = ($color[1] & 0x4 ) >> 2; break;
  593. case 6: $color[1] = ($color[1] & 0x2 ) >> 1; break;
  594. case 7: $color[1] = ($color[1] & 0x1 ); break;
  595. }
  596. $color[1] = $palette[ $color[1] + 1 ];
  597. break;
  598. default:
  599. trigger_error('imagecreatefrombmp: ' . $filename . ' has ' . $meta['bits'] . ' bits and this is not supported!', E_USER_WARNING);
  600. return false;
  601. }
  602. imagesetpixel($im, $x, $y, $color[1]);
  603. $x++;
  604. $p += $meta['bytes'];
  605. }
  606. $y--;
  607. $p += $meta['decal'];
  608. }
  609. fclose($fh);
  610. return $im;
  611. }
  612. }
  613. /**
  614. * getimagesize doesn't give a good size for 32bit BMP image v5
  615. *
  616. * @param string $filename
  617. * @return array The same format as getimagesize($filename)
  618. */
  619. function dompdf_getimagesize($filename) {
  620. static $cache = array();
  621. if ( isset($cache[$filename]) ) {
  622. return $cache[$filename];
  623. }
  624. list($width, $height, $type) = getimagesize($filename);
  625. if ( $width == null || $height == null ) {
  626. $data = file_get_contents($filename, null, null, 0, 26);
  627. if ( substr($data, 0, 2) === "BM" ) {
  628. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset/Vheadersize/Vwidth/Vheight', $data);
  629. $width = (int)$meta['width'];
  630. $height = (int)$meta['height'];
  631. $type = IMAGETYPE_BMP;
  632. }
  633. }
  634. return $cache[$filename] = array($width, $height, $type);
  635. }
  636. /**
  637. * Converts a CMYK color to RGB
  638. *
  639. * @param float|float[] $c
  640. * @param float $m
  641. * @param float $y
  642. * @param float $k
  643. *
  644. * @return float[]
  645. */
  646. function cmyk_to_rgb($c, $m = null, $y = null, $k = null) {
  647. if (is_array($c)) {
  648. list($c, $m, $y, $k) = $c;
  649. }
  650. $c *= 255;
  651. $m *= 255;
  652. $y *= 255;
  653. $k *= 255;
  654. $r = (1 - round(2.55 * ($c+$k))) ;
  655. $g = (1 - round(2.55 * ($m+$k))) ;
  656. $b = (1 - round(2.55 * ($y+$k))) ;
  657. if ($r < 0) $r = 0;
  658. if ($g < 0) $g = 0;
  659. if ($b < 0) $b = 0;
  660. return array(
  661. $r, $g, $b,
  662. "r" => $r, "g" => $g, "b" => $b
  663. );
  664. }
  665. function unichr($c) {
  666. if ($c <= 0x7F) {
  667. return chr($c);
  668. }
  669. else if ($c <= 0x7FF) {
  670. return chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F);
  671. }
  672. else if ($c <= 0xFFFF) {
  673. return chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F)
  674. . chr(0x80 | $c & 0x3F);
  675. }
  676. else if ($c <= 0x10FFFF) {
  677. return chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F)
  678. . chr(0x80 | $c >> 6 & 0x3F)
  679. . chr(0x80 | $c & 0x3F);
  680. }
  681. return false;
  682. }
  683. if ( !function_exists("date_default_timezone_get") ) {
  684. function date_default_timezone_get() {
  685. return "";
  686. }
  687. function date_default_timezone_set($timezone_identifier) {
  688. return true;
  689. }
  690. }
  691. /**
  692. * Stores warnings in an array for display later
  693. * This function allows warnings generated by the DomDocument parser
  694. * and CSS loader ({@link Stylesheet}) to be captured and displayed
  695. * later. Without this function, errors are displayed immediately and
  696. * PDF streaming is impossible.
  697. * @see http://www.php.net/manual/en/function.set-error_handler.php
  698. *
  699. * @param int $errno
  700. * @param string $errstr
  701. * @param string $errfile
  702. * @param string $errline
  703. *
  704. * @throws DOMPDF_Exception
  705. */
  706. function record_warnings($errno, $errstr, $errfile, $errline) {
  707. // Not a warning or notice
  708. if ( !($errno & (E_WARNING | E_NOTICE | E_USER_NOTICE | E_USER_WARNING )) ) {
  709. throw new DOMPDF_Exception($errstr . " $errno");
  710. }
  711. global $_dompdf_warnings;
  712. global $_dompdf_show_warnings;
  713. if ( $_dompdf_show_warnings ) {
  714. echo $errstr . "\n";
  715. }
  716. $_dompdf_warnings[] = $errstr;
  717. }
  718. /**
  719. * Print a useful backtrace
  720. */
  721. function bt() {
  722. if ( php_sapi_name() !== "cli") {
  723. echo "<pre>";
  724. }
  725. $bt = debug_backtrace();
  726. array_shift($bt); // remove actual bt() call
  727. echo "\n";
  728. $i = 0;
  729. foreach ($bt as $call) {
  730. $file = basename($call["file"]) . " (" . $call["line"] . ")";
  731. if ( isset($call["class"]) ) {
  732. $func = $call["class"] . "->" . $call["function"] . "()";
  733. }
  734. else {
  735. $func = $call["function"] . "()";
  736. }
  737. echo "#" . str_pad($i, 2, " ", STR_PAD_RIGHT) . ": " . str_pad($file.":", 42) . " $func\n";
  738. $i++;
  739. }
  740. echo "\n";
  741. if ( php_sapi_name() !== "cli") {
  742. echo "</pre>";
  743. }
  744. }
  745. /**
  746. * Print debug messages
  747. *
  748. * @param string $type The type of debug messages to print
  749. * @param string $msg The message to show
  750. */
  751. function dompdf_debug($type, $msg) {
  752. global $_DOMPDF_DEBUG_TYPES, $_dompdf_show_warnings, $_dompdf_debug;
  753. if ( isset($_DOMPDF_DEBUG_TYPES[$type]) && ($_dompdf_show_warnings || $_dompdf_debug) ) {
  754. $arr = debug_backtrace();
  755. echo basename($arr[0]["file"]) . " (" . $arr[0]["line"] ."): " . $arr[1]["function"] . ": ";
  756. pre_r($msg);
  757. }
  758. }
  759. if ( !function_exists("print_memusage") ) {
  760. /**
  761. * Dump memory usage
  762. */
  763. function print_memusage() {
  764. global $memusage;
  765. echo "Memory Usage\n";
  766. $prev = 0;
  767. $initial = reset($memusage);
  768. echo str_pad("Initial:", 40) . $initial . "\n\n";
  769. foreach ($memusage as $key=>$mem) {
  770. $mem -= $initial;
  771. echo str_pad("$key:" , 40);
  772. echo str_pad("$mem", 12) . "(diff: " . ($mem - $prev) . ")\n";
  773. $prev = $mem;
  774. }
  775. echo "\n" . str_pad("Total:", 40) . memory_get_usage() . "\n";
  776. }
  777. }
  778. if ( !function_exists("enable_mem_profile") ) {
  779. /**
  780. * Initialize memory profiling code
  781. */
  782. function enable_mem_profile() {
  783. global $memusage;
  784. $memusage = array("Startup" => memory_get_usage());
  785. register_shutdown_function("print_memusage");
  786. }
  787. }
  788. if ( !function_exists("mark_memusage") ) {
  789. /**
  790. * Record the current memory usage
  791. *
  792. * @param string $location a meaningful location
  793. */
  794. function mark_memusage($location) {
  795. global $memusage;
  796. if ( isset($memusage) ) {
  797. $memusage[$location] = memory_get_usage();
  798. }
  799. }
  800. }
  801. if ( !function_exists('sys_get_temp_dir')) {
  802. /**
  803. * Find the current system temporary directory
  804. *
  805. * @link http://us.php.net/manual/en/function.sys-get-temp-dir.php#85261
  806. */
  807. function sys_get_temp_dir() {
  808. if (!empty($_ENV['TMP'])) {
  809. return realpath($_ENV['TMP']);
  810. }
  811. if (!empty($_ENV['TMPDIR'])) {
  812. return realpath( $_ENV['TMPDIR']);
  813. }
  814. if (!empty($_ENV['TEMP'])) {
  815. return realpath( $_ENV['TEMP']);
  816. }
  817. $tempfile=tempnam(uniqid(rand(), true), '');
  818. if (file_exists($tempfile)) {
  819. unlink($tempfile);
  820. return realpath(dirname($tempfile));
  821. }
  822. }
  823. }
  824. if ( function_exists("memory_get_peak_usage") ) {
  825. function DOMPDF_memory_usage(){
  826. return memory_get_peak_usage(true);
  827. }
  828. }
  829. else if ( function_exists("memory_get_usage") ) {
  830. function DOMPDF_memory_usage(){
  831. return memory_get_usage(true);
  832. }
  833. }
  834. else {
  835. function DOMPDF_memory_usage(){
  836. return "N/A";
  837. }
  838. }
  839. if ( function_exists("curl_init") ) {
  840. function DOMPDF_fetch_url($url, &$headers = null) {
  841. $ch = curl_init($url);
  842. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  843. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  844. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  845. curl_setopt($ch, CURLOPT_HEADER, true);
  846. $data = curl_exec($ch);
  847. $raw_headers = substr($data, 0, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
  848. $headers = preg_split("/[\n\r]+/", trim($raw_headers));
  849. $data = substr($data, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
  850. curl_close($ch);
  851. return $data;
  852. }
  853. }
  854. else {
  855. function DOMPDF_fetch_url($url, &$headers = null) {
  856. $data = file_get_contents($url);
  857. $headers = $http_response_header;
  858. return $data;
  859. }
  860. }
  861. /**
  862. * Affect null to the unused objects
  863. * @param mixed $object
  864. */
  865. if ( PHP_VERSION_ID < 50300 ) {
  866. function clear_object(&$object) {
  867. if ( is_object($object) ) {
  868. foreach ($object as &$value) {
  869. clear_object($value);
  870. }
  871. }
  872. $object = null;
  873. unset($object);
  874. }
  875. }
  876. else {
  877. function clear_object(&$object) {
  878. // void
  879. }
  880. }