]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/BookController.php
a9a24d2ff519a56a888e66450ba8a5e4c4e9b555
[bookstack] / app / Http / Controllers / BookController.php
1 <?php namespace BookStack\Http\Controllers;
2
3 use Activity;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Entities\Book;
6 use BookStack\Entities\Bookshelf;
7 use BookStack\Entities\EntityContextManager;
8 use BookStack\Entities\Repos\BookRepo;
9 use BookStack\Exceptions\ImageUploadException;
10 use BookStack\Exceptions\NotFoundException;
11 use BookStack\Exceptions\NotifyException;
12 use BookStack\Uploads\ImageRepo;
13 use Illuminate\Contracts\View\Factory;
14 use Illuminate\Http\RedirectResponse;
15 use Illuminate\Http\Request;
16 use Illuminate\Http\Response;
17 use Illuminate\Routing\Redirector;
18 use Illuminate\Validation\ValidationException;
19 use Illuminate\View\View;
20 use Throwable;
21 use Views;
22
23 class BookController extends Controller
24 {
25
26     protected $bookRepo;
27     protected $userRepo;
28     protected $entityContextManager;
29     protected $imageRepo;
30
31     /**
32      * BookController constructor.
33      * @param BookRepo $bookRepo
34      * @param UserRepo $userRepo
35      * @param EntityContextManager $entityContextManager
36      * @param ImageRepo $imageRepo
37      */
38     public function __construct(
39         BookRepo $bookRepo,
40         UserRepo $userRepo,
41         EntityContextManager $entityContextManager,
42         ImageRepo $imageRepo
43     ) {
44         $this->bookRepo = $bookRepo;
45         $this->userRepo = $userRepo;
46         $this->entityContextManager = $entityContextManager;
47         $this->imageRepo = $imageRepo;
48         parent::__construct();
49     }
50
51     /**
52      * Display a listing of the book.
53      * @return Response
54      */
55     public function index()
56     {
57         $view = setting()->getForCurrentUser('books_view_type', config('app.views.books'));
58         $sort = setting()->getForCurrentUser('books_sort', 'name');
59         $order = setting()->getForCurrentUser('books_sort_order', 'asc');
60
61         $books = $this->bookRepo->getAllPaginated('book', 18, $sort, $order);
62         $recents = $this->isSignedIn() ? $this->bookRepo->getRecentlyViewed('book', 4, 0) : false;
63         $popular = $this->bookRepo->getPopular('book', 4, 0);
64         $new = $this->bookRepo->getRecentlyCreated('book', 4, 0);
65
66         $this->entityContextManager->clearShelfContext();
67
68         $this->setPageTitle(trans('entities.books'));
69         return view('books.index', [
70             'books' => $books,
71             'recents' => $recents,
72             'popular' => $popular,
73             'new' => $new,
74             'view' => $view,
75             'sort' => $sort,
76             'order' => $order,
77         ]);
78     }
79
80     /**
81      * Show the form for creating a new book.
82      * @param string $shelfSlug
83      * @return Response
84      * @throws NotFoundException
85      */
86     public function create(string $shelfSlug = null)
87     {
88         $bookshelf = null;
89         if ($shelfSlug !== null) {
90             $bookshelf = $this->bookRepo->getEntityBySlug('bookshelf', $shelfSlug);
91             $this->checkOwnablePermission('bookshelf-update', $bookshelf);
92         }
93
94         $this->checkPermission('book-create-all');
95         $this->setPageTitle(trans('entities.books_create'));
96         return view('books.create', [
97             'bookshelf' => $bookshelf
98         ]);
99     }
100
101     /**
102      * Store a newly created book in storage.
103      *
104      * @param Request $request
105      * @param string $shelfSlug
106      * @return Response
107      * @throws NotFoundException
108      * @throws ImageUploadException
109      * @throws ValidationException
110      */
111     public function store(Request $request, string $shelfSlug = null)
112     {
113         $this->checkPermission('book-create-all');
114         $this->validate($request, [
115             'name' => 'required|string|max:255',
116             'description' => 'string|max:1000',
117             'image' => $this->imageRepo->getImageValidationRules(),
118         ]);
119
120         $bookshelf = null;
121         if ($shelfSlug !== null) {
122             /** @var Bookshelf $bookshelf */
123             $bookshelf = $this->bookRepo->getEntityBySlug('bookshelf', $shelfSlug);
124             $this->checkOwnablePermission('bookshelf-update', $bookshelf);
125         }
126
127         /** @var Book $book */
128         $book = $this->bookRepo->createFromInput('book', $request->all());
129         $this->bookUpdateActions($book, $request);
130         Activity::add($book, 'book_create', $book->id);
131
132         if ($bookshelf) {
133             $bookshelf->appendBook($book);
134             Activity::add($bookshelf, 'bookshelf_update');
135         }
136
137         return redirect($book->getUrl());
138     }
139
140     /**
141      * Display the specified book.
142      * @param Request $request
143      * @param string $slug
144      * @return Response
145      * @throws NotFoundException
146      */
147     public function show(Request $request, string $slug)
148     {
149         $book = $this->bookRepo->getBySlug($slug);
150         $this->checkOwnablePermission('book-view', $book);
151
152         $bookChildren = $this->bookRepo->getBookChildren($book);
153
154         Views::add($book);
155         if ($request->has('shelf')) {
156             $this->entityContextManager->setShelfContext(intval($request->get('shelf')));
157         }
158
159         $this->setPageTitle($book->getShortName());
160         return view('books.show', [
161             'book' => $book,
162             'current' => $book,
163             'bookChildren' => $bookChildren,
164             'activity' => Activity::entityActivity($book, 20, 1)
165         ]);
166     }
167
168     /**
169      * Show the form for editing the specified book.
170      * @param string $slug
171      * @return Response
172      * @throws NotFoundException
173      */
174     public function edit(string $slug)
175     {
176         $book = $this->bookRepo->getBySlug($slug);
177         $this->checkOwnablePermission('book-update', $book);
178         $this->setPageTitle(trans('entities.books_edit_named', ['bookName'=>$book->getShortName()]));
179         return view('books.edit', ['book' => $book, 'current' => $book]);
180     }
181
182     /**
183      * Update the specified book in storage.
184      * @param Request $request
185      * @param string $slug
186      * @return Response
187      * @throws ImageUploadException
188      * @throws NotFoundException
189      * @throws ValidationException
190      * @throws Throwable
191      */
192     public function update(Request $request, string $slug)
193     {
194         $book = $this->bookRepo->getBySlug($slug);
195         $this->checkOwnablePermission('book-update', $book);
196         $this->validate($request, [
197             'name' => 'required|string|max:255',
198             'description' => 'string|max:1000',
199             'image' => $this->imageRepo->getImageValidationRules(),
200         ]);
201
202          $book = $this->bookRepo->updateFromInput($book, $request->all());
203          $this->bookUpdateActions($book, $request);
204
205          Activity::add($book, 'book_update', $book->id);
206
207          return redirect($book->getUrl());
208     }
209
210     /**
211      * Shows the page to confirm deletion
212      * @param string $bookSlug
213      * @return View
214      * @throws NotFoundException
215      */
216     public function showDelete(string $bookSlug)
217     {
218         $book = $this->bookRepo->getBySlug($bookSlug);
219         $this->checkOwnablePermission('book-delete', $book);
220         $this->setPageTitle(trans('entities.books_delete_named', ['bookName' => $book->getShortName()]));
221         return view('books.delete', ['book' => $book, 'current' => $book]);
222     }
223
224     /**
225      * Shows the view which allows pages to be re-ordered and sorted.
226      * @param string $bookSlug
227      * @return View
228      * @throws NotFoundException
229      */
230     public function sort(string $bookSlug)
231     {
232         $book = $this->bookRepo->getBySlug($bookSlug);
233         $this->checkOwnablePermission('book-update', $book);
234
235         $bookChildren = $this->bookRepo->getBookChildren($book, true);
236
237         $this->setPageTitle(trans('entities.books_sort_named', ['bookName'=>$book->getShortName()]));
238         return view('books.sort', ['book' => $book, 'current' => $book, 'bookChildren' => $bookChildren]);
239     }
240
241     /**
242      * Shows the sort box for a single book.
243      * Used via AJAX when loading in extra books to a sort.
244      * @param string $bookSlug
245      * @return Factory|View
246      * @throws NotFoundException
247      */
248     public function sortItem(string $bookSlug)
249     {
250         $book = $this->bookRepo->getBySlug($bookSlug);
251         $bookChildren = $this->bookRepo->getBookChildren($book);
252         return view('books.sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
253     }
254
255     /**
256      * Saves an array of sort mapping to pages and chapters.
257      * @param Request $request
258      * @param string $bookSlug
259      * @return RedirectResponse|Redirector
260      * @throws NotFoundException
261      */
262     public function saveSort(Request $request, string $bookSlug)
263     {
264         $book = $this->bookRepo->getBySlug($bookSlug);
265         $this->checkOwnablePermission('book-update', $book);
266
267         // Return if no map sent
268         if (!$request->filled('sort-tree')) {
269             return redirect($book->getUrl());
270         }
271
272         // Sort pages and chapters
273         $sortMap = collect(json_decode($request->get('sort-tree')));
274         $bookIdsInvolved = collect([$book->id]);
275
276         // Load models into map
277         $sortMap->each(function ($mapItem) use ($bookIdsInvolved) {
278             $mapItem->type = ($mapItem->type === 'page' ? 'page' : 'chapter');
279             $mapItem->model = $this->bookRepo->getById($mapItem->type, $mapItem->id);
280             // Store source and target books
281             $bookIdsInvolved->push(intval($mapItem->model->book_id));
282             $bookIdsInvolved->push(intval($mapItem->book));
283         });
284
285         // Get the books involved in the sort
286         $bookIdsInvolved = $bookIdsInvolved->unique()->toArray();
287         $booksInvolved = $this->bookRepo->getManyById('book', $bookIdsInvolved, false, true);
288
289         // Throw permission error if invalid ids or inaccessible books given.
290         if (count($bookIdsInvolved) !== count($booksInvolved)) {
291             $this->showPermissionError();
292         }
293
294         // Check permissions of involved books
295         $booksInvolved->each(function (Book $book) {
296              $this->checkOwnablePermission('book-update', $book);
297         });
298
299         // Perform the sort
300         $sortMap->each(function ($mapItem) {
301             $model = $mapItem->model;
302
303             $priorityChanged = intval($model->priority) !== intval($mapItem->sort);
304             $bookChanged = intval($model->book_id) !== intval($mapItem->book);
305             $chapterChanged = ($mapItem->type === 'page') && intval($model->chapter_id) !== $mapItem->parentChapter;
306
307             if ($bookChanged) {
308                 $this->bookRepo->changeBook($model, $mapItem->book);
309             }
310             if ($chapterChanged) {
311                 $model->chapter_id = intval($mapItem->parentChapter);
312                 $model->save();
313             }
314             if ($priorityChanged) {
315                 $model->priority = intval($mapItem->sort);
316                 $model->save();
317             }
318         });
319
320         // Rebuild permissions and add activity for involved books.
321         $booksInvolved->each(function (Book $book) {
322             $book->rebuildPermissions();
323             Activity::add($book, 'book_sort', $book->id);
324         });
325
326         return redirect($book->getUrl());
327     }
328
329     /**
330      * Remove the specified book from storage.
331      * @param string $bookSlug
332      * @return Response
333      * @throws NotFoundException
334      * @throws Throwable
335      * @throws NotifyException
336      */
337     public function destroy(string $bookSlug)
338     {
339         $book = $this->bookRepo->getBySlug($bookSlug);
340         $this->checkOwnablePermission('book-delete', $book);
341         Activity::addMessage('book_delete', $book->name);
342
343         if ($book->cover) {
344             $this->imageRepo->destroyImage($book->cover);
345         }
346         $this->bookRepo->destroyBook($book);
347
348         return redirect('/books');
349     }
350
351     /**
352      * Show the Restrictions view.
353      * @param string $bookSlug
354      * @return Factory|View
355      * @throws NotFoundException
356      */
357     public function showPermissions(string $bookSlug)
358     {
359         $book = $this->bookRepo->getBySlug($bookSlug);
360         $this->checkOwnablePermission('restrictions-manage', $book);
361         $roles = $this->userRepo->getRestrictableRoles();
362         return view('books.permissions', [
363             'book' => $book,
364             'roles' => $roles
365         ]);
366     }
367
368     /**
369      * Set the restrictions for this book.
370      * @param Request $request
371      * @param string $bookSlug
372      * @return RedirectResponse|Redirector
373      * @throws NotFoundException
374      * @throws Throwable
375      */
376     public function permissions(Request $request, string $bookSlug)
377     {
378         $book = $this->bookRepo->getBySlug($bookSlug);
379         $this->checkOwnablePermission('restrictions-manage', $book);
380         $this->bookRepo->updateEntityPermissionsFromRequest($request, $book);
381         $this->showSuccessNotification(trans('entities.books_permissions_updated'));
382         return redirect($book->getUrl());
383     }
384
385     /**
386      * Common actions to run on book update.
387      * Handles updating the cover image.
388      * @param Book $book
389      * @param Request $request
390      * @throws ImageUploadException
391      */
392     protected function bookUpdateActions(Book $book, Request $request)
393     {
394         // Update the cover image if in request
395         if ($request->has('image')) {
396             $this->imageRepo->destroyImage($book->cover);
397             $newImage = $request->file('image');
398             $image = $this->imageRepo->saveNew($newImage, 'cover_book', $book->id, 512, 512, true);
399             $book->image_id = $image->id;
400             $book->save();
401         }
402
403         if ($request->has('image_reset')) {
404             $this->imageRepo->destroyImage($book->cover);
405             $book->image_id = 0;
406             $book->save();
407         }
408     }
409 }