]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/ImageController.php
Fixed entity messages on delete. Fixes #21.
[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 use Illuminate\Support\Facades\Auth;
8 use Intervention\Image\Facades\Image as ImageTool;
9 use Illuminate\Support\Facades\DB;
10 use Oxbow\Http\Requests;
11 use Oxbow\Image;
12
13 class ImageController extends Controller
14 {
15     protected $image;
16     protected $file;
17
18     /**
19      * ImageController constructor.
20      * @param Image $image
21      * @param File $file
22      */
23     public function __construct(Image $image, File $file)
24     {
25         $this->image = $image;
26         $this->file = $file;
27     }
28
29     /**
30      * Returns an image from behind the public-facing application.
31      * @param Request $request
32      * @return \Illuminate\Http\Response
33      */
34     public function getImage(Request $request)
35     {
36         $cacheTime = 60*60*24;
37         $path = storage_path() . '/' . $request->path();
38         $modifiedTime = $this->file->lastModified($path);
39         $eTag = md5($modifiedTime . $path);
40         $headerLastModified = gmdate('r', $modifiedTime);
41         $headerExpires = gmdate('r', $modifiedTime + $cacheTime);
42
43         $headers = [
44             'Last-Modified' => $headerLastModified,
45             'Cache-Control' => 'must-revalidate',
46             'Pragma' => 'public',
47             'Expires' => $headerExpires,
48             'Etag' => $eTag
49         ];
50
51         $browserModifiedSince = $request->header('If-Modified-Since');
52         $browserNoneMatch = $request->header('If-None-Match');
53         if($browserModifiedSince !== null && file_exists($path) && ($browserModifiedSince == $headerLastModified || $browserNoneMatch == $eTag)) {
54             return response()->make('', 304, $headers);
55         }
56
57         if(file_exists($path)) {
58             return response()->make(file_get_contents($path), 200, array_merge($headers, [
59                 'Content-Type' => $this->file->mimeType($path),
60                 'Content-Length' => filesize($path),
61             ]));
62         }
63         abort(404);
64     }
65
66     /**
67      * Get all images, Paginated
68      * @param int $page
69      * @return \Illuminate\Http\JsonResponse
70      */
71     public function getAll($page = 0)
72     {
73         $pageSize = 30;
74         $images = DB::table('images')->orderBy('created_at', 'desc')
75             ->skip($page*$pageSize)->take($pageSize)->get();
76         foreach($images as $image) {
77             $image->thumbnail = $this->getThumbnail($image, 150, 150);
78         }
79         $hasMore = count(DB::table('images')->orderBy('created_at', 'desc')
80             ->skip(($page+1)*$pageSize)->take($pageSize)->get()) > 0;
81         return response()->json([
82             'images' => $images,
83             'hasMore' => $hasMore
84         ]);
85     }
86
87     /**
88      * Get the thumbnail for an image.
89      * @param $image
90      * @param int $width
91      * @param int $height
92      * @return string
93      */
94     public function getThumbnail($image, $width = 220, $height = 220)
95     {
96         $explodedPath = explode('/', $image->url);
97         array_splice($explodedPath, 4, 0, ['thumbs-' . $width . '-' . $height]);
98         $thumbPath = implode('/', $explodedPath);
99         $thumbFilePath = public_path() . $thumbPath;
100
101         // Return the thumbnail url path if already exists
102         if(file_exists($thumbFilePath)) {
103             return $thumbPath;
104         }
105
106         // Otherwise create the thumbnail
107         $thumb = ImageTool::make(public_path() . $image->url);
108         $thumb->fit($width, $height);
109
110         // Create thumbnail folder if it does not exist
111         if(!file_exists(dirname($thumbFilePath))) {
112             mkdir(dirname($thumbFilePath), 0775, true);
113         }
114
115         //Save Thumbnail
116         $thumb->save($thumbFilePath);
117         return $thumbPath;
118     }
119
120     /**
121      * Handles image uploads for use on pages.
122      * @param Request $request
123      * @return \Illuminate\Http\JsonResponse
124      */
125     public function upload(Request $request)
126     {
127         $imageUpload = $request->file('file');
128         $name = str_replace(' ', '-', $imageUpload->getClientOriginalName());
129         $storageName = substr(sha1(time()), 0, 10) . '-' . $name;
130         $imagePath = '/uploads/images/'.Date('Y-m-M').'/';
131         $storagePath = public_path(). $imagePath;
132         $fullPath = $storagePath . $storageName;
133         while(file_exists($fullPath)) {
134             $storageName = substr(sha1(rand()), 0, 3) . $storageName;
135             $fullPath = $storagePath . $storageName;
136         }
137         $imageUpload->move($storagePath, $storageName);
138         // Create and save image object
139         $this->image->name = $name;
140         $this->image->url = $imagePath . $storageName;
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      * Update image details
150      * @param $imageId
151      * @param Request $request
152      * @return \Illuminate\Http\JsonResponse
153      */
154     public function update($imageId, Request $request)
155     {
156         $this->validate($request, [
157             'name' => 'required|min:2|string'
158         ]);
159         $image = $this->image->findOrFail($imageId);
160         $image->fill($request->all());
161         $image->save();
162         return response()->json($this->image);
163     }
164
165     /**
166      * Deletes an image and all thumbnail/image files
167      * @param $id
168      * @return \Illuminate\Http\JsonResponse
169      */
170     public function destroy($id)
171     {
172         $image = $this->image->findOrFail($id);
173
174         // Delete files
175         $folder = public_path() . dirname($image->url);
176         $fileName = basename($image->url);
177
178         // Delete thumbnails
179         foreach(glob($folder . '/*') as $file) {
180             if(is_dir($file)) {
181                 $thumbName = $file . '/' . $fileName;
182                 if(file_exists($file)) {
183                     unlink($thumbName);
184                 }
185                 // Remove thumb folder if empty
186                 if(count(glob($file . '/*')) === 0) {
187                     rmdir($file);
188                 }
189             }
190         }
191
192         // Delete file and database entry
193         unlink($folder . '/' . $fileName);
194         $image->delete();
195
196         // Delete parent folder if empty
197         if(count(glob($folder . '/*')) === 0) {
198             rmdir($folder);
199         }
200         return response()->json('Image Deleted');
201     }
202
203
204 }