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