forked from rosell-dk/webp-convert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebp-convert.inc
2856 lines (2418 loc) · 101 KB
/
webp-convert.inc
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
?><?php
namespace WebPConvert\Exceptions;
class WebPConvertBaseException extends \Exception
{
}
?><?php
namespace WebPConvert\Loggers;
abstract class BaseLogger
{
/*
$msg: message to log
$style: null | bold | italic
*/
abstract public function log($msg, $style = '');
abstract public function ln();
public function logLn($msg, $style = '')
{
$this->log($msg, $style);
$this->ln();
}
public function logLnLn($msg, $style = '')
{
$this->logLn($msg, $style);
$this->ln();
}
}
?><?php
namespace WebPConvert;
use WebPConvert\Converters\ConverterHelper;
use WebPConvert\ServeExistingOrConvert;
use WebPConvert\Serve\ServeExistingOrHandOver;
class WebPConvert
{
/*
@param (string) $source: Absolute path to image to be converted (no backslashes). Image must be jpeg or png
@param (string) $destination: Absolute path (no backslashes)
@param (object) $options: Array of named options, such as 'quality' and 'metadata'
*/
public static function convert($source, $destination, $options = [], $logger = null)
{
return ConverterHelper::runConverterStack($source, $destination, $options, $logger);
}
public static function convertAndServe($source, $destination, $options = [])
{
//return ServeExistingOrConvert::serveExistingOrConvert($source, $destination, $options);
return ServeExistingOrHandOver::serveConverted($source, $destination, $options);
}
}
?><?php
namespace WebPConvert\Converters;
//use WebPConvert\Converters\Cwebp;
use WebPConvert\Exceptions\ConverterNotFoundException;
use WebPConvert\Exceptions\CreateDestinationFileException;
use WebPConvert\Exceptions\CreateDestinationFolderException;
use WebPConvert\Exceptions\InvalidFileExtensionException;
use WebPConvert\Exceptions\TargetNotFoundException;
use WebPConvert\Converters\Exceptions\ConverterNotOperationalException;
use WebPConvert\Converters\Exceptions\ConverterFailedException;
class ConverterHelper
{
public static $availableConverters = ['cwebp', 'gd', 'imagick', 'gmagick', 'imagickbinary', 'wpc', 'ewww'];
public static $localConverters = ['cwebp', 'gd', 'imagick', 'gmagick', 'imagickbinary'];
public static $allowedExtensions = ['jpg', 'jpeg', 'png'];
public static $defaultOptions = [
'quality' => 'auto',
'max-quality' => 85,
'default-quality' => 75,
'metadata' => 'none',
'method' => 6,
'low-memory' => false,
'lossless' => false,
'converters' => ['cwebp', 'gd', 'imagick', 'gmagick'],
'converter-options' => []
];
public static function mergeOptions($options, $extraOptions)
{
return $options;
}
public static function getClassNameOfConverter($converterId)
{
return 'WebPConvert\\Converters\\' . ucfirst($converterId);
}
/* Call the "convert" method on a converter, by id.
- but also prepares options (merges in the $extraOptions of the converter),
prepares destination folder, and runs some standard validations
If it fails, it throws an exception. Otherwise it don't (there is no return value)
*/
public static function runConverter(
$converterId,
$source,
$destination,
$options = [],
$prepareDestinationFolder = true,
$logger = null
) {
if ($prepareDestinationFolder) {
self::prepareDestinationFolderAndRunCommonValidations($source, $destination);
}
if (!isset($logger)) {
$logger = new \WebPConvert\Loggers\VoidLogger();
}
$className = self::getClassNameOfConverter($converterId);
if (!is_callable([$className, 'convert'])) {
throw new ConverterNotFoundException();
}
// Prepare options.
// - Remove 'converters'
$defaultOptions = self::$defaultOptions;
unset($defaultOptions['converters']);
// - Merge defaults of the converters extra options into the standard default options.
$defaultOptions = array_merge($defaultOptions, array_column($className::$extraOptions, 'default', 'name'));
// - Merge $defaultOptions into provided options
$options = array_merge($defaultOptions, $options);
// Individual converters do not accept quality = auto. They need a number.
// Change $options['quality'] to number, based on quality of source and several settings
self::processQualityOption($source, $options, $logger);
call_user_func(
[$className, 'doConvert'],
$source,
$destination,
$options,
$logger
);
if (!@file_exists($destination)) {
throw new ConverterFailedException('Destination file is not there');
} else {
$sourceSize = @filesize($source);
if ($sourceSize !== false) {
$msg = 'Success. ';
$msg .= 'Reduced file size with ' .
round((filesize($source) - filesize($destination))/filesize($source) * 100) . '% ';
if ($sourceSize < 10000) {
$msg .= '(went from ' . round(filesize($source)) . ' bytes to ';
$msg .= round(filesize($destination)) . ' bytes)';
} else {
$msg .= '(went from ' . round(filesize($source)/1024) . ' kb to ';
$msg .= round(filesize($destination)/1024) . ' kb)';
}
$logger->logLn($msg);
}
}
}
public static function runConverterWithTiming(
$converterId,
$source,
$destination,
$options = [],
$prepareDestinationFolder = true,
$logger = null
) {
$beginTime = microtime(true);
if (!isset($logger)) {
$logger = new \WebPConvert\Loggers\VoidLogger();
}
try {
self::runConverter($converterId, $source, $destination, $options, $prepareDestinationFolder, $logger);
$logger->logLn(
'Successfully converted image in ' .
round((microtime(true) - $beginTime) * 1000) . ' ms'
);
} catch (\Exception $e) {
$logger->logLn('Failed in ' . round((microtime(true) - $beginTime) * 1000) . ' ms');
throw $e;
}
}
/*
@param (string) $source: Absolute path to image to be converted (no backslashes). Image must be jpeg or png
@param (string) $destination: Absolute path (no backslashes)
@param (object) $options: Array of named options, such as 'quality' and 'metadata'
*/
public static function runConverterStack($source, $destination, $options = [], $logger = null)
{
if (!isset($logger)) {
$logger = new \WebPConvert\Loggers\VoidLogger();
}
self::prepareDestinationFolderAndRunCommonValidations($source, $destination);
$options = array_merge(self::$defaultOptions, $options);
self::processQualityOption($source, $options, $logger);
// Force lossless option to true for PNG images
if (self::getExtension($source) == 'png') {
$options['lossless'] = true;
}
$defaultConverterOptions = $options;
$defaultConverterOptions['converters'] = null;
$firstFailException = null;
// If we have set converter options for a converter, which is not in the converter array,
// then we add it to the array
if (isset($options['converter-options'])) {
foreach ($options['converter-options'] as $converterName => $converterOptions) {
if (!in_array($converterName, $options['converters'])) {
$options['converters'][] = $converterName;
}
}
}
foreach ($options['converters'] as $converter) {
if (is_array($converter)) {
$converterId = $converter['converter'];
$converterOptions = $converter['options'];
} else {
$converterId = $converter;
$converterOptions = [];
if (isset($options['converter-options'][$converterId])) {
// Note: right now, converter-options are not meant to be used,
// when you have several converters of the same type
$converterOptions = $options['converter-options'][$converterId];
}
}
$converterOptions = array_merge($defaultConverterOptions, $converterOptions);
try {
$logger->logLn('Trying:' . $converterId, 'italic');
// If quality is different, we must recalculate
if ($converterOptions['quality'] != $defaultConverterOptions['quality']) {
unset($converterOptions['_calculated_quality']);
self::processQualityOption($source, $converterOptions, $logger);
}
self::runConverterWithTiming($converterId, $source, $destination, $converterOptions, false, $logger);
$logger->logLn('ok', 'bold');
return true;
} catch (\WebPConvert\Converters\Exceptions\ConverterNotOperationalException $e) {
// $logger->logLnLn($e->description . ' : ' . $e->getMessage());
$logger->logLnLn($e->getMessage());
// The converter is not operational.
// Well, well, we will just have to try the next, then
} catch (\WebPConvert\Converters\Exceptions\ConverterFailedException $e) {
$logger->logLnLn($e->getMessage());
// Converter failed in an anticipated, yet somewhat surprising fashion.
// The converter seemed operational - requirements was in order - but it failed anyway.
// This is moderately bad.
// If some other converter can handle the conversion, we will let this one go.
// But if not, we shall throw the exception
if (!$firstFailException) {
$firstFailException = $e;
}
} catch (\WebPConvert\Converters\Exceptions\ConversionDeclinedException $e) {
$logger->logLnLn($e->getMessage());
// The converter declined.
// Gd is for example throwing this, when asked to convert a PNG, but configured not to
// We also possibly rethrow this, because it may have come as a surprise to the user
// who perhaps only tested jpg
if (!$firstFailException) {
$firstFailException = $e;
}
}
}
if ($firstFailException) {
// At least one converter failed or declined.
$logger->logLn('Conversion failed. None of the tried converters could convert the image', 'bold');
} else {
// All converters threw a ConverterNotOperationalException
$logger->logLn('Conversion failed. None of the tried converters are operational', 'bold');
}
// No converters could do the job.
// If one of them failed moderately bad, rethrow that exception.
if ($firstFailException) {
throw $firstFailException;
}
return false;
}
/* Try to detect quality of jpeg.
If not possible, nothing is returned (null). Otherwise quality is returned (int)
*/
public static function detectQualityOfJpg($filename)
{
// Try Imagick extension
if (extension_loaded('imagick') && class_exists('\\Imagick')) {
$img = new \Imagick($filename);
// The required function is available as from PECL imagick v2.2.2
if (method_exists($img, 'getImageCompressionQuality')) {
return $img->getImageCompressionQuality();
}
}
// Gmagick extension doesn't seem to support this (yet):
// https://bugs.php.net/bug.php?id=63939
if (function_exists('shell_exec')) {
// Try Imagick
$quality = shell_exec("identify -format '%Q' " . $filename);
if ($quality) {
return intval($quality);
}
// Try GraphicsMagick
$quality = shell_exec("gm identify -format '%Q' " . $filename);
if ($quality) {
return intval($quality);
}
}
}
public static function processQualityOption($source, &$options, $logger)
{
if (isset($options['_calculated_quality'])) {
return;
}
if ($options['quality'] == 'auto') {
$q = self::detectQualityOfJpg($source);
//$logger->log('Quality set to auto... Quality of source: ');
if (!$q) {
$q = $options['default-quality'];
$logger->logLn(
'Quality of source could not be established (Imagick or GraphicsMagick is required)' .
' - Using default instead (' . $options['default-quality'] . ').'
);
// this allows the wpc converter to know
$options['_quality_could_not_be_detected'] = true;
} else {
if ($q > $options['max-quality']) {
$logger->log(
'Quality of source is ' . $q . '. ' .
'This is higher than max-quality, so using that instead (' . $options['max-quality'] . ')'
);
} else {
$logger->log('Quality set to same as source: ' . $q);
}
}
$logger->ln();
$q = min($q, $options['max-quality']);
$options['_calculated_quality'] = $q;
//$logger->logLn('Using quality: ' . $options['quality']);
} else {
$logger->logLn(
'Quality: ' . $options['quality'] . '. ' .
'Consider setting quality to "auto" instead. It is generally a better idea'
);
$options['_calculated_quality'] = $options['quality'];
}
$logger->ln();
}
public static function getExtension($filePath)
{
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
return strtolower($fileExtension);
}
// Throws an exception if the provided file doesn't exist
public static function isValidTarget($filePath)
{
if (!@file_exists($filePath)) {
throw new TargetNotFoundException('File or directory not found: ' . $filePath);
}
return true;
}
// Throws an exception if the provided file's extension is invalid
public static function isAllowedExtension($filePath)
{
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
if (!in_array(strtolower($fileExtension), self::$allowedExtensions)) {
throw new InvalidFileExtensionException('Unsupported file extension: ' . $fileExtension);
}
return true;
}
// Creates folder in provided path & sets correct permissions
// also deletes the file at filePath (if it already exists)
public static function createWritableFolder($filePath)
{
$folder = dirname($filePath);
if (!@file_exists($folder)) {
// TODO: what if this is outside open basedir?
// see http://php.net/manual/en/ini.core.php#ini.open-basedir
// First, we have to figure out which permissions to set.
// We want same permissions as parent folder
// But which parent? - the parent to the first missing folder
$parentFolders = explode('/', $folder);
$poppedFolders = [];
while (!(@file_exists(implode('/', $parentFolders))) && count($parentFolders) > 0) {
array_unshift($poppedFolders, array_pop($parentFolders));
}
// Retrieving permissions of closest existing folder
$closestExistingFolder = implode('/', $parentFolders);
$permissions = @fileperms($closestExistingFolder) & 000777;
$stat = @stat($closestExistingFolder);
// Trying to create the given folder (recursively)
if (!@mkdir($folder, $permissions, true)) {
throw new CreateDestinationFolderException('Failed creating folder: ' . $folder);
}
// `mkdir` doesn't always respect permissions, so we have to `chmod` each created subfolder
foreach ($poppedFolders as $subfolder) {
$closestExistingFolder .= '/' . $subfolder;
// Setting directory permissions
if ($permissions !== false) {
@chmod($folder, $permissions);
}
if ($stat !== false) {
if (isset($stat['uid'])) {
@chown($folder, $stat['uid']);
}
if (isset($stat['gid'])) {
@chgrp($folder, $stat['gid']);
}
}
}
}
if (@file_exists($filePath)) {
// A file already exists in this folder...
// We delete it, to make way for a new webp
if (!@unlink($filePath)) {
throw new CreateDestinationFileException(
'Existing file cannot be removed: ' . basename($filePath)
);
}
}
return true;
}
public static function prepareDestinationFolderAndRunCommonValidations($source, $destination)
{
self::isValidTarget($source);
self::isAllowedExtension($source);
self::createWritableFolder($destination);
}
public static function initCurlForConverter()
{
if (!extension_loaded('curl')) {
throw new ConverterNotOperationalException('Required cURL extension is not available.');
}
if (!function_exists('curl_init')) {
throw new ConverterNotOperationalException('Required url_init() function is not available.');
}
if (!function_exists('curl_file_create')) {
throw new ConverterNotOperationalException(
'Required curl_file_create() function is not available (requires PHP > 5.5).'
);
}
$ch = curl_init();
if (!$ch) {
throw new ConverterNotOperationalException('Could not initialise cURL.');
}
return $ch;
}
}
?><?php
namespace WebPConvert\Converters;
use WebPConvert\Converters\Exceptions\ConverterNotOperationalException;
use WebPConvert\Converters\Exceptions\ConverterFailedException;
class Cwebp
{
public static $extraOptions = [
[
'name' => 'use-nice',
'type' => 'boolean',
'sensitive' => false,
'default' => false,
'required' => false
],
// low-memory is defined for all, in ConverterHelper
[
'name' => 'try-common-system-paths',
'type' => 'boolean',
'sensitive' => false,
'default' => true,
'required' => false
],
[
'name' => 'try-supplied-binary-for-os',
'type' => 'boolean',
'sensitive' => false,
'default' => true,
'required' => false
],
[
'name' => 'size-in-percentage',
'type' => 'number',
'sensitive' => false,
'default' => null,
'required' => false
],
[
'name' => 'command-line-options',
'type' => 'string',
'sensitive' => false,
'default' => '',
'required' => false
],
[
'name' => 'rel-path-to-precompiled-binaries',
'type' => 'string',
'sensitive' => false,
'default' => './Binaries',
'required' => false
],
];
public static function convert($source, $destination, $options = [])
{
ConverterHelper::runConverter('cwebp', $source, $destination, $options, true);
}
// System paths to look for cwebp binary
private static $cwebpDefaultPaths = [
'/usr/bin/cwebp',
'/usr/local/bin/cwebp',
'/usr/gnu/bin/cwebp',
'/usr/syno/bin/cwebp'
];
// OS-specific binaries included in this library, along with hashes
private static $suppliedBinariesInfo = [
'WinNT' => [ 'cwebp.exe', '49e9cb98db30bfa27936933e6fd94d407e0386802cb192800d9fd824f6476873'],
'Darwin' => [ 'cwebp-mac12', 'a06a3ee436e375c89dbc1b0b2e8bd7729a55139ae072ed3f7bd2e07de0ebb379'],
'SunOS' => [ 'cwebp-sol', '1febaffbb18e52dc2c524cda9eefd00c6db95bc388732868999c0f48deb73b4f'],
'FreeBSD' => [ 'cwebp-fbsd', 'e5cbea11c97fadffe221fdf57c093c19af2737e4bbd2cb3cd5e908de64286573'],
'Linux' => [ 'cwebp-linux', '916623e5e9183237c851374d969aebdb96e0edc0692ab7937b95ea67dc3b2568']
];
private static function escapeFilename($string)
{
// Escaping whitespace
$string = preg_replace('/\s/', '\\ ', $string);
// filter_var() is should normally be available, but it is not always
// - https://stackoverflow.com/questions/11735538/call-to-undefined-function-filter-var
if (function_exists('filter_var')) {
// Sanitize quotes
$string = filter_var($string, FILTER_SANITIZE_MAGIC_QUOTES);
// Stripping control characters
// see https://stackoverflow.com/questions/12769462/filter-flag-strip-low-vs-filter-flag-strip-high
$string = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
}
return $string;
}
// Checks if 'Nice' is available
private static function hasNiceSupport()
{
exec("nice 2>&1", $niceOutput);
if (is_array($niceOutput) && isset($niceOutput[0])) {
if (preg_match('/usage/', $niceOutput[0]) || (preg_match('/^\d+$/', $niceOutput[0]))) {
/*
* Nice is available - default niceness (+10)
* https://www.lifewire.com/uses-of-commands-nice-renice-2201087
* https://www.computerhope.com/unix/unice.htm
*/
return true;
}
return false;
}
}
private static function executeBinary($binary, $commandOptions, $useNice, $logger)
{
$command = ($useNice ? 'nice ' : '') . $binary . ' ' . $commandOptions;
//$logger->logLn('command options:' . $commandOptions);
//$logger->logLn('Trying to execute binary:' . $binary);
exec($command, $output, $returnCode);
//$logger->logLn(self::msgForExitCode($returnCode));
return intval($returnCode);
}
// Although this method is public, do not call directly.
public static function doConvert($source, $destination, $options, $logger)
{
$errorMsg = '';
// Force lossless option to true for PNG images
if (ConverterHelper::getExtension($source) == 'png') {
$options['lossless'] = true;
}
if (!function_exists('exec')) {
throw new ConverterNotOperationalException('exec() is not enabled.');
}
/*
* Prepare cwebp options
*/
$commandOptionsArray = [];
// Metadata (all, exif, icc, xmp or none (default))
// Comma-separated list of existing metadata to copy from input to output
$commandOptionsArray[] = '-metadata ' . $options['metadata'];
// Size
if (!is_null($options['size-in-percentage'])) {
$sizeSource = @filesize($source);
if ($sizeSource !== false) {
$targetSize = floor($sizeSource * $options['size-in-percentage'] / 100);
}
}
if (isset($targetSize)) {
$commandOptionsArray[] = '-size ' . $targetSize;
} else {
// Image quality
$commandOptionsArray[] = '-q ' . $options['_calculated_quality'];
}
// Losless PNG conversion
$commandOptionsArray[] = ($options['lossless'] ? '-lossless' : '');
// Built-in method option
$commandOptionsArray[] = '-m ' . strval($options['method']);
// Built-in low memory option
if ($options['low-memory']) {
$commandOptionsArray[] = '-low_memory';
}
// command-line-options
if ($options['command-line-options']) {
$arr = explode(' -', ' ' . $options['command-line-options']);
foreach ($arr as $cmdOption) {
$pos = strpos($cmdOption, ' ');
$cName = '';
$cValue = '';
if (!$pos) {
$cName = $cmdOption;
if ($cName == '') {
continue;
}
$commandOptionsArray[] = '-' . $cName;
} else {
$cName = substr($cmdOption, 0, $pos);
$cValues = substr($cmdOption, $pos + 1);
$cValuesArr = explode(' ', $cValues);
foreach ($cValuesArr as &$cArg) {
$cArg = escapeshellarg($cArg);
}
$cValues = implode(' ', $cValuesArr);
$commandOptionsArray[] = '-' . $cName . ' ' . $cValues;
}
}
}
// Source file
$commandOptionsArray[] = self::escapeFilename($source);
// Output
$commandOptionsArray[] = '-o ' . self::escapeFilename($destination);
// Redirect stderr to same place as stdout
// https://www.brianstorti.com/understanding-shell-script-idiom-redirect/
$commandOptionsArray[] = '2>&1';
$useNice = (($options['use-nice']) && self::hasNiceSupport()) ? true : false;
$commandOptions = implode(' ', $commandOptionsArray);
$logger->logLn('cwebp options:' . $commandOptions);
// Init with common system paths
$cwebpPathsToTest = self::$cwebpDefaultPaths;
// Remove paths that doesn't exist
/*
$cwebpPathsToTest = array_filter($cwebpPathsToTest, function ($binary) {
//return file_exists($binary);
return @is_readable($binary);
});
*/
// Try all common paths that exists
$success = false;
$failures = [];
$failureCodes = [];
if (!$options['try-supplied-binary-for-os'] && !$options['try-common-system-paths']) {
$errorMsg .= 'Configured to neither look for cweb binaries in common system locations, ' .
'nor to use one of the supplied precompiled binaries. But these are the only ways ' .
'this converter can convert images. No conversion can be made!';
}
if ($options['try-common-system-paths']) {
foreach ($cwebpPathsToTest as $index => $binary) {
$returnCode = self::executeBinary($binary, $commandOptions, $useNice, $logger);
if ($returnCode == 0) {
$logger->logLn('Successfully executed binary: ' . $binary);
$success = true;
break;
} else {
$failures[] = [$binary, $returnCode];
if (!in_array($returnCode, $failureCodes)) {
$failureCodes[] = $returnCode;
}
}
}
$majorFailCode = 0;
if (!$success) {
if (count($failureCodes) == 1) {
$majorFailCode = $failureCodes[0];
switch ($majorFailCode) {
case 126:
$errorMsg = 'Permission denied. The user that the command was run with (' .
shell_exec('whoami') . ') does not have permission to execute any of the ' .
'cweb binaries found in common system locations. ';
break;
case 127:
$errorMsg .= 'Found no cwebp binaries in any common system locations. ';
break;
default:
$errorMsg .= 'Tried executing cwebp binaries in common system locations. ' .
'All failed (exit code: ' . $majorFailCode . '). ';
}
} else {
$failureCodesBesides127 = array_diff($failureCodes, [127]);
if (count($failureCodesBesides127) == 1) {
$majorFailCode = $failureCodesBesides127[0];
switch ($returnCode) {
case 126:
$errorMsg = 'Permission denied. The user that the command was run with (' .
shell_exec('whoami') . ') does not have permission to execute any of the cweb ' .
'binaries found in common system locations. ';
break;
default:
$errorMsg .= 'Tried executing cwebp binaries in common system locations. ' .
'All failed (exit code: ' . $majorFailCode . '). ';
}
} else {
$errorMsg .= 'None of the cwebp binaries in the common system locations could be executed ' .
'(mixed results - got the following exit codes: ' . implode(',', $failureCodes) . '). ';
}
}
}
}
if (!$success && $options['try-supplied-binary-for-os']) {
// Try supplied binary (if available for OS, and hash is correct)
if (isset(self::$suppliedBinariesInfo[PHP_OS])) {
$info = self::$suppliedBinariesInfo[PHP_OS];
$file = $info[0];
$hash = $info[1];
$binaryFile = __DIR__ . '/' . $options['rel-path-to-precompiled-binaries'] . '/' . $file;
// The file should exist, but may have been removed manually.
if (@file_exists($binaryFile)) {
// File exists, now generate its hash
// hash_file() is normally available, but it is not always
// - https://stackoverflow.com/questions/17382712/php-5-3-20-undefined-function-hash
// If available, validate that hash is correct.
$proceedAfterHashCheck = true;
if (function_exists('hash_file')) {
$binaryHash = hash_file('sha256', $binaryFile);
if ($binaryHash != $hash) {
$errorMsg .= 'Binary checksum of supplied binary is invalid! ' .
'Did you transfer with FTP, but not in binary mode? ' .
'File:' . $binaryFile . '. ' .
'Expected checksum: ' . $hash . '. ' .
'Actual checksum:' . $binaryHash . '.';
$proceedAfterHashCheck = false;
}
}
if ($proceedAfterHashCheck) {
$returnCode = self::executeBinary($binaryFile, $commandOptions, $useNice, $logger);
if ($returnCode == 0) {
$success = true;
} else {
$errorMsg .= 'Tried executing supplied binary for ' . PHP_OS . ', ' .
($options['try-common-system-paths'] ? 'but that failed too' : 'but failed');
if ($options['try-common-system-paths'] && ($majorFailCode > 0)) {
$errorMsg .= ' (same error)';
} else {
switch ($returnCode) {
case 0:
$success = true;
;
break;
case 126:
$errorMsg .= ': Permission denied. The user that the command was run with (' .
shell_exec('whoami') . ') does not have permission to execute that binary.';
break;
case 127:
$errorMsg .= '. The binary was not found! It ought to be here: ' . $binaryFile;
break;
default:
$errorMsg .= ' (exit code:' . $returnCode . ').';
}
}
}
}
} else {
$errorMsg .= 'Supplied binary not found! It ought to be here:' . $binaryFile;
}
} else {
$errorMsg .= 'No supplied binaries found for OS:' . PHP_OS;
}
}
// cwebp sets file permissions to 664 but instead ..
// .. $destination's parent folder's permissions should be used (except executable bits)
if ($success) {
$destinationParent = dirname($destination);
$fileStatistics = @stat($destinationParent);
if ($fileStatistics !== false) {
// Apply same permissions as parent folder but strip off the executable bits
$permissions = $fileStatistics['mode'] & 0000666;
@chmod($destination, $permissions);
}
}
if (!$success) {
throw new ConverterNotOperationalException($errorMsg);
}
}
}
?><?php
namespace WebPConvert\Converters;
use WebPConvert\Converters\Exceptions\ConverterNotOperationalException;
use WebPConvert\Converters\Exceptions\ConverterFailedException;
class Ewww
{
public static $extraOptions = [
[
'name' => 'key',
'type' => 'string',
'sensitive' => true,
'default' => '',
'required' => true
],
];
public static function convert($source, $destination, $options = [])
{
ConverterHelper::runConverter('ewww', $source, $destination, $options, true);
}
// Took this parser from Drupal
private static function parseSize($size)
{
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
if ($unit) {
// Find the position of the unit in the ordered string which is the power
// of magnitude to multiply a kilobyte by.
return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
} else {
return round($size);
}
}
// Although this method is public, do not call directly.
public static function doConvert($source, $destination, $options, $logger)
{
if ($options['key'] == '') {
throw new ConverterNotOperationalException('Missing API key.');
}
if (strlen($options['key']) < 20) {
throw new ConverterNotOperationalException(
'Key is invalid. Keys are supposed to be 32 characters long - your key is much shorter'
);
}
$keyStatus = self::getKeyStatus($options['key']);
switch ($keyStatus) {
case 'great':
break;
case 'exceeded':
throw new ConverterNotOperationalException('quota has exceeded');
break;
case 'invalid':
throw new ConverterNotOperationalException('key is invalid');
break;
}
$fileSize = @filesize($source);
if ($fileSize !== false) {
$uploadMaxSize = self::parseSize(ini_get('upload_max_filesize'));
if (($uploadMaxSize !== false) && ($uploadMaxSize < $fileSize)) {
throw new ConverterFailedException(
'File is larger than your max upload (set in your php.ini). File size:' .
round($fileSize/1024) . ' kb. ' .
'upload_max_filesize in php.ini: ' . ini_get('upload_max_filesize') .
' (parsed as ' . round($uploadMaxSize/1024) . ' kb)'
);
}
$postMaxSize = self::parseSize(ini_get('post_max_size'));
if (($postMaxSize !== false) && ($postMaxSize < $fileSize)) {
throw new ConverterFailedException(
'File is larger than your post_max_size limit (set in your php.ini). File size:' .
round($fileSize/1024) . ' kb. ' .
'post_max_size in php.ini: ' . ini_get('post_max_size') .
' (parsed as ' . round($postMaxSize/1024) . ' kb)'
);
}
// ini_get('memory_limit')
}
$ch = ConverterHelper::initCurlForConverter();
$curlOptions = [
'api_key' => $options['key'],
'webp' => '1',
'file' => curl_file_create($source),
'domain' => $_SERVER['HTTP_HOST'],
'quality' => $options['_calculated_quality'],
'metadata' => ($options['metadata'] == 'none' ? '0' : '1')
];
curl_setopt_array(
$ch,
[
CURLOPT_URL => "https://optimize.exactlywww.com/v2/",
CURLOPT_HTTPHEADER => [
'User-Agent: WebPConvert',