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