source: trunk/filemanager/tp/dompdf/include/functions.inc.php @ 7655

Revision 7655, 15.1 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Melhorias de performance no codigo do Expresso.

Line 
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.digitaljunkies.ca/dompdf
32 *
33 * @link http://www.digitaljunkies.ca/dompdf
34 * @copyright 2004 Benj Carson
35 * @author Benj Carson <benjcarson@digitaljunkies.ca>
36 * @contributor Helmut Tischer <htischer@weihenstephan.org>
37 * @package dompdf
38 * @version 0.5.1
39 *
40 * Changes
41 * @contributor Helmut Tischer <htischer@weihenstephan.org>
42 * @version 0.5.1.htischer.20090507
43 * - trailing slash of base_path in build_url is no longer optional when
44 *   required. This allows paths not ending in a slash, e.g. on dynamically
45 *   created sites with page id in the url parameters.
46 * @version 20090601
47 * - fix windows paths
48 * @version 20090610
49 * - relax windows path syntax, use uniform path delimiter. Used for background images.
50 */
51
52/* $Id: functions.inc.php 187 2009-10-20 19:09:52Z eclecticgeek@gmail.com $ */
53
54/**
55 * print_r wrapper for html/cli output
56 *
57 * Wraps print_r() output in < pre > tags if the current sapi is not
58 * 'cli'.  Returns the output string instead of displaying it if $return is
59 * true.
60 *
61 * @param mixed $mixed variable or expression to display
62 * @param bool $return
63 *
64 */
65if ( !function_exists("pre_r") ) {
66function pre_r($mixed, $return = false) {
67  if ($return)
68    return "<pre>" . print_r($mixed, true) . "</pre>";
69
70  if ( php_sapi_name() != "cli")
71    echo ("<pre>");
72  print_r($mixed);
73
74  if ( php_sapi_name() != "cli")
75    echo("</pre>");
76  else
77    echo ("\n");
78  flush();
79
80}
81}
82
83/**
84 * var_dump wrapper for html/cli output
85 *
86 * Wraps var_dump() output in < pre > tags if the current sapi is not
87 * 'cli'.
88 *
89 * @param mixed $mixed variable or expression to display.
90 */
91if ( !function_exists("pre_var_dump") ) {
92function pre_var_dump($mixed) {
93  if ( php_sapi_name() != "cli")
94    echo("<pre>");
95  var_dump($mixed);
96  if ( php_sapi_name() != "cli")
97    echo("</pre>");
98}
99}
100
101/**
102 * builds a full url given a protocol, hostname, base path and url
103 *
104 * @param string $protocol
105 * @param string $host
106 * @param string $base_path
107 * @param string $url
108 * @return string
109 *
110 * Initially the trailing slash of $base_path was optional, and conditionally appended.
111 * However on dynamically created sites, where the page is given as url parameter,
112 * the base path might not end with an url.
113 * Therefore do not append a slash, and **require** the $base_url to ending in a slash
114 * when needed.
115 * Vice versa, on using the local file system path of a file, make sure that the slash
116 * is appended (o.k. also for Windows)
117 */
118function build_url($protocol, $host, $base_path, $url) {
119  if ( mb_strlen($url) == 0 ) {
120    //return $protocol . $host . rtrim($base_path, "/\\") . "/";
121    return $protocol . $host . $base_path;
122  }
123
124  // Is the url already fully qualified?
125  if ( mb_strpos($url, "://") !== false )
126    return $url;
127
128  $ret = $protocol;
129
130  if (!in_array(mb_strtolower($protocol), array("http://", "https://", "ftp://", "ftps://"))) {
131    //On Windows local file, an abs path can begin also with a '\' or a drive letter and colon
132    //drive: followed by a relative path would be a drive specific default folder.
133    //not known in php app code, treat as abs path
134    //($url{1} !== ':' || ($url{2}!=='\\' && $url{2}!=='/'))
135    if ($url{0} !== '/' && (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' || ($url{0} != '\\' && $url{1} !== ':'))) {
136      // For rel path and local acess we ignore the host, and run the path through realpath()
137      $ret .= dompdf_realpath($base_path).'/';
138    }
139    $ret .= $url;
140    return $ret;
141  }
142
143  //remote urls with backslash in html/css are not really correct, but lets be genereous
144  if ( $url{0} === '/' || $url{0} === '\\' ) {
145    // Absolute path
146    $ret .= $host . $url;
147  } else {
148    // Relative path
149    //$base_path = $base_path !== "" ? rtrim($base_path, "/\\") . "/" : "";
150    $ret .= $host . $base_path . $url;
151  }
152
153  return $ret;
154
155}
156
157/**
158 * parse a full url or pathname and return an array(protocol, host, path,
159 * file + query + fragment)
160 *
161 * @param string $url
162 * @return array
163 */
164function explode_url($url) {
165  $protocol = "";
166  $host = "";
167  $path = "";
168  $file = "";
169
170  $arr = parse_url($url);
171
172  if ( isset($arr["scheme"]) &&
173       $arr["scheme"] != "file" &&
174       mb_strlen($arr["scheme"]) > 1 ) // Exclude windows drive letters...
175    {
176    $protocol = $arr["scheme"] . "://";
177
178    if ( isset($arr["user"]) ) {
179      $host .= $arr["user"];
180
181      if ( isset($arr["pass"]) )
182        $host .= "@" . $arr["pass"];
183
184      $host .= ":";
185    }
186
187    if ( isset($arr["host"]) )
188      $host .= $arr["host"];
189
190    if ( isset($arr["port"]) )
191      $host .= ":" . $arr["port"];
192
193    if ( isset($arr["path"]) && $arr["path"] !== "" ) {
194      // Do we have a trailing slash?
195      if ( $arr["path"]{ mb_strlen($arr["path"]) - 1 } == "/" ) {
196        $path = $arr["path"];
197        $file = "";
198      } else {
199        $path = dirname($arr["path"]) . "/";
200        $file = basename($arr["path"]);
201      }
202    }
203
204    if ( isset($arr["query"]) )
205      $file .= "?" . $arr["query"];
206
207    if ( isset($arr["fragment"]) )
208      $file .= "#" . $arr["fragment"];
209
210  } else {
211
212    $i = mb_strpos($url, "file://");
213    if ( $i !== false)
214      $url = mb_substr($url, $i + 7);
215
216    $protocol = ""; // "file://"; ? why doesn't this work... It's because of
217                    // network filenames like //COMPU/SHARENAME
218
219    $host = ""; // localhost, really
220    $file = basename($url);
221
222    $path = dirname($url);
223
224    // Check that the path exists
225    if ( $path !== false ) {
226      $path .= '/';
227
228    } else {
229      // generate a url to access the file if no real path found.
230      $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
231
232      $host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : php_uname("n");
233
234      if ( substr($arr["path"], 0, 1) == '/' ) {
235        $path = dirname($arr["path"]);
236      } else {
237        $path = '/' . rtrim(dirname($_SERVER["SCRIPT_NAME"]), '/') . '/' . $arr["path"];
238      }
239    }
240  }
241
242  $ret = array($protocol, $host, $path, $file,
243               "protocol" => $protocol,
244               "host" => $host,
245               "path" => $path,
246               "file" => $file);
247  return $ret;
248}
249
250/**
251 * converts decimal numbers to roman numerals
252 *
253 * @param int $num
254 * @return string
255 */
256function dec2roman($num) {
257
258  static $ones = array("", "i", "ii", "iii", "iv", "v",
259                       "vi", "vii", "viii", "ix");
260  static $tens = array("", "x", "xx", "xxx", "xl", "l",
261                       "lx", "lxx", "lxxx", "xc");
262  static $hund = array("", "c", "cc", "ccc", "cd", "d",
263                       "dc", "dcc", "dccc", "cm");
264  static $thou = array("", "m", "mm", "mmm");
265
266  if ( !is_numeric($num) )
267    throw new DOMPDF_Exception("dec2roman() requires a numeric argument.");
268
269  if ( $num > 4000 || $num < 0 )
270    return "(out of range)";
271
272  $num = strrev((string)$num);
273
274  $ret = "";
275  switch (mb_strlen($num)) {
276
277  case 4:
278    $ret .= $thou[$num{3}];
279
280  case 3:
281    $ret .= $hund[$num{2}];
282
283  case 2:
284    $ret .= $tens[$num{1}];
285
286  case 1:
287    $ret .= $ones[$num{0}];
288
289  default:
290    break;
291  }
292  return $ret;
293
294}
295
296/**
297 * Determines whether $value is a percentage or not
298 *
299 * @param float $value
300 * @return bool
301 */
302function is_percent($value) { return false !== mb_strpos($value, "%"); }
303
304/**
305 * Canonicalize a path without checking if the file exists
306 *
307 * @param  string $path The path to canonicalize
308 * @return string The canonical path, or null if the path is invalid (e.g. /../../foo)
309 */
310function dompdf_realpath($path) {
311  // If the path is relative, prepend the current directory
312  if ( strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ) {
313    if ( $path{0} == '/' || $path{0} == '\\' ) {
314      $path = substr(getcwd(),0,2) . $path;
315    } else if ($path{1} != ':' ) {
316      $path = getcwd() . DIRECTORY_SEPARATOR . $path;
317    }
318  } else if ($path{0} != '/') {
319    $path = getcwd() . DIRECTORY_SEPARATOR . $path;
320  }
321  $path = strtr( $path, DIRECTORY_SEPARATOR == "\\" ? "/" : DIRECTORY_SEPARATOR , DIRECTORY_SEPARATOR);
322
323  $parts = explode(DIRECTORY_SEPARATOR, $path);
324  $path = array();
325
326  $i = 0;
327  foreach ($parts as $dir) {
328
329    if ( $dir == "." )
330      continue;
331
332    if ( $dir == ".." ) {
333      $i--;
334      if ( $i < 0 )
335        $i = 0;
336
337      unset($path[$i]);
338      continue;
339    }
340
341    if ( $dir == "" )
342      continue;
343
344    $path[$i] = $dir;
345    ++$i;
346  }
347
348  return (DIRECTORY_SEPARATOR === '/' ? DIRECTORY_SEPARATOR : NULL) . join(DIRECTORY_SEPARATOR, $path);
349}
350
351/**
352 * mb_string compatibility
353 */
354
355if ( !function_exists("mb_convert_encoding") ) {
356  function mb_convert_encoding($data, $to_encoding, $from_encoding='UTF-8') {
357    if (str_replace('-', '', strtolower($to_encoding)) == 'utf8') {
358      return utf8_encode($data);
359    } else {
360      return utf8_decode($data);
361    }
362  }
363}
364
365if ( !function_exists("mb_detect_encoding") ) {
366  function mb_detect_encoding($data, $encoding_list=array('iso-8859-1'), $strict=false) {
367    return 'iso-8859-1';
368  }
369}
370
371if ( !function_exists("mb_internal_encoding") ) {
372  function mb_internal_encoding($encoding=NULL) {
373    if (isset($encoding)) {
374      return true;
375    } else {
376      return 'iso-8859-1';
377    }
378  }
379}
380
381if ( !function_exists("mb_strlen") ) {
382  function mb_strlen($str, $encoding='iso-8859-1') {
383    return strlen($str);
384  }
385}
386
387if ( !function_exists("mb_strpos") ) {
388  function mb_strpos($haystack, $needle, $offset = 0) {
389    return strpos($haystack, $needle, $offset);
390  }
391}
392
393if ( !function_exists("mb_strrpos") ) {
394  function mb_strrpos($haystack, $needle, $offset = 0) {
395    return strrpos($haystack, $needle, $offset);
396  }
397}
398
399if ( !function_exists("mb_strtolower") ) {
400  function mb_strtolower($str) {
401    return strtolower($str);
402  }
403}
404
405if ( !function_exists("mb_strtoupper") ) {
406  function mb_strtoupper($str) {
407    return strtoupper($str);
408  }
409}
410
411if ( !function_exists("mb_substr") ) {
412  function mb_substr($str, $start, $length=null, $encoding='iso-8859-1') {
413    if ( is_null($length) )
414      return substr($str, $start);
415    else
416      return substr($str, $start, $length);
417  }
418}
419
420if ( !function_exists("mb_substr_count") ) {
421  function mb_substr_count($haystack, $needle) {
422    return substr_count($haystack, $needle);
423  }
424}
425
426/**
427 * Stores warnings in an array for display later
428 *
429 * This function allows warnings generated by the DomDocument parser
430 * and CSS loader ({@link Stylesheet}) to be captured and displayed
431 * later.  Without this function, errors are displayed immediately and
432 * PDF streaming is impossible.
433 *
434 * @see http://www.php.net/manual/en/function.set-error_handler.php
435 *
436 * @param int $errno
437 * @param string $errstr
438 * @param string $errfile
439 * @param string $errline
440 */
441function record_warnings($errno, $errstr, $errfile, $errline) {
442
443  if ( !($errno & (E_WARNING | E_NOTICE | E_USER_NOTICE | E_USER_WARNING )) ) // Not a warning or notice
444    throw new DOMPDF_Exception($errstr . " $errno");
445
446  global $_dompdf_warnings;
447  global $_dompdf_show_warnings;
448
449  if ( $_dompdf_show_warnings )
450    echo $errstr . "\n";
451
452  $_dompdf_warnings[] = $errstr;
453}
454
455/**
456 * Print a useful backtrace
457 */
458function bt() {
459  $bt = debug_backtrace();
460
461  array_shift($bt); // remove actual bt() call
462  echo "\n";
463
464  $i = 0;
465  foreach ($bt as $call) {
466    $file = basename($call["file"]) . " (" . $call["line"] . ")";
467    if ( isset($call["class"]) ) {
468      $func = $call["class"] . "->" . $call["function"] . "()";
469    } else {
470      $func = $call["function"] . "()";
471    }
472
473    echo "#" . str_pad($i, 2, " ", STR_PAD_RIGHT) . ": " . str_pad($file.":", 42) . " $func\n";
474    ++$i;
475  }
476  echo "\n";
477}
478
479/**
480 * Print debug messages
481 *
482 * @param string $type  The type of debug messages to print
483 */
484function dompdf_debug($type, $msg) {
485  global $_DOMPDF_DEBUG_TYPES;
486  global $_dompdf_show_warnings;
487  global $_dompdf_debug;
488  if ( isset($_DOMPDF_DEBUG_TYPES[$type]) && ($_dompdf_show_warnings || $_dompdf_debug) ) {
489    $arr = debug_backtrace();
490
491    echo basename($arr[0]["file"]) . " (" . $arr[0]["line"] ."): " . $arr[1]["function"] . ": ";
492    pre_r($msg);
493  }
494}
495
496/**
497 * Dump memory usage
498 */
499if ( !function_exists("print_memusage") ) {
500function print_memusage() {
501  global $memusage;
502  echo ("Memory Usage\n");
503  $prev = 0;
504  $initial = reset($memusage);
505  echo (str_pad("Initial:", 40) . $initial . "\n\n");
506
507  foreach ($memusage as $key=>$mem) {
508    $mem -= $initial;
509    echo (str_pad("$key:" , 40));
510    echo (str_pad("$mem", 12) . "(diff: " . ($mem - $prev) . ")\n");
511    $prev = $mem;
512  }
513
514  echo ("\n" . str_pad("Total:", 40) . memory_get_usage()) . "\n";
515}
516}
517
518/**
519 * Initialize memory profiling code
520 */
521if ( !function_exists("enable_mem_profile") ) {
522function enable_mem_profile() {
523    global $memusage;
524    $memusage = array("Startup" => memory_get_usage());
525    register_shutdown_function("print_memusage");
526}
527}
528
529/**
530 * Record the current memory usage
531 *
532 * @param string $location a meaningful location
533 */
534if ( !function_exists("mark_memusage") ) {
535function mark_memusage($location) {
536  global $memusage;
537  if ( isset($memusage) )
538    $memusage[$location] = memory_get_usage();
539}
540}
541
542/**
543 * Find the current system temporary directory
544 *
545 * @link http://us.php.net/manual/en/function.sys-get-temp-dir.php#85261
546 */
547if ( !function_exists('sys_get_temp_dir')) {
548  function sys_get_temp_dir() {
549    if (!empty($_ENV['TMP'])) { return realpath($_ENV['TMP']); }
550    if (!empty($_ENV['TMPDIR'])) { return realpath( $_ENV['TMPDIR']); }
551    if (!empty($_ENV['TEMP'])) { return realpath( $_ENV['TEMP']); }
552    $tempfile=tempnam(uniqid(rand(),TRUE),'');
553    if (file_exists($tempfile)) {
554    unlink($tempfile);
555    return realpath(dirname($tempfile));
556    }
557  }
558}
559?>
Note: See TracBrowser for help on using the repository browser.