]> BookStack Code Mirror - bookstack/blob - app/Util/WebSafeMimeSniffer.php
Added testing for our request method overrides
[bookstack] / app / Util / WebSafeMimeSniffer.php
1 <?php
2
3 namespace BookStack\Util;
4
5 use finfo;
6
7 /**
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.
10  */
11 class WebSafeMimeSniffer
12 {
13     /**
14      * @var string[]
15      */
16     protected $safeMimes = [
17         'application/json',
18         'application/octet-stream',
19         'application/pdf',
20         'image/apng',
21         'image/bmp',
22         'image/jpeg',
23         'image/png',
24         'image/gif',
25         'image/webp',
26         'image/avif',
27         'image/heic',
28         'text/css',
29         'text/csv',
30         'text/javascript',
31         'text/json',
32         'text/plain',
33         'video/x-msvideo',
34         'video/mp4',
35         'video/mpeg',
36         'video/ogg',
37         'video/webm',
38         'video/vp9',
39         'video/h264',
40         'video/av1',
41     ];
42
43     /**
44      * Sniff the mime-type from the given file content while running the result
45      * through an allow-list to ensure a web-safe result.
46      * Takes the content as a reference since the value may be quite large.
47      */
48     public function sniff(string &$content): string
49     {
50         $fInfo = new finfo(FILEINFO_MIME_TYPE);
51         $mime = $fInfo->buffer($content) ?: 'application/octet-stream';
52
53         if (in_array($mime, $this->safeMimes)) {
54             return $mime;
55         }
56
57         [$category] = explode('/', $mime, 2);
58         if ($category === 'text') {
59             return 'text/plain';
60         }
61
62         return 'application/octet-stream';
63     }
64 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.