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