Ingen beskrivning

functions.inc.php 26KB

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