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