]> BookStack Code Mirror - bookstack/blob - app/Entities/Controllers/PageController.php
eab53bb2510c361a0b849eee542f2eb8214326bc
[bookstack] / app / Entities / Controllers / PageController.php
1 <?php
2
3 namespace BookStack\Entities\Controllers;
4
5 use BookStack\Activity\Models\View;
6 use BookStack\Activity\Tools\CommentTree;
7 use BookStack\Activity\Tools\UserEntityWatchOptions;
8 use BookStack\Entities\Models\Book;
9 use BookStack\Entities\Models\Chapter;
10 use BookStack\Entities\Queries\EntityQueries;
11 use BookStack\Entities\Queries\PageQueries;
12 use BookStack\Entities\Repos\PageRepo;
13 use BookStack\Entities\Tools\BookContents;
14 use BookStack\Entities\Tools\Cloner;
15 use BookStack\Entities\Tools\NextPreviousContentLocator;
16 use BookStack\Entities\Tools\PageContent;
17 use BookStack\Entities\Tools\PageEditActivity;
18 use BookStack\Entities\Tools\PageEditorData;
19 use BookStack\Exceptions\NotFoundException;
20 use BookStack\Exceptions\PermissionsException;
21 use BookStack\Http\Controller;
22 use BookStack\References\ReferenceFetcher;
23 use Exception;
24 use Illuminate\Database\Eloquent\Relations\BelongsTo;
25 use Illuminate\Http\Request;
26 use Illuminate\Validation\ValidationException;
27 use Throwable;
28
29 class PageController extends Controller
30 {
31     public function __construct(
32         protected PageRepo $pageRepo,
33         protected PageQueries $queries,
34         protected EntityQueries $entityQueries,
35         protected ReferenceFetcher $referenceFetcher
36     ) {
37     }
38
39     /**
40      * Show the form for creating a new page.
41      *
42      * @throws Throwable
43      */
44     public function create(string $bookSlug, string $chapterSlug = null)
45     {
46         if ($chapterSlug) {
47             $parent = $this->entityQueries->chapters->findVisibleBySlugsOrFail($bookSlug, $chapterSlug);
48         } else {
49             $parent = $this->entityQueries->books->findVisibleBySlugOrFail($bookSlug);
50         }
51
52         $this->checkOwnablePermission('page-create', $parent);
53
54         // Redirect to draft edit screen if signed in
55         if ($this->isSignedIn()) {
56             $draft = $this->pageRepo->getNewDraftPage($parent);
57
58             return redirect($draft->getUrl());
59         }
60
61         // Otherwise show the edit view if they're a guest
62         $this->setPageTitle(trans('entities.pages_new'));
63
64         return view('pages.guest-create', ['parent' => $parent]);
65     }
66
67     /**
68      * Create a new page as a guest user.
69      *
70      * @throws ValidationException
71      */
72     public function createAsGuest(Request $request, string $bookSlug, string $chapterSlug = null)
73     {
74         $this->validate($request, [
75             'name' => ['required', 'string', 'max:255'],
76         ]);
77
78         if ($chapterSlug) {
79             $parent = $this->entityQueries->chapters->findVisibleBySlugsOrFail($bookSlug, $chapterSlug);
80         } else {
81             $parent = $this->entityQueries->books->findVisibleBySlugOrFail($bookSlug);
82         }
83
84         $this->checkOwnablePermission('page-create', $parent);
85
86         $page = $this->pageRepo->getNewDraftPage($parent);
87         $this->pageRepo->publishDraft($page, [
88             'name' => $request->get('name'),
89         ]);
90
91         return redirect($page->getUrl('/edit'));
92     }
93
94     /**
95      * Show form to continue editing a draft page.
96      *
97      * @throws NotFoundException
98      */
99     public function editDraft(Request $request, string $bookSlug, int $pageId)
100     {
101         $draft = $this->queries->findVisibleByIdOrFail($pageId);
102         $this->checkOwnablePermission('page-create', $draft->getParent());
103
104         $editorData = new PageEditorData($draft, $this->entityQueries, $request->query('editor', ''));
105         $this->setPageTitle(trans('entities.pages_edit_draft'));
106
107         return view('pages.edit', $editorData->getViewData());
108     }
109
110     /**
111      * Store a new page by changing a draft into a page.
112      *
113      * @throws NotFoundException
114      * @throws ValidationException
115      */
116     public function store(Request $request, string $bookSlug, int $pageId)
117     {
118         $this->validate($request, [
119             'name' => ['required', 'string', 'max:255'],
120         ]);
121         $draftPage = $this->queries->findVisibleByIdOrFail($pageId);
122         $this->checkOwnablePermission('page-create', $draftPage->getParent());
123
124         $page = $this->pageRepo->publishDraft($draftPage, $request->all());
125
126         return redirect($page->getUrl());
127     }
128
129     /**
130      * Display the specified page.
131      * If the page is not found via the slug the revisions are searched for a match.
132      *
133      * @throws NotFoundException
134      */
135     public function show(string $bookSlug, string $pageSlug)
136     {
137         try {
138             $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
139         } catch (NotFoundException $e) {
140             $revision = $this->entityQueries->revisions->findLatestVersionBySlugs($bookSlug, $pageSlug);
141             $page = $revision->page ?? null;
142
143             if (is_null($page)) {
144                 throw $e;
145             }
146
147             return redirect($page->getUrl());
148         }
149
150         $this->checkOwnablePermission('page-view', $page);
151
152         $pageContent = (new PageContent($page));
153         $page->html = $pageContent->render();
154         $pageNav = $pageContent->getNavigation($page->html);
155
156         $sidebarTree = (new BookContents($page->book))->getTree();
157         $commentTree = (new CommentTree($page));
158         $nextPreviousLocator = new NextPreviousContentLocator($page, $sidebarTree);
159
160         View::incrementFor($page);
161         $this->setPageTitle($page->getShortName());
162
163         return view('pages.show', [
164             'page'            => $page,
165             'book'            => $page->book,
166             'current'         => $page,
167             'sidebarTree'     => $sidebarTree,
168             'commentTree'     => $commentTree,
169             'pageNav'         => $pageNav,
170             'watchOptions'    => new UserEntityWatchOptions(user(), $page),
171             'next'            => $nextPreviousLocator->getNext(),
172             'previous'        => $nextPreviousLocator->getPrevious(),
173             'referenceCount'  => $this->referenceFetcher->getReferenceCountToEntity($page),
174         ]);
175     }
176
177     /**
178      * Get page from an ajax request.
179      *
180      * @throws NotFoundException
181      */
182     public function getPageAjax(int $pageId)
183     {
184         $page = $this->queries->findVisibleByIdOrFail($pageId);
185         $page->setHidden(array_diff($page->getHidden(), ['html', 'markdown']));
186         $page->makeHidden(['book']);
187
188         return response()->json($page);
189     }
190
191     /**
192      * Show the form for editing the specified page.
193      *
194      * @throws NotFoundException
195      */
196     public function edit(Request $request, string $bookSlug, string $pageSlug)
197     {
198         $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
199         $this->checkOwnablePermission('page-update', $page);
200
201         $editorData = new PageEditorData($page, $this->entityQueries, $request->query('editor', ''));
202         if ($editorData->getWarnings()) {
203             $this->showWarningNotification(implode("\n", $editorData->getWarnings()));
204         }
205
206         $this->setPageTitle(trans('entities.pages_editing_named', ['pageName' => $page->getShortName()]));
207
208         return view('pages.edit', $editorData->getViewData());
209     }
210
211     /**
212      * Update the specified page in storage.
213      *
214      * @throws ValidationException
215      * @throws NotFoundException
216      */
217     public function update(Request $request, string $bookSlug, string $pageSlug)
218     {
219         $this->validate($request, [
220             'name' => ['required', 'string', 'max:255'],
221         ]);
222         $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
223         $this->checkOwnablePermission('page-update', $page);
224
225         $this->pageRepo->update($page, $request->all());
226
227         return redirect($page->getUrl());
228     }
229
230     /**
231      * Save a draft update as a revision.
232      *
233      * @throws NotFoundException
234      */
235     public function saveDraft(Request $request, int $pageId)
236     {
237         $page = $this->queries->findVisibleByIdOrFail($pageId);
238         $this->checkOwnablePermission('page-update', $page);
239
240         if (!$this->isSignedIn()) {
241             return $this->jsonError(trans('errors.guests_cannot_save_drafts'), 500);
242         }
243
244         $draft = $this->pageRepo->updatePageDraft($page, $request->only(['name', 'html', 'markdown']));
245         $warnings = (new PageEditActivity($page))->getWarningMessagesForDraft($draft);
246
247         return response()->json([
248             'status'    => 'success',
249             'message'   => trans('entities.pages_edit_draft_save_at'),
250             'warning'   => implode("\n", $warnings),
251             'timestamp' => $draft->updated_at->timestamp,
252         ]);
253     }
254
255     /**
256      * Redirect from a special link url which uses the page id rather than the name.
257      *
258      * @throws NotFoundException
259      */
260     public function redirectFromLink(int $pageId)
261     {
262         $page = $this->queries->findVisibleByIdOrFail($pageId);
263
264         return redirect($page->getUrl());
265     }
266
267     /**
268      * Show the deletion page for the specified page.
269      *
270      * @throws NotFoundException
271      */
272     public function showDelete(string $bookSlug, string $pageSlug)
273     {
274         $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
275         $this->checkOwnablePermission('page-delete', $page);
276         $this->setPageTitle(trans('entities.pages_delete_named', ['pageName' => $page->getShortName()]));
277         $usedAsTemplate =
278             $this->entityQueries->books->start()->where('default_template_id', '=', $page->id)->count() > 0 ||
279             $this->entityQueries->chapters->start()->where('default_template_id', '=', $page->id)->count() > 0;
280
281         return view('pages.delete', [
282             'book'    => $page->book,
283             'page'    => $page,
284             'current' => $page,
285             'usedAsTemplate' => $usedAsTemplate,
286         ]);
287     }
288
289     /**
290      * Show the deletion page for the specified page.
291      *
292      * @throws NotFoundException
293      */
294     public function showDeleteDraft(string $bookSlug, int $pageId)
295     {
296         $page = $this->queries->findVisibleByIdOrFail($pageId);
297         $this->checkOwnablePermission('page-update', $page);
298         $this->setPageTitle(trans('entities.pages_delete_draft_named', ['pageName' => $page->getShortName()]));
299         $usedAsTemplate =
300             $this->entityQueries->books->start()->where('default_template_id', '=', $page->id)->count() > 0 ||
301             $this->entityQueries->chapters->start()->where('default_template_id', '=', $page->id)->count() > 0;
302
303         return view('pages.delete', [
304             'book'    => $page->book,
305             'page'    => $page,
306             'current' => $page,
307             'usedAsTemplate' => $usedAsTemplate,
308         ]);
309     }
310
311     /**
312      * Remove the specified page from storage.
313      *
314      * @throws NotFoundException
315      * @throws Throwable
316      */
317     public function destroy(string $bookSlug, string $pageSlug)
318     {
319         $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
320         $this->checkOwnablePermission('page-delete', $page);
321         $parent = $page->getParent();
322
323         $this->pageRepo->destroy($page);
324
325         return redirect($parent->getUrl());
326     }
327
328     /**
329      * Remove the specified draft page from storage.
330      *
331      * @throws NotFoundException
332      * @throws Throwable
333      */
334     public function destroyDraft(string $bookSlug, int $pageId)
335     {
336         $page = $this->queries->findVisibleByIdOrFail($pageId);
337         $book = $page->book;
338         $chapter = $page->chapter;
339         $this->checkOwnablePermission('page-update', $page);
340
341         $this->pageRepo->destroy($page);
342
343         $this->showSuccessNotification(trans('entities.pages_delete_draft_success'));
344
345         if ($chapter && userCan('view', $chapter)) {
346             return redirect($chapter->getUrl());
347         }
348
349         return redirect($book->getUrl());
350     }
351
352     /**
353      * Show a listing of recently created pages.
354      */
355     public function showRecentlyUpdated()
356     {
357         $visibleBelongsScope = function (BelongsTo $query) {
358             $query->scopes('visible');
359         };
360
361         $pages = $this->queries->visibleForList()
362             ->addSelect('updated_by')
363             ->with(['updatedBy', 'book' => $visibleBelongsScope, 'chapter' => $visibleBelongsScope])
364             ->orderBy('updated_at', 'desc')
365             ->paginate(20)
366             ->setPath(url('/pages/recently-updated'));
367
368         $this->setPageTitle(trans('entities.recently_updated_pages'));
369
370         return view('common.detailed-listing-paginated', [
371             'title'         => trans('entities.recently_updated_pages'),
372             'entities'      => $pages,
373             'showUpdatedBy' => true,
374             'showPath'      => true,
375         ]);
376     }
377
378     /**
379      * Show the view to choose a new parent to move a page into.
380      *
381      * @throws NotFoundException
382      */
383     public function showMove(string $bookSlug, string $pageSlug)
384     {
385         $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
386         $this->checkOwnablePermission('page-update', $page);
387         $this->checkOwnablePermission('page-delete', $page);
388
389         return view('pages.move', [
390             'book' => $page->book,
391             'page' => $page,
392         ]);
393     }
394
395     /**
396      * Does the action of moving the location of a page.
397      *
398      * @throws NotFoundException
399      * @throws Throwable
400      */
401     public function move(Request $request, string $bookSlug, string $pageSlug)
402     {
403         $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
404         $this->checkOwnablePermission('page-update', $page);
405         $this->checkOwnablePermission('page-delete', $page);
406
407         $entitySelection = $request->get('entity_selection', null);
408         if ($entitySelection === null || $entitySelection === '') {
409             return redirect($page->getUrl());
410         }
411
412         try {
413             $this->pageRepo->move($page, $entitySelection);
414         } catch (PermissionsException $exception) {
415             $this->showPermissionError();
416         } catch (Exception $exception) {
417             $this->showErrorNotification(trans('errors.selected_book_chapter_not_found'));
418
419             return redirect($page->getUrl('/move'));
420         }
421
422         return redirect($page->getUrl());
423     }
424
425     /**
426      * Show the view to copy a page.
427      *
428      * @throws NotFoundException
429      */
430     public function showCopy(string $bookSlug, string $pageSlug)
431     {
432         $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
433         $this->checkOwnablePermission('page-view', $page);
434         session()->flashInput(['name' => $page->name]);
435
436         return view('pages.copy', [
437             'book' => $page->book,
438             'page' => $page,
439         ]);
440     }
441
442     /**
443      * Create a copy of a page within the requested target destination.
444      *
445      * @throws NotFoundException
446      * @throws Throwable
447      */
448     public function copy(Request $request, Cloner $cloner, string $bookSlug, string $pageSlug)
449     {
450         $page = $this->queries->findVisibleBySlugsOrFail($bookSlug, $pageSlug);
451         $this->checkOwnablePermission('page-view', $page);
452
453         $entitySelection = $request->get('entity_selection') ?: null;
454         $newParent = $entitySelection ? $this->entityQueries->findVisibleByStringIdentifier($entitySelection) : $page->getParent();
455
456         if (!$newParent instanceof Book && !$newParent instanceof Chapter) {
457             $this->showErrorNotification(trans('errors.selected_book_chapter_not_found'));
458
459             return redirect($page->getUrl('/copy'));
460         }
461
462         $this->checkOwnablePermission('page-create', $newParent);
463
464         $newName = $request->get('name') ?: $page->name;
465         $pageCopy = $cloner->clonePage($page, $newParent, $newName);
466         $this->showSuccessNotification(trans('entities.pages_copy_success'));
467
468         return redirect($pageCopy->getUrl());
469     }
470 }