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