]> BookStack Code Mirror - bookstack/blob - app/Uploads/FaviconHandler.php
f61e7ae64b2c779e6d8caa7053db8579e824fac9
[bookstack] / app / Uploads / FaviconHandler.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use Illuminate\Http\UploadedFile;
6 use Intervention\Image\ImageManager;
7
8 class FaviconHandler
9 {
10     public function __construct(
11         protected ImageManager $imageTool
12     ) {
13     }
14
15     /**
16      * Save the given UploadedFile instance as the application favicon.
17      */
18     public function saveForUploadedImage(UploadedFile $file): void
19     {
20         $targetPath = public_path('favicon.ico');
21         if (!is_writeable($targetPath)) {
22             return;
23         }
24
25         $imageData = file_get_contents($file->getRealPath());
26         $image = $this->imageTool->make($imageData);
27         $image->resize(32, 32);
28         $bmpData = $image->encode('bmp');
29         $icoData = $this->bmpToIco($bmpData, 32, 32);
30
31         file_put_contents($targetPath, $icoData);
32     }
33
34     /**
35      * Restore the original favicon image.
36      */
37     public function restoreOriginal(): void
38     {
39         $targetPath = public_path('favicon.ico');
40         $original = public_path('icon.ico');
41         if (!is_writeable($targetPath)) {
42             return;
43         }
44
45         copy($original, $targetPath);
46     }
47
48     /**
49      * Convert BMP image data to ICO file format.
50      * Built following the file format info from Wikipedia:
51      * https://en.wikipedia.org/wiki/ICO_(file_format)
52      */
53     protected function bmpToIco(string $bmpData, int $width, int $height): string
54     {
55         // Trim off the header of the bitmap file
56         $rawBmpData = substr($bmpData, 14);
57
58         // ICO header
59         $header = pack('v', 0x00); // Reserved. Must always be 0
60         $header .= pack('v', 0x01); // Specifies ico image
61         $header .= pack('v', 0x01); // Specifies number of images
62
63         // ICO Image Directory
64         $entry = hex2bin(dechex($width)); // Image width
65         $entry .= hex2bin(dechex($height)); // Image height
66         $entry .= "\0"; // Color palette, typically 0
67         $entry .= "\0"; // Reserved
68
69         // Color planes, Appears to remain 1 for bmp image data
70         $entry .= pack('v', 0x01);
71         // Bits per pixel, can range from 1 to 32. From testing conversion
72         // via intervention from png typically provides this as 32.
73         $entry .= pack('v', 0x20);
74         // Size of the image data in bytes
75         $entry .= pack('V', strlen($rawBmpData));
76         // Offset of the bmp data from file start
77         $entry .= pack('V', strlen($header) + strlen($entry) + 4);
78
79         // Join & return the combined parts of the ICO image data
80         return $header . $entry . $rawBmpData;
81     }
82 }