*/ protected const EXTENSIONS = [ 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'image/gif' => 'gif', 'image/avif' => 'avif', 'image/svg+xml' => 'svg', ]; public function store(MediaRequest $request, RemoteImage $remote): JsonResponse { $for = (string) $request->input('for', 'pages'); $this->authorize('upload', [Media::class, $for]); $field = $request->hasFile('file') ? 'file' : 'url'; $contents = $field === 'file' ? (string) $request->file('file')->get() : $remote->fetch((string) $request->string('url')); $mime = (new finfo(FILEINFO_MIME_TYPE))->buffer($contents) ?: null; if (! in_array($mime, (array) config('media.upload.mimes'), true)) { $this->refuse($field); } if ($mime === 'image/svg+xml') { $contents = $this->sanitize($contents) ?? $this->refuse($field); // A vector has no pixel size; the processor copies it through. $size = [null, null]; } else { // The type is read from the magic bytes; this catches a file that // has them but does not decode, which nobody could render either. $size = @getimagesizefromstring($contents) ?: $this->refuse($field); } $path = config("media.upload.for.{$for}").'/'.Str::random(40).'.'.self::EXTENSIONS[$mime]; Storage::disk((string) config('media.disk'))->put($path, $contents); $media = Media::for($path); // What is already known, so the answer carries dimensions straight // away rather than after the queue has run. The processor writes the // same values, and the rest, when it does. if (! $media->isProcessed()) { $media->forceFill([ 'mime' => $mime, 'size' => strlen($contents), 'width' => $size[0], 'height' => $size[1], ])->save(); } return MediaResource::make($media->fresh())->response()->setStatusCode(201); } /** * An SVG with what could run taken out: scripts, event handlers, and * references to anything outside the file. Null when what is left is not * an SVG at all. */ protected function sanitize(string $svg): ?string { $sanitizer = new Sanitizer; $sanitizer->removeRemoteReferences(true); $clean = $sanitizer->sanitize($svg); return is_string($clean) && str_contains($clean, ' [__('rules.media.not_an_image')]]); } }