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