3 namespace BookStack\Util;
8 * Helper class to sniff out the mime-type of content resulting in
9 * a mime-type that's relatively safe to serve to a browser.
11 class WebSafeMimeSniffer
16 protected array $safeMimes = [
18 'application/octet-stream',
51 protected array $textTypesByExtension = [
53 'js' => 'text/javascript',
54 'json' => 'application/json',
59 * Sniff the mime-type from the given file content while running the result
60 * through an allow-list to ensure a web-safe result.
61 * Takes the content as a reference since the value may be quite large.
62 * Accepts an optional $extension which can be used for further guessing.
64 public function sniff(string &$content, string $extension = ''): string
66 $fInfo = new finfo(FILEINFO_MIME_TYPE);
67 $mime = $fInfo->buffer($content) ?: 'application/octet-stream';
69 if ($mime === 'text/plain' && $extension) {
70 $mime = $this->textTypesByExtension[$extension] ?? 'text/plain';
73 if (in_array($mime, $this->safeMimes)) {
77 [$category] = explode('/', $mime, 2);
78 if ($category === 'text') {
82 return 'application/octet-stream';