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