1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
|
<?php namespace Dompdf;
class Helpers { /** * print_r wrapper for html/cli output * * Wraps print_r() output in < pre > tags if the current sapi is not 'cli'. * Returns the output string instead of displaying it if $return is true. * * @param mixed $mixed variable or expression to display * @param bool $return * * @return string */ public static function pre_r($mixed, $return = false) { if ($return) { return "<pre>" . print_r($mixed, true) . "</pre>"; }
if (php_sapi_name() !== "cli") { echo "<pre>"; }
print_r($mixed);
if (php_sapi_name() !== "cli") { echo "</pre>"; } else { echo "\n"; }
flush(); }
/** * builds a full url given a protocol, hostname, base path and url * * @param string $protocol * @param string $host * @param string $base_path * @param string $url * @return string * * Initially the trailing slash of $base_path was optional, and conditionally appended. * However on dynamically created sites, where the page is given as url parameter, * the base path might not end with an url. * Therefore do not append a slash, and **require** the $base_url to ending in a slash * when needed. * Vice versa, on using the local file system path of a file, make sure that the slash * is appended (o.k. also for Windows) */ public static function build_url($protocol, $host, $base_path, $url) { $protocol = mb_strtolower($protocol); if (strlen($url) == 0) { //return $protocol . $host . rtrim($base_path, "/\\") . "/"; return $protocol . $host . $base_path; }
// Is the url already fully qualified, a Data URI, or a reference to a named anchor? if (mb_strpos($url, "://") !== false || mb_substr($url, 0, 1) === "#" || mb_strpos($url, "data:") === 0 || mb_strpos($url, "mailto:") === 0) { return $url; }
$ret = $protocol;
if (!in_array(mb_strtolower($protocol), array("http://", "https://", "ftp://", "ftps://"))) { //On Windows local file, an abs path can begin also with a '\' or a drive letter and colon //drive: followed by a relative path would be a drive specific default folder. //not known in php app code, treat as abs path //($url[1] !== ':' || ($url[2]!=='\\' && $url[2]!=='/')) if ($url[0] !== '/' && (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' || ($url[0] !== '\\' && $url[1] !== ':'))) { // For rel path and local acess we ignore the host, and run the path through realpath() $ret .= realpath($base_path) . '/'; } $ret .= $url; $ret = preg_replace('/\?(.*)$/', "", $ret); return $ret; }
// Protocol relative urls (e.g. "//example.org/style.css") if (strpos($url, '//') === 0) { $ret .= substr($url, 2); //remote urls with backslash in html/css are not really correct, but lets be genereous } elseif ($url[0] === '/' || $url[0] === '\\') { // Absolute path $ret .= $host . $url; } else { // Relative path //$base_path = $base_path !== "" ? rtrim($base_path, "/\\") . "/" : ""; $ret .= $host . $base_path . $url; }
return $ret; }
/** * Converts decimal numbers to roman numerals * * @param int $num * * @throws Exception * @return string */ public static function dec2roman($num) {
static $ones = array("", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"); static $tens = array("", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc"); static $hund = array("", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm"); static $thou = array("", "m", "mm", "mmm");
if (!is_numeric($num)) { throw new Exception("dec2roman() requires a numeric argument."); }
if ($num > 4000 || $num < 0) { return "(out of range)"; }
$num = strrev((string)$num);
$ret = ""; switch (mb_strlen($num)) { case 4: $ret .= $thou[$num[3]]; case 3: $ret .= $hund[$num[2]]; case 2: $ret .= $tens[$num[1]]; case 1: $ret .= $ones[$num[0]]; default: break; }
return $ret; }
/** * Determines whether $value is a percentage or not * * @param float $value * * @return bool */ public static function is_percent($value) { return false !== mb_strpos($value, "%"); }
/** * Parses a data URI scheme * http://en.wikipedia.org/wiki/Data_URI_scheme * * @param string $data_uri The data URI to parse * * @return array The result with charset, mime type and decoded data */ public static function parse_data_uri($data_uri) { if (!preg_match('/^data:(?P<mime>[a-z0-9\/+-.]+)(;charset=(?P<charset>[a-z0-9-])+)?(?P<base64>;base64)?\,(?P<data>.*)?/is', $data_uri, $match)) { return false; }
$match['data'] = rawurldecode($match['data']); $result = array( 'charset' => $match['charset'] ? $match['charset'] : 'US-ASCII', 'mime' => $match['mime'] ? $match['mime'] : 'text/plain', 'data' => $match['base64'] ? base64_decode($match['data']) : $match['data'], );
return $result; }
/** * Decoder for RLE8 compression in windows bitmaps * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp * * @param string $str Data to decode * @param integer $width Image width * * @return string */ public static function rle8_decode($str, $width) { $lineWidth = $width + (3 - ($width - 1) % 4); $out = ''; $cnt = strlen($str);
for ($i = 0; $i < $cnt; $i++) { $o = ord($str[$i]); switch ($o) { case 0: # ESCAPE $i++; switch (ord($str[$i])) { case 0: # NEW LINE $padCnt = $lineWidth - strlen($out) % $lineWidth; if ($padCnt < $lineWidth) $out .= str_repeat(chr(0), $padCnt); # pad line break; case 1: # END OF FILE $padCnt = $lineWidth - strlen($out) % $lineWidth; if ($padCnt < $lineWidth) $out .= str_repeat(chr(0), $padCnt); # pad line break 3; case 2: # DELTA $i += 2; break; default: # ABSOLUTE MODE $num = ord($str[$i]); for ($j = 0; $j < $num; $j++) $out .= $str[++$i]; if ($num % 2) $i++; } break; default: $out .= str_repeat($str[++$i], $o); } } return $out; }
/** * Decoder for RLE4 compression in windows bitmaps * see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/bitmaps_6x0u.asp * * @param string $str Data to decode * @param integer $width Image width * * @return string */ public static function rle4_decode($str, $width) { $w = floor($width / 2) + ($width % 2); $lineWidth = $w + (3 - (($width - 1) / 2) % 4); $pixels = array(); $cnt = strlen($str); $c = 0;
for ($i = 0; $i < $cnt; $i++) { $o = ord($str[$i]); switch ($o) { case 0: # ESCAPE $i++; switch (ord($str[$i])) { case 0: # NEW LINE while (count($pixels) % $lineWidth != 0) { $pixels[] = 0; } break; case 1: # END OF FILE while (count($pixels) % $lineWidth != 0) { $pixels[] = 0; } break 3; case 2: # DELTA $i += 2; break; default: # ABSOLUTE MODE $num = ord($str[$i]); for ($j = 0; $j < $num; $j++) { if ($j % 2 == 0) { $c = ord($str[++$i]); $pixels[] = ($c & 240) >> 4; } else { $pixels[] = $c & 15; } }
if ($num % 2 == 0) { $i++; } } break; default: $c = ord($str[++$i]); for ($j = 0; $j < $o; $j++) { $pixels[] = ($j % 2 == 0 ? ($c & 240) >> 4 : $c & 15); } } }
$out = ''; if (count($pixels) % 2) { $pixels[] = 0; }
$cnt = count($pixels) / 2;
for ($i = 0; $i < $cnt; $i++) { $out .= chr(16 * $pixels[2 * $i] + $pixels[2 * $i + 1]); }
return $out; }
/** * parse a full url or pathname and return an array(protocol, host, path, * file + query + fragment) * * @param string $url * @return array */ public static function explode_url($url) { $protocol = ""; $host = ""; $path = ""; $file = "";
$arr = parse_url($url); if ( isset($arr["scheme"]) ) { $arr["scheme"] = mb_strtolower($arr["scheme"]); }
// Exclude windows drive letters... if (isset($arr["scheme"]) && $arr["scheme"] !== "file" && strlen($arr["scheme"]) > 1) { $protocol = $arr["scheme"] . "://";
if (isset($arr["user"])) { $host .= $arr["user"];
if (isset($arr["pass"])) { $host .= ":" . $arr["pass"]; }
$host .= "@"; }
if (isset($arr["host"])) { $host .= $arr["host"]; }
if (isset($arr["port"])) { $host .= ":" . $arr["port"]; }
if (isset($arr["path"]) && $arr["path"] !== "") { // Do we have a trailing slash? if ($arr["path"][mb_strlen($arr["path"]) - 1] === "/") { $path = $arr["path"]; $file = ""; } else { $path = rtrim(dirname($arr["path"]), '/\\') . "/"; $file = basename($arr["path"]); } }
if (isset($arr["query"])) { $file .= "?" . $arr["query"]; }
if (isset($arr["fragment"])) { $file .= "#" . $arr["fragment"]; }
} else {
$i = mb_stripos($url, "file://"); if ($i !== false) { $url = mb_substr($url, $i + 7); }
$protocol = ""; // "file://"; ? why doesn't this work... It's because of // network filenames like //COMPU/SHARENAME
$host = ""; // localhost, really $file = basename($url);
$path = dirname($url);
// Check that the path exists if ($path !== false) { $path .= '/';
} else { // generate a url to access the file if no real path found. $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : php_uname("n");
if (substr($arr["path"], 0, 1) === '/') { $path = dirname($arr["path"]); } else { $path = '/' . rtrim(dirname($_SERVER["SCRIPT_NAME"]), '/') . '/' . $arr["path"]; } } }
$ret = array($protocol, $host, $path, $file, "protocol" => $protocol, "host" => $host, "path" => $path, "file" => $file); return $ret; }
/** * Print debug messages * * @param string $type The type of debug messages to print * @param string $msg The message to show */ public static function dompdf_debug($type, $msg) { global $_DOMPDF_DEBUG_TYPES, $_dompdf_show_warnings, $_dompdf_debug; if (isset($_DOMPDF_DEBUG_TYPES[$type]) && ($_dompdf_show_warnings || $_dompdf_debug)) { $arr = debug_backtrace();
echo basename($arr[0]["file"]) . " (" . $arr[0]["line"] . "): " . $arr[1]["function"] . ": "; Helpers::pre_r($msg); } }
/** * Stores warnings in an array for display later * This function allows warnings generated by the DomDocument parser * and CSS loader ({@link Stylesheet}) to be captured and displayed * later. Without this function, errors are displayed immediately and * PDF streaming is impossible. * @see http://www.php.net/manual/en/function.set-error_handler.php * * @param int $errno * @param string $errstr * @param string $errfile * @param string $errline * * @throws Exception */ public static function record_warnings($errno, $errstr, $errfile, $errline) { // Not a warning or notice if (!($errno & (E_WARNING | E_NOTICE | E_USER_NOTICE | E_USER_WARNING))) { throw new Exception($errstr . " $errno"); }
global $_dompdf_warnings; global $_dompdf_show_warnings;
if ($_dompdf_show_warnings) { echo $errstr . "\n"; }
$_dompdf_warnings[] = $errstr; }
/** * @param $c * @return bool|string */ public static function unichr($c) { if ($c <= 0x7F) { return chr($c); } else if ($c <= 0x7FF) { return chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F); } else if ($c <= 0xFFFF) { return chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F) . chr(0x80 | $c & 0x3F); } else if ($c <= 0x10FFFF) { return chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F) . chr(0x80 | $c >> 6 & 0x3F) . chr(0x80 | $c & 0x3F); } return false; }
/** * Converts a CMYK color to RGB * * @param float|float[] $c * @param float $m * @param float $y * @param float $k * * @return float[] */ public static function cmyk_to_rgb($c, $m = null, $y = null, $k = null) { if (is_array($c)) { list($c, $m, $y, $k) = $c; }
$c *= 255; $m *= 255; $y *= 255; $k *= 255;
$r = (1 - round(2.55 * ($c + $k))); $g = (1 - round(2.55 * ($m + $k))); $b = (1 - round(2.55 * ($y + $k)));
if ($r < 0) $r = 0; if ($g < 0) $g = 0; if ($b < 0) $b = 0;
return array( $r, $g, $b, "r" => $r, "g" => $g, "b" => $b ); }
/** * getimagesize doesn't give a good size for 32bit BMP image v5 * * @param string $filename * @return array The same format as getimagesize($filename) */ public static function dompdf_getimagesize($filename, $context = null) { static $cache = array();
if (isset($cache[$filename])) { return $cache[$filename]; }
list($width, $height, $type) = getimagesize($filename);
// Custom types $types = array( IMAGETYPE_JPEG => "jpeg", IMAGETYPE_GIF => "gif", IMAGETYPE_BMP => "bmp", IMAGETYPE_PNG => "png", );
$type = isset($types[$type]) ? $types[$type] : null;
if ($width == null || $height == null) { $data = file_get_contents($filename, null, $context, 0, 26);
if (substr($data, 0, 2) === "BM") { $meta = unpack('vtype/Vfilesize/Vreserved/Voffset/Vheadersize/Vwidth/Vheight', $data); $width = (int)$meta['width']; $height = (int)$meta['height']; $type = "bmp"; } else { if (strpos(file_get_contents($filename), "<svg") !== false) { $doc = new \Svg\Document(); $doc->loadFile($filename);
list($width, $height) = $doc->getDimensions(); $type = "svg"; } }
}
return $cache[$filename] = array($width, $height, $type); }
/** * Credit goes to mgutt * http://www.programmierer-forum.de/function-imagecreatefrombmp-welche-variante-laeuft-t143137.htm * Modified by Fabien Menager to support RGB555 BMP format */ public static function imagecreatefrombmp($filename, $context = null) { if (!function_exists("imagecreatetruecolor")) { trigger_error("The PHP GD extension is required, but is not installed.", E_ERROR); return false; }
// version 1.00 if (!($fh = fopen($filename, 'rb'))) { trigger_error('imagecreatefrombmp: Can not open ' . $filename, E_USER_WARNING); return false; }
$bytes_read = 0;
// read file header $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
// check for bitmap if ($meta['type'] != 19778) { trigger_error('imagecreatefrombmp: ' . $filename . ' is not a bitmap!', E_USER_WARNING); return false; }
// read image header $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40)); $bytes_read += 40;
// read additional bitfield header if ($meta['compression'] == 3) { $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12)); $bytes_read += 12; }
// set bytes and padding $meta['bytes'] = $meta['bits'] / 8; $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4))); if ($meta['decal'] == 4) { $meta['decal'] = 0; }
// obtain imagesize if ($meta['imagesize'] < 1) { $meta['imagesize'] = $meta['filesize'] - $meta['offset']; // in rare cases filesize is equal to offset so we need to read physical size if ($meta['imagesize'] < 1) { $meta['imagesize'] = @filesize($filename) - $meta['offset']; if ($meta['imagesize'] < 1) { trigger_error('imagecreatefrombmp: Can not obtain filesize of ' . $filename . '!', E_USER_WARNING); return false; } } }
// calculate colors $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
// read color palette $palette = array(); if ($meta['bits'] < 16) { $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4)); // in rare cases the color value is signed if ($palette[1] < 0) { foreach ($palette as $i => $color) { $palette[$i] = $color + 16777216; } } }
// ignore extra bitmap headers if ($meta['headersize'] > $bytes_read) { fread($fh, $meta['headersize'] - $bytes_read); }
// create gd image $im = imagecreatetruecolor($meta['width'], $meta['height']); $data = fread($fh, $meta['imagesize']);
// uncompress data switch ($meta['compression']) { case 1: $data = Helpers::rle8_decode($data, $meta['width']); break; case 2: $data = Helpers::rle4_decode($data, $meta['width']); break; }
$p = 0; $vide = chr(0); $y = $meta['height'] - 1; $error = 'imagecreatefrombmp: ' . $filename . ' has not enough data!';
// loop through the image data beginning with the lower left corner while ($y >= 0) { $x = 0; while ($x < $meta['width']) { switch ($meta['bits']) { case 32: case 24: if (!($part = substr($data, $p, 3 /*$meta['bytes']*/))) { trigger_error($error, E_USER_WARNING); return $im; } $color = unpack('V', $part . $vide); break; case 16: if (!($part = substr($data, $p, 2 /*$meta['bytes']*/))) { trigger_error($error, E_USER_WARNING); return $im; } $color = unpack('v', $part);
if (empty($meta['rMask']) || $meta['rMask'] != 0xf800) { $color[1] = (($color[1] & 0x7c00) >> 7) * 65536 + (($color[1] & 0x03e0) >> 2) * 256 + (($color[1] & 0x001f) << 3); // 555 } else { $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3); // 565 } break; case 8: $color = unpack('n', $vide . substr($data, $p, 1)); $color[1] = $palette[$color[1] + 1]; break; case 4: $color = unpack('n', $vide . substr($data, floor($p), 1)); $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F; $color[1] = $palette[$color[1] + 1]; break; case 1: $color = unpack('n', $vide . substr($data, floor($p), 1)); switch (($p * 8) % 8) { case 0: $color[1] = $color[1] >> 7; break; case 1: $color[1] = ($color[1] & 0x40) >> 6; break; case 2: $color[1] = ($color[1] & 0x20) >> 5; break; case 3: $color[1] = ($color[1] & 0x10) >> 4; break; case 4: $color[1] = ($color[1] & 0x8) >> 3; break; case 5: $color[1] = ($color[1] & 0x4) >> 2; break; case 6: $color[1] = ($color[1] & 0x2) >> 1; break; case 7: $color[1] = ($color[1] & 0x1); break; } $color[1] = $palette[$color[1] + 1]; break; default: trigger_error('imagecreatefrombmp: ' . $filename . ' has ' . $meta['bits'] . ' bits and this is not supported!', E_USER_WARNING); return false; } imagesetpixel($im, $x, $y, $color[1]); $x++; $p += $meta['bytes']; } $y--; $p += $meta['decal']; } fclose($fh); return $im; }
}
|