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