Passed
Push — master ( b142cf...cc0ceb )
by Bjørn
02:47
created

Cwebp::escapeShellArgOnCommandLineOptions()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 7.0322

Importance

Changes 0
Metric Value
cc 7
eloc 23
nc 7
nop 1
dl 0
loc 33
ccs 21
cts 23
cp 0.913
crap 7.0322
rs 8.6186
c 0
b 0
f 0
1
<?php
2
3
namespace WebPConvert\Convert\Converters;
4
5
use WebPConvert\Convert\Converters\AbstractConverter;
6
use WebPConvert\Convert\Converters\ConverterTraits\EncodingAutoTrait;
7
use WebPConvert\Convert\Converters\ConverterTraits\ExecTrait;
8
use WebPConvert\Convert\Exceptions\ConversionFailed\ConverterNotOperational\SystemRequirementsNotMetException;
9
use WebPConvert\Convert\Exceptions\ConversionFailedException;
10
use WebPConvert\Convert\Exceptions\ConversionFailed\ConverterNotOperationalException;
11
use WebPConvert\Options\BooleanOption;
12
use WebPConvert\Options\SensitiveStringOption;
13
use WebPConvert\Options\StringOption;
14
15
/**
16
 * Convert images to webp by calling cwebp binary.
17
 *
18
 * @package    WebPConvert
19
 * @author     Bjørn Rosell <[email protected]>
20
 * @since      Class available since Release 2.0.0
21
 */
22
class Cwebp extends AbstractConverter
23
{
24
25
    use EncodingAutoTrait;
26
    use ExecTrait;
27
28
    protected function getUnsupportedDefaultOptions()
29
    {
30
        return [];
31
    }
32
33 8
    protected function createOptions()
34
    {
35 8
        parent::createOptions();
36
37 8
        $this->options2->addOptions(
38 8
            new StringOption('command-line-options', ''),
39 8
            new SensitiveStringOption('rel-path-to-precompiled-binaries', './Binaries'),
40 8
            new BooleanOption('try-common-system-paths', true),
41 8
            new BooleanOption('try-supplied-binary-for-os', true)
42
        );
43 8
    }
44
45
    // System paths to look for cwebp binary
46
    private static $cwebpDefaultPaths = [
47
        'cwebp',
48
        '/usr/bin/cwebp',
49
        '/usr/local/bin/cwebp',
50
        '/usr/gnu/bin/cwebp',
51
        '/usr/syno/bin/cwebp'
52
    ];
53
54
    // OS-specific binaries included in this library, along with hashes
55
    // If other binaries are going to be added, notice that the first argument is what PHP_OS returns.
56
    // (possible values, see here: https://stackoverflow.com/questions/738823/possible-values-for-php-os)
57
    // Got the precompiled binaries here: https://developers.google.com/speed/webp/docs/precompiled
58
    private static $suppliedBinariesInfo = [
59
        'WINNT' => [['cwebp.exe', '49e9cb98db30bfa27936933e6fd94d407e0386802cb192800d9fd824f6476873']],
60
        'Darwin' => [['cwebp-mac12', 'a06a3ee436e375c89dbc1b0b2e8bd7729a55139ae072ed3f7bd2e07de0ebb379']],
61
        'SunOS' => [['cwebp-sol', '1febaffbb18e52dc2c524cda9eefd00c6db95bc388732868999c0f48deb73b4f']],
62
        'FreeBSD' => [['cwebp-fbsd', 'e5cbea11c97fadffe221fdf57c093c19af2737e4bbd2cb3cd5e908de64286573']],
63
        'Linux' => [
64
            // Dynamically linked executable.
65
            // It seems it is slightly faster than the statically linked
66
            ['cwebp-linux-1.0.2-shared', 'd6142e9da2f1cab541de10a31527c597225fff5644e66e31d62bb391c41bfbf4'],
67
68
            // Statically linked executable
69
            // It may be that it on some systems works, where the dynamically linked does not (see #196)
70
            ['cwebp-linux-1.0.2-static', 'a67092563d9de0fbced7dde61b521d60d10c0ad613327a42a81845aefa612b29'],
71
72
            // Old executable for systems where both of the above fails
73
            ['cwebp-linux-0.6.1', '916623e5e9183237c851374d969aebdb96e0edc0692ab7937b95ea67dc3b2568'],
74
        ]
75
    ];
76
77 3
    public function checkOperationality()
78
    {
79 3
        $this->checkOperationalityExecTrait();
80
81 3
        $options = $this->options;
82 3
        if (!$options['try-supplied-binary-for-os'] && !$options['try-common-system-paths']) {
83 1
            throw new ConverterNotOperationalException(
84
                'Configured to neither look for cweb binaries in common system locations, ' .
85
                'nor to use one of the supplied precompiled binaries. But these are the only ways ' .
86 1
                'this converter can convert images. No conversion can be made!'
87
            );
88
        }
89 2
    }
90
91 2
    private function executeBinary($binary, $commandOptions, $useNice)
92
    {
93
        //$version = $this->detectVersion($binary);
94
95 2
        $command = ($useNice ? 'nice ' : '') . $binary . ' ' . $commandOptions;
96
97
        //$logger->logLn('command options:' . $commandOptions);
98 2
        $this->logLn('Trying to convert by executing the following command:');
99 2
        $this->logLn($command);
100 2
        exec($command, $output, $returnCode);
101 2
        $this->logExecOutput($output);
102
        /*
103
        if ($returnCode == 255) {
104
            if (isset($output[0])) {
105
                // Could be an error like 'Error! Cannot open output file' or 'Error! ...preset... '
106
                $this->logLn(print_r($output[0], true));
107
            }
108
        }*/
109
        //$logger->logLn(self::msgForExitCode($returnCode));
110 2
        return intval($returnCode);
111
    }
112
113
    /**
114
     *  Use "escapeshellarg()" on all arguments in a commandline string of options
115
     *
116
     *  For example, passing '-sharpness 5 -crop 10 10 40 40 -low_memory' will result in:
117
     *  [
118
     *    "-sharpness '5'"
119
     *    "-crop '10' '10' '40' '40'"
120
     *    "-low_memory"
121
     *  ]
122
     * @param  string $commandLineOptions  string which can contain multiple commandline options
123
     * @return array  Array of command options
124
     */
125 1
    private static function escapeShellArgOnCommandLineOptions($commandLineOptions)
126
    {
127 1
        if (!ctype_print($commandLineOptions)) {
128
            throw new ConversionFailedException('Non-printable characters are not allowed in the extra command line options');
129
        }
130
131 1
        if (preg_match('#[^a-zA-Z0-9_\s\-]#', $commandLineOptions)) {
132
            throw new ConversionFailedException('The extra command line options contains inacceptable characters');
133
        }
134
135 1
        $cmdOptions = [];
136 1
        $arr = explode(' -', ' ' . $commandLineOptions);
137 1
        foreach ($arr as $cmdOption) {
138 1
            $pos = strpos($cmdOption, ' ');
139 1
            $cName = '';
140 1
            if (!$pos) {
141 1
                $cName = $cmdOption;
142 1
                if ($cName == '') {
143 1
                    continue;
144
                }
145 1
                $cmdOptions[] = '-' . $cName;
146
            } else {
147 1
                $cName = substr($cmdOption, 0, $pos);
148 1
                $cValues = substr($cmdOption, $pos + 1);
149 1
                $cValuesArr = explode(' ', $cValues);
150 1
                foreach ($cValuesArr as &$cArg) {
151 1
                    $cArg = escapeshellarg($cArg);
152
                }
153 1
                $cValues = implode(' ', $cValuesArr);
154 1
                $cmdOptions[] = '-' . $cName . ' ' . $cValues;
155
            }
156
        }
157 1
        return $cmdOptions;
158
    }
159
160
    /**
161
     * Build command line options for a given version of cwebp.
162
     *
163
     * The "-near_lossless" param is not supported on older versions of cwebp, so skip on those.
164
     *
165
     * @param  string $version  Version of cwebp.
166
     * @return string
167
     */
168 6
    private function createCommandLineOptions($version)
169
    {
170
171 6
        $this->logLn('Creating command line options for version: ' . $version);
172
173
        // we only need two decimal places for version.
174
        // convert to number to make it easier to compare
175 6
        $version = preg_match('#^\d+\.\d+#', $version, $matches);
176 6
        $versionNum = 0;
177 6
        if (isset($matches[0])) {
178 6
            $versionNum = floatval($matches[0]);
179
        } else {
180
            $this->logLn(
181
                'Could not extract version number from the following version string: ' . $version,
182
                'bold'
183
            );
184
        }
185
186
        //$this->logLn('version:' . strval($versionNum));
187
188 6
        $options = $this->options;
189
190 6
        $cmdOptions = [];
191
192
        // Metadata (all, exif, icc, xmp or none (default))
193
        // Comma-separated list of existing metadata to copy from input to output
194 6
        if ($versionNum >= 0.3) {
195 6
            $cmdOptions[] = '-metadata ' . $options['metadata'];
196
        }
197
198
        // preset. Appears first in the list as recommended in the docs
199 6
        if (!is_null($options['preset'])) {
200 6
            if ($options['preset'] != 'none') {
201 1
                $cmdOptions[] = '-preset ' . $options['preset'];
202
            }
203
        }
204
205
        // Size
206 6
        $addedSizeOption = false;
207 6
        if (!is_null($options['size-in-percentage'])) {
208 1
            $sizeSource = filesize($this->source);
209 1
            if ($sizeSource !== false) {
210 1
                $targetSize = floor($sizeSource * $options['size-in-percentage'] / 100);
211 1
                $cmdOptions[] = '-size ' . $targetSize;
212 1
                $addedSizeOption = true;
213
            }
214
        }
215
216
        // quality
217 6
        if (!$addedSizeOption) {
218 5
            $cmdOptions[] = '-q ' . $this->getCalculatedQuality();
219
        }
220
221
        // alpha-quality
222 6
        if ($this->options['alpha-quality'] !== 100) {
223 6
            $cmdOptions[] = '-alpha_q ' . escapeshellarg($this->options['alpha-quality']);
224
        }
225
226
        // Losless PNG conversion
227 6
        if ($options['encoding'] == 'lossless') {
228
            // No need to add -lossless when near-lossless is used (on version >= 0.5)
229 4
            if (($options['near-lossless'] === 100) || ($versionNum < 0.5)) {
230 1
                $cmdOptions[] = '-lossless';
231
            }
232
        }
233
234
        // Near-lossles
235 6
        if ($options['near-lossless'] !== 100) {
236 5
            if ($versionNum < 0.5) {
237
                $this->logLn(
238
                    'The near-lossless option is not supported on this (rather old) version of cwebp' .
239
                        '- skipping it.',
240
                    'italic'
241
                );
242
            } else {
243
                // We only let near_lossless have effect when encoding is set to "lossless"
244
                // otherwise encoding=auto would not work as expected
245
246 5
                if ($options['encoding'] == 'lossless') {
247 3
                    $cmdOptions[] ='-near_lossless ' . $options['near-lossless'];
248
                } else {
249 4
                    $this->logLn(
250 4
                        'The near-lossless option ignored for lossy'
251
                    );
252
                }
253
            }
254
        }
255
256 6
        if ($options['auto-filter'] === true) {
257 1
            $cmdOptions[] = '-af';
258
        }
259
260
        // Built-in method option
261 6
        $cmdOptions[] = '-m ' . strval($options['method']);
262
263
        // Built-in low memory option
264 6
        if ($options['low-memory']) {
265 1
            $cmdOptions[] = '-low_memory';
266
        }
267
268
        // command-line-options
269 6
        if ($options['command-line-options']) {
270 1
            array_push(
271 1
                $cmdOptions,
272 1
                ...self::escapeShellArgOnCommandLineOptions($options['command-line-options'])
273
            );
274
        }
275
276
        // Source file
277 6
        $cmdOptions[] = escapeshellarg($this->source);
278
279
        // Output
280 6
        $cmdOptions[] = '-o ' . escapeshellarg($this->destination);
281
282
        // Redirect stderr to same place as stdout
283
        // https://www.brianstorti.com/understanding-shell-script-idiom-redirect/
284 6
        $cmdOptions[] = '2>&1';
285
286 6
        $commandOptions = implode(' ', $cmdOptions);
287
        //$this->logLn('command line options:' . $commandOptions);
288
289 6
        return $commandOptions;
290
    }
291
292
    /**
293
     *  Get path for supplied binary for current OS - and validate hash.
294
     *
295
     *  @return  array  Array of supplied binaries (which actually exists, and where hash validates)
296
     */
297 2
    private function getSuppliedBinaryPathForOS()
298
    {
299 2
        $this->log('Checking if we have a supplied binary for OS: ' . PHP_OS . '... ');
300
301
        // Try supplied binary (if available for OS, and hash is correct)
302 2
        $options = $this->options;
303 2
        if (!isset(self::$suppliedBinariesInfo[PHP_OS])) {
304
            $this->logLn('No we dont - not for that OS');
305
            return [];
306
        }
307 2
        $this->logLn('We do.');
308
309 2
        $result = [];
310 2
        $files = self::$suppliedBinariesInfo[PHP_OS];
311 2
        if (count($files) > 0) {
312 2
            $this->logLn('We in fact have ' . count($files));
313
        }
314
315 2
        foreach ($files as $i => list($file, $hash)) {
316
            //$file = $info[0];
317
            //$hash = $info[1];
318
319 2
            $binaryFile = __DIR__ . '/' . $options['rel-path-to-precompiled-binaries'] . '/' . $file;
320
321
            // Replace "/./" with "/" in path (we could alternatively use realpath)
322
            //$binaryFile = preg_replace('#\/\.\/#', '/', $binaryFile);
323
            // The file should exist, but may have been removed manually.
324
            /*
325
            if (!file_exists($binaryFile)) {
326
                $this->logLn('Supplied binary not found! It ought to be here:' . $binaryFile, 'italic');
327
                return false;
328
            }*/
329
330 2
            $realPathResult = realpath($binaryFile);
331 2
            if ($realPathResult === false) {
332
                $this->logLn('Supplied binary not found! It ought to be here:' . $binaryFile, 'italic');
333
                continue;
334
            }
335 2
            $binaryFile = $realPathResult;
336
337
            // File exists, now generate its hash
338
            // hash_file() is normally available, but it is not always
339
            // - https://stackoverflow.com/questions/17382712/php-5-3-20-undefined-function-hash
340
            // If available, validate that hash is correct.
341
342 2
            if (function_exists('hash_file')) {
343 2
                $binaryHash = hash_file('sha256', $binaryFile);
344
345 2
                if ($binaryHash != $hash) {
346
                    $this->logLn(
347
                        'Binary checksum of supplied binary is invalid! ' .
348
                        'Did you transfer with FTP, but not in binary mode? ' .
349
                        'File:' . $binaryFile . '. ' .
350
                        'Expected checksum: ' . $hash . '. ' .
351
                        'Actual checksum:' . $binaryHash . '.',
352
                        'bold'
353
                    );
354
                    continue;
355
                }
356
            }
357 2
            $result[] = $binaryFile;
358
        }
359
360 2
        return $result;
361
    }
362
363 2
    private function discoverBinaries()
364
    {
365 2
        $this->logLn('Locating cwebp binaries');
366
367 2
        if (defined('WEBPCONVERT_CWEBP_PATH')) {
368
            $this->logLn('WEBPCONVERT_CWEBP_PATH was defined, so using that path and ignoring any other');
369
            //$this->logLn('Value: "' . getenv('WEBPCONVERT_CWEBP_PATH') . '"');
370
            return [constant('WEBPCONVERT_CWEBP_PATH')];
371
        }
372 2
        if (!empty(getenv('WEBPCONVERT_CWEBP_PATH'))) {
373
            $this->logLn(
374
                'WEBPCONVERT_CWEBP_PATH environment variable was set, so using that path and ignoring any other'
375
            );
376
            //$this->logLn('Value: "' . getenv('WEBPCONVERT_CWEBP_PATH') . '"');
377
            return [getenv('WEBPCONVERT_CWEBP_PATH')];
378
        }
379
380 2
        $binaries = [];
381 2
        if ($this->options['try-common-system-paths']) {
382 1
            foreach (self::$cwebpDefaultPaths as $binary) {
383 1
                if (@file_exists($binary)) {
384 1
                    $binaries[] = $binary;
385
                }
386
            }
387 1
            if (count($binaries) == 0) {
388 1
                $this->logLn('No cwebp binaries where located in common system locations');
389
            } else {
390
                $this->logLn(strval(count($binaries)) . ' cwebp binaries found in common system locations');
391
            }
392
        }
393
        // TODO: exec('whereis cwebp');
394 2
        if ($this->options['try-supplied-binary-for-os']) {
395 2
            $suppliedBinaries = $this->getSuppliedBinaryPathForOS();
396 2
            foreach ($suppliedBinaries as $suppliedBinary) {
397 2
                $binaries[] = $suppliedBinary;
398
            }
399
        } else {
400
            $this->logLn('Configured not to try the cwebp binary that comes bundled with webp-convert');
401
        }
402
403 2
        if (count($binaries) == 0) {
404
            $this->logLn('No cwebp binaries to try!');
405
        }
406 2
        $this->logLn('A total of ' . strval(count($binaries)) . ' cwebp binaries where found');
407 2
        return $binaries;
408
    }
409
410
    /**
411
     *
412
     * @return  string|int  Version string (ie "1.0.2") OR return code, in case of failure
413
     */
414 2
    private function detectVersion($binary)
415
    {
416
        //$this->logLn('Examining binary: ' . $binary);
417 2
        $command = $binary . ' -version';
418 2
        $this->log('Executing: ' . $command);
419 2
        exec($command, $output, $returnCode);
420
421 2
        if ($returnCode == 0) {
422
            //$this->logLn('Success');
423 2
            if (isset($output[0])) {
424 2
                $this->logLn('. Result: version: ' . $output[0]);
425 2
                return $output[0];
426
            }
427
        } else {
428
            $this->logExecOutput($output);
429
            $this->logLn('');
430
            if ($returnCode == 127) {
431
                $this->logLn('Exec failed (the cwebp binary was not found at path: ' . $binary. ')');
432
            } else {
433
                $this->logLn(
434
                    'Exec failed (return code: ' . $returnCode . ')'
435
                );
436
                if ($returnCode == 126) {
437
                    $this->logLn(
438
                        'PS: Return code 126 means "Permission denied". The user that the command was run with does ' .
439
                            'not have permission to execute that binary.'
440
                    );
441
                    // TODO: further info: shell_exec('whoami')
442
                }
443
            }
444
            return $returnCode;
445
        }
446
    }
447
448
    /**
449
     *  Check versions for binaries, and return array (indexed by the binary, value being the version of the binary).
450
     *
451
     *  @return  array
452
     */
453 2
    private function detectVersions($binaries)
454
    {
455 2
        $binariesWithVersions = [];
456 2
        $binariesWithFailCodes = [];
457
458 2
        $this->logLn(
459 2
            'Detecting versions of the cwebp binaries found (and verifying that they can be executed in the process)'
460
        );
461 2
        foreach ($binaries as $binary) {
462 2
            $versionStringOrFailCode = $this->detectVersion($binary);
463
        //    $this->logLn($binary . ': ' . $versionString);
464 2
            if (gettype($versionStringOrFailCode) == 'string') {
465 2
                $binariesWithVersions[$binary] = $versionStringOrFailCode;
466
            } else {
467 2
                $binariesWithFailCodes[$binary] = $versionStringOrFailCode;
468
            }
469
        }
470 2
        return ['detected' => $binariesWithVersions, 'failed' => $binariesWithFailCodes];
471
    }
472
473
    /**
474
     * @return  boolean  success or not.
475
     */
476 2
    private function tryBinary($binary, $version, $useNice)
477
    {
478
479
        //$this->logLn('Trying binary: ' . $binary);
480 2
        $commandOptions = $this->createCommandLineOptions($version);
481
482 2
        $returnCode = $this->executeBinary($binary, $commandOptions, $useNice);
483 2
        if ($returnCode == 0) {
484 2
            $this->logLn('Success');
485 2
            return true;
486
        } else {
487
            $this->logLn(
488
                'Exec failed (return code: ' . $returnCode . ')'
489
            );
490
            return false;
491
        }
492
    }
493
494 2
    protected function doActualConvert()
495
    {
496 2
        $binaries = $this->discoverBinaries();
497
498 2
        if (count($binaries) == 0) {
499
            throw new SystemRequirementsNotMetException(
500
                'No cwebp binaries located. Check the conversion log for details.'
501
            );
502
        }
503
504 2
        $versions = $this->detectVersions($binaries);
505 2
        if (count($versions['detected']) == 0) {
506
            //$this->logLn('None of the cwebp files located can be executed.');
507
            if (count($binaries) == 1) {
508
                $errorMsg = 'The cwebp file found cannot be can be executed.';
509
            } else {
510
                $errorMsg = 'None of the cwebp files located can be executed.';
511
            }
512
            $uniqueFailCodes = array_unique(array_values($versions['failed']));
513
            if (count($uniqueFailCodes) == 1) {
514
                $errorMsg .= ' ' . (count($binaries) == 1 ? 'It' : 'All') .
515
                    ' failed with return code ' . $uniqueFailCodes[0];
516
                if ($uniqueFailCodes[0] == 126) {
517
                    $errorMsg .= ' (permission denied)';
518
                }
519
            } else {
520
                $errorMsg .= ' Failure codes : ' . implode(', ', $uniqueFailCodes);
521
            }
522
523
            throw new SystemRequirementsNotMetException($errorMsg);
524
        }
525
526 2
        $binaryVersions = $versions['detected'];
527
528 2
        if (count($binaries) > 1) {
529 2
            $this->logLn(
530 2
                'Trying executing the cwebs found until success. Starting with the ones with highest version number.'
531
            );
532
        }
533
        //$this->logLn('binary versions: ' . print_r($binaryVersions, true));
534
535
        // Sort binaries so those with highest numbers comes first
536 2
        arsort($binaryVersions);
537
538
        //$this->logLn('binary versions (ordered by version): ' . print_r($binaryVersions, true));
539
540 2
        $useNice = (($this->options['use-nice']) && self::hasNiceSupport());
541
542 2
        $success = false;
543 2
        foreach ($binaryVersions as $binary => $version) {
544 2
            if ($this->tryBinary($binary, $version, $useNice)) {
545 2
                $success = true;
546 2
                break;
547
            }
548
        }
549
550
        // cwebp sets file permissions to 664 but instead ..
551
        // .. $destination's parent folder's permissions should be used (except executable bits)
552
        // (or perhaps the current umask instead? https://www.php.net/umask)
553
554 2
        if ($success) {
555 2
            $destinationParent = dirname($this->destination);
556 2
            $fileStatistics = stat($destinationParent);
557 2
            if ($fileStatistics !== false) {
558
                // Apply same permissions as parent folder but strip off the executable bits
559 2
                $permissions = $fileStatistics['mode'] & 0000666;
560 2
                chmod($this->destination, $permissions);
561
            }
562
        } else {
563
            throw new SystemRequirementsNotMetException('Failed converting. Check the conversion log for details.');
564
        }
565 2
    }
566
}
567