]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/BookController.php
Show bookshelves that a book belongs to on a book view
[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         $bookParentShelves = $this->bookRepo->getBookParentShelves($book);
154
155         Views::add($book);
156         if ($request->has('shelf')) {
157             $this->entityContextManager->setShelfContext(intval($request->get('shelf')));
158         }
159
160         $this->setPageTitle($book->getShortName());
161         return view('books.show', [
162             'book' => $book,
163             'current' => $book,
164             'bookChildren' => $bookChildren,
165             'bookParentShelves' => $bookParentShelves,
166             'activity' => Activity::entityActivity($book, 20, 1)
167         ]);
168     }
169
170     /**
171      * Show the form for editing the specified book.
172      * @param string $slug
173      * @return Response
174      * @throws NotFoundException
175      */
176     public function edit(string $slug)
177     {
178         $book = $this->bookRepo->getBySlug($slug);
179         $this->checkOwnablePermission('book-update', $book);
180         $this->setPageTitle(trans('entities.books_edit_named', ['bookName'=>$book->getShortName()]));
181         return view('books.edit', ['book' => $book, 'current' => $book]);
182     }
183
184     /**
185      * Update the specified book in storage.
186      * @param Request $request
187      * @param string $slug
188      * @return Response
189      * @throws ImageUploadException
190      * @throws NotFoundException
191      * @throws ValidationException
192      * @throws Throwable
193      */
194     public function update(Request $request, string $slug)
195     {
196         $book = $this->bookRepo->getBySlug($slug);
197         $this->checkOwnablePermission('book-update', $book);
198         $this->validate($request, [
199             'name' => 'required|string|max:255',
200             'description' => 'string|max:1000',
201             'image' => $this->imageRepo->getImageValidationRules(),
202         ]);
203
204          $book = $this->bookRepo->updateFromInput($book, $request->all());
205          $this->bookUpdateActions($book, $request);
206
207          Activity::add($book, 'book_update', $book->id);
208
209          return redirect($book->getUrl());
210     }
211
212     /**
213      * Shows the page to confirm deletion
214      * @param string $bookSlug
215      * @return View
216      * @throws NotFoundException
217      */
218     public function showDelete(string $bookSlug)
219     {
220         $book = $this->bookRepo->getBySlug($bookSlug);
221         $this->checkOwnablePermission('book-delete', $book);
222         $this->setPageTitle(trans('entities.books_delete_named', ['bookName' => $book->getShortName()]));
223         return view('books.delete', ['book' => $book, 'current' => $book]);
224     }
225
226     /**
227      * Shows the view which allows pages to be re-ordered and sorted.
228      * @param string $bookSlug
229      * @return View
230      * @throws NotFoundException
231      */
232     public function sort(string $bookSlug)
233     {
234         $book = $this->bookRepo->getBySlug($bookSlug);
235         $this->checkOwnablePermission('book-update', $book);
236
237         $bookChildren = $this->bookRepo->getBookChildren($book, true);
238
239         $this->setPageTitle(trans('entities.books_sort_named', ['bookName'=>$book->getShortName()]));
240         return view('books.sort', ['book' => $book, 'current' => $book, 'bookChildren' => $bookChildren]);
241     }
242
243     /**
244      * Shows the sort box for a single book.
245      * Used via AJAX when loading in extra books to a sort.
246      * @param string $bookSlug
247      * @return Factory|View
248      * @throws NotFoundException
249      */
250     public function sortItem(string $bookSlug)
251     {
252         $book = $this->bookRepo->getBySlug($bookSlug);
253         $bookChildren = $this->bookRepo->getBookChildren($book);
254         return view('books.sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
255     }
256
257     /**
258      * Saves an array of sort mapping to pages and chapters.
259      * @param Request $request
260      * @param string $bookSlug
261      * @return RedirectResponse|Redirector
262      * @throws NotFoundException
263      */
264     public function saveSort(Request $request, string $bookSlug)
265     {
266         $book = $this->bookRepo->getBySlug($bookSlug);
267         $this->checkOwnablePermission('book-update', $book);
268
269         // Return if no map sent
270         if (!$request->filled('sort-tree')) {
271             return redirect($book->getUrl());
272         }
273
274         // Sort pages and chapters
275         $sortMap = collect(json_decode($request->get('sort-tree')));
276         $bookIdsInvolved = collect([$book->id]);
277
278         // Load models into map
279         $sortMap->each(function ($mapItem) use ($bookIdsInvolved) {
280             $mapItem->type = ($mapItem->type === 'page' ? 'page' : 'chapter');
281             $mapItem->model = $this->bookRepo->getById($mapItem->type, $mapItem->id);
282             // Store source and target books
283             $bookIdsInvolved->push(intval($mapItem->model->book_id));
284             $bookIdsInvolved->push(intval($mapItem->book));
285         });
286
287         // Get the books involved in the sort
288         $bookIdsInvolved = $bookIdsInvolved->unique()->toArray();
289         $booksInvolved = $this->bookRepo->getManyById('book', $bookIdsInvolved, false, true);
290
291         // Throw permission error if invalid ids or inaccessible books given.
292         if (count($bookIdsInvolved) !== count($booksInvolved)) {
293             $this->showPermissionError();
294         }
295
296         // Check permissions of involved books
297         $booksInvolved->each(function (Book $book) {
298              $this->checkOwnablePermission('book-update', $book);
299         });
300
301         // Perform the sort
302         $sortMap->each(function ($mapItem) {
303             $model = $mapItem->model;
304
305             $priorityChanged = intval($model->priority) !== intval($mapItem->sort);
306             $bookChanged = intval($model->book_id) !== intval($mapItem->book);
307             $chapterChanged = ($mapItem->type === 'page') && intval($model->chapter_id) !== $mapItem->parentChapter;
308
309             if ($bookChanged) {
310                 $this->bookRepo->changeBook($model, $mapItem->book);
311             }
312             if ($chapterChanged) {
313                 $model->chapter_id = intval($mapItem->parentChapter);
314                 $model->save();
315             }
316             if ($priorityChanged) {
317                 $model->priority = intval($mapItem->sort);
318                 $model->save();
319             }
320         });
321
322         // Rebuild permissions and add activity for involved books.
323         $booksInvolved->each(function (Book $book) {
324             $book->rebuildPermissions();
325             Activity::add($book, 'book_sort', $book->id);
326         });
327
328         return redirect($book->getUrl());
329     }
330
331     /**
332      * Remove the specified book from storage.
333      * @param string $bookSlug
334      * @return Response
335      * @throws NotFoundException
336      * @throws Throwable
337      * @throws NotifyException
338      */
339     public function destroy(string $bookSlug)
340     {
341         $book = $this->bookRepo->getBySlug($bookSlug);
342         $this->checkOwnablePermission('book-delete', $book);
343         Activity::addMessage('book_delete', $book->name);
344
345         if ($book->cover) {
346             $this->imageRepo->destroyImage($book->cover);
347         }
348         $this->bookRepo->destroyBook($book);
349
350         return redirect('/books');
351     }
352
353     /**
354      * Show the Restrictions view.
355      * @param string $bookSlug
356      * @return Factory|View
357      * @throws NotFoundException
358      */
359     public function showPermissions(string $bookSlug)
360     {
361         $book = $this->bookRepo->getBySlug($bookSlug);
362         $this->checkOwnablePermission('restrictions-manage', $book);
363         $roles = $this->userRepo->getRestrictableRoles();
364         return view('books.permissions', [
365             'book' => $book,
366             'roles' => $roles
367         ]);
368     }
369
370     /**
371      * Set the restrictions for this book.
372      * @param Request $request
373      * @param string $bookSlug
374      * @return RedirectResponse|Redirector
375      * @throws NotFoundException
376      * @throws Throwable
377      */
378     public function permissions(Request $request, string $bookSlug)
379     {
380         $book = $this->bookRepo->getBySlug($bookSlug);
381         $this->checkOwnablePermission('restrictions-manage', $book);
382         $this->bookRepo->updateEntityPermissionsFromRequest($request, $book);
383         $this->showSuccessNotification(trans('entities.books_permissions_updated'));
384         return redirect($book->getUrl());
385     }
386
387     /**
388      * Common actions to run on book update.
389      * Handles updating the cover image.
390      * @param Book $book
391      * @param Request $request
392      * @throws ImageUploadException
393      */
394     protected function bookUpdateActions(Book $book, Request $request)
395     {
396         // Update the cover image if in request
397         if ($request->has('image')) {
398             $this->imageRepo->destroyImage($book->cover);
399             $newImage = $request->file('image');
400             $image = $this->imageRepo->saveNew($newImage, 'cover_book', $book->id, 512, 512, true);
401             $book->image_id = $image->id;
402             $book->save();
403         }
404
405         if ($request->has('image_reset')) {
406             $this->imageRepo->destroyImage($book->cover);
407             $book->image_id = 0;
408             $book->save();
409         }
410     }
411 }