]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/ImageController.php
Added permission system
[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         parent::__construct();
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 = 30;
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, 4, 0, ['thumbs-' . $width . '-' . $height]);
99         $thumbPath = implode('/', $explodedPath);
100         $thumbFilePath = public_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(public_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         $this->checkPermission('image-create');
129         $imageUpload = $request->file('file');
130         $name = str_replace(' ', '-', $imageUpload->getClientOriginalName());
131         $storageName = substr(sha1(time()), 0, 10) . '-' . $name;
132         $imagePath = '/uploads/images/' . Date('Y-m-M') . '/';
133         $storagePath = public_path() . $imagePath;
134         $fullPath = $storagePath . $storageName;
135         while (file_exists($fullPath)) {
136             $storageName = substr(sha1(rand()), 0, 3) . $storageName;
137             $fullPath = $storagePath . $storageName;
138         }
139         $imageUpload->move($storagePath, $storageName);
140         // Create and save image object
141         $this->image->name = $name;
142         $this->image->url = $imagePath . $storageName;
143         $this->image->created_by = Auth::user()->id;
144         $this->image->updated_by = Auth::user()->id;
145         $this->image->save();
146         $this->image->thumbnail = $this->getThumbnail($this->image, 150, 150);
147         return response()->json($this->image);
148     }
149
150     /**
151      * Update image details
152      * @param         $imageId
153      * @param Request $request
154      * @return \Illuminate\Http\JsonResponse
155      */
156     public function update($imageId, Request $request)
157     {
158         $this->checkPermission('image-update');
159         $this->validate($request, [
160             'name' => 'required|min:2|string'
161         ]);
162         $image = $this->image->findOrFail($imageId);
163         $image->fill($request->all());
164         $image->save();
165         return response()->json($this->image);
166     }
167
168     /**
169      * Deletes an image and all thumbnail/image files
170      * @param $id
171      * @return \Illuminate\Http\JsonResponse
172      */
173     public function destroy($id)
174     {
175         $this->checkPermission('image-delete');
176         $image = $this->image->findOrFail($id);
177
178         // Delete files
179         $folder = public_path() . dirname($image->url);
180         $fileName = basename($image->url);
181
182         // Delete thumbnails
183         foreach (glob($folder . '/*') as $file) {
184             if (is_dir($file)) {
185                 $thumbName = $file . '/' . $fileName;
186                 if (file_exists($file)) {
187                     unlink($thumbName);
188                 }
189                 // Remove thumb folder if empty
190                 if (count(glob($file . '/*')) === 0) {
191                     rmdir($file);
192                 }
193             }
194         }
195
196         // Delete file and database entry
197         unlink($folder . '/' . $fileName);
198         $image->delete();
199
200         // Delete parent folder if empty
201         if (count(glob($folder . '/*')) === 0) {
202             rmdir($folder);
203         }
204         return response()->json('Image Deleted');
205     }
206
207
208 }