]> BookStack Code Mirror - bookstack/blob - app/Entities/Controllers/BookController.php
Merge branch 'development' into default-templates
[bookstack] / app / Entities / Controllers / BookController.php
1 <?php
2
3 namespace BookStack\Entities\Controllers;
4
5 use BookStack\Activity\ActivityQueries;
6 use BookStack\Activity\ActivityType;
7 use BookStack\Activity\Models\View;
8 use BookStack\Activity\Tools\UserEntityWatchOptions;
9 use BookStack\Entities\Models\Bookshelf;
10 use BookStack\Entities\Models\Page;
11 use BookStack\Entities\Repos\BookRepo;
12 use BookStack\Entities\Tools\BookContents;
13 use BookStack\Entities\Tools\Cloner;
14 use BookStack\Entities\Tools\HierarchyTransformer;
15 use BookStack\Entities\Tools\ShelfContext;
16 use BookStack\Exceptions\ImageUploadException;
17 use BookStack\Exceptions\NotFoundException;
18 use BookStack\Facades\Activity;
19 use BookStack\Http\Controller;
20 use BookStack\References\ReferenceFetcher;
21 use BookStack\Util\SimpleListOptions;
22 use Illuminate\Http\Request;
23 use Illuminate\Validation\ValidationException;
24 use Throwable;
25
26 class BookController extends Controller
27 {
28     protected BookRepo $bookRepo;
29     protected ShelfContext $shelfContext;
30     protected ReferenceFetcher $referenceFetcher;
31
32     public function __construct(ShelfContext $entityContextManager, BookRepo $bookRepo, ReferenceFetcher $referenceFetcher)
33     {
34         $this->bookRepo = $bookRepo;
35         $this->shelfContext = $entityContextManager;
36         $this->referenceFetcher = $referenceFetcher;
37     }
38
39     /**
40      * Display a listing of the book.
41      */
42     public function index(Request $request)
43     {
44         $view = setting()->getForCurrentUser('books_view_type');
45         $listOptions = SimpleListOptions::fromRequest($request, 'books')->withSortOptions([
46             'name' => trans('common.sort_name'),
47             'created_at' => trans('common.sort_created_at'),
48             'updated_at' => trans('common.sort_updated_at'),
49         ]);
50
51         $books = $this->bookRepo->getAllPaginated(18, $listOptions->getSort(), $listOptions->getOrder());
52         $recents = $this->isSignedIn() ? $this->bookRepo->getRecentlyViewed(4) : false;
53         $popular = $this->bookRepo->getPopular(4);
54         $new = $this->bookRepo->getRecentlyCreated(4);
55
56         $this->shelfContext->clearShelfContext();
57
58         $this->setPageTitle(trans('entities.books'));
59
60         return view('books.index', [
61             'books'   => $books,
62             'recents' => $recents,
63             'popular' => $popular,
64             'new'     => $new,
65             'view'    => $view,
66             'listOptions' => $listOptions,
67         ]);
68     }
69
70     /**
71      * Show the form for creating a new book.
72      */
73     public function create(string $shelfSlug = null)
74     {
75         $this->checkPermission('book-create-all');
76
77         $bookshelf = null;
78         if ($shelfSlug !== null) {
79             $bookshelf = Bookshelf::visible()->where('slug', '=', $shelfSlug)->firstOrFail();
80             $this->checkOwnablePermission('bookshelf-update', $bookshelf);
81         }
82
83         $this->setPageTitle(trans('entities.books_create'));
84
85         $templates = Page::visible()
86             ->where('template', '=', true)
87             ->orderBy('name', 'asc')
88             ->get();
89
90         return view('books.create', [
91             'bookshelf' => $bookshelf,
92             'templates' => $templates,
93         ]);
94     }
95
96     /**
97      * Store a newly created book in storage.
98      *
99      * @throws ImageUploadException
100      * @throws ValidationException
101      */
102     public function store(Request $request, string $shelfSlug = null)
103     {
104         $this->checkPermission('book-create-all');
105         $validated = $this->validate($request, [
106             'name'        => ['required', 'string', 'max:255'],
107             'description' => ['string', 'max:1000'],
108             'image'       => array_merge(['nullable'], $this->getImageValidationRules()),
109             'tags'        => ['array'],
110             'default_template'  => ['nullable', 'exists:pages,id'], 
111         ]);
112
113         $bookshelf = null;
114         if ($shelfSlug !== null) {
115             $bookshelf = Bookshelf::visible()->where('slug', '=', $shelfSlug)->firstOrFail();
116             $this->checkOwnablePermission('bookshelf-update', $bookshelf);
117         }
118
119         $book = $this->bookRepo->create($validated);
120
121         if ($bookshelf) {
122             $bookshelf->appendBook($book);
123             Activity::add(ActivityType::BOOKSHELF_UPDATE, $bookshelf);
124         }
125
126         return redirect($book->getUrl());
127     }
128
129     /**
130      * Display the specified book.
131      */
132     public function show(Request $request, ActivityQueries $activities, string $slug)
133     {
134         $book = $this->bookRepo->getBySlug($slug);
135         $bookChildren = (new BookContents($book))->getTree(true);
136         $bookParentShelves = $book->shelves()->scopes('visible')->get();
137
138         View::incrementFor($book);
139         if ($request->has('shelf')) {
140             $this->shelfContext->setShelfContext(intval($request->get('shelf')));
141         }
142
143         $this->setPageTitle($book->getShortName());
144
145         return view('books.show', [
146             'book'              => $book,
147             'current'           => $book,
148             'bookChildren'      => $bookChildren,
149             'bookParentShelves' => $bookParentShelves,
150             'watchOptions'      => new UserEntityWatchOptions(user(), $book),
151             'activity'          => $activities->entityActivity($book, 20, 1),
152             'referenceCount'    => $this->referenceFetcher->getPageReferenceCountToEntity($book),
153         ]);
154     }
155
156     /**
157      * Show the form for editing the specified book.
158      */
159     public function edit(string $slug)
160     {
161         $book = $this->bookRepo->getBySlug($slug);
162         $this->checkOwnablePermission('book-update', $book);
163         $this->setPageTitle(trans('entities.books_edit_named', ['bookName' => $book->getShortName()]));
164
165         $templates = Page::visible()
166             ->where('template', '=', true)
167             ->orderBy('name', 'asc')
168             ->get();
169
170         return view('books.edit', ['book' => $book, 'current' => $book, 'templates' => $templates]);
171     }
172
173     /**
174      * Update the specified book in storage.
175      *
176      * @throws ImageUploadException
177      * @throws ValidationException
178      * @throws Throwable
179      */
180     public function update(Request $request, string $slug)
181     {
182         $book = $this->bookRepo->getBySlug($slug);
183         $this->checkOwnablePermission('book-update', $book);
184
185         $validated = $this->validate($request, [
186             'name'        => ['required', 'string', 'max:255'],
187             'description' => ['string', 'max:1000'],
188             'image'       => array_merge(['nullable'], $this->getImageValidationRules()),
189             'tags'        => ['array'],
190             'default_template'  => ['nullable', 'exists:pages,id'], 
191         ]);
192
193         if ($request->has('image_reset')) {
194             $validated['image'] = null;
195         } elseif (array_key_exists('image', $validated) && is_null($validated['image'])) {
196             unset($validated['image']);
197         }
198
199         $book = $this->bookRepo->update($book, $validated);
200
201         return redirect($book->getUrl());
202     }
203
204     /**
205      * Shows the page to confirm deletion.
206      */
207     public function showDelete(string $bookSlug)
208     {
209         $book = $this->bookRepo->getBySlug($bookSlug);
210         $this->checkOwnablePermission('book-delete', $book);
211         $this->setPageTitle(trans('entities.books_delete_named', ['bookName' => $book->getShortName()]));
212
213         return view('books.delete', ['book' => $book, 'current' => $book]);
214     }
215
216     /**
217      * Remove the specified book from the system.
218      *
219      * @throws Throwable
220      */
221     public function destroy(string $bookSlug)
222     {
223         $book = $this->bookRepo->getBySlug($bookSlug);
224         $this->checkOwnablePermission('book-delete', $book);
225
226         $this->bookRepo->destroy($book);
227
228         return redirect('/books');
229     }
230
231     /**
232      * Show the view to copy a book.
233      *
234      * @throws NotFoundException
235      */
236     public function showCopy(string $bookSlug)
237     {
238         $book = $this->bookRepo->getBySlug($bookSlug);
239         $this->checkOwnablePermission('book-view', $book);
240
241         session()->flashInput(['name' => $book->name]);
242
243         return view('books.copy', [
244             'book' => $book,
245         ]);
246     }
247
248     /**
249      * Create a copy of a book within the requested target destination.
250      *
251      * @throws NotFoundException
252      */
253     public function copy(Request $request, Cloner $cloner, string $bookSlug)
254     {
255         $book = $this->bookRepo->getBySlug($bookSlug);
256         $this->checkOwnablePermission('book-view', $book);
257         $this->checkPermission('book-create-all');
258
259         $newName = $request->get('name') ?: $book->name;
260         $bookCopy = $cloner->cloneBook($book, $newName);
261         $this->showSuccessNotification(trans('entities.books_copy_success'));
262
263         return redirect($bookCopy->getUrl());
264     }
265
266     /**
267      * Convert the chapter to a book.
268      */
269     public function convertToShelf(HierarchyTransformer $transformer, string $bookSlug)
270     {
271         $book = $this->bookRepo->getBySlug($bookSlug);
272         $this->checkOwnablePermission('book-update', $book);
273         $this->checkOwnablePermission('book-delete', $book);
274         $this->checkPermission('bookshelf-create-all');
275         $this->checkPermission('book-create-all');
276
277         $shelf = $transformer->transformBookToShelf($book);
278
279         return redirect($shelf->getUrl());
280     }
281 }