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