vendor/dompdf/dompdf/src/Helpers.php line 665

Open in your IDE?
  1. <?php
  2. namespace Dompdf;
  3. class Helpers
  4. {
  5.     /**
  6.      * print_r wrapper for html/cli output
  7.      *
  8.      * Wraps print_r() output in < pre > tags if the current sapi is not 'cli'.
  9.      * Returns the output string instead of displaying it if $return is true.
  10.      *
  11.      * @param mixed $mixed variable or expression to display
  12.      * @param bool $return
  13.      *
  14.      * @return string|null
  15.      */
  16.     public static function pre_r($mixed$return false)
  17.     {
  18.         if ($return) {
  19.             return "<pre>" print_r($mixedtrue) . "</pre>";
  20.         }
  21.         if (php_sapi_name() !== "cli") {
  22.             echo "<pre>";
  23.         }
  24.         print_r($mixed);
  25.         if (php_sapi_name() !== "cli") {
  26.             echo "</pre>";
  27.         } else {
  28.             echo "\n";
  29.         }
  30.         flush();
  31.         return null;
  32.     }
  33.     /**
  34.      * builds a full url given a protocol, hostname, base path and url
  35.      *
  36.      * @param string $protocol
  37.      * @param string $host
  38.      * @param string $base_path
  39.      * @param string $url
  40.      * @return string
  41.      *
  42.      * Initially the trailing slash of $base_path was optional, and conditionally appended.
  43.      * However on dynamically created sites, where the page is given as url parameter,
  44.      * the base path might not end with an url.
  45.      * Therefore do not append a slash, and **require** the $base_url to ending in a slash
  46.      * when needed.
  47.      * Vice versa, on using the local file system path of a file, make sure that the slash
  48.      * is appended (o.k. also for Windows)
  49.      */
  50.     public static function build_url($protocol$host$base_path$url)
  51.     {
  52.         $protocol mb_strtolower($protocol);
  53.         if (empty($protocol)) {
  54.             $protocol "file://";
  55.         }
  56.         if ($url === "") {
  57.             return null;
  58.         }
  59.         $url_lc mb_strtolower($url);
  60.         // Is the url already fully qualified, a Data URI, or a reference to a named anchor?
  61.         // File-protocol URLs may require additional processing (e.g. for URLs with a relative path)
  62.         if (
  63.             (
  64.                 mb_strpos($url_lc"://") !== false
  65.                 && !in_array(substr($url_lc07), ["file://""phar://"], true)
  66.             )
  67.             || mb_substr($url_lc01) === "#"
  68.             || mb_strpos($url_lc"data:") === 0
  69.             || mb_strpos($url_lc"mailto:") === 0
  70.             || mb_strpos($url_lc"tel:") === 0
  71.         ) {
  72.             return $url;
  73.         }
  74.         $res "";
  75.         if (strpos($url_lc"file://") === 0) {
  76.             $url substr($url7);
  77.             $protocol "file://";
  78.         } elseif (strpos($url_lc"phar://") === 0) {
  79.             $res substr($urlstrpos($url_lc".phar")+5);
  80.             $url substr($url7strpos($url_lc".phar")-2);
  81.             $protocol "phar://";
  82.         }
  83.         $ret "";
  84.         $is_local_path in_array($protocol, ["file://""phar://"], true);
  85.         if ($is_local_path) {
  86.             //On Windows local file, an abs path can begin also with a '\' or a drive letter and colon
  87.             //drive: followed by a relative path would be a drive specific default folder.
  88.             //not known in php app code, treat as abs path
  89.             //($url[1] !== ':' || ($url[2]!=='\\' && $url[2]!=='/'))
  90.             if ($url[0] !== '/' && (strtoupper(substr(PHP_OS03)) !== 'WIN' || (mb_strlen($url) > && $url[0] !== '\\' && $url[1] !== ':'))) {
  91.                 // For rel path and local access we ignore the host, and run the path through realpath()
  92.                 $ret .= realpath($base_path) . '/';
  93.             }
  94.             $ret .= $url;
  95.             $ret preg_replace('/\?(.*)$/'""$ret);
  96.             $filepath realpath($ret);
  97.             if ($filepath === false) {
  98.                 return null;
  99.             }
  100.             $ret "$protocol$filepath$res";
  101.             return $ret;
  102.         }
  103.         $ret $protocol;
  104.         // Protocol relative urls (e.g. "//example.org/style.css")
  105.         if (strpos($url'//') === 0) {
  106.             $ret .= substr($url2);
  107.             //remote urls with backslash in html/css are not really correct, but lets be genereous
  108.         } elseif ($url[0] === '/' || $url[0] === '\\') {
  109.             // Absolute path
  110.             $ret .= $host $url;
  111.         } else {
  112.             // Relative path
  113.             //$base_path = $base_path !== "" ? rtrim($base_path, "/\\") . "/" : "";
  114.             $ret .= $host $base_path $url;
  115.         }
  116.         // URL should now be complete, final cleanup
  117.         $parsed_url parse_url($ret);
  118.         // reproduced from https://www.php.net/manual/en/function.parse-url.php#106731
  119.         $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' '';
  120.         $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  121.         $port     = isset($parsed_url['port']) ? ':' $parsed_url['port'] : '';
  122.         $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  123.         $pass     = isset($parsed_url['pass']) ? ':' $parsed_url['pass']  : '';
  124.         $pass     = ($user || $pass) ? "$pass@" '';
  125.         $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  126.         $query    = isset($parsed_url['query']) ? '?' $parsed_url['query'] : '';
  127.         $fragment = isset($parsed_url['fragment']) ? '#' $parsed_url['fragment'] : '';
  128.         
  129.         // partially reproduced from https://stackoverflow.com/a/1243431/264628
  130.         /* replace '//' or '/./' or '/foo/../' with '/' */
  131.         $re = array('#(/\.?/)#''#/(?!\.\.)[^/]+/\.\./#');
  132.         for ($n=1$n>0$path=preg_replace($re'/'$path, -1$n)) {}
  133.         $ret "$scheme$user$pass$host$port$path$query$fragment";
  134.         return $ret;
  135.     }
  136.     /**
  137.      * Builds a HTTP Content-Disposition header string using `$dispositionType`
  138.      * and `$filename`.
  139.      *
  140.      * If the filename contains any characters not in the ISO-8859-1 character
  141.      * set, a fallback filename will be included for clients not supporting the
  142.      * `filename*` parameter.
  143.      *
  144.      * @param string $dispositionType
  145.      * @param string $filename
  146.      * @return string
  147.      */
  148.     public static function buildContentDispositionHeader($dispositionType$filename)
  149.     {
  150.         $encoding mb_detect_encoding($filename);
  151.         $fallbackfilename mb_convert_encoding($filename"ISO-8859-1"$encoding);
  152.         $fallbackfilename str_replace("\""""$fallbackfilename);
  153.         $encodedfilename rawurlencode($filename);
  154.         $contentDisposition "Content-Disposition: $dispositionType; filename=\"$fallbackfilename\"";
  155.         if ($fallbackfilename !== $filename) {
  156.             $contentDisposition .= "; filename*=UTF-8''$encodedfilename";
  157.         }
  158.         return $contentDisposition;
  159.     }
  160.     /**
  161.      * Converts decimal numbers to roman numerals.
  162.      *
  163.      * As numbers larger than 3999 (and smaller than 1) cannot be represented in
  164.      * the standard form of roman numerals, those are left in decimal form.
  165.      *
  166.      * See https://en.wikipedia.org/wiki/Roman_numerals#Standard_form
  167.      *
  168.      * @param int|string $num
  169.      *
  170.      * @throws Exception
  171.      * @return string
  172.      */
  173.     public static function dec2roman($num): string
  174.     {
  175.         static $ones = ["""i""ii""iii""iv""v""vi""vii""viii""ix"];
  176.         static $tens = ["""x""xx""xxx""xl""l""lx""lxx""lxxx""xc"];
  177.         static $hund = ["""c""cc""ccc""cd""d""dc""dcc""dccc""cm"];
  178.         static $thou = ["""m""mm""mmm"];
  179.         if (!is_numeric($num)) {
  180.             throw new Exception("dec2roman() requires a numeric argument.");
  181.         }
  182.         if ($num >= 4000 || $num <= 0) {
  183.             return (string) $num;
  184.         }
  185.         $num strrev((string)$num);
  186.         $ret "";
  187.         switch (mb_strlen($num)) {
  188.             /** @noinspection PhpMissingBreakStatementInspection */
  189.             case 4:
  190.                 $ret .= $thou[$num[3]];
  191.             /** @noinspection PhpMissingBreakStatementInspection */
  192.             case 3:
  193.                 $ret .= $hund[$num[2]];
  194.             /** @noinspection PhpMissingBreakStatementInspection */
  195.             case 2:
  196.                 $ret .= $tens[$num[1]];
  197.             /** @noinspection PhpMissingBreakStatementInspection */
  198.             case 1:
  199.                 $ret .= $ones[$num[0]];
  200.             default:
  201.                 break;
  202.         }
  203.         return $ret;
  204.     }
  205.     /**
  206.      * Restrict a length to the given range.
  207.      *
  208.      * If min > max, the result is min.
  209.      *
  210.      * @param float $length
  211.      * @param float $min
  212.      * @param float $max
  213.      *
  214.      * @return float
  215.      */
  216.     public static function clamp(float $lengthfloat $minfloat $max): float
  217.     {
  218.         return max($minmin($length$max));
  219.     }
  220.     /**
  221.      * Determines whether $value is a percentage or not
  222.      *
  223.      * @param string|float|int $value
  224.      *
  225.      * @return bool
  226.      */
  227.     public static function is_percent($value): bool
  228.     {
  229.         return is_string($value) && false !== mb_strpos($value"%");
  230.     }
  231.     /**
  232.      * Parses a data URI scheme
  233.      * http://en.wikipedia.org/wiki/Data_URI_scheme
  234.      *
  235.      * @param string $data_uri The data URI to parse
  236.      *
  237.      * @return array|bool The result with charset, mime type and decoded data
  238.      */
  239.     public static function parse_data_uri($data_uri)
  240.     {
  241.         if (!preg_match('/^data:(?P<mime>[a-z0-9\/+-.]+)(;charset=(?P<charset>[a-z0-9-])+)?(?P<base64>;base64)?\,(?P<data>.*)?/is'$data_uri$match)) {
  242.             return false;
  243.         }
  244.         $match['data'] = rawurldecode($match['data']);
  245.         $result = [
  246.             'charset' => $match['charset'] ? $match['charset'] : 'US-ASCII',
  247.             'mime' => $match['mime'] ? $match['mime'] : 'text/plain',
  248.             'data' => $match['base64'] ? base64_decode($match['data']) : $match['data'],
  249.         ];
  250.         return $result;
  251.     }
  252.     /**
  253.      * Encodes a Uniform Resource Identifier (URI) by replacing non-alphanumeric
  254.      * characters with a percent (%) sign followed by two hex digits, excepting
  255.      * characters in the URI reserved character set.
  256.      *
  257.      * Assumes that the URI is a complete URI, so does not encode reserved
  258.      * characters that have special meaning in the URI.
  259.      *
  260.      * Simulates the encodeURI function available in JavaScript
  261.      * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI
  262.      *
  263.      * Source: http://stackoverflow.com/q/4929584/264628
  264.      *
  265.      * @param string $uri The URI to encode
  266.      * @return string The original URL with special characters encoded
  267.      */
  268.     public static function encodeURI($uri) {
  269.         $unescaped = [
  270.             '%2D'=>'-','%5F'=>'_','%2E'=>'.','%21'=>'!''%7E'=>'~',
  271.             '%2A'=>'*''%27'=>"'"'%28'=>'(''%29'=>')'
  272.         ];
  273.         $reserved = [
  274.             '%3B'=>';','%2C'=>',','%2F'=>'/','%3F'=>'?','%3A'=>':',
  275.             '%40'=>'@','%26'=>'&','%3D'=>'=','%2B'=>'+','%24'=>'$'
  276.         ];
  277.         $score = [
  278.             '%23'=>'#'
  279.         ];
  280.         return strtr(rawurlencode(rawurldecode($uri)), array_merge($reserved$unescaped$score));
  281.     }
  282.     /**
  283.      * Decoder for RLE8 compression in windows bitmaps
  284.      * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp
  285.      *
  286.      * @param string $str Data to decode
  287.      * @param int $width Image width
  288.      *
  289.      * @return string
  290.      */
  291.     public static function rle8_decode($str$width)
  292.     {
  293.         $lineWidth $width + (- ($width 1) % 4);
  294.         $out '';
  295.         $cnt strlen($str);
  296.         for ($i 0$i $cnt$i++) {
  297.             $o ord($str[$i]);
  298.             switch ($o) {
  299.                 case 0# ESCAPE
  300.                     $i++;
  301.                     switch (ord($str[$i])) {
  302.                         case 0# NEW LINE
  303.                             $padCnt $lineWidth strlen($out) % $lineWidth;
  304.                             if ($padCnt $lineWidth) {
  305.                                 $out .= str_repeat(chr(0), $padCnt); # pad line
  306.                             }
  307.                             break;
  308.                         case 1# END OF FILE
  309.                             $padCnt $lineWidth strlen($out) % $lineWidth;
  310.                             if ($padCnt $lineWidth) {
  311.                                 $out .= str_repeat(chr(0), $padCnt); # pad line
  312.                             }
  313.                             break 3;
  314.                         case 2# DELTA
  315.                             $i += 2;
  316.                             break;
  317.                         default: # ABSOLUTE MODE
  318.                             $num ord($str[$i]);
  319.                             for ($j 0$j $num$j++) {
  320.                                 $out .= $str[++$i];
  321.                             }
  322.                             if ($num 2) {
  323.                                 $i++;
  324.                             }
  325.                     }
  326.                     break;
  327.                 default:
  328.                     $out .= str_repeat($str[++$i], $o);
  329.             }
  330.         }
  331.         return $out;
  332.     }
  333.     /**
  334.      * Decoder for RLE4 compression in windows bitmaps
  335.      * see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp
  336.      *
  337.      * @param string $str Data to decode
  338.      * @param int $width Image width
  339.      *
  340.      * @return string
  341.      */
  342.     public static function rle4_decode($str$width)
  343.     {
  344.         $w floor($width 2) + ($width 2);
  345.         $lineWidth $w + (- (($width 1) / 2) % 4);
  346.         $pixels = [];
  347.         $cnt strlen($str);
  348.         $c 0;
  349.         for ($i 0$i $cnt$i++) {
  350.             $o ord($str[$i]);
  351.             switch ($o) {
  352.                 case 0# ESCAPE
  353.                     $i++;
  354.                     switch (ord($str[$i])) {
  355.                         case 0# NEW LINE
  356.                             while (count($pixels) % $lineWidth != 0) {
  357.                                 $pixels[] = 0;
  358.                             }
  359.                             break;
  360.                         case 1# END OF FILE
  361.                             while (count($pixels) % $lineWidth != 0) {
  362.                                 $pixels[] = 0;
  363.                             }
  364.                             break 3;
  365.                         case 2# DELTA
  366.                             $i += 2;
  367.                             break;
  368.                         default: # ABSOLUTE MODE
  369.                             $num ord($str[$i]);
  370.                             for ($j 0$j $num$j++) {
  371.                                 if ($j == 0) {
  372.                                     $c ord($str[++$i]);
  373.                                     $pixels[] = ($c 240) >> 4;
  374.                                 } else {
  375.                                     $pixels[] = $c 15;
  376.                                 }
  377.                             }
  378.                             if ($num == 0) {
  379.                                 $i++;
  380.                             }
  381.                     }
  382.                     break;
  383.                 default:
  384.                     $c ord($str[++$i]);
  385.                     for ($j 0$j $o$j++) {
  386.                         $pixels[] = ($j == ? ($c 240) >> $c 15);
  387.                     }
  388.             }
  389.         }
  390.         $out '';
  391.         if (count($pixels) % 2) {
  392.             $pixels[] = 0;
  393.         }
  394.         $cnt count($pixels) / 2;
  395.         for ($i 0$i $cnt$i++) {
  396.             $out .= chr(16 $pixels[$i] + $pixels[$i 1]);
  397.         }
  398.         return $out;
  399.     }
  400.     /**
  401.      * parse a full url or pathname and return an array(protocol, host, path,
  402.      * file + query + fragment)
  403.      *
  404.      * @param string $url
  405.      * @return array
  406.      */
  407.     public static function explode_url($url)
  408.     {
  409.         $protocol "";
  410.         $host "";
  411.         $path "";
  412.         $file "";
  413.         $res "";
  414.         $arr parse_url($url);
  415.         if ( isset($arr["scheme"]) ) {
  416.             $arr["scheme"] = mb_strtolower($arr["scheme"]);
  417.         }
  418.         if (isset($arr["scheme"]) && $arr["scheme"] !== "file" && $arr["scheme"] !== "phar" && strlen($arr["scheme"]) > 1) {
  419.             $protocol $arr["scheme"] . "://";
  420.             if (isset($arr["user"])) {
  421.                 $host .= $arr["user"];
  422.                 if (isset($arr["pass"])) {
  423.                     $host .= ":" $arr["pass"];
  424.                 }
  425.                 $host .= "@";
  426.             }
  427.             if (isset($arr["host"])) {
  428.                 $host .= $arr["host"];
  429.             }
  430.             if (isset($arr["port"])) {
  431.                 $host .= ":" $arr["port"];
  432.             }
  433.             if (isset($arr["path"]) && $arr["path"] !== "") {
  434.                 // Do we have a trailing slash?
  435.                 if ($arr["path"][mb_strlen($arr["path"]) - 1] === "/") {
  436.                     $path $arr["path"];
  437.                     $file "";
  438.                 } else {
  439.                     $path rtrim(dirname($arr["path"]), '/\\') . "/";
  440.                     $file basename($arr["path"]);
  441.                 }
  442.             }
  443.             if (isset($arr["query"])) {
  444.                 $file .= "?" $arr["query"];
  445.             }
  446.             if (isset($arr["fragment"])) {
  447.                 $file .= "#" $arr["fragment"];
  448.             }
  449.         } else {
  450.             $protocol "";
  451.             $host ""// localhost, really
  452.             $i mb_stripos($url"://");
  453.             if ($i !== false) {
  454.                 $protocol mb_strtolower(mb_substr($url0$i 3));
  455.                 $url mb_substr($url$i 3);
  456.             } else {
  457.                 $protocol "file://";
  458.             }
  459.             if ($protocol === "phar://") {
  460.                 $res substr($urlstripos($url".phar")+5);
  461.                 $url substr($url7stripos($url".phar")-2);
  462.             }
  463.             $file basename($url);
  464.             $path dirname($url) . "/";
  465.         }
  466.         $ret = [$protocol$host$path$file,
  467.             "protocol" => $protocol,
  468.             "host" => $host,
  469.             "path" => $path,
  470.             "file" => $file,
  471.             "resource" => $res];
  472.         return $ret;
  473.     }
  474.     /**
  475.      * Print debug messages
  476.      *
  477.      * @param string $type The type of debug messages to print
  478.      * @param string $msg The message to show
  479.      */
  480.     public static function dompdf_debug($type$msg)
  481.     {
  482.         global $_DOMPDF_DEBUG_TYPES$_dompdf_show_warnings$_dompdf_debug;
  483.         if (isset($_DOMPDF_DEBUG_TYPES[$type]) && ($_dompdf_show_warnings || $_dompdf_debug)) {
  484.             $arr debug_backtrace();
  485.             echo basename($arr[0]["file"]) . " (" $arr[0]["line"] . "): " $arr[1]["function"] . ": ";
  486.             Helpers::pre_r($msg);
  487.         }
  488.     }
  489.     /**
  490.      * Stores warnings in an array for display later
  491.      * This function allows warnings generated by the DomDocument parser
  492.      * and CSS loader ({@link Stylesheet}) to be captured and displayed
  493.      * later.  Without this function, errors are displayed immediately and
  494.      * PDF streaming is impossible.
  495.      * @see http://www.php.net/manual/en/function.set-error_handler.php
  496.      *
  497.      * @param int $errno
  498.      * @param string $errstr
  499.      * @param string $errfile
  500.      * @param string $errline
  501.      *
  502.      * @throws Exception
  503.      */
  504.     public static function record_warnings($errno$errstr$errfile$errline)
  505.     {
  506.         // Not a warning or notice
  507.         if (!($errno & (E_WARNING E_NOTICE E_USER_NOTICE E_USER_WARNING E_STRICT E_DEPRECATED E_USER_DEPRECATED))) {
  508.             throw new Exception($errstr $errno");
  509.         }
  510.         global $_dompdf_warnings;
  511.         global $_dompdf_show_warnings;
  512.         if ($_dompdf_show_warnings) {
  513.             echo $errstr "\n";
  514.         }
  515.         $_dompdf_warnings[] = $errstr;
  516.     }
  517.     /**
  518.      * @param $c
  519.      * @return bool|string
  520.      */
  521.     public static function unichr($c)
  522.     {
  523.         if ($c <= 0x7F) {
  524.             return chr($c);
  525.         } elseif ($c <= 0x7FF) {
  526.             return chr(0xC0 $c >> 6) . chr(0x80 $c 0x3F);
  527.         } elseif ($c <= 0xFFFF) {
  528.             return chr(0xE0 $c >> 12) . chr(0x80 $c >> 0x3F)
  529.             . chr(0x80 $c 0x3F);
  530.         } elseif ($c <= 0x10FFFF) {
  531.             return chr(0xF0 $c >> 18) . chr(0x80 $c >> 12 0x3F)
  532.             . chr(0x80 $c >> 0x3F)
  533.             . chr(0x80 $c 0x3F);
  534.         }
  535.         return false;
  536.     }
  537.     /**
  538.      * Converts a CMYK color to RGB
  539.      *
  540.      * @param float|float[] $c
  541.      * @param float $m
  542.      * @param float $y
  543.      * @param float $k
  544.      *
  545.      * @return float[]
  546.      */
  547.     public static function cmyk_to_rgb($c$m null$y null$k null)
  548.     {
  549.         if (is_array($c)) {
  550.             [$c$m$y$k] = $c;
  551.         }
  552.         $c *= 255;
  553.         $m *= 255;
  554.         $y *= 255;
  555.         $k *= 255;
  556.         $r = (round(2.55 * ($c $k)));
  557.         $g = (round(2.55 * ($m $k)));
  558.         $b = (round(2.55 * ($y $k)));
  559.         if ($r 0) {
  560.             $r 0;
  561.         }
  562.         if ($g 0) {
  563.             $g 0;
  564.         }
  565.         if ($b 0) {
  566.             $b 0;
  567.         }
  568.         return [
  569.             $r$g$b,
  570.             "r" => $r"g" => $g"b" => $b
  571.         ];
  572.     }
  573.     /**
  574.      * getimagesize doesn't give a good size for 32bit BMP image v5
  575.      *
  576.      * @param string $filename
  577.      * @param resource $context
  578.      * @return array An array of three elements: width and height as
  579.      *         `float|int`, and image type as `string|null`.
  580.      */
  581.     public static function dompdf_getimagesize($filename$context null)
  582.     {
  583.         static $cache = [];
  584.         if (isset($cache[$filename])) {
  585.             return $cache[$filename];
  586.         }
  587.         [$width$height$type] = getimagesize($filename);
  588.         // Custom types
  589.         $types = [
  590.             IMAGETYPE_JPEG => "jpeg",
  591.             IMAGETYPE_GIF  => "gif",
  592.             IMAGETYPE_BMP  => "bmp",
  593.             IMAGETYPE_PNG  => "png",
  594.             IMAGETYPE_WEBP => "webp",
  595.         ];
  596.         $type $types[$type] ?? null;
  597.         if ($width == null || $height == null) {
  598.             [$data] = Helpers::getFileContent($filename$context);
  599.             if ($data !== null) {
  600.                 if (substr($data02) === "BM") {
  601.                     $meta unpack("vtype/Vfilesize/Vreserved/Voffset/Vheadersize/Vwidth/Vheight"$data);
  602.                     $width = (int) $meta["width"];
  603.                     $height = (int) $meta["height"];
  604.                     $type "bmp";
  605.                 } elseif (strpos($data"<svg") !== false) {
  606.                     $doc = new \Svg\Document();
  607.                     $doc->loadFile($filename);
  608.                     [$width$height] = $doc->getDimensions();
  609.                     $width = (float) $width;
  610.                     $height = (float) $height;
  611.                     $type "svg";
  612.                 }
  613.             }
  614.         }
  615.         return $cache[$filename] = [$width ?? 0$height ?? 0$type];
  616.     }
  617.     /**
  618.      * Credit goes to mgutt
  619.      * http://www.programmierer-forum.de/function-imagecreatefrombmp-welche-variante-laeuft-t143137.htm
  620.      * Modified by Fabien Menager to support RGB555 BMP format
  621.      */
  622.     public static function imagecreatefrombmp($filename$context null)
  623.     {
  624.         if (!function_exists("imagecreatetruecolor")) {
  625.             trigger_error("The PHP GD extension is required, but is not installed."E_ERROR);
  626.             return false;
  627.         }
  628.         // version 1.00
  629.         if (!($fh fopen($filename'rb'))) {
  630.             trigger_error('imagecreatefrombmp: Can not open ' $filenameE_USER_WARNING);
  631.             return false;
  632.         }
  633.         $bytes_read 0;
  634.         // read file header
  635.         $meta unpack('vtype/Vfilesize/Vreserved/Voffset'fread($fh14));
  636.         // check for bitmap
  637.         if ($meta['type'] != 19778) {
  638.             trigger_error('imagecreatefrombmp: ' $filename ' is not a bitmap!'E_USER_WARNING);
  639.             return false;
  640.         }
  641.         // read image header
  642.         $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant'fread($fh40));
  643.         $bytes_read += 40;
  644.         // read additional bitfield header
  645.         if ($meta['compression'] == 3) {
  646.             $meta += unpack('VrMask/VgMask/VbMask'fread($fh12));
  647.             $bytes_read += 12;
  648.         }
  649.         // set bytes and padding
  650.         $meta['bytes'] = $meta['bits'] / 8;
  651.         $meta['decal'] = - (* (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4)));
  652.         if ($meta['decal'] == 4) {
  653.             $meta['decal'] = 0;
  654.         }
  655.         // obtain imagesize
  656.         if ($meta['imagesize'] < 1) {
  657.             $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
  658.             // in rare cases filesize is equal to offset so we need to read physical size
  659.             if ($meta['imagesize'] < 1) {
  660.                 $meta['imagesize'] = @filesize($filename) - $meta['offset'];
  661.                 if ($meta['imagesize'] < 1) {
  662.                     trigger_error('imagecreatefrombmp: Can not obtain filesize of ' $filename '!'E_USER_WARNING);
  663.                     return false;
  664.                 }
  665.             }
  666.         }
  667.         // calculate colors
  668.         $meta['colors'] = !$meta['colors'] ? pow(2$meta['bits']) : $meta['colors'];
  669.         // read color palette
  670.         $palette = [];
  671.         if ($meta['bits'] < 16) {
  672.             $palette unpack('l' $meta['colors'], fread($fh$meta['colors'] * 4));
  673.             // in rare cases the color value is signed
  674.             if ($palette[1] < 0) {
  675.                 foreach ($palette as $i => $color) {
  676.                     $palette[$i] = $color 16777216;
  677.                 }
  678.             }
  679.         }
  680.         // ignore extra bitmap headers
  681.         if ($meta['headersize'] > $bytes_read) {
  682.             fread($fh$meta['headersize'] - $bytes_read);
  683.         }
  684.         // create gd image
  685.         $im imagecreatetruecolor($meta['width'], $meta['height']);
  686.         $data fread($fh$meta['imagesize']);
  687.         // uncompress data
  688.         switch ($meta['compression']) {
  689.             case 1:
  690.                 $data Helpers::rle8_decode($data$meta['width']);
  691.                 break;
  692.             case 2:
  693.                 $data Helpers::rle4_decode($data$meta['width']);
  694.                 break;
  695.         }
  696.         $p 0;
  697.         $vide chr(0);
  698.         $y $meta['height'] - 1;
  699.         $error 'imagecreatefrombmp: ' $filename ' has not enough data!';
  700.         // loop through the image data beginning with the lower left corner
  701.         while ($y >= 0) {
  702.             $x 0;
  703.             while ($x $meta['width']) {
  704.                 switch ($meta['bits']) {
  705.                     case 32:
  706.                     case 24:
  707.                         if (!($part substr($data$p/*$meta['bytes']*/))) {
  708.                             trigger_error($errorE_USER_WARNING);
  709.                             return $im;
  710.                         }
  711.                         $color unpack('V'$part $vide);
  712.                         break;
  713.                     case 16:
  714.                         if (!($part substr($data$p/*$meta['bytes']*/))) {
  715.                             trigger_error($errorE_USER_WARNING);
  716.                             return $im;
  717.                         }
  718.                         $color unpack('v'$part);
  719.                         if (empty($meta['rMask']) || $meta['rMask'] != 0xf800) {
  720.                             $color[1] = (($color[1] & 0x7c00) >> 7) * 65536 + (($color[1] & 0x03e0) >> 2) * 256 + (($color[1] & 0x001f) << 3); // 555
  721.                         } else {
  722.                             $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3); // 565
  723.                         }
  724.                         break;
  725.                     case 8:
  726.                         $color unpack('n'$vide substr($data$p1));
  727.                         $color[1] = $palette[$color[1] + 1];
  728.                         break;
  729.                     case 4:
  730.                         $color unpack('n'$vide substr($datafloor($p), 1));
  731.                         $color[1] = ($p 2) % == $color[1] >> $color[1] & 0x0F;
  732.                         $color[1] = $palette[$color[1] + 1];
  733.                         break;
  734.                     case 1:
  735.                         $color unpack('n'$vide substr($datafloor($p), 1));
  736.                         switch (($p 8) % 8) {
  737.                             case 0:
  738.                                 $color[1] = $color[1] >> 7;
  739.                                 break;
  740.                             case 1:
  741.                                 $color[1] = ($color[1] & 0x40) >> 6;
  742.                                 break;
  743.                             case 2:
  744.                                 $color[1] = ($color[1] & 0x20) >> 5;
  745.                                 break;
  746.                             case 3:
  747.                                 $color[1] = ($color[1] & 0x10) >> 4;
  748.                                 break;
  749.                             case 4:
  750.                                 $color[1] = ($color[1] & 0x8) >> 3;
  751.                                 break;
  752.                             case 5:
  753.                                 $color[1] = ($color[1] & 0x4) >> 2;
  754.                                 break;
  755.                             case 6:
  756.                                 $color[1] = ($color[1] & 0x2) >> 1;
  757.                                 break;
  758.                             case 7:
  759.                                 $color[1] = ($color[1] & 0x1);
  760.                                 break;
  761.                         }
  762.                         $color[1] = $palette[$color[1] + 1];
  763.                         break;
  764.                     default:
  765.                         trigger_error('imagecreatefrombmp: ' $filename ' has ' $meta['bits'] . ' bits and this is not supported!'E_USER_WARNING);
  766.                         return false;
  767.                 }
  768.                 imagesetpixel($im$x$y$color[1]);
  769.                 $x++;
  770.                 $p += $meta['bytes'];
  771.             }
  772.             $y--;
  773.             $p += $meta['decal'];
  774.         }
  775.         fclose($fh);
  776.         return $im;
  777.     }
  778.     /**
  779.      * Gets the content of the file at the specified path using one of
  780.      * the following methods, in preferential order:
  781.      *  - file_get_contents: if allow_url_fopen is true or the file is local
  782.      *  - curl: if allow_url_fopen is false and curl is available
  783.      *
  784.      * @param string $uri
  785.      * @param resource $context
  786.      * @param int $offset
  787.      * @param int $maxlen
  788.      * @return string[]
  789.      */
  790.     public static function getFileContent($uri$context null$offset 0$maxlen null)
  791.     {
  792.         $content null;
  793.         $headers null;
  794.         [$protocol] = Helpers::explode_url($uri);
  795.         $is_local_path in_array(strtolower($protocol), ["""file://""phar://"], true);
  796.         $can_use_curl in_array(strtolower($protocol), ["http://""https://"], true);
  797.         set_error_handler([self::class, 'record_warnings']);
  798.         try {
  799.             if ($is_local_path || ini_get('allow_url_fopen') || !$can_use_curl) {
  800.                 if ($is_local_path === false) {
  801.                     $uri Helpers::encodeURI($uri);
  802.                 }
  803.                 if (isset($maxlen)) {
  804.                     $result file_get_contents($urifalse$context$offset$maxlen);
  805.                 } else {
  806.                     $result file_get_contents($urifalse$context$offset);
  807.                 }
  808.                 if ($result !== false) {
  809.                     $content $result;
  810.                 }
  811.                 if (isset($http_response_header)) {
  812.                     $headers $http_response_header;
  813.                 }
  814.             } elseif ($can_use_curl && function_exists('curl_exec')) {
  815.                 $curl curl_init($uri);
  816.                 curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);
  817.                 curl_setopt($curlCURLOPT_HEADERtrue);
  818.                 if ($offset 0) {
  819.                     curl_setopt($curlCURLOPT_RESUME_FROM$offset);
  820.                 }
  821.                 if ($maxlen 0) {
  822.                     curl_setopt($curlCURLOPT_BUFFERSIZE128);
  823.                     curl_setopt($curlCURLOPT_NOPROGRESSfalse);
  824.                     curl_setopt($curlCURLOPT_PROGRESSFUNCTION, function ($res$download_size_total$download_size$upload_size_total$upload_size) use ($maxlen) {
  825.                         return ($download_size $maxlen) ? 0;
  826.                     });
  827.                 }
  828.                 $context_options = [];
  829.                 if (!is_null($context)) {
  830.                     $context_options stream_context_get_options($context);
  831.                 }
  832.                 foreach ($context_options as $stream => $options) {
  833.                     foreach ($options as $option => $value) {
  834.                         $key strtolower($stream) . ":" strtolower($option);
  835.                         switch ($key) {
  836.                             case "curl:curl_verify_ssl_host":
  837.                                 curl_setopt($curlCURLOPT_SSL_VERIFYHOST, !$value 2);
  838.                                 break;
  839.                             case "curl:max_redirects":
  840.                                 curl_setopt($curlCURLOPT_MAXREDIRS$value);
  841.                                 break;
  842.                             case "http:follow_location":
  843.                                 curl_setopt($curlCURLOPT_FOLLOWLOCATION$value);
  844.                                 break;
  845.                             case "http:header":
  846.                                 if (is_string($value)) {
  847.                                     curl_setopt($curlCURLOPT_HTTPHEADER, [$value]);
  848.                                 } else {
  849.                                     curl_setopt($curlCURLOPT_HTTPHEADER$value);
  850.                                 }
  851.                                 break;
  852.                             case "http:timeout":
  853.                                 curl_setopt($curlCURLOPT_TIMEOUT$value);
  854.                                 break;
  855.                             case "http:user_agent":
  856.                                 curl_setopt($curlCURLOPT_USERAGENT$value);
  857.                                 break;
  858.                             case "curl:curl_verify_ssl_peer":
  859.                             case "ssl:verify_peer":
  860.                                 curl_setopt($curlCURLOPT_SSL_VERIFYPEER$value);
  861.                                 break;
  862.                         }
  863.                     }
  864.                 }
  865.                 $data curl_exec($curl);
  866.                 if ($data !== false && !curl_errno($curl)) {
  867.                     switch ($http_code curl_getinfo($curlCURLINFO_HTTP_CODE)) {
  868.                         case 200:
  869.                             $raw_headers substr($data0curl_getinfo($curlCURLINFO_HEADER_SIZE));
  870.                             $headers preg_split("/[\n\r]+/"trim($raw_headers));
  871.                             $content substr($datacurl_getinfo($curlCURLINFO_HEADER_SIZE));
  872.                             break;
  873.                     }
  874.                 }
  875.                 curl_close($curl);
  876.             }
  877.         } finally {
  878.             restore_error_handler();
  879.         }
  880.         return [$content$headers];
  881.     }
  882.     /**
  883.      * @param string $str
  884.      * @return string
  885.      */
  886.     public static function mb_ucwords(string $str): string
  887.     {
  888.         $max_len mb_strlen($str);
  889.         if ($max_len === 1) {
  890.             return mb_strtoupper($str);
  891.         }
  892.         $str mb_strtoupper(mb_substr($str01)) . mb_substr($str1);
  893.         foreach ([' ''.'',''!''?''-''+'] as $s) {
  894.             $pos 0;
  895.             while (($pos mb_strpos($str$s$pos)) !== false) {
  896.                 $pos++;
  897.                 // Nothing to do if the separator is the last char of the string
  898.                 if ($pos !== false && $pos $max_len) {
  899.                     // If the char we want to upper is the last char there is nothing to append behind
  900.                     if ($pos $max_len) {
  901.                         $str mb_substr($str0$pos) . mb_strtoupper(mb_substr($str$pos1)) . mb_substr($str$pos 1);
  902.                     } else {
  903.                         $str mb_substr($str0$pos) . mb_strtoupper(mb_substr($str$pos1));
  904.                     }
  905.                 }
  906.             }
  907.         }
  908.         return $str;
  909.     }
  910.     /**
  911.      * Check whether two lengths should be considered equal, accounting for
  912.      * inaccuracies in float computation.
  913.      *
  914.      * The implementation relies on the fact that we are neither dealing with
  915.      * very large, nor with very small numbers in layout. Adapted from
  916.      * https://floating-point-gui.de/errors/comparison/.
  917.      *
  918.      * @param float $a
  919.      * @param float $b
  920.      *
  921.      * @return bool
  922.      */
  923.     public static function lengthEqual(float $afloat $b): bool
  924.     {
  925.         // The epsilon results in a precision of at least:
  926.         // * 7 decimal digits at around 1
  927.         // * 4 decimal digits at around 1000 (around the size of common paper formats)
  928.         // * 2 decimal digits at around 100,000 (100,000pt ~ 35.28m)
  929.         static $epsilon 1e-8;
  930.         static $almostZero 1e-12;
  931.         $diff abs($a $b);
  932.         if ($a === $b || $diff $almostZero) {
  933.             return true;
  934.         }
  935.         return $diff $epsilon max(abs($a), abs($b));
  936.     }
  937.     /**
  938.      * Check `$a < $b`, accounting for inaccuracies in float computation.
  939.      */
  940.     public static function lengthLess(float $afloat $b): bool
  941.     {
  942.         return $a $b && !self::lengthEqual($a$b);
  943.     }
  944.     /**
  945.      * Check `$a <= $b`, accounting for inaccuracies in float computation.
  946.      */
  947.     public static function lengthLessOrEqual(float $afloat $b): bool
  948.     {
  949.         return $a <= $b || self::lengthEqual($a$b);
  950.     }
  951.     /**
  952.      * Check `$a > $b`, accounting for inaccuracies in float computation.
  953.      */
  954.     public static function lengthGreater(float $afloat $b): bool
  955.     {
  956.         return $a $b && !self::lengthEqual($a$b);
  957.     }
  958.     /**
  959.      * Check `$a >= $b`, accounting for inaccuracies in float computation.
  960.      */
  961.     public static function lengthGreaterOrEqual(float $afloat $b): bool
  962.     {
  963.         return $a >= $b || self::lengthEqual($a$b);
  964.     }
  965. }