]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/ImageController.php
Improved image serving and uploading. Fixes #7 and #8.
[bookstack] / app / Http / Controllers / ImageController.php
1 <?php
2
3 namespace Oxbow\Http\Controllers;
4
5 use Illuminate\Filesystem\Filesystem as File;
6 use Illuminate\Http\Request;
7
8 use Illuminate\Support\Facades\Auth;
9 use Intervention\Image\Facades\Image as ImageTool;
10 use Illuminate\Support\Facades\DB;
11 use Oxbow\Http\Requests;
12 use Oxbow\Image;
13
14 class ImageController extends Controller
15 {
16     protected $image;
17     protected $file;
18
19     /**
20      * ImageController constructor.
21      * @param Image $image
22      * @param File $file
23      */
24     public function __construct(Image $image, File $file)
25     {
26         $this->image = $image;
27         $this->file = $file;
28     }
29
30     /**
31      * Returns an image from behind the public-facing application.
32      * @param Request $request
33      * @return \Illuminate\Http\Response
34      */
35     public function getImage(Request $request)
36     {
37         $cacheTime = 60*60*24;
38         $path = storage_path() . '/' . $request->path();
39         $modifiedTime = $this->file->lastModified($path);
40         $eTag = md5($modifiedTime . $path);
41         $headerLastModified = gmdate('r', $modifiedTime);
42         $headerExpires = gmdate('r', $modifiedTime + $cacheTime);
43
44         $headers = [
45             'Last-Modified' => $headerLastModified,
46             'Cache-Control' => 'must-revalidate',
47             'Pragma' => 'public',
48             'Expires' => $headerExpires,
49             'Etag' => $eTag
50         ];
51
52         $browserModifiedSince = $request->header('If-Modified-Since');
53         $browserNoneMatch = $request->header('If-None-Match');
54         if($browserModifiedSince !== null && file_exists($path) && ($browserModifiedSince == $headerLastModified || $browserNoneMatch == $eTag)) {
55             return response()->make('', 304, $headers);
56         }
57
58         if(file_exists($path)) {
59             return response()->make(file_get_contents($path), 200, array_merge($headers, [
60                 'Content-Type' => $this->file->mimeType($path),
61                 'Content-Length' => filesize($path),
62             ]));
63         }
64         abort(404);
65     }
66
67     /**
68      * Get all images, Paginated
69      * @param int $page
70      * @return \Illuminate\Http\JsonResponse
71      */
72     public function getAll($page = 0)
73     {
74         $pageSize = 13;
75         $images = DB::table('images')->orderBy('created_at', 'desc')
76             ->skip($page*$pageSize)->take($pageSize)->get();
77         foreach($images as $image) {
78             $image->thumbnail = $this->getThumbnail($image, 150, 150);
79         }
80         $hasMore = count(DB::table('images')->orderBy('created_at', 'desc')
81             ->skip(($page+1)*$pageSize)->take($pageSize)->get()) > 0;
82         return response()->json([
83             'images' => $images,
84             'hasMore' => $hasMore
85         ]);
86     }
87
88     /**
89      * Get the thumbnail for an image.
90      * @param $image
91      * @param int $width
92      * @param int $height
93      * @return string
94      */
95     public function getThumbnail($image, $width = 220, $height = 220)
96     {
97         $explodedPath = explode('/', $image->url);
98         array_splice($explodedPath, 3, 0, ['thumbs-' . $width . '-' . $height]);
99         $thumbPath = implode('/', $explodedPath);
100         $thumbFilePath = storage_path() . $thumbPath;
101
102         // Return the thumbnail url path if already exists
103         if(file_exists($thumbFilePath)) {
104             return $thumbPath;
105         }
106
107         // Otherwise create the thumbnail
108         $thumb = ImageTool::make(storage_path() . $image->url);
109         $thumb->fit($width, $height);
110
111         // Create thumbnail folder if it does not exist
112         if(!file_exists(dirname($thumbFilePath))) {
113             mkdir(dirname($thumbFilePath), 0775, true);
114         }
115
116         //Save Thumbnail
117         $thumb->save($thumbFilePath);
118         return $thumbPath;
119     }
120
121     /**
122      * Handles image uploads for use on pages.
123      * @param Request $request
124      * @return \Illuminate\Http\JsonResponse
125      */
126     public function upload(Request $request)
127     {
128         $imageUpload = $request->file('file');
129         $name = str_replace(' ', '-', $imageUpload->getClientOriginalName());
130         $imagePath = '/images/' . Date('Y-m-M') . '/';
131         $storagePath = storage_path(). $imagePath;
132         $fullPath = $storagePath . $name;
133         while(file_exists($fullPath)) {
134             $name = substr(sha1(rand()), 0, 3) . $name;
135             $fullPath = $storagePath . $name;
136         }
137         $imageUpload->move($storagePath, $name);
138         // Create and save image object
139         $this->image->name = $name;
140         $this->image->url = $imagePath . $name;
141         $this->image->created_by = Auth::user()->id;
142         $this->image->updated_by = Auth::user()->id;
143         $this->image->save();
144         $this->image->thumbnail = $this->getThumbnail($this->image, 150, 150);
145         return response()->json($this->image);
146     }
147
148
149 }