]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/BookController.php
Simplified activity facade interface
[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\EntityContextManager;
7 use BookStack\Entities\Repos\BookRepo;
8 use BookStack\Entities\Repos\EntityRepo;
9 use BookStack\Entities\ExportService;
10 use BookStack\Exceptions\ImageUploadException;
11 use BookStack\Exceptions\NotFoundException;
12 use BookStack\Exceptions\NotifyException;
13 use BookStack\Uploads\ImageRepo;
14 use Illuminate\Contracts\View\Factory;
15 use Illuminate\Http\RedirectResponse;
16 use Illuminate\Http\Request;
17 use Illuminate\Http\Response;
18 use Illuminate\Routing\Redirector;
19 use Illuminate\Validation\ValidationException;
20 use Illuminate\View\View;
21 use Throwable;
22 use Views;
23
24 class BookController extends Controller
25 {
26
27     protected $bookRepo;
28     protected $userRepo;
29     protected $entityContextManager;
30     protected $imageRepo;
31
32     /**
33      * BookController constructor.
34      * @param BookRepo $bookRepo
35      * @param UserRepo $userRepo
36      * @param EntityContextManager $entityContextManager
37      * @param ImageRepo $imageRepo
38      */
39     public function __construct(
40         BookRepo $bookRepo,
41         UserRepo $userRepo,
42         EntityContextManager $entityContextManager,
43         ImageRepo $imageRepo
44     ) {
45         $this->bookRepo = $bookRepo;
46         $this->userRepo = $userRepo;
47         $this->entityContextManager = $entityContextManager;
48         $this->imageRepo = $imageRepo;
49         parent::__construct();
50     }
51
52     /**
53      * Display a listing of the book.
54      * @return Response
55      */
56     public function index()
57     {
58         $view = setting()->getUser($this->currentUser, 'books_view_type', config('app.views.books'));
59         $sort = setting()->getUser($this->currentUser, 'books_sort', 'name');
60         $order = setting()->getUser($this->currentUser, 'books_sort_order', 'asc');
61
62         $books = $this->bookRepo->getAllPaginated('book', 18, $sort, $order);
63         $recents = $this->signedIn ? $this->bookRepo->getRecentlyViewed('book', 4, 0) : false;
64         $popular = $this->bookRepo->getPopular('book', 4, 0);
65         $new = $this->bookRepo->getRecentlyCreated('book', 4, 0);
66
67         $this->entityContextManager->clearShelfContext();
68
69         $this->setPageTitle(trans('entities.books'));
70         return view('books.index', [
71             'books' => $books,
72             'recents' => $recents,
73             'popular' => $popular,
74             'new' => $new,
75             'view' => $view,
76             'sort' => $sort,
77             'order' => $order,
78         ]);
79     }
80
81     /**
82      * Show the form for creating a new book.
83      * @param string $shelfSlug
84      * @return Response
85      * @throws NotFoundException
86      */
87     public function create(string $shelfSlug = null)
88     {
89         $bookshelf = null;
90         if ($shelfSlug !== null) {
91             $bookshelf = $this->bookRepo->getEntityBySlug('bookshelf', $shelfSlug);
92             $this->checkOwnablePermission('bookshelf-update', $bookshelf);
93         }
94
95         $this->checkPermission('book-create-all');
96         $this->setPageTitle(trans('entities.books_create'));
97         return view('books.create', [
98             'bookshelf' => $bookshelf
99         ]);
100     }
101
102     /**
103      * Store a newly created book in storage.
104      *
105      * @param Request $request
106      * @param string $shelfSlug
107      * @return Response
108      * @throws NotFoundException
109      * @throws ImageUploadException
110      * @throws ValidationException
111      * @throws Throwable
112      */
113     public function store(Request $request, string $shelfSlug = null)
114     {
115         $this->checkPermission('book-create-all');
116         $this->validate($request, [
117             'name' => 'required|string|max:255',
118             'description' => 'string|max:1000',
119             'image' => $this->imageRepo->getImageValidationRules(),
120         ]);
121
122         $bookshelf = null;
123         if ($shelfSlug !== null) {
124             $bookshelf = $this->bookRepo->getEntityBySlug('bookshelf', $shelfSlug);
125             $this->checkOwnablePermission('bookshelf-update', $bookshelf);
126         }
127
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             $this->bookRepo->appendBookToShelf($bookshelf, $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', $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 getSortItem(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         // Throw permission error if invalid ids or inaccessible books given.
289         if (count($bookIdsInvolved) !== count($booksInvolved)) {
290             $this->showPermissionError();
291         }
292         // Check permissions of involved books
293         $booksInvolved->each(function (Book $book) {
294              $this->checkOwnablePermission('book-update', $book);
295         });
296
297         // Perform the sort
298         $sortMap->each(function ($mapItem) {
299             $model = $mapItem->model;
300
301             $priorityChanged = intval($model->priority) !== intval($mapItem->sort);
302             $bookChanged = intval($model->book_id) !== intval($mapItem->book);
303             $chapterChanged = ($mapItem->type === 'page') && intval($model->chapter_id) !== $mapItem->parentChapter;
304
305             if ($bookChanged) {
306                 $this->bookRepo->changeBook($mapItem->type, $mapItem->book, $model);
307             }
308             if ($chapterChanged) {
309                 $model->chapter_id = intval($mapItem->parentChapter);
310                 $model->save();
311             }
312             if ($priorityChanged) {
313                 $model->priority = intval($mapItem->sort);
314                 $model->save();
315             }
316         });
317
318         // Rebuild permissions and add activity for involved books.
319         $booksInvolved->each(function (Book $book) {
320             $this->bookRepo->buildJointPermissionsForBook($book);
321             Activity::add($book, 'book_sort', $book->id);
322         });
323
324         return redirect($book->getUrl());
325     }
326
327     /**
328      * Remove the specified book from storage.
329      * @param string $bookSlug
330      * @return Response
331      * @throws NotFoundException
332      * @throws Throwable
333      * @throws NotifyException
334      */
335     public function destroy(string $bookSlug)
336     {
337         $book = $this->bookRepo->getBySlug($bookSlug);
338         $this->checkOwnablePermission('book-delete', $book);
339         Activity::addMessage('book_delete', $book->name);
340
341         if ($book->cover) {
342             $this->imageRepo->destroyImage($book->cover);
343         }
344         $this->bookRepo->destroyBook($book);
345
346         return redirect('/books');
347     }
348
349     /**
350      * Show the Restrictions view.
351      * @param string $bookSlug
352      * @return Factory|View
353      * @throws NotFoundException
354      */
355     public function showPermissions(string $bookSlug)
356     {
357         $book = $this->bookRepo->getBySlug($bookSlug);
358         $this->checkOwnablePermission('restrictions-manage', $book);
359         $roles = $this->userRepo->getRestrictableRoles();
360         return view('books.permissions', [
361             'book' => $book,
362             'roles' => $roles
363         ]);
364     }
365
366     /**
367      * Set the restrictions for this book.
368      * @param Request $request
369      * @param string $bookSlug
370      * @return RedirectResponse|Redirector
371      * @throws NotFoundException
372      * @throws Throwable
373      */
374     public function permissions(Request $request, string $bookSlug)
375     {
376         $book = $this->bookRepo->getBySlug($bookSlug);
377         $this->checkOwnablePermission('restrictions-manage', $book);
378         $this->bookRepo->updateEntityPermissionsFromRequest($request, $book);
379         $this->showSuccessNotification(trans('entities.books_permissions_updated'));
380         return redirect($book->getUrl());
381     }
382
383     /**
384      * Common actions to run on book update.
385      * Handles updating the cover image.
386      * @param Book $book
387      * @param Request $request
388      * @throws ImageUploadException
389      */
390     protected function bookUpdateActions(Book $book, Request $request)
391     {
392         // Update the cover image if in request
393         if ($request->has('image')) {
394             $this->imageRepo->destroyImage($book->cover);
395             $newImage = $request->file('image');
396             $image = $this->imageRepo->saveNew($newImage, 'cover_book', $book->id, 512, 512, true);
397             $book->image_id = $image->id;
398             $book->save();
399         }
400
401         if ($request->has('image_reset')) {
402             $this->imageRepo->destroyImage($book->cover);
403             $book->image_id = 0;
404             $book->save();
405         }
406     }
407 }