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