PageRenderTime 41ms CodeModel.GetById 3ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 0ms

/include/functions.inc.php

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