|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace BookStack\Uploads; |
| 4 | + |
| 5 | +use BookStack\Util\WebSafeMimeSniffer; |
| 6 | +use Closure; |
| 7 | +use Illuminate\Contracts\Validation\ValidationRule; |
| 8 | +use Illuminate\Translation\PotentiallyTranslatedString; |
| 9 | +use InvalidArgumentException; |
| 10 | + |
| 11 | +class Base64UriMimeRule implements ValidationRule |
| 12 | +{ |
| 13 | + public function __construct( |
| 14 | + protected string $requiredMime |
| 15 | + ) { |
| 16 | + if (empty($requiredMime)) { |
| 17 | + throw new InvalidArgumentException('A required mime type must be provided'); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Run the validation rule. |
| 23 | + * |
| 24 | + * @param Closure(string, ?string=): PotentiallyTranslatedString $fail |
| 25 | + */ |
| 26 | + public function validate(string $attribute, mixed $value, Closure $fail): void |
| 27 | + { |
| 28 | + $imageDataEncoded = explode(',', $value, 2)[1] ?? ''; |
| 29 | + if (empty($imageDataEncoded)) { |
| 30 | + $fail('validation.base64_uri_mime')->translate(['mime' => $this->requiredMime]); |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + $imageData = base64_decode($imageDataEncoded); |
| 35 | + if (empty($imageData)) { |
| 36 | + $fail('validation.base64_uri_mime')->translate(['mime' => $this->requiredMime]); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + $sniffer = new WebSafeMimeSniffer(); |
| 41 | + $mime = $sniffer->sniff($imageData); |
| 42 | + |
| 43 | + if ($mime !== $this->requiredMime) { |
| 44 | + $fail('validation.base64_uri_mime')->translate(['mime' => $this->requiredMime]); |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments