-
Notifications
You must be signed in to change notification settings - Fork 2
/
AdaptiveImages.php
2169 lines (1938 loc) · 68.6 KB
/
AdaptiveImages.php
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* AdaptiveImages
*
* @version 3.5.0
* @copyright 2013-2023
* @author Nursit
* @licence GNU/GPL3
* @source https://github.com/nursit/AdaptiveImages
*/
class AdaptiveImages {
/**
* @var Array
*/
static protected $instances = array();
/**
* Use progressive rendering for PNG and GIF when JS disabled ?
* @var boolean
*/
protected $nojsPngGifProgressiveRendering = false;
/**
* Background color for JPG lowsrc generation
* (if source has transparency layer)
* @var string
*/
protected $lowsrcJpgBgColor = '#ffffff';
/**
* JPG compression quality for JPG lowsrc
* @var int
*/
protected $lowsrcJpgQuality = 40;
/**
* JPG compression quality for 1x JPG images
* @var int
*/
protected $x10JpgQuality = 75;
/**
* JPG compression quality for 1.5x JPG images
* @var int
*/
protected $x15JpgQuality = 65;
/**
* JPG compression quality for 2x JPG images
* @var int
*/
protected $x20JpgQuality = 45;
/**
* Breakpoints width for image generation
* @var array
*/
protected $defaultBkpts = array(480, 960, 1440);
/**
* Maximum display width for images
* @var int
*/
protected $maxWidth1x = 640;
/**
* Minimum display width for adaptive images (smaller will be unchanged)
* @var int
*/
protected $minWidth1x = 480;
/**
* Minimum filesize for adaptive images (smaller will be unchanged)
* @var int
*/
protected $minFileSize = 20480; // 20ko
/**
* Maximum width for delivering mobile version in data-src-mobile=""
* @var int
*/
protected $maxWidthMobileVersion = 480;
/**
* target width for fallback thumbnail
* @var int
*/
protected $lowsrcWidth = 160;
/**
* Set to true to generate adapted image only at first request from users
* (speed up initial page generation)
* @var int
*/
protected $onDemandImages = false;
/**
* Allowed format images to be adapted
* @var array
*/
protected $acceptedFormats = array('gif', 'png', 'jpeg', 'jpg');
/**
* Alternatives format to propose as a source (potentially better but not fully supported by all browsers like webp)
* @var array
*/
protected $alternativeFormats = array(
/*
'gif' => array('webp'),
'png' => array('webp'),
'jpg' => array('webp')
*/
);
/**
* separator used between source extension and alternative extension
* ex [email protected]
* needed to neutralize jpg extension in Apache negotiation content strategy
* @var string
*/
protected $alternativeFormatSeparator = '@';
/**
* directory for storing adaptive images
* @var string
*/
protected $destDirectory = "local/adapt-img/";
/**
* Maximum number of px for image that can be loaded in memory by GD
* can be used to avoid Fatal Memory Error on large image if PHP memory limited
* @var string
*/
protected $maxImagePxGDMemoryLimit = 0;
/**
* Choose the markup Methd : '3layers' (default) or 'srcset'
* @var string
*/
protected $markupMethod = 'srcset';
/**
* Should images always be in an instrinsic container, even if using srcset method?
* @var bool
*/
protected $alwaysIntrinsic = true;
/**
* Set to true to delay loading with .lazy class on <html>
* need extra js to add .lazy on adapt-img-wrapper, remove .lazy on <html>
* and then remove .lazy on each .adapt-img-wrapper when visible
* @var int
*/
protected $lazyload = false;
/**
* Name of a function to call to generate the thumbnail instead of the internal process
* @var string
*/
protected $thumbnailGeneratorCallback = null;
/**
* Constructor
*/
protected function __construct(){
}
/**
* get
* @param $property
* @return mixed
* @throws InvalidArgumentException
*/
public function __get($property){
if (!property_exists($this, $property) or $property=="instances"){
throw new InvalidArgumentException("Property {$property} doesn't exist");
}
return $this->{$property};
}
/**
* set
* @param $property
* @param $value
* @return mixed
* @throws InvalidArgumentException
*/
public function __set($property, $value){
if (!property_exists($this, $property) or $property=="instances"){
throw new InvalidArgumentException("Property {$property} doesn't exist");
}
if (in_array($property, array("nojsPngGifProgressiveRendering", "onDemandImages", "lazyload", "alwaysIntrinsic"))){
if (!is_bool($value)){
throw new InvalidArgumentException("Property {$property} needs a bool value");
}
} elseif (in_array($property, array("lowsrcJpgBgColor", "destDirectory", "thumbnailGeneratorCallback", "markupMethod"))) {
if (!is_string($value)){
throw new InvalidArgumentException("Property {$property} needs a string value");
}
} elseif (in_array($property, array("defaultBkpts", "acceptedFormats", "alternativeFormats"))) {
if (!is_array($value)){
throw new InvalidArgumentException("Property {$property} needs an array value");
}
} elseif (!is_int($value)) {
throw new InvalidArgumentException("Property {$property} needs an int value");
}
if ($property=="defaultBkpts"){
sort($value);
}
return ($this->{$property} = $value);
}
/**
* Disable cloning
*/
protected function __clone(){
trigger_error("Cannot clone a singleton class", E_USER_ERROR);
}
/**
* Retrieve the AdaptiveImages object
*
* @return AdaptiveImages
*/
static public function getInstance(){
$class_name = (function_exists("get_called_class") ? get_called_class() : "AdaptiveImages");
if (!array_key_exists($class_name, self::$instances)){
self::$instances[$class_name] = new $class_name();
}
return self::$instances[$class_name];
}
/**
* Log function for internal warning if we can avoid to throw an Exception
* Do nothing, should be overriden with your personal log function
* @param $message
*/
protected function log($message){
}
/**
* Convert URL path to file system path
* By default just remove existing timestamp
* Should be overriden depending of your URL mapping rules vs DOCUMENT_ROOT
* can also remap Absolute URL of current website to filesystem path
* @param $url
* @return string
*/
protected function URL2filepath($url){
// remove timestamp on URL
if (($p = strpos($url, '?'))!==FALSE){
$url = substr($url, 0, $p);
}
return $url;
}
/**
* Convert file system path to URL path
* By default just add timestamp for webperf issue
* Should be overriden depending of your URL mapping rules vs DOCUMENT_ROOT
* can map URL on specific domain (domain sharding for Webperf purpose)
* @param string $filepath
* @param bool $relative
* @return string
*/
protected function filepath2URL($filepath, $relative = false){
// be carefull : maybe file doesn't exists yet (On demand generation)
if ($t = @filemtime($filepath)){
$filepath = "$filepath?$t";
}
return $filepath;
}
/**
* Wrapper for filepath2URL with a precheck on filepath freshness and file removal if too old
* @param string $filepath
* @param int $originalSrcTimestamp
* @param bool $relative
* @return string
*/
protected function filepath2URLwFreshnessCheck($filepath, $originalSrcTimestamp, $relative = false){
if ($originalSrcTimestamp
and $t = @filemtime($filepath)
and $t < $originalSrcTimestamp) {
@unlink($filepath);
clearstatcache();
}
return $this->filepath2URL($filepath, $relative);
}
/**
* This hook allows to personalize markup depending on source img style and class attributes
* This do-noting method should be adapted to source markup generated by your CMS
*
* For instance : <img style="display:block;float:right" /> could be adapted in
* <span style="display:block;float:right"><span class="adapt-img-wrapper"><img class="adapt-img"/></span></span>
*
* @param string $markup
* @param string $originalClass
* @param string $originalStyle
* @return mixed
*/
protected function imgMarkupHook(&$markup, $originalClass, $originalStyle){
return $markup;
}
/**
* Translate src of original image to URL subpath of adapted image
* the result will makes subdirectory of $destDirectory/320/10x/ and other variants
* the result must allow to retrive src from url in adaptedURLToSrc() methof
* @param string $src
* @return string
*/
protected function adaptedSrcToURL($src){
$url = $this->filepath2URL($src, true);
if (($p = strpos($url, '?'))!==FALSE){
$url = substr($url, 0, $p);
}
// avoid / starting url : replace / by root/
if (strncmp($url, "/", 1)==0){
$url = "root" . $url;
}
return $url;
}
/**
* Translate URL of subpath of adapted image to original image src
* This reverse the adaptedSrcToURL() method
* @param string $url
* @return string
*/
protected function adaptedURLToSrc($url){
// replace root/ by /
if (strncmp($url, "root/", 5)==0){
$url = substr($url, 4);
}
$src = $this->URL2filepath($url);
return $src;
}
/**
* Process the full HTML page :
* - adapt all <img> in the HTML
* - collect all inline <style> and put in the <head>
* - add necessary JS
*
* @param string $html
* HTML source page
* @param int $maxWidth1x
* max display width for images 1x
* @param array|null $bkpt
* @return string
* HTML modified page
*/
public function adaptHTMLPage($html, $maxWidth1x = null, $bkpt = null){
// adapt all images that need it, if not already
$html = $this->adaptHTMLPart($html, $maxWidth1x, $bkpt);
// if there is adapted images in the page, add the necessary CSS and JS
if (strpos($html, "adapt-img-wrapper")!==false){
$ins_style = "";
// collect all adapt-img <style> in order to put it in the <head>
preg_match_all(",(<style[^>]*adaptive[^>]*>(.*)</style>),Ums", $html, $matches);
if (count($matches[2])){
$html = str_replace($matches[1], "", $html);
$ins_style .= "\n<style>" . implode("\n", $matches[2]) . "\n</style>";
// in case of this was only including <style>
$html = str_replace("<!--[if !IE]><!--><!--<![endif]-->", "", $html);
}
// Common styles for all adaptive images during loading
$noscript = "";
switch ($this->markupMethod) {
case 'srcset':
$minwidthdesktop = $this->maxWidthMobileVersion+0.5;
$base_style = "<style type='text/css'>"
. "img.adapt-img{max-width:100%;height:auto;}"
. ".adapt-img-wrapper {display:inline-block;max-width:100%;position:relative;background-position:center;background-size:cover;background-repeat:no-repeat;line-height:1px;overflow:hidden}"
. ".adapt-img-wrapper.intrinsic{display:block}.adapt-img-wrapper.intrinsic::before{content:'';display:block;height:0;width:100%;}.adapt-img-wrapper.intrinsic img{position:absolute;left:0;top:0;width:100%;height:auto;}"
. ".adapt-img-wrapper.loading:not(.loaded){background-size: cover;}" // lazy-load
. "@media (min-width:{$minwidthdesktop}px){.adapt-img-wrapper.intrinsic-desktop{display:block}.adapt-img-wrapper.intrinsic-desktop::before{content:'';display:block;height:0;width:100%;}.adapt-img-wrapper.intrinsic-desktop img{position:absolute;left:0;top:0;width:100%;height:auto;}}"
. ".adapt-img-background{width:100%;height:0}"
. "@media print{html .adapt-img-wrapper{background:none}}"
. "</style>\n";
// JS that evaluate connection speed and add a aislow class on <html> if slow connection
// and onload JS that adds CSS to finish rendering
$async_style = "picture.adapt-img-wrapper{background-size:0;}";
$length = 1500; // ~1500 bytes for CSS and minified JS we add here
// minified version of AdaptiveImages-light.js (using https://closure-compiler.appspot.com/home)
$js = <<<JS
(function(){function d(a){var b=document.documentElement;b.className=b.className+" "+a}function f(a){var b=window.onload;window.onload="function"!=typeof window.onload?a:function(){b&&b();a()}}document.createElement("picture");adaptImgLazy&&d("lazy");var a=!1;if("undefined"!==typeof window.performance)a=window.performance.timing,a=(a=~~(adaptImgDocLength/(a.responseEnd-a.connectStart)))&&50>a;else{var c=navigator.connection||navigator.mozConnection||navigator.webkitConnection;"undefined"!==typeof c&&
(a=3==c.type||4==c.type||/^[23]g$/.test(c.type))}a&&d("aislow");var e=function(){var a=document.createElement("style");a.type="text/css";a.innerHTML=adaptImgAsyncStyles;var b=document.getElementsByTagName("style")[0];b.parentNode.insertBefore(a,b);window.matchMedia||window.onbeforeprint||beforePrint()};"undefined"!==typeof jQuery?jQuery(function(){jQuery(window).on('load',e)}):f(e)})();
JS;
break;
case '3layers':
default:
$base_style = "<style type='text/css'>" . "img.adapt-img,.lazy img.adapt-img{max-width:100%;height:auto;}img.adapt-img.blur{filter:blur(5px)}"
. ".adapt-img-wrapper,.adapt-img-wrapper::after{display:block;max-width:100%;position:relative;background-size:cover;background-repeat:no-repeat;line-height:1px;overflow:hidden}"
. ".adapt-img-background{width:100%;height:0}.adapt-img-background::after{display:none;width:100%;height:0;}"
. "html body .adapt-img-wrapper.lazy,html.lazy body .adapt-img-wrapper,html body .adapt-img-wrapper.lazy::after,html.lazy body .adapt-img-wrapper::after{background-image:none}"
. ".adapt-img-wrapper::after{position:absolute;top:0;left:0;right:0;bottom:0;content:\"\"}"
. "@media print{html .adapt-img-wrapper{background:none}html .adapt-img-wrapper img {opacity:1}html .adapt-img-wrapper::after{display:none}}"
. "</style>\n";
// JS that evaluate connection speed and add a aislow class on <html> if slow connection
// and onload JS that adds CSS to finish rendering
$async_style = "html img.adapt-img{opacity:0.01}html .adapt-img-wrapper::after{display:none;}";
$length = 2000; // ~2000 bytes for CSS and minified JS we add here
// minified version of AdaptiveImages.js (using https://closure-compiler.appspot.com/home)
$js = <<<JS
function adaptImgFix(d){var e=window.getComputedStyle(d.parentNode).backgroundImage.replace(/\W?\)$/,"").replace(/^url\(\W?|/,"");d.src=e&&"none"!=e?e:d.src}(function(){function d(a){var b=document.documentElement;b.className=b.className+" "+a}function e(a){var b=window.onload;window.onload="function"!=typeof window.onload?a:function(){b&&b();a()}}document.createElement("picture");/android 2[.]/i.test(navigator.userAgent.toLowerCase())&&d("android2");var c=!1;if("undefined"!==typeof window.performance)c=window.performance.timing,c=(c=~~(adaptImgDocLength/(c.responseEnd-c.connectStart)))&&50>c;else{var f=navigator.connection||navigator.mozConnection||navigator.webkitConnection;"undefined"!==typeof f&&(c=3==f.type||4==f.type||/^[23]g$/.test(f.type))}c&&d("aislow");var h=function(){var a=document.createElement("style");a.type="text/css";a.innerHTML=adaptImgAsyncStyles;var b=document.getElementsByTagName("style")[0];b.parentNode.insertBefore(a,b);window.matchMedia||window.onbeforeprint||g()};"undefined"!==typeof jQuery?jQuery(function(){jQuery(window).on('load',h)}):e(h);var g=function(){for(var a=document.getElementsByClassName("adapt-img"),b=0;b<a.length;b++)adaptImgFix(a[b])};window.matchMedia&&window.matchMedia("print").addListener(function(a){g()});"undefined"!==typeof window.onbeforeprint&&(window.onbeforeprint=g)})();
JS;
// alternative noscript if no js (to de-activate progressive rendering on PNG and GIF)
if (!$this->nojsPngGifProgressiveRendering){
$noscript = "<noscript><style type='text/css'>.png img.adapt-img,.gif img.adapt-img{opacity:0.01} .adapt-img-wrapper.png::after,.adapt-img-wrapper.gif::after{display:none;}</style></noscript>";
}
break;
}
$length += strlen($html)+strlen($ins_style);
$ins = "<script type='text/javascript'>/*<![CDATA[*/var adaptImgDocLength=$length;adaptImgAsyncStyles=\"$async_style\";adaptImgLazy=" . ($this->lazyload ? "true" : "false") . ";{$js}/*]]>*/</script>\n";
$ins .= $noscript;
$ins .= $ins_style;
// insert before first <script or <link
$ins = "$base_style<!--[if !IE]><!-->$ins\n<!--<![endif]-->\n";
if ($p = strpos($html, "<link")
or $p = strpos($html, "<script")
or $p = strpos($html, "</head")
or $p = strpos($html, "</body")){
$html = substr_replace($html, $ins, $p, 0);
} else {
$html .= $ins;
}
}
return $html;
}
/**
* Adapt each <img> from HTML part
*
* @param string $html
* HTML source page
* @param int $maxWidth1x
* max display width for images 1x
* @param bool $asBackgroundOrSizes
* true : markup with image as a background only
* string|array : sizes attribut for srcset method
* @param array|null $bkpt
* @return string
* @throws Exception
*/
public function adaptHTMLPart($html, $maxWidth1x = null, $bkpt = null, $asBackgroundOrSizes = false){
$asBackground = false;
$sizes = null;
if ($asBackgroundOrSizes===true){
$asBackground = true;
} elseif (is_array($asBackgroundOrSizes) or is_string($asBackgroundOrSizes)) {
$sizes = $asBackgroundOrSizes;
}
static $bkpts = array();
if (is_null($maxWidth1x) or !intval($maxWidth1x)){
$maxWidth1x = $this->maxWidth1x;
}
if (is_null($bkpt)){
if ($maxWidth1x and !isset($bkpts[$maxWidth1x])){
$b = $this->defaultBkpts;
while (count($b) and end($b)>$maxWidth1x) array_pop($b);
// la largeur maxi affichee
if (!count($b) or end($b)<$maxWidth1x){
$b[] = $maxWidth1x;
}
$bkpts[$maxWidth1x] = $b;
}
$bkpt = (isset($bkpts[$maxWidth1x]) ? $bkpts[$maxWidth1x] : null);
} else {
while (count($bkpt) and end($bkpt)>$maxWidth1x) array_pop($bkpt);
}
$replace = array();
preg_match_all(",<img\s[^>]*>,Uims", $html, $matches, PREG_SET_ORDER);
if (count($matches)){
foreach ($matches as $m){
$ri = $this->processImgTag($m[0], $bkpt, $maxWidth1x, $sizes, $asBackground);
if ($ri!==$m[0]){
$replace[$m[0]] = $ri;
}
}
if (count($replace)){
$html = str_replace(array_keys($replace), array_values($replace), $html);
}
}
return $html;
}
/**
* OnDemand production and delivery of BkptImage from it's URL
* @param string path
* local/adapt-img/w/x/file
* ex : 320/20x/file
* w is the display width
* x is the dpi resolution (10x => 1, 15x => 1.5, 20x => 2)
* file is the original source image file path
* @throws Exception
*/
public function deliverBkptImage($path){
try {
$mime = "";
$file = $this->processBkptImageFromPath($path, $mime);
} catch (Exception $e) {
$file = "";
}
if (!$file
or !$mime){
http_response_code(404);
throw new InvalidArgumentException("Unable to find {$path} image");
}
header("Content-Type: " . $mime);
#header("Expires: 3600"); // set expiration time
if ($cl = filesize($file)){
header("Content-Length: " . $cl);
}
readfile($file);
}
/**
* Build an image variant for a resolution breakpoint
* file path of image is constructed from source file, width and resolution on scheme :
* bkptwidth/resolution/full/path/to/src/image/file
* it allows to reverse-build the image variant from the path
*
* if $force==false and $this->onDemandImages==true we only compute the file path
* and the image variant will be built on first request
*
* @param string $src
* source image
* @param int $wkpt
* breakpoint width (display width) for which the image is built
* @param int $wx
* real width in px of image
* @param string $x
* resolution 10x 15x 20x
* @param string $extension
* extension
* @param bool $force
* true to force immediate image building if not existing or if too old
* @param int $quality
* to set an output image quality outside the predefined preset
* @param bool $forceQuality
* to force a read/save on the original image even if not resized to ensure quality applied
* @param bool $sharpResize
* to force a read/save on the original image even if not resized to ensure quality applied
* @return string
* name of image file
* @throws Exception
*/
protected function processBkptImage($src, $wkpt, $wx, $x, $extension, $force = false, $quality = null, $forceQuality = false, $sharpResize = true){
$dir_dest = $this->destDirectory . "$wkpt/$x/";
$dest = $dir_dest . $this->adaptedSrcToURL($src);
// format variation from the source image?
// we add a @ to neutralize the source extension vs Apache negociation Content
if (substr($dest, -strlen($extension)-1) !== ".{$extension}") {
$dest .= $this->alternativeFormatSeparator . ".{$extension}";
}
if (($exist = file_exists($dest)) and filemtime($dest)>=filemtime($src)){
return $dest;
}
$force = ($force ? true : !$this->onDemandImages);
// if file already exists but too old, delete it if we don't want to generate it now
// it will be generated on first request
if ($exist and !$force){
@unlink($dest);
}
if (!$force){
return $dest;
}
if (is_null($quality)){
$quality = $this->qualityFromX(intval($x));
$forceQuality = (intval($x)>10 ? true : false);
}
$i = $this->imgResize($src, $dest, $wx, 10000, $quality, $forceQuality, $sharpResize);
if ($i and $i!==$dest and $i!==$src){
throw new Exception("Error in imgSharpResize: return \"$i\" whereas \"$dest\" expected");
}
if (!file_exists($i)){
throw new Exception("Error file \"$i\" not found: check the right to write in " . $this->destDirectory);
}
return $i;
}
/**
* @param $x
* @return int
*/
protected function qualityFromX($x){
$x = intval($x);
if ($x<=10){
return $this->x10JpgQuality;
}
if ($x<=15){
if ($x===15){
return $this->x15JpgQuality;
}
return intval(round($this->x10JpgQuality+($x-10)/5*($this->x15JpgQuality-$this->x10JpgQuality)));
}
if ($x>=20){
return $this->x20JpgQuality;
}
return intval(round($this->x15JpgQuality+($x-15)/5*($this->x20JpgQuality-$this->x15JpgQuality)));
}
/**
* Build an image variant from it's URL
* this function is used when $this->onDemandImages==true
* needs a RewriteRule such as following and a router to call this function on first request
*
* RewriteRule \badapt-img/(\d+/\d\dx/.*)$ spip.php?action=adapt_img&arg=$1 [QSA,L]
*
* @param string $URLPath
* @param string $mime
* @return string
* @throws Exception
*/
protected function processBkptImageFromPath($URLPath, &$mime){
$base = $this->destDirectory;
$path = $URLPath;
// if base path is provided, remove it
if (strncmp($path, $base, strlen($base))==0){
$path = substr($path, strlen($base));
}
$path = explode("/", $path);
$wkpt = intval(array_shift($path));
$x = array_shift($path);
$url = implode("/", $path);
// translate URL part to file path
$src = $this->adaptedURLToSrc($url);
$extension = null;
// extension not the same as the source file? (alternative format)
// type IMG/jpg/[email protected]
// the @ is needed to neutralize the original extension
// otherwise Apache would match IMG/jpg/toto.jpg.webp as a valid existing file for IMG/jpg/toto.jpg
// due to negociation content strategy, this is not what we want
// TODO : check extension
if (!file_exists($src)
and preg_match(',\.\w+(' . $this->alternativeFormatSeparator . '?\.(\w+))$,', $src, $m)
//and in_array($m[2], $this->acceptedFormats)
) {
$extension = $m[2];
$src = substr($src, 0, -strlen($m[1]));
}
$parts = pathinfo($src);
if (empty($extension)) {
$extension = strtolower($parts['extension']);
}
$mime = $this->extensionToMimeType($extension);
$dpi = array('10x' => 1, '15x' => 1.5, '20x' => 2);
// check that path is well formed
if (!$wkpt
or !isset($dpi[$x])
or !file_exists($src)
or !$mime){
throw new Exception("Unable to build adapted image $URLPath");
}
$wx = intval(round($wkpt*$dpi[$x]));
$file = $this->processBkptImage($src, $wkpt, $wx, $x, $extension, true);
return $file;
}
/**
* Process one single <img> tag :
* extract informations of src attribute
* and data-src-mobile attribute if provided
* compute images versions for provided breakpoints
*
* Don't do anything if img width is lower than $this->minWidth1x
* or img filesize smaller than $this->minFileSize
*
* @param string $img
* html img tag
* @param array $bkpt
* breakpoints
* @param int $maxWidth1x
* max display with of image (in 1x)
* @param string|array $sizes
* informations for sizez attribut in the srcset method
* @param bool $asBackground
* markup with image as a background only
* @return string
* html markup : original markup or adapted markup
* @throws Exception
*/
protected function processImgTag($img, $bkpt, $maxWidth1x, $sizes = null, $asBackground = false){
if (!$img){
return $img;
}
// don't do anyting if has adapt-img (already adaptive) or no-adapt-img class (no adaptative needed)
if (strpos($img, "adapt-img")!==false){
return $img;
}
if (is_null($bkpt) or !is_array($bkpt)){
$bkpt = $this->defaultBkpts;
}
list($w, $h) = $this->imgSize($img);
$src = $this->tagAttribute($img, 'src');
if (!is_null($src)) {
$src = trim($src);
}
if (is_null($src) or strlen($src)<1){
$src = $img;
$img = "<img src='" . $src . "' />";
}
$adapt = true;
// Don't do anything if img is to small or unknown width
if (!$w or $w<=$this->minWidth1x){
$adapt = false;
} else {
$srcMobile = $this->tagAttribute($img, 'data-src-mobile');
// don't do anything with data-URI images
if (strncmp($src, "data:", 5)==0){
$adapt = false;
} else {
$src = $this->URL2filepath($src);
// don't do anyting if we can't find file
if (!$src or !file_exists($src)){
$adapt = false;
$extension = '';
} else {
// Don't do anything if img filesize is to small
$parts = pathinfo($src);
$extension = $parts['extension'];
$filesize = @filesize($src);
if ($filesize and $filesize<$this->minFileSize){
$adapt = false;
} else {
if (!in_array($extension, $this->acceptedFormats)
// don't do anyting if it's an animated GIF
or ($extension === "gif" and $this->isAnimatedGif($src))){
$adapt = false;
}
}
}
}
}
if (!$adapt){
if (!$asBackground){
return $img;
}
$images[$w] = array(
'10x' => $src,
);
// build the markup for background
return $this->imgAdaptiveMarkup($img, $images, $w, $h, $extension, $maxWidth1x, $sizes, $asBackground);
}
if ($srcMobile){
$srcMobile = $this->URL2filepath($srcMobile);
list($wmobile, $hmobile) = @getimagesize($srcMobile);
if (!$wmobile){
$wmobile = $w;
}
}
$images = array();
if ($w<end($bkpt)){
$bkpt[] = $w;
sort($bkpt);
}
// build images (or at least URLs of images) on breakpoints
$fallback = $src;
$wfallback = $w;
$dpi = array('10x' => 1, '15x' => 1.5, '20x' => 2);
$wk = 0;
foreach ($bkpt as $wk){
if ($wk>$w){
break;
}
$is_mobile = (($srcMobile and $wk<=$this->maxWidthMobileVersion) ? true : false);
if ($is_mobile){
// say we have a mobile version for width under
$images['maxWidthMobile'] = $this->maxWidthMobileVersion;
}
foreach ($dpi as $k => $x){
$wkx = intval(round($wk*$x));
if ($wkx>($is_mobile ? $wmobile : $w) and $x==1){
$images[$wk][$k] = $is_mobile ? $srcMobile : $src;
} else {
// adapter la qualite a la vraie resolution si l'image n'est pas aussi grande que souhaitee
$ratio = min(1.0, intval($is_mobile ? $wmobile : $w)/$wkx);
$quality = $this->qualityFromX(round($x*10*$ratio));
$images[$wk][$k] = $this->processBkptImage($is_mobile ? $srcMobile : $src, $wk, $wkx, $k, $extension, false, $quality, $x!==1);
}
}
if ($wk<=$maxWidth1x
and ($wk<=$this->lowsrcWidth)
and ($is_mobile or !$srcMobile)){
$fallback = $images[$wk]['10x'];
$wfallback = $wk;
}
}
if (!$asBackground){
$fallback_directory = $this->destDirectory . "fallback/";
if (!is_null($this->thumbnailGeneratorCallback) && is_callable($this->thumbnailGeneratorCallback)){
$options = [
'dir' => $fallback_directory,
'images' => $images,
'src' => $src,
'srcMobile' => $srcMobile,
'lowsrcWidth' => $this->lowsrcWidth,
'lowsrcJpgQuality' => $this->lowsrcJpgQuality,
];
$callback = $this->thumbnailGeneratorCallback;
if ($res = $callback($img, $options)){
list($image, $class) = $res;
$images["fallback"] = $image;
$images["fallback_class"] = $class;
}
}
// default method for fallback generation if no external callback provided or if it failed
if (empty($images["fallback"])){
// Build the fallback img : High-compressed JPG
// Start from the mobile version if available or from the larger version otherwise
if ($wk>$w
and $w<$maxWidth1x
and $w<$this->lowsrcWidth){
$fallback = $images[$w]['10x'];
$wfallback = $w;
}
$process_fallback = true;
if ($wfallback>$this->lowsrcWidth){
$bigger_mistake = $h;
$best_width = $this->lowsrcWidth;
// optimise this $wfallback to avoid a too big rounding mistake in the height thumbnail resizing
foreach ([1, 1.25, 1.333, 1.5, 1.666, 1.75, 2] as $x){
$wfallback = round($x*$this->lowsrcWidth);
list($fw, $fh) = $this->computeImageSize($w, $h, $wfallback, 10000);
$mistake = abs(($h-($fh*$w/$fw))*$maxWidth1x/$w);
if ($mistake<$bigger_mistake){
$best_width = $wfallback;
$bigger_mistake = $mistake;
// if less than 1px of rounding mistake, let's take this size
if ($mistake<1){
break;
}
}
}
$wfallback = $best_width;
$q = $this->lowsrcQualityOptimize($wfallback, $this->lowsrcJpgQuality, $w, $h, $maxWidth1x);
if ($extension !== 'jpg'
and !empty($this->alternativeFormats[$extension])
and in_array('webp', $this->alternativeFormats[$extension])
) {
$fallback = $this->processBkptImage($is_mobile ? $srcMobile : $src, $wfallback, $wfallback, '10x', 'webp', true, $q);
$process_fallback = false;
}
else {
$fallback = $this->processBkptImage($is_mobile ? $srcMobile : $src, $wfallback, $wfallback, '10x', $extension, true, $q);
// if it's already a jpg nothing more to do here, otherwise double compress produce artefacts
if ($extension==='jpg'){
$process_fallback = false;
}
}
}
// if $this->onDemandImages == true image has not been built yet
// in this case ask for immediate generation
if (!file_exists($fallback)){
$mime = ""; // not used here
$this->processBkptImageFromPath($fallback, $mime);
}
if ($process_fallback){
$q = $this->lowsrcQualityOptimize($wfallback, $this->lowsrcJpgQuality, $w, $h, $maxWidth1x);
$images["fallback"] = $this->img2JPG($fallback, $fallback_directory, $this->lowsrcJpgBgColor, $q);
} else {
$infos = $this->readSourceImage($fallback, $fallback_directory);
if ($infos['creer']){
@copy($fallback, $infos["fichier_dest"]);
}
$images["fallback"] = $infos["fichier_dest"];
}
$images["fallback_class"] = 'blur';
}
}
// if not using srcset limit $src image width to $maxWidth1x for old IE
// with srcet it doesnt matters, no fallback for old IEs neither small default image
// so avoid this useless image building
if ($this->markupMethod !== 'srcset'){
$src = $this->processBkptImage($src, $maxWidth1x, $maxWidth1x, '10x', $extension, true);
list($w, $h) = $this->imgSize($src);
$img = $this->setTagAttribute($img, "src", $this->filepath2URL($src));
$img = $this->setTagAttribute($img, "width", $w);
$img = $this->setTagAttribute($img, "height", $h);
}
else {
list($w, $h) = $this->imgSize($src);
if ($w > $maxWidth1x) {
list($w, $h) = $this->computeImageSize($w, $h, $maxWidth1x, $h);
$img = $this->setTagAttribute($img, "width", $w);
$img = $this->setTagAttribute($img, "height", $h);
}
}
// ok, now build the markup
return $this->imgAdaptiveMarkup($img, $images, $w, $h, $extension, $maxWidth1x, $sizes, $asBackground);
}
/**
* Compute an "optimal" jpg quality for the fallback image
* @param $width_fallback
* @param $lowsrcBaseQuality
* @param $width
* @param $height
* @param $maxWidth1x
* @return float|mixed
*/
protected function lowsrcQualityOptimize($width_fallback, $lowsrcBaseQuality, $width, $height, $maxWidth1x){
// $this->lowsrcJpgQuality give a base quality for a 450kpx image size
// quality is varying around this value (+/- 50%) depending of image pixel size
// in order to limit the weight of fallback (empirical rule)
$q = round($lowsrcBaseQuality-((min($maxWidth1x, $width_fallback)*$height/$width*min($maxWidth1x, $width_fallback))/75000-6));
$q = min($q, round($this->lowsrcJpgQuality)*1.5);
$q = max($q, round($this->lowsrcJpgQuality)*0.5);
return $q;
}
/**
* Build html markup with CSS rules in <style> tag
* from provided img tag an array of bkpt images
*
* @param string $img
* source img tag
* @param array $bkptImages
* falbback => file
* width =>
* 10x => file
* 15x => file
* 20x => file
* @param int $width
* @param int $height
* @param string $extension
* @param int $maxWidth1x
* @param string|array $sizes
* @param bool $asBackground
* @return string
*/
protected function imgAdaptiveMarkup($img, $bkptImages, $width, $height, $extension, $maxWidth1x, $sizes = null, $asBackground = false){
$class = $this->tagAttribute($img, "class");
$class = is_null($class) ? '' : $class;
if (!$width or strpos($class, "adapt-img")!==false){
return $img;
}