PageRenderTime 69ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/smartpdf/code/include/functions.inc.php

https://bitbucket.org/1blankz7/bibioteka
PHP | 856 lines | 552 code | 110 blank | 194 comment | 133 complexity | 65826c1cbd9c69ed4dac1f1b66249aad MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * DOMPDF - PHP5 HTML to PDF renderer
  4. *
  5. * File: $RCSfile: functions.inc.php,v $
  6. * Created on: 2004-08-04
  7. *
  8. * Copyright (c) 2004 - Benj Carson <benjcarson@digitaljunkies.ca>
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public License
  21. * along with this library in the file LICENSE.LGPL; if not, write to the
  22. * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  23. * 02111-1307 USA
  24. *
  25. * Alternatively, you may distribute this software under the terms of the
  26. * PHP License, version 3.0 or later. A copy of this license should have
  27. * been distributed with this file in the file LICENSE.PHP . If this is not
  28. * the case, you can obtain a copy at http://www.php.net/license/3_0.txt.
  29. *
  30. * The latest version of DOMPDF might be available at:
  31. * http://www.dompdf.com/
  32. *
  33. * @link http://www.dompdf.com/
  34. * @copyright 2004 Benj Carson
  35. * @author Benj Carson <benjcarson@digitaljunkies.ca>
  36. * @contributor Helmut Tischer <htischer@weihenstephan.org>
  37. * @package dompdf
  38. *
  39. * Changes
  40. * @contributor Helmut Tischer <htischer@weihenstephan.org>
  41. * @version 0.5.1.htischer.20090507
  42. * - trailing slash of base_path in build_url is no longer optional when
  43. * required. This allows paths not ending in a slash, e.g. on dynamically
  44. * created sites with page id in the url parameters.
  45. * @version 20090601
  46. * - fix windows paths
  47. * @version 20090610
  48. * - relax windows path syntax, use uniform path delimiter. Used for background images.
  49. */
  50. /* $Id: functions.inc.php 313 2010-09-10 16:18:44Z fabien.menager $ */
  51. function def($name, $value = true) {
  52. if (!defined($name)) {
  53. define($name, $value);
  54. }
  55. }
  56. /**
  57. * print_r wrapper for html/cli output
  58. *
  59. * Wraps print_r() output in < pre > tags if the current sapi is not
  60. * 'cli'. Returns the output string instead of displaying it if $return is
  61. * true.
  62. *
  63. * @param mixed $mixed variable or expression to display
  64. * @param bool $return
  65. *
  66. */
  67. if ( !function_exists("pre_r") ) {
  68. function pre_r($mixed, $return = false) {
  69. if ($return)
  70. return "<pre>" . print_r($mixed, true) . "</pre>";
  71. if ( php_sapi_name() !== "cli")
  72. echo ("<pre>");
  73. print_r($mixed);
  74. if ( php_sapi_name() !== "cli")
  75. echo("</pre>");
  76. else
  77. echo ("\n");
  78. flush();
  79. }
  80. }
  81. /**
  82. * var_dump wrapper for html/cli output
  83. *
  84. * Wraps var_dump() output in < pre > tags if the current sapi is not
  85. * 'cli'.
  86. *
  87. * @param mixed $mixed variable or expression to display.
  88. */
  89. if ( !function_exists("pre_var_dump") ) {
  90. function pre_var_dump($mixed) {
  91. if ( php_sapi_name() !== "cli")
  92. echo("<pre>");
  93. var_dump($mixed);
  94. if ( php_sapi_name() !== "cli")
  95. echo("</pre>");
  96. }
  97. }
  98. /**
  99. * builds a full url given a protocol, hostname, base path and url
  100. *
  101. * @param string $protocol
  102. * @param string $host
  103. * @param string $base_path
  104. * @param string $url
  105. * @return string
  106. *
  107. * Initially the trailing slash of $base_path was optional, and conditionally appended.
  108. * However on dynamically created sites, where the page is given as url parameter,
  109. * the base path might not end with an url.
  110. * Therefore do not append a slash, and **require** the $base_url to ending in a slash
  111. * when needed.
  112. * Vice versa, on using the local file system path of a file, make sure that the slash
  113. * is appended (o.k. also for Windows)
  114. */
  115. function build_url($protocol, $host, $base_path, $url) {
  116. if ( mb_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. $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. } else {
  142. // Relative path
  143. //$base_path = $base_path !== "" ? rtrim($base_path, "/\\") . "/" : "";
  144. $ret .= $host . $base_path . $url;
  145. }
  146. return $ret;
  147. }
  148. /**
  149. * parse a full url or pathname and return an array(protocol, host, path,
  150. * file + query + fragment)
  151. *
  152. * @param string $url
  153. * @return array
  154. */
  155. function explode_url($url) {
  156. $protocol = "";
  157. $host = "";
  158. $path = "";
  159. $file = "";
  160. $arr = parse_url($url);
  161. if ( isset($arr["scheme"]) &&
  162. $arr["scheme"] !== "file" &&
  163. mb_strlen($arr["scheme"]) > 1 ) // Exclude windows drive letters...
  164. {
  165. $protocol = $arr["scheme"] . "://";
  166. if ( isset($arr["user"]) ) {
  167. $host .= $arr["user"];
  168. if ( isset($arr["pass"]) )
  169. $host .= "@" . $arr["pass"];
  170. $host .= ":";
  171. }
  172. if ( isset($arr["host"]) )
  173. $host .= $arr["host"];
  174. if ( isset($arr["port"]) )
  175. $host .= ":" . $arr["port"];
  176. if ( isset($arr["path"]) && $arr["path"] !== "" ) {
  177. // Do we have a trailing slash?
  178. if ( $arr["path"]{ mb_strlen($arr["path"]) - 1 } === "/" ) {
  179. $path = $arr["path"];
  180. $file = "";
  181. } else {
  182. $path = dirname($arr["path"]) . "/";
  183. $file = basename($arr["path"]);
  184. }
  185. }
  186. if ( isset($arr["query"]) )
  187. $file .= "?" . $arr["query"];
  188. if ( isset($arr["fragment"]) )
  189. $file .= "#" . $arr["fragment"];
  190. } else {
  191. $i = mb_strpos($url, "file://");
  192. if ( $i !== false)
  193. $url = mb_substr($url, $i + 7);
  194. $protocol = ""; // "file://"; ? why doesn't this work... It's because of
  195. // network filenames like //COMPU/SHARENAME
  196. $host = ""; // localhost, really
  197. $file = basename($url);
  198. $path = dirname($url);
  199. // Check that the path exists
  200. if ( $path !== false ) {
  201. $path .= '/';
  202. } else {
  203. // generate a url to access the file if no real path found.
  204. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
  205. $host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : php_uname("n");
  206. if ( substr($arr["path"], 0, 1) === '/' ) {
  207. $path = dirname($arr["path"]);
  208. } else {
  209. $path = '/' . rtrim(dirname($_SERVER["SCRIPT_NAME"]), '/') . '/' . $arr["path"];
  210. }
  211. }
  212. }
  213. $ret = array($protocol, $host, $path, $file,
  214. "protocol" => $protocol,
  215. "host" => $host,
  216. "path" => $path,
  217. "file" => $file);
  218. return $ret;
  219. }
  220. /**
  221. * converts decimal numbers to roman numerals
  222. *
  223. * @param int $num
  224. * @return string
  225. */
  226. function dec2roman($num) {
  227. static $ones = array("", "i", "ii", "iii", "iv", "v",
  228. "vi", "vii", "viii", "ix");
  229. static $tens = array("", "x", "xx", "xxx", "xl", "l",
  230. "lx", "lxx", "lxxx", "xc");
  231. static $hund = array("", "c", "cc", "ccc", "cd", "d",
  232. "dc", "dcc", "dccc", "cm");
  233. static $thou = array("", "m", "mm", "mmm");
  234. if ( !is_numeric($num) )
  235. throw new DOMPDF_Exception("dec2roman() requires a numeric argument.");
  236. if ( $num > 4000 || $num < 0 )
  237. return "(out of range)";
  238. $num = strrev((string)$num);
  239. $ret = "";
  240. switch (mb_strlen($num)) {
  241. case 4:
  242. $ret .= $thou[$num[3]];
  243. case 3:
  244. $ret .= $hund[$num[2]];
  245. case 2:
  246. $ret .= $tens[$num[1]];
  247. case 1:
  248. $ret .= $ones[$num[0]];
  249. default:
  250. break;
  251. }
  252. return $ret;
  253. }
  254. /**
  255. * Determines whether $value is a percentage or not
  256. *
  257. * @param float $value
  258. * @return bool
  259. */
  260. function is_percent($value) { return false !== mb_strpos($value, "%"); }
  261. function parse_data_uri($data_uri) {
  262. if (!preg_match('/^data:(?P<mime>[a-z0-9\/+-.]+)(;charset=(?P<charset>[a-z0-9-])+)?(?P<base64>;base64)?\,(?P<data>.*)?/i', $data_uri, $match)) {
  263. return false;
  264. }
  265. $match['data'] = urldecode($match['data']);
  266. $result = array(
  267. 'charset' => $match['charset'] ? $match['charset'] : 'US-ASCII',
  268. 'mime' => $match['mime'] ? $match['mime'] : 'text/plain',
  269. 'data' => $match['base64'] ? base64_decode($match['data']) : $match['data'],
  270. );
  271. return $result;
  272. }
  273. /**
  274. * mb_string compatibility
  275. */
  276. if ( !function_exists("mb_convert_encoding") ) {
  277. function mb_convert_encoding($data, $to_encoding, $from_encoding='UTF-8') {
  278. if (str_replace('-', '', strtolower($to_encoding)) == 'utf8') {
  279. return utf8_encode($data);
  280. } else {
  281. return utf8_decode($data);
  282. }
  283. }
  284. }
  285. if ( !function_exists("mb_detect_encoding") ) {
  286. function mb_detect_encoding($data, $encoding_list=array('iso-8859-1'), $strict=false) {
  287. return 'iso-8859-1';
  288. }
  289. }
  290. if ( !function_exists("mb_detect_order") ) {
  291. function mb_detect_order($encoding_list=array('iso-8859-1')) {
  292. return 'iso-8859-1';
  293. }
  294. }
  295. if ( !function_exists("mb_internal_encoding") ) {
  296. function mb_internal_encoding($encoding=NULL) {
  297. if (isset($encoding)) {
  298. return true;
  299. } else {
  300. return 'iso-8859-1';
  301. }
  302. }
  303. }
  304. if ( !function_exists("mb_strlen") ) {
  305. function mb_strlen($str, $encoding='iso-8859-1') {
  306. if (str_replace('-', '', strtolower($encoding)) == 'utf8') {
  307. return strlen(utf8_encode($str));
  308. } else {
  309. return strlen(utf8_decode($str));
  310. }
  311. }
  312. }
  313. if ( !function_exists("mb_strpos") ) {
  314. function mb_strpos($haystack, $needle, $offset = 0) {
  315. return strpos($haystack, $needle, $offset);
  316. }
  317. }
  318. if ( !function_exists("mb_strrpos") ) {
  319. function mb_strrpos($haystack, $needle, $offset = 0) {
  320. return strrpos($haystack, $needle, $offset);
  321. }
  322. }
  323. if ( !function_exists("mb_strtolower") ) {
  324. function mb_strtolower($str) {
  325. return strtolower($str);
  326. }
  327. }
  328. if ( !function_exists("mb_strtoupper") ) {
  329. function mb_strtoupper($str) {
  330. return strtoupper($str);
  331. }
  332. }
  333. if ( !function_exists("mb_substr") ) {
  334. function mb_substr($str, $start, $length=null, $encoding='iso-8859-1') {
  335. if ( is_null($length) )
  336. return substr($str, $start);
  337. else
  338. return substr($str, $start, $length);
  339. }
  340. }
  341. if ( !function_exists("mb_substr_count") ) {
  342. function mb_substr_count($haystack, $needle) {
  343. return substr_count($haystack, $needle);
  344. }
  345. }
  346. # Decoder for RLE8 compression in windows bitmaps
  347. # see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp
  348. function rle8_decode ($str, $width){
  349. $lineWidth = $width + (3 - ($width-1) % 4);
  350. $out = '';
  351. $cnt = strlen($str);
  352. for ($i = 0; $i <$cnt; $i++) {
  353. $o = ord($str[$i]);
  354. switch ($o){
  355. case 0: # ESCAPE
  356. $i++;
  357. switch (ord($str[$i])){
  358. case 0: # NEW LINE
  359. $padCnt = $lineWidth - strlen($out)%$lineWidth;
  360. if ($padCnt<$lineWidth) $out .= str_repeat(chr(0), $padCnt); # pad line
  361. break;
  362. case 1: # END OF FILE
  363. $padCnt = $lineWidth - strlen($out)%$lineWidth;
  364. if ($padCnt<$lineWidth) $out .= str_repeat(chr(0), $padCnt); # pad line
  365. break 3;
  366. case 2: # DELTA
  367. $i += 2;
  368. break;
  369. default: # ABSOLUTE MODE
  370. $num = ord($str[$i]);
  371. for ($j = 0; $j < $num; $j++)
  372. $out .= $str[++$i];
  373. if ($num % 2) $i++;
  374. }
  375. break;
  376. default:
  377. $out .= str_repeat($str[++$i], $o);
  378. }
  379. }
  380. return $out;
  381. }
  382. # Decoder for RLE4 compression in windows bitmaps
  383. # see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp
  384. function rle4_decode ($str, $width) {
  385. $w = floor($width/2) + ($width % 2);
  386. $lineWidth = $w + (3 - ( ($width-1) / 2) % 4);
  387. $pixels = array();
  388. $cnt = strlen($str);
  389. for ($i = 0; $i < $cnt; $i++) {
  390. $o = ord($str[$i]);
  391. switch ($o) {
  392. case 0: # ESCAPE
  393. $i++;
  394. switch (ord($str[$i])){
  395. case 0: # NEW LINE
  396. while (count($pixels)%$lineWidth!=0)
  397. $pixels[]=0;
  398. break;
  399. case 1: # END OF FILE
  400. while (count($pixels)%$lineWidth!=0)
  401. $pixels[]=0;
  402. break 3;
  403. case 2: # DELTA
  404. $i += 2;
  405. break;
  406. default: # ABSOLUTE MODE
  407. $num = ord($str[$i]);
  408. for ($j = 0; $j < $num; $j++){
  409. if ($j%2 == 0){
  410. $c = ord($str[++$i]);
  411. $pixels[] = ($c & 240)>>4;
  412. } else
  413. $pixels[] = $c & 15;
  414. }
  415. if ($num % 2) $i++;
  416. }
  417. break;
  418. default:
  419. $c = ord($str[++$i]);
  420. for ($j = 0; $j < $o; $j++)
  421. $pixels[] = ($j%2==0 ? ($c & 240)>>4 : $c & 15);
  422. }
  423. }
  424. $out = '';
  425. if (count($pixels)%2) $pixels[]=0;
  426. $cnt = count($pixels)/2;
  427. for ($i = 0; $i < $cnt; $i++)
  428. $out .= chr(16*$pixels[2*$i] + $pixels[2*$i+1]);
  429. return $out;
  430. }
  431. /**
  432. * Credit goes to mgutt
  433. * http://www.programmierer-forum.de/function-imagecreatefrombmp-welche-variante-laeuft-t143137.htm
  434. * Modified by Fabien Ménager to support RGB555 BMP format
  435. */
  436. if ( !function_exists("imagecreatefrombmp") ) {
  437. function imagecreatefrombmp($filename) {
  438. try {
  439. // version 1.00
  440. if (!($fh = fopen($filename, 'rb'))) {
  441. trigger_error('imagecreatefrombmp: Can not open ' . $filename, E_USER_WARNING);
  442. return false;
  443. }
  444. // read file header
  445. $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
  446. // check for bitmap
  447. if ($meta['type'] != 19778) {
  448. trigger_error('imagecreatefrombmp: ' . $filename . ' is not a bitmap!', E_USER_WARNING);
  449. return false;
  450. }
  451. // read image header
  452. $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
  453. // read additional bitfield header
  454. if ($meta['compression'] == 3) {
  455. $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
  456. }
  457. //pre_r($filename);pre_r($meta);
  458. // set bytes and padding
  459. $meta['bytes'] = $meta['bits'] / 8;
  460. $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4)- floor($meta['width'] * $meta['bytes'] / 4)));
  461. if ($meta['decal'] == 4) {
  462. $meta['decal'] = 0;
  463. }
  464. // obtain imagesize
  465. if ($meta['imagesize'] < 1) {
  466. $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
  467. // in rare cases filesize is equal to offset so we need to read physical size
  468. if ($meta['imagesize'] < 1) {
  469. $meta['imagesize'] = @filesize($filename) - $meta['offset'];
  470. if ($meta['imagesize'] < 1) {
  471. trigger_error('imagecreatefrombmp: Can not obtain filesize of ' . $filename . '!', E_USER_WARNING);
  472. return false;
  473. }
  474. }
  475. }
  476. // calculate colors
  477. $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
  478. // read color palette
  479. $palette = array();
  480. if ($meta['bits'] < 16) {
  481. $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
  482. // in rare cases the color value is signed
  483. if ($palette[1] < 0) {
  484. foreach ($palette as $i => $color) {
  485. $palette[$i] = $color + 16777216;
  486. }
  487. }
  488. }
  489. // create gd image
  490. $im = imagecreatetruecolor($meta['width'], $meta['height']);
  491. $data = fread($fh, $meta['imagesize']);
  492. // uncompress data
  493. switch ($meta['compression']) {
  494. case 1: $data = rle8_decode($data, $meta['width']); break;
  495. case 2: $data = rle4_decode($data, $meta['width']); break;
  496. }
  497. $p = 0;
  498. $vide = chr(0);
  499. $y = $meta['height'] - 1;
  500. $error = 'imagecreatefrombmp: ' . $filename . ' has not enough data!';
  501. // loop through the image data beginning with the lower left corner
  502. while ($y >= 0) {
  503. $x = 0;
  504. while ($x < $meta['width']) {
  505. switch ($meta['bits']) {
  506. case 32:
  507. case 24:
  508. if (!($part = substr($data, $p, 3 /*$meta['bytes']*/))) {
  509. trigger_error($error, E_USER_WARNING);
  510. return $im;
  511. }
  512. $color = unpack('V', $part . $vide);
  513. break;
  514. case 16:
  515. if (!($part = substr($data, $p, 2 /*$meta['bytes']*/))) {
  516. trigger_error($error, E_USER_WARNING);
  517. return $im;
  518. }
  519. $color = unpack('v', $part);
  520. if (empty($meta['rMask']) || $meta['rMask'] != 0xf800)
  521. $color[1] = (($color[1] & 0x7c00) >> 7) * 65536 + (($color[1] & 0x03e0) >> 2) * 256 + (($color[1] & 0x001f) << 3); // 555
  522. else
  523. $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3); // 565
  524. break;
  525. case 8:
  526. $color = unpack('n', $vide . substr($data, $p, 1));
  527. $color[1] = $palette[ $color[1] + 1 ];
  528. break;
  529. case 4:
  530. $color = unpack('n', $vide . substr($data, floor($p), 1));
  531. $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
  532. $color[1] = $palette[ $color[1] + 1 ];
  533. break;
  534. case 1:
  535. $color = unpack('n', $vide . substr($data, floor($p), 1));
  536. switch (($p * 8) % 8) {
  537. case 0: $color[1] = $color[1] >> 7; break;
  538. case 1: $color[1] = ($color[1] & 0x40) >> 6; break;
  539. case 2: $color[1] = ($color[1] & 0x20) >> 5; break;
  540. case 3: $color[1] = ($color[1] & 0x10) >> 4; break;
  541. case 4: $color[1] = ($color[1] & 0x8 ) >> 3; break;
  542. case 5: $color[1] = ($color[1] & 0x4 ) >> 2; break;
  543. case 6: $color[1] = ($color[1] & 0x2 ) >> 1; break;
  544. case 7: $color[1] = ($color[1] & 0x1 ); break;
  545. }
  546. $color[1] = $palette[ $color[1] + 1 ];
  547. break;
  548. default:
  549. trigger_error('imagecreatefrombmp: ' . $filename . ' has ' . $meta['bits'] . ' bits and this is not supported!', E_USER_WARNING);
  550. return false;
  551. }
  552. imagesetpixel($im, $x, $y, $color[1]);
  553. $x++;
  554. $p += $meta['bytes'];
  555. }
  556. $y--;
  557. $p += $meta['decal'];
  558. }
  559. fclose($fh);
  560. return $im;
  561. } catch (Exception $e) {var_dump($e);}
  562. }
  563. }
  564. /**
  565. * @param int $c
  566. * @param int $m
  567. * @param int $y
  568. * @param int $k
  569. * @return object
  570. */
  571. function cmyk_to_rgb($c, $m = null, $y = null, $k = null) {
  572. if (is_array($c)) {
  573. list($c, $m, $y, $k) = $c;
  574. }
  575. $c *= 255;
  576. $m *= 255;
  577. $y *= 255;
  578. $k *= 255;
  579. $r = (1 - round(2.55 * ($c+$k))) ;
  580. $g = (1 - round(2.55 * ($m+$k))) ;
  581. $b = (1 - round(2.55 * ($y+$k))) ;
  582. if($r<0) $r = 0;
  583. if($g<0) $g = 0;
  584. if($b<0) $b = 0;
  585. return array(
  586. $r, $g, $b,
  587. "r" => $r, "g" => $g, "b" => $b
  588. );
  589. }
  590. function unichr($c) {
  591. if ($c <= 0x7F) {
  592. return chr($c);
  593. } else if ($c <= 0x7FF) {
  594. return chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F);
  595. } else if ($c <= 0xFFFF) {
  596. return chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F)
  597. . chr(0x80 | $c & 0x3F);
  598. } else if ($c <= 0x10FFFF) {
  599. return chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F)
  600. . chr(0x80 | $c >> 6 & 0x3F)
  601. . chr(0x80 | $c & 0x3F);
  602. }
  603. return false;
  604. }
  605. if ( !function_exists("date_default_timezone_get") ) {
  606. function date_default_timezone_get() {
  607. return "";
  608. }
  609. }
  610. if ( !function_exists("date_default_timezone_set") ) {
  611. function date_default_timezone_set($timezone_identifier) {
  612. return true;
  613. }
  614. }
  615. /**
  616. * Stores warnings in an array for display later
  617. *
  618. * This function allows warnings generated by the DomDocument parser
  619. * and CSS loader ({@link Stylesheet}) to be captured and displayed
  620. * later. Without this function, errors are displayed immediately and
  621. * PDF streaming is impossible.
  622. *
  623. * @see http://www.php.net/manual/en/function.set-error_handler.php
  624. *
  625. * @param int $errno
  626. * @param string $errstr
  627. * @param string $errfile
  628. * @param string $errline
  629. */
  630. function record_warnings($errno, $errstr, $errfile, $errline) {
  631. if ( !($errno & (E_WARNING | E_NOTICE | E_USER_NOTICE | E_USER_WARNING )) ) // Not a warning or notice
  632. throw new DOMPDF_Exception($errstr . " $errno");
  633. global $_dompdf_warnings;
  634. global $_dompdf_show_warnings;
  635. if ( $_dompdf_show_warnings )
  636. echo $errstr . "\n";
  637. $_dompdf_warnings[] = $errstr;
  638. }
  639. /**
  640. * Print a useful backtrace
  641. */
  642. function bt() {
  643. $bt = debug_backtrace();
  644. array_shift($bt); // remove actual bt() call
  645. echo "\n";
  646. $i = 0;
  647. foreach ($bt as $call) {
  648. $file = basename($call["file"]) . " (" . $call["line"] . ")";
  649. if ( isset($call["class"]) ) {
  650. $func = $call["class"] . "->" . $call["function"] . "()";
  651. } else {
  652. $func = $call["function"] . "()";
  653. }
  654. echo "#" . str_pad($i, 2, " ", STR_PAD_RIGHT) . ": " . str_pad($file.":", 42) . " $func\n";
  655. $i++;
  656. }
  657. echo "\n";
  658. }
  659. /**
  660. * Print debug messages
  661. *
  662. * @param string $type The type of debug messages to print
  663. */
  664. function dompdf_debug($type, $msg) {
  665. global $_DOMPDF_DEBUG_TYPES, $_dompdf_show_warnings, $_dompdf_debug;
  666. if ( isset($_DOMPDF_DEBUG_TYPES[$type]) && ($_dompdf_show_warnings || $_dompdf_debug) ) {
  667. $arr = debug_backtrace();
  668. echo basename($arr[0]["file"]) . " (" . $arr[0]["line"] ."): " . $arr[1]["function"] . ": ";
  669. pre_r($msg);
  670. }
  671. }
  672. /**
  673. * Dump memory usage
  674. */
  675. if ( !function_exists("print_memusage") ) {
  676. function print_memusage() {
  677. global $memusage;
  678. echo ("Memory Usage\n");
  679. $prev = 0;
  680. $initial = reset($memusage);
  681. echo (str_pad("Initial:", 40) . $initial . "\n\n");
  682. foreach ($memusage as $key=>$mem) {
  683. $mem -= $initial;
  684. echo (str_pad("$key:" , 40));
  685. echo (str_pad("$mem", 12) . "(diff: " . ($mem - $prev) . ")\n");
  686. $prev = $mem;
  687. }
  688. echo ("\n" . str_pad("Total:", 40) . memory_get_usage()) . "\n";
  689. }
  690. }
  691. /**
  692. * Initialize memory profiling code
  693. */
  694. if ( !function_exists("enable_mem_profile") ) {
  695. function enable_mem_profile() {
  696. global $memusage;
  697. $memusage = array("Startup" => memory_get_usage());
  698. register_shutdown_function("print_memusage");
  699. }
  700. }
  701. /**
  702. * Record the current memory usage
  703. *
  704. * @param string $location a meaningful location
  705. */
  706. if ( !function_exists("mark_memusage") ) {
  707. function mark_memusage($location) {
  708. global $memusage;
  709. if ( isset($memusage) )
  710. $memusage[$location] = memory_get_usage();
  711. }
  712. }
  713. /**
  714. * Find the current system temporary directory
  715. *
  716. * @link http://us.php.net/manual/en/function.sys-get-temp-dir.php#85261
  717. */
  718. if ( !function_exists('sys_get_temp_dir')) {
  719. function sys_get_temp_dir() {
  720. if (!empty($_ENV['TMP'])) { return realpath($_ENV['TMP']); }
  721. if (!empty($_ENV['TMPDIR'])) { return realpath( $_ENV['TMPDIR']); }
  722. if (!empty($_ENV['TEMP'])) { return realpath( $_ENV['TEMP']); }
  723. $tempfile=tempnam(uniqid(rand(),TRUE),'');
  724. if (file_exists($tempfile)) {
  725. unlink($tempfile);
  726. return realpath(dirname($tempfile));
  727. }
  728. }
  729. }
  730. /**
  731. * Affect null to the unused objects
  732. * @param unknown_type $object
  733. */
  734. function clear_object(&$object) {
  735. if ( is_object($object) ) {
  736. foreach (array_keys((array)$object) as $key) {
  737. clear_object($property);
  738. }
  739. foreach(get_class_vars(get_class($object)) as $property => $value) {
  740. clear_object($property);
  741. }
  742. }
  743. $object = null;
  744. unset($object);
  745. }