]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/BookController.php
Refactored the code to first check for the permissions before sorting the book.
[bookstack] / app / Http / Controllers / BookController.php
1 <?php namespace BookStack\Http\Controllers;
2
3 use Activity;
4 use BookStack\Book;
5 use BookStack\Repos\EntityRepo;
6 use BookStack\Repos\UserRepo;
7 use BookStack\Services\ExportService;
8 use Illuminate\Http\Request;
9 use Illuminate\Http\Response;
10 use Views;
11
12 class BookController extends Controller
13 {
14
15     protected $entityRepo;
16     protected $userRepo;
17     protected $exportService;
18
19     /**
20      * BookController constructor.
21      * @param EntityRepo $entityRepo
22      * @param UserRepo $userRepo
23      * @param ExportService $exportService
24      */
25     public function __construct(EntityRepo $entityRepo, UserRepo $userRepo, ExportService $exportService)
26     {
27         $this->entityRepo = $entityRepo;
28         $this->userRepo = $userRepo;
29         $this->exportService = $exportService;
30         parent::__construct();
31     }
32
33     /**
34      * Display a listing of the book.
35      * @return Response
36      */
37     public function index()
38     {
39         $books = $this->entityRepo->getAllPaginated('book', 20);
40         $recents = $this->signedIn ? $this->entityRepo->getRecentlyViewed('book', 4, 0) : false;
41         $popular = $this->entityRepo->getPopular('book', 4, 0);
42         $new = $this->entityRepo->getRecentlyCreated('book', 4, 0);
43         $booksViewType = setting()->getUser($this->currentUser, 'books_view_type', 'list');
44         $this->setPageTitle(trans('entities.books'));
45         return view('books/index', [
46             'books' => $books,
47             'recents' => $recents,
48             'popular' => $popular,
49             'new' => $new,
50             'booksViewType' => $booksViewType
51         ]);
52     }
53
54     /**
55      * Show the form for creating a new book.
56      * @return Response
57      */
58     public function create()
59     {
60         $this->checkPermission('book-create-all');
61         $this->setPageTitle(trans('entities.books_create'));
62         return view('books/create');
63     }
64
65     /**
66      * Store a newly created book in storage.
67      *
68      * @param  Request $request
69      * @return Response
70      */
71     public function store(Request $request)
72     {
73         $this->checkPermission('book-create-all');
74         $this->validate($request, [
75             'name' => 'required|string|max:255',
76             'description' => 'string|max:1000'
77         ]);
78         $book = $this->entityRepo->createFromInput('book', $request->all());
79         Activity::add($book, 'book_create', $book->id);
80         return redirect($book->getUrl());
81     }
82
83     /**
84      * Display the specified book.
85      * @param $slug
86      * @return Response
87      */
88     public function show($slug)
89     {
90         $book = $this->entityRepo->getBySlug('book', $slug);
91         $this->checkOwnablePermission('book-view', $book);
92         $bookChildren = $this->entityRepo->getBookChildren($book);
93         Views::add($book);
94         $this->setPageTitle($book->getShortName());
95         return view('books/show', [
96             'book' => $book,
97             'current' => $book,
98             'bookChildren' => $bookChildren,
99             'activity' => Activity::entityActivity($book, 20, 0)
100         ]);
101     }
102
103     /**
104      * Show the form for editing the specified book.
105      * @param $slug
106      * @return Response
107      */
108     public function edit($slug)
109     {
110         $book = $this->entityRepo->getBySlug('book', $slug);
111         $this->checkOwnablePermission('book-update', $book);
112         $this->setPageTitle(trans('entities.books_edit_named',['bookName'=>$book->getShortName()]));
113         return view('books/edit', ['book' => $book, 'current' => $book]);
114     }
115
116     /**
117      * Update the specified book in storage.
118      * @param  Request $request
119      * @param          $slug
120      * @return Response
121      */
122     public function update(Request $request, $slug)
123     {
124         $book = $this->entityRepo->getBySlug('book', $slug);
125         $this->checkOwnablePermission('book-update', $book);
126         $this->validate($request, [
127             'name' => 'required|string|max:255',
128             'description' => 'string|max:1000'
129         ]);
130          $book = $this->entityRepo->updateFromInput('book', $book, $request->all());
131          Activity::add($book, 'book_update', $book->id);
132          return redirect($book->getUrl());
133     }
134
135     /**
136      * Shows the page to confirm deletion
137      * @param $bookSlug
138      * @return \Illuminate\View\View
139      */
140     public function showDelete($bookSlug)
141     {
142         $book = $this->entityRepo->getBySlug('book', $bookSlug);
143         $this->checkOwnablePermission('book-delete', $book);
144         $this->setPageTitle(trans('entities.books_delete_named', ['bookName'=>$book->getShortName()]));
145         return view('books/delete', ['book' => $book, 'current' => $book]);
146     }
147
148     /**
149      * Shows the view which allows pages to be re-ordered and sorted.
150      * @param string $bookSlug
151      * @return \Illuminate\View\View
152      */
153     public function sort($bookSlug)
154     {
155         $book = $this->entityRepo->getBySlug('book', $bookSlug);
156         $this->checkOwnablePermission('book-update', $book);
157         $bookChildren = $this->entityRepo->getBookChildren($book, true);
158         $books = $this->entityRepo->getAll('book', false, 'update');
159         $this->setPageTitle(trans('entities.books_sort_named', ['bookName'=>$book->getShortName()]));
160         return view('books/sort', ['book' => $book, 'current' => $book, 'books' => $books, 'bookChildren' => $bookChildren]);
161     }
162
163     /**
164      * Shows the sort box for a single book.
165      * Used via AJAX when loading in extra books to a sort.
166      * @param $bookSlug
167      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
168      */
169     public function getSortItem($bookSlug)
170     {
171         $book = $this->entityRepo->getBySlug('book', $bookSlug);
172         $bookChildren = $this->entityRepo->getBookChildren($book);
173         return view('books/sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
174     }
175
176     /**
177      * Saves an array of sort mapping to pages and chapters.
178      * @param  string $bookSlug
179      * @param Request $request
180      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
181      */
182     public function saveSort($bookSlug, Request $request)
183     {
184         $book = $this->entityRepo->getBySlug('book', $bookSlug);
185         $this->checkOwnablePermission('book-update', $book);
186
187         // Return if no map sent
188         if (!$request->filled('sort-tree')) {
189             return redirect($book->getUrl());
190         }
191
192         // Sort pages and chapters
193         $sortedBooks = [];
194         $updatedModels = collect();
195         $sortMap = json_decode($request->get('sort-tree'));
196         $defaultBookId = $book->id;
197
198         // Check permissions for all target and source books
199         $permissionsList = [$book->id];
200         foreach ($sortMap as $bookChild) {
201             // Check permission for target book
202             if (!in_array($bookChild->book, $permissionsList)) {
203                 $targetBook = $this->entityRepo->getById('book', $bookChild->book);
204                 if (!empty($targetBook)) {
205                     $bookId = $targetBook->id;
206                     $this->checkOwnablePermission('book-update', $targetBook);
207                     // cache the permission for future use.
208                     $permissionsList[] = $bookId;
209                 }
210             }
211
212             // Check permissions for the source book
213             $id = intval($bookChild->id);
214             $isPage = $bookChild->type == 'page';
215             $model = $this->entityRepo->getById($isPage?'page':'chapter', $id);
216             $sourceBook = $model->book;
217             if (!in_array($sourceBook->id, $permissionsList)) {
218                 $this->checkOwnablePermission('book-update', $sourceBook);
219
220                 // cache the permission for future use.
221                 $permissionsList[] = $sourceBook->id;
222             }
223         }
224
225         // Loop through contents of provided map and update entities accordingly
226         foreach ($sortMap as $bookChild) {
227             $priority = $bookChild->sort;
228             $id = intval($bookChild->id);
229             $isPage = $bookChild->type == 'page';
230             $bookId = $defaultBookId;
231             $targetBook = $this->entityRepo->getById('book', $bookChild->book);
232
233             $chapterId = ($isPage && $bookChild->parentChapter === false) ? 0 : intval($bookChild->parentChapter);
234             $model = $this->entityRepo->getById($isPage?'page':'chapter', $id);
235
236             // Update models only if there's a change in parent chain or ordering.
237             if ($model->priority !== $priority || $model->book_id !== $bookId || ($isPage && $model->chapter_id !== $chapterId)) {
238                 $this->entityRepo->changeBook($isPage?'page':'chapter', $bookId, $model);
239                 $model->priority = $priority;
240                 if ($isPage) $model->chapter_id = $chapterId;
241                 $model->save();
242                 $updatedModels->push($model);
243             }
244
245             // Store involved books to be sorted later
246             if (!in_array($bookId, $sortedBooks)) {
247                 $sortedBooks[] = $bookId;
248             }
249         }
250
251         // Add activity for books
252         foreach ($sortedBooks as $bookId) {
253             /** @var Book $updatedBook */
254             $updatedBook = $this->entityRepo->getById('book', $bookId);
255             $this->entityRepo->buildJointPermissionsForBook($updatedBook);
256             Activity::add($updatedBook, 'book_sort', $updatedBook->id);
257         }
258
259         return redirect($book->getUrl());
260     }
261
262     /**
263      * Remove the specified book from storage.
264      * @param $bookSlug
265      * @return Response
266      */
267     public function destroy($bookSlug)
268     {
269         $book = $this->entityRepo->getBySlug('book', $bookSlug);
270         $this->checkOwnablePermission('book-delete', $book);
271         Activity::addMessage('book_delete', 0, $book->name);
272         $this->entityRepo->destroyBook($book);
273         return redirect('/books');
274     }
275
276     /**
277      * Show the Restrictions view.
278      * @param $bookSlug
279      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
280      */
281     public function showRestrict($bookSlug)
282     {
283         $book = $this->entityRepo->getBySlug('book', $bookSlug);
284         $this->checkOwnablePermission('restrictions-manage', $book);
285         $roles = $this->userRepo->getRestrictableRoles();
286         return view('books/restrictions', [
287             'book' => $book,
288             'roles' => $roles
289         ]);
290     }
291
292     /**
293      * Set the restrictions for this book.
294      * @param $bookSlug
295      * @param $bookSlug
296      * @param Request $request
297      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
298      */
299     public function restrict($bookSlug, Request $request)
300     {
301         $book = $this->entityRepo->getBySlug('book', $bookSlug);
302         $this->checkOwnablePermission('restrictions-manage', $book);
303         $this->entityRepo->updateEntityPermissionsFromRequest($request, $book);
304         session()->flash('success', trans('entities.books_permissions_updated'));
305         return redirect($book->getUrl());
306     }
307
308     /**
309      * Export a book as a PDF file.
310      * @param string $bookSlug
311      * @return mixed
312      */
313     public function exportPdf($bookSlug)
314     {
315         $book = $this->entityRepo->getBySlug('book', $bookSlug);
316         $pdfContent = $this->exportService->bookToPdf($book);
317         return response()->make($pdfContent, 200, [
318             'Content-Type'        => 'application/octet-stream',
319             'Content-Disposition' => 'attachment; filename="' . $bookSlug . '.pdf'
320         ]);
321     }
322
323     /**
324      * Export a book as a contained HTML file.
325      * @param string $bookSlug
326      * @return mixed
327      */
328     public function exportHtml($bookSlug)
329     {
330         $book = $this->entityRepo->getBySlug('book', $bookSlug);
331         $htmlContent = $this->exportService->bookToContainedHtml($book);
332         return response()->make($htmlContent, 200, [
333             'Content-Type'        => 'application/octet-stream',
334             'Content-Disposition' => 'attachment; filename="' . $bookSlug . '.html'
335         ]);
336     }
337
338     /**
339      * Export a book as a plain text file.
340      * @param $bookSlug
341      * @return mixed
342      */
343     public function exportPlainText($bookSlug)
344     {
345         $book = $this->entityRepo->getBySlug('book', $bookSlug);
346         $htmlContent = $this->exportService->bookToPlainText($book);
347         return response()->make($htmlContent, 200, [
348             'Content-Type'        => 'application/octet-stream',
349             'Content-Disposition' => 'attachment; filename="' . $bookSlug . '.txt'
350         ]);
351     }
352 }