Completed
Push — master ( 36e2d9...033daa )
by Bjørn
03:15
created

composeErrorMessageForCommonSystemPathsFailures()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 36
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 15.7547

Importance

Changes 0
Metric Value
cc 6
eloc 26
nc 6
nop 1
dl 0
loc 36
ccs 6
cts 17
cp 0.3529
crap 15.7547
rs 8.8817
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\LosslessAutoTrait;
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
12
/**
13
 * Convert images to webp by calling cwebp binary.
14
 *
15
 * @package    WebPConvert
16
 * @author     Bjørn Rosell <[email protected]>
17
 * @since      Class available since Release 2.0.0
18
 */
19
class Cwebp extends AbstractConverter
20
{
21
22
    use LosslessAutoTrait;
23
    use ExecTrait;
24
25 8
    protected function getOptionDefinitionsExtra()
26
    {
27
        return [
28 8
            ['command-line-options', 'string', ''],
29
            ['rel-path-to-precompiled-binaries', 'string', './Binaries'],
30
            ['try-common-system-paths', 'boolean', true],
31
            ['try-supplied-binary-for-os', 'boolean', true],
32
        ];
33
    }
34
35
    // System paths to look for cwebp binary
36
    private static $cwebpDefaultPaths = [
37
        'cwebp',
38
        '/usr/bin/cwebp',
39
        '/usr/local/bin/cwebp',
40
        '/usr/gnu/bin/cwebp',
41
        '/usr/syno/bin/cwebp'
42
    ];
43
44
    // OS-specific binaries included in this library, along with hashes
45
    // If other binaries are going to be added, notice that the first argument is what PHP_OS returns.
46
    // (possible values, see here: https://stackoverflow.com/questions/738823/possible-values-for-php-os)
47
    private static $suppliedBinariesInfo = [
48
        'WINNT' => [ 'cwebp.exe', '49e9cb98db30bfa27936933e6fd94d407e0386802cb192800d9fd824f6476873'],
49
        'Darwin' => [ 'cwebp-mac12', 'a06a3ee436e375c89dbc1b0b2e8bd7729a55139ae072ed3f7bd2e07de0ebb379'],
50
        'SunOS' => [ 'cwebp-sol', '1febaffbb18e52dc2c524cda9eefd00c6db95bc388732868999c0f48deb73b4f'],
51
        'FreeBSD' => [ 'cwebp-fbsd', 'e5cbea11c97fadffe221fdf57c093c19af2737e4bbd2cb3cd5e908de64286573'],
52
        'Linux' => [ 'cwebp-linux', '916623e5e9183237c851374d969aebdb96e0edc0692ab7937b95ea67dc3b2568']
53
    ];
54
55 3
    public function checkOperationality()
56
    {
57 3
        $this->checkOperationalityExecTrait();
58
59 3
        $options = $this->options;
60 3
        if (!$options['try-supplied-binary-for-os'] && !$options['try-common-system-paths']) {
61 1
            throw new ConverterNotOperationalException(
62
                'Configured to neither look for cweb binaries in common system locations, ' .
63
                'nor to use one of the supplied precompiled binaries. But these are the only ways ' .
64 1
                'this converter can convert images. No conversion can be made!'
65
            );
66
        }
67 2
    }
68
69 2
    private function executeBinary($binary, $commandOptions, $useNice)
70
    {
71 2
        $command = ($useNice ? 'nice ' : '') . $binary . ' ' . $commandOptions;
72
73
        //$logger->logLn('command options:' . $commandOptions);
74
        //$logger->logLn('Trying to execute binary:' . $binary);
75 2
        exec($command, $output, $returnCode);
76
        //$logger->logLn(self::msgForExitCode($returnCode));
77 2
        return intval($returnCode);
78
    }
79
80
    /**
81
     *  Use "escapeshellarg()" on all arguments in a commandline string of options
82
     *
83
     *  For example, passing '-sharpness 5 -crop 10 10 40 40 -low_memory' will result in:
84
     *  [
85
     *    "-sharpness '5'"
86
     *    "-crop '10' '10' '40' '40'"
87
     *    "-low_memory"
88
     *  ]
89
     * @param  string $commandLineOptions  string which can contain multiple commandline options
90
     * @return array  Array of command options
91
     */
92 1
    private static function escapeShellArgOnCommandLineOptions($commandLineOptions)
93
    {
94 1
        $cmdOptions = [];
95 1
        $arr = explode(' -', ' ' . $commandLineOptions);
96 1
        foreach ($arr as $cmdOption) {
97 1
            $pos = strpos($cmdOption, ' ');
98 1
            $cName = '';
99 1
            if (!$pos) {
100 1
                $cName = $cmdOption;
101 1
                if ($cName == '') {
102 1
                    continue;
103
                }
104 1
                $cmdOptions[] = '-' . $cName;
105
            } else {
106 1
                $cName = substr($cmdOption, 0, $pos);
107 1
                $cValues = substr($cmdOption, $pos + 1);
108 1
                $cValuesArr = explode(' ', $cValues);
109 1
                foreach ($cValuesArr as &$cArg) {
110 1
                    $cArg = escapeshellarg($cArg);
111
                }
112 1
                $cValues = implode(' ', $cValuesArr);
113 1
                $cmdOptions[] = '-' . $cName . ' ' . $cValues;
114
            }
115
        }
116 1
        return $cmdOptions;
117
    }
118
119
    /**
120
     * Build command line options
121
     *
122
     * @return string
123
     */
124 6
    private function createCommandLineOptions()
125
    {
126 6
        $options = $this->options;
127
128 6
        $cmdOptions = [];
129
130
        // Metadata (all, exif, icc, xmp or none (default))
131
        // Comma-separated list of existing metadata to copy from input to output
132 6
        $cmdOptions[] = '-metadata ' . $options['metadata'];
133
134
        // preset. Appears first in the list as recommended in the docs
135 6
        if (!is_null($options['preset'])) {
136 1
            $cmdOptions[] = '-preset ' . $options['preset'];
137
        }
138
139
        // Size
140 6
        $addedSizeOption = false;
141 6
        if (!is_null($options['size-in-percentage'])) {
142 1
            $sizeSource = filesize($this->source);
143 1
            if ($sizeSource !== false) {
144 1
                $targetSize = floor($sizeSource * $options['size-in-percentage'] / 100);
145 1
                $cmdOptions[] = '-size ' . $targetSize;
146 1
                $addedSizeOption = true;
147
            }
148
        }
149
150
        // quality
151 6
        if (!$addedSizeOption) {
152 5
            $cmdOptions[] = '-q ' . $this->getCalculatedQuality();
153
        }
154
155
        // alpha-quality
156 6
        if ($this->options['alpha-quality'] !== 100) {
157 6
            $cmdOptions[] = '-alpha_q ' . escapeshellarg($this->options['alpha-quality']);
158
        }
159
160
        // Losless PNG conversion
161 6
        if ($options['lossless'] === true) {
162
            // No need to add -lossless when near-lossless is used
163 4
            if ($options['near-lossless'] === 100) {
164 1
                $cmdOptions[] = '-lossless';
165
            }
166
        }
167
168
        // Near-lossles
169 6
        if ($options['near-lossless'] !== 100) {
170
            // We only let near_lossless have effect when lossless is set.
171
            // otherwise lossless auto would not work as expected
172 5
            if ($options['lossless'] === true) {
173 3
                $cmdOptions[] ='-near_lossless ' . $options['near-lossless'];
174
            }
175
        }
176
177 6
        if ($options['autofilter'] === true) {
178 1
            $cmdOptions[] = '-af';
179
        }
180
181
        // Built-in method option
182 6
        $cmdOptions[] = '-m ' . strval($options['method']);
183
184
        // Built-in low memory option
185 6
        if ($options['low-memory']) {
186 1
            $cmdOptions[] = '-low_memory';
187
        }
188
189
        // command-line-options
190 6
        if ($options['command-line-options']) {
191 1
            array_push(
192 1
                $cmdOptions,
193 1
                ...self::escapeShellArgOnCommandLineOptions($options['command-line-options'])
194
            );
195
        }
196
197
        // Source file
198 6
        $cmdOptions[] = escapeshellarg($this->source);
199
200
        // Output
201 6
        $cmdOptions[] = '-o ' . escapeshellarg($this->destination);
202
203
        // Redirect stderr to same place as stdout
204
        // https://www.brianstorti.com/understanding-shell-script-idiom-redirect/
205 6
        $cmdOptions[] = '2>&1';
206
207 6
        $commandOptions = implode(' ', $cmdOptions);
208 6
        $this->logLn('command line options:' . $commandOptions);
209
210 6
        return $commandOptions;
211
    }
212
213
    /**
214
     *
215
     *
216
     * @return  string  Error message if failure, empty string if successful
217
     */
218 1
    private function composeErrorMessageForCommonSystemPathsFailures($failureCodes)
219
    {
220 1
        if (count($failureCodes) == 1) {
221 1
            switch ($failureCodes[0]) {
222 1
                case 126:
223
                    return 'Permission denied. The user that the command was run with (' .
224
                        shell_exec('whoami') . ') does not have permission to execute any of the ' .
225
                        'cweb binaries found in common system locations. ';
226 1
                case 127:
227 1
                    return 'Found no cwebp binaries in any common system locations. ';
228
                default:
229
                    return 'Tried executing cwebp binaries in common system locations. ' .
230
                        'All failed (exit code: ' . $failureCodes[0] . '). ';
231
            }
232
        } else {
233
            /**
234
             * $failureCodesBesides127 is used to check first position ($failureCodesBesides127[0])
235
             * however position can vary as index can be 1 or something else. array_values() would
236
             * always start from 0.
237
             */
238
            $failureCodesBesides127 = array_values(array_diff($failureCodes, [127]));
239
240
            if (count($failureCodesBesides127) == 1) {
241
                switch ($failureCodesBesides127[0]) {
242
                    case 126:
243
                        return 'Permission denied. The user that the command was run with (' .
244
                        shell_exec('whoami') . ') does not have permission to execute any of the cweb ' .
245
                        'binaries found in common system locations. ';
246
                        break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
247
                    default:
248
                        return 'Tried executing cwebp binaries in common system locations. ' .
249
                        'All failed (exit code: ' . $failureCodesBesides127[0] . '). ';
250
                }
251
            } else {
252
                return 'None of the cwebp binaries in the common system locations could be executed ' .
253
                '(mixed results - got the following exit codes: ' . implode(',', $failureCodes) . '). ';
254
            }
255
        }
256
    }
257
258
    /**
259
     * Try executing cwebp in common system paths
260
     *
261
     * @param  boolean  $useNice          Whether to use nice
262
     * @param  string   $commandOptions   for the exec call
263
     *
264
     * @return  array  Unique failure codes in case of failure, empty array in case of success
265
     */
266 1
    private function tryCommonSystemPaths($useNice, $commandOptions)
267
    {
268 1
        $failureCodes = [];
269
270
        // Loop through paths
271 1
        foreach (self::$cwebpDefaultPaths as $index => $binary) {
272 1
            $returnCode = $this->executeBinary($binary, $commandOptions, $useNice);
273 1
            if ($returnCode == 0) {
274
                $this->logLn('Successfully executed binary: ' . $binary);
275
                return [];
276
            } else {
277 1
                if ($returnCode == 127) {
278 1
                    $this->logLn(
279 1
                        'Trying to execute binary: ' . $binary . '. Failed (not found)'
280
                    );
281
                } else {
282
                    $this->logLn(
283
                        'Trying to execute binary: ' . $binary . '. Failed (return code: ' . $returnCode . ')'
284
                    );
285
                }
286 1
                if (!in_array($returnCode, $failureCodes)) {
287 1
                    $failureCodes[] = $returnCode;
288
                }
289
            }
290
        }
291 1
        return $failureCodes;
292
    }
293
294
    /**
295
     * Try executing supplied cwebp for PHP_OS.
296
     *
297
     * @param  boolean  $useNice          Whether to use nice
298
     * @param  string   $commandOptions   for the exec call
299
     * @param  array    $failureCodesForCommonSystemPaths  Return codes from the other attempt
300
     *                                                     (in order to produce short error message)
301
     *
302
     * @return  string  Error message if failure, empty string if successful
303
     */
304 2
    private function trySuppliedBinaryForOS($useNice, $commandOptions, $failureCodesForCommonSystemPaths)
305
    {
306 2
        $this->logLn('Trying to execute supplied binary for OS: ' . PHP_OS);
307
308
        // Try supplied binary (if available for OS, and hash is correct)
309 2
        $options = $this->options;
310 2
        if (!isset(self::$suppliedBinariesInfo[PHP_OS])) {
311
            return 'No supplied binaries found for OS:' . PHP_OS;
312
        }
313
314 2
        $info = self::$suppliedBinariesInfo[PHP_OS];
315
316 2
        $file = $info[0];
317 2
        $hash = $info[1];
318
319 2
        $binaryFile = __DIR__ . '/' . $options['rel-path-to-precompiled-binaries'] . '/' . $file;
320
321
322
        // The file should exist, but may have been removed manually.
323 2
        if (!file_exists($binaryFile)) {
324
            return 'Supplied binary not found! It ought to be here:' . $binaryFile;
325
        }
326
327
        // File exists, now generate its hash
328
329
        // hash_file() is normally available, but it is not always
330
        // - https://stackoverflow.com/questions/17382712/php-5-3-20-undefined-function-hash
331
        // If available, validate that hash is correct.
332
333 2
        if (function_exists('hash_file')) {
334 2
            $binaryHash = hash_file('sha256', $binaryFile);
335
336 2
            if ($binaryHash != $hash) {
337
                return 'Binary checksum of supplied binary is invalid! ' .
338
                    'Did you transfer with FTP, but not in binary mode? ' .
339
                    'File:' . $binaryFile . '. ' .
340
                    'Expected checksum: ' . $hash . '. ' .
341
                    'Actual checksum:' . $binaryHash . '.';
342
            }
343
        }
344
345 2
        $returnCode = $this->executeBinary($binaryFile, $commandOptions, $useNice);
346 2
        if ($returnCode == 0) {
347
            // yay!
348 2
            $this->logLn('success!');
349 2
            return '';
350
        }
351
352
        $errorMsg = 'Tried executing supplied binary for ' . PHP_OS . ', ' .
353
            ($options['try-common-system-paths'] ? 'but that failed too' : 'but failed');
354
355
356
        if (($options['try-common-system-paths']) && (count($failureCodesForCommonSystemPaths) > 0)) {
357
            // check if it was the same error
358
            // if it was, simply refer to that with "(same problem)"
359
            $majorFailCode = 0;
360
            if (count($failureCodesForCommonSystemPaths) == 1) {
361
                $majorFailCode = $failureCodesForCommonSystemPaths[0];
362
            } else {
363
                $failureCodesBesides127 = array_values(array_diff($failureCodesForCommonSystemPaths, [127]));
364
                if (count($failureCodesBesides127) == 1) {
365
                    $majorFailCode = $failureCodesBesides127[0];
366
                } else {
367
                    // it cannot be summarized into a single code
368
                }
369
            }
370
            if ($majorFailCode != 0) {
371
                $errorMsg .= ' (same problem)';
372
                return $errorMsg;
373
            }
374
        }
375
376
        if ($returnCode > 128) {
377
            $errorMsg .= '. The binary did not work (exit code: ' . $returnCode . '). ' .
378
                'Check out https://github.com/rosell-dk/webp-convert/issues/92';
379
        } else {
380
            switch ($returnCode) {
381
                case 0:
382
                    // success!
383
                    break;
384
                case 126:
385
                    $errorMsg .= ': Permission denied. The user that the command was run' .
386
                        ' with (' . shell_exec('whoami') . ') does not have permission to ' .
387
                        'execute that binary.';
388
                    break;
389
                case 127:
390
                    $errorMsg .= '. The binary was not found! ' .
391
                        'It ought to be here: ' . $binaryFile;
392
                    break;
393
                default:
394
                    $errorMsg .= ' (exit code:' .  $returnCode . ').';
395
            }
396
        }
397
        return $errorMsg;
398
    }
399
400 2
    protected function doActualConvert()
401
    {
402 2
        $errorMsg = '';
403 2
        $options = $this->options;
404 2
        $useNice = (($options['use-nice']) && self::hasNiceSupport());
405
406 2
        $commandOptions = $this->createCommandLineOptions();
407
408
        // Try all common paths that exists
409 2
        $success = false;
410
411 2
        $failureCodes = [];
412
413 2
        if ($options['try-common-system-paths']) {
414 1
            $failureCodes = $this->tryCommonSystemPaths($useNice, $commandOptions);
415 1
            $success = (count($failureCodes) == 0);
416 1
            $errorMsg = $this->composeErrorMessageForCommonSystemPathsFailures($failureCodes);
417
        }
418
419 2
        if (!$success && $options['try-supplied-binary-for-os']) {
420 2
            $errorMsg2 = $this->trySuppliedBinaryForOS($useNice, $commandOptions, $failureCodes);
421 2
            $errorMsg .= $errorMsg2;
422 2
            $success = ($errorMsg2 == '');
423
        }
424
425
        // cwebp sets file permissions to 664 but instead ..
426
        // .. $destination's parent folder's permissions should be used (except executable bits)
427
        // (or perhaps the current umask instead? https://www.php.net/umask)
428
429 2
        if ($success) {
430 2
            $destinationParent = dirname($this->destination);
431 2
            $fileStatistics = stat($destinationParent);
432 2
            if ($fileStatistics !== false) {
433
                // Apply same permissions as parent folder but strip off the executable bits
434 2
                $permissions = $fileStatistics['mode'] & 0000666;
435 2
                chmod($this->destination, $permissions);
436
            }
437
        }
438
439 2
        if (!$success) {
440
            throw new SystemRequirementsNotMetException($errorMsg);
441
        }
442 2
    }
443
}
444