|
6 | 6 | namespace Joppuyo\JpegXlEncode; |
7 | 7 |
|
8 | 8 | use ImageMimeTypeGuesser\ImageMimeTypeGuesser; |
| 9 | +use Joppuyo\JpegXlEncode\Exception\BinaryValidationException; |
9 | 10 | use Joppuyo\JpegXlEncode\Exception\InvalidArgumentException; |
10 | 11 | use Symfony\Component\Process\Process; |
11 | 12 | use Respect\Validation\Validator as v; |
12 | 13 |
|
13 | 14 | class Encoder { |
| 15 | + |
| 16 | + /** |
| 17 | + * @var bool false |
| 18 | + */ |
| 19 | + private static $binaryValidated; |
| 20 | + |
| 21 | + function __construct() { |
| 22 | + self::$binaryValidated = false; |
| 23 | + } |
| 24 | + |
14 | 25 | /* |
15 | 26 | * Convert a JPEG or PNG file to JPEG XL |
16 | 27 | * @throws \Exception |
@@ -86,6 +97,7 @@ public static function encode(string $source, string $destination, array $option |
86 | 97 | } |
87 | 98 |
|
88 | 99 | $binary_path = self::getBinaryPath(); |
| 100 | + self::validateBinary($binary_path); |
89 | 101 | self::ensure_permissions($binary_path); |
90 | 102 |
|
91 | 103 | $process_parameters = array_merge([$binary_path, $source, $destination], $flags); |
@@ -152,4 +164,37 @@ private static function validateOptions(array $options) |
152 | 164 | } |
153 | 165 |
|
154 | 166 | } |
| 167 | + |
| 168 | + private static function validateBinary($binaryPath) { |
| 169 | + if(self::$binaryValidated) { |
| 170 | + // We validate binary only once per request to improve performance |
| 171 | + self::debug('Binary already validated.'); |
| 172 | + return; |
| 173 | + } |
| 174 | + self::debug("Binary hasn't been validated yet. Validating..."); |
| 175 | + $comparisonHash = self::getHash(); |
| 176 | + $binaryHash = hash_file('sha256', $binaryPath); |
| 177 | + if(!hash_equals($binaryHash, $comparisonHash)) { |
| 178 | + self::debug('Hash does not match.'); |
| 179 | + throw new BinaryValidationException("Binary hash check failed."); |
| 180 | + } |
| 181 | + self::debug('Hash hash matches. Caching result of hash comparison to speed up further conversions.'); |
| 182 | + self::$binaryValidated = true; |
| 183 | + } |
| 184 | + |
| 185 | + private static function getHash() |
| 186 | + { |
| 187 | + if (PHP_OS_FAMILY === 'Darwin') { |
| 188 | + // https://github.com/joppuyo/jpeg-xl-static-mac/releases/tag/v0.5.0-static-2 |
| 189 | + return '292927130b4a83c639df6ba573916c2205234ca85f68a1e1357201e5b33b1904'; |
| 190 | + } |
| 191 | + if (PHP_OS_FAMILY === 'Linux') { |
| 192 | + // https://github.com/joppuyo/jpeg-xl-static/releases/tag/v0.5.0-static-2 |
| 193 | + return '50715d6af73bf177113ec4d46c35036b6295eb9a1be7e434c1a8ebbe5a1b8bda'; |
| 194 | + } |
| 195 | + if (PHP_OS_FAMILY === 'Windows') { |
| 196 | + // https://github.com/joppuyo/jpeg-xl-static/releases/tag/v0.5.0-static |
| 197 | + return 'b78ec5a1b48c48c1e0dbb47865f7af8057a92291c65581a59e744a3dac6d5490'; |
| 198 | + } |
| 199 | + } |
155 | 200 | } |
0 commit comments