]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/PageController.php
Adding testcases for comments disable / enable setting.
[bookstack] / app / Http / Controllers / PageController.php
1 <?php namespace BookStack\Http\Controllers;
2
3 use Activity;
4 use BookStack\Exceptions\NotFoundException;
5 use BookStack\Repos\EntityRepo;
6 use BookStack\Repos\UserRepo;
7 use BookStack\Services\ExportService;
8 use Carbon\Carbon;
9 use Illuminate\Http\Request;
10 use Illuminate\Http\Response;
11 use Views;
12 use GatherContent\Htmldiff\Htmldiff;
13
14 class PageController extends Controller
15 {
16
17     protected $entityRepo;
18     protected $exportService;
19     protected $userRepo;
20
21     /**
22      * PageController constructor.
23      * @param EntityRepo $entityRepo
24      * @param ExportService $exportService
25      * @param UserRepo $userRepo
26      */
27     public function __construct(EntityRepo $entityRepo, ExportService $exportService, UserRepo $userRepo)
28     {
29         $this->entityRepo = $entityRepo;
30         $this->exportService = $exportService;
31         $this->userRepo = $userRepo;
32         parent::__construct();
33     }
34
35     /**
36      * Show the form for creating a new page.
37      * @param string $bookSlug
38      * @param string $chapterSlug
39      * @return Response
40      * @internal param bool $pageSlug
41      */
42     public function create($bookSlug, $chapterSlug = null)
43     {
44         $book = $this->entityRepo->getBySlug('book', $bookSlug);
45         $chapter = $chapterSlug ? $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug) : null;
46         $parent = $chapter ? $chapter : $book;
47         $this->checkOwnablePermission('page-create', $parent);
48
49         // Redirect to draft edit screen if signed in
50         if ($this->signedIn) {
51             $draft = $this->entityRepo->getDraftPage($book, $chapter);
52             return redirect($draft->getUrl());
53         }
54
55         // Otherwise show edit view
56         $this->setPageTitle(trans('entities.pages_new'));
57         return view('pages/guest-create', ['parent' => $parent]);
58     }
59
60     /**
61      * Create a new page as a guest user.
62      * @param Request $request
63      * @param string $bookSlug
64      * @param string|null $chapterSlug
65      * @return mixed
66      * @throws NotFoundException
67      */
68     public function createAsGuest(Request $request, $bookSlug, $chapterSlug = null)
69     {
70         $this->validate($request, [
71             'name' => 'required|string|max:255'
72         ]);
73
74         $book = $this->entityRepo->getBySlug('book', $bookSlug);
75         $chapter = $chapterSlug ? $this->entityRepo->getBySlug('chapter', $chapterSlug, $bookSlug) : null;
76         $parent = $chapter ? $chapter : $book;
77         $this->checkOwnablePermission('page-create', $parent);
78
79         $page = $this->entityRepo->getDraftPage($book, $chapter);
80         $this->entityRepo->publishPageDraft($page, [
81             'name' => $request->get('name'),
82             'html' => ''
83         ]);
84         return redirect($page->getUrl('/edit'));
85     }
86
87     /**
88      * Show form to continue editing a draft page.
89      * @param string $bookSlug
90      * @param int $pageId
91      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
92      */
93     public function editDraft($bookSlug, $pageId)
94     {
95         $draft = $this->entityRepo->getById('page', $pageId, true);
96         $this->checkOwnablePermission('page-create', $draft->book);
97         $this->setPageTitle(trans('entities.pages_edit_draft'));
98
99         $draftsEnabled = $this->signedIn;
100         return view('pages/edit', [
101             'page' => $draft,
102             'book' => $draft->book,
103             'isDraft' => true,
104             'draftsEnabled' => $draftsEnabled
105         ]);
106     }
107
108     /**
109      * Store a new page by changing a draft into a page.
110      * @param  Request $request
111      * @param  string $bookSlug
112      * @param  int $pageId
113      * @return Response
114      */
115     public function store(Request $request, $bookSlug, $pageId)
116     {
117         $this->validate($request, [
118             'name' => 'required|string|max:255'
119         ]);
120
121         $input = $request->all();
122         $book = $this->entityRepo->getBySlug('book', $bookSlug);
123
124         $draftPage = $this->entityRepo->getById('page', $pageId, true);
125
126         $chapterId = intval($draftPage->chapter_id);
127         $parent = $chapterId !== 0 ? $this->entityRepo->getById('chapter', $chapterId) : $book;
128         $this->checkOwnablePermission('page-create', $parent);
129
130         if ($parent->isA('chapter')) {
131             $input['priority'] = $this->entityRepo->getNewChapterPriority($parent);
132         } else {
133             $input['priority'] = $this->entityRepo->getNewBookPriority($parent);
134         }
135
136         $page = $this->entityRepo->publishPageDraft($draftPage, $input);
137
138         Activity::add($page, 'page_create', $book->id);
139         return redirect($page->getUrl());
140     }
141
142     /**
143      * Display the specified page.
144      * If the page is not found via the slug the revisions are searched for a match.
145      * @param string $bookSlug
146      * @param string $pageSlug
147      * @return Response
148      */
149     public function show($bookSlug, $pageSlug)
150     {
151         try {
152             $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
153         } catch (NotFoundException $e) {
154             $page = $this->entityRepo->getPageByOldSlug($pageSlug, $bookSlug);
155             if ($page === null) abort(404);
156             return redirect($page->getUrl());
157         }
158
159         $this->checkOwnablePermission('page-view', $page);
160
161         $page->html = $this->entityRepo->renderPage($page);
162         $sidebarTree = $this->entityRepo->getBookChildren($page->book);
163         $pageNav = $this->entityRepo->getPageNav($page->html);
164
165         // check if the comment's are enabled
166         $areCommentsEnabled = !setting('app-disable-comments');
167         if ($areCommentsEnabled) {
168           $page->load(['comments.createdBy']);
169         }
170
171         Views::add($page);
172         $this->setPageTitle($page->getShortName());
173         return view('pages/show', [
174             'page' => $page,'book' => $page->book,
175             'current' => $page, 'sidebarTree' => $sidebarTree,
176             'commentsEnabled' => $areCommentsEnabled,
177             'pageNav' => $pageNav]);
178     }
179
180     /**
181      * Get page from an ajax request.
182      * @param int $pageId
183      * @return \Illuminate\Http\JsonResponse
184      */
185     public function getPageAjax($pageId)
186     {
187         $page = $this->entityRepo->getById('page', $pageId);
188         return response()->json($page);
189     }
190
191     /**
192      * Show the form for editing the specified page.
193      * @param string $bookSlug
194      * @param string $pageSlug
195      * @return Response
196      */
197     public function edit($bookSlug, $pageSlug)
198     {
199         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
200         $this->checkOwnablePermission('page-update', $page);
201         $this->setPageTitle(trans('entities.pages_editing_named', ['pageName'=>$page->getShortName()]));
202         $page->isDraft = false;
203
204         // Check for active editing
205         $warnings = [];
206         if ($this->entityRepo->isPageEditingActive($page, 60)) {
207             $warnings[] = $this->entityRepo->getPageEditingActiveMessage($page, 60);
208         }
209
210         // Check for a current draft version for this user
211         if ($this->entityRepo->hasUserGotPageDraft($page, $this->currentUser->id)) {
212             $draft = $this->entityRepo->getUserPageDraft($page, $this->currentUser->id);
213             $page->name = $draft->name;
214             $page->html = $draft->html;
215             $page->markdown = $draft->markdown;
216             $page->isDraft = true;
217             $warnings [] = $this->entityRepo->getUserPageDraftMessage($draft);
218         }
219
220         if (count($warnings) > 0) session()->flash('warning', implode("\n", $warnings));
221
222         $draftsEnabled = $this->signedIn;
223         return view('pages/edit', [
224             'page' => $page,
225             'book' => $page->book,
226             'current' => $page,
227             'draftsEnabled' => $draftsEnabled
228         ]);
229     }
230
231     /**
232      * Update the specified page in storage.
233      * @param  Request $request
234      * @param  string $bookSlug
235      * @param  string $pageSlug
236      * @return Response
237      */
238     public function update(Request $request, $bookSlug, $pageSlug)
239     {
240         $this->validate($request, [
241             'name' => 'required|string|max:255'
242         ]);
243         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
244         $this->checkOwnablePermission('page-update', $page);
245         $this->entityRepo->updatePage($page, $page->book->id, $request->all());
246         Activity::add($page, 'page_update', $page->book->id);
247         return redirect($page->getUrl());
248     }
249
250     /**
251      * Save a draft update as a revision.
252      * @param Request $request
253      * @param int $pageId
254      * @return \Illuminate\Http\JsonResponse
255      */
256     public function saveDraft(Request $request, $pageId)
257     {
258         $page = $this->entityRepo->getById('page', $pageId, true);
259         $this->checkOwnablePermission('page-update', $page);
260
261         if (!$this->signedIn) {
262             return response()->json([
263                 'status' => 'error',
264                 'message' => trans('errors.guests_cannot_save_drafts'),
265             ], 500);
266         }
267
268         $draft = $this->entityRepo->updatePageDraft($page, $request->only(['name', 'html', 'markdown']));
269
270         $updateTime = $draft->updated_at->timestamp;
271         $utcUpdateTimestamp = $updateTime + Carbon::createFromTimestamp(0)->offset;
272         return response()->json([
273             'status'    => 'success',
274             'message'   => trans('entities.pages_edit_draft_save_at'),
275             'timestamp' => $utcUpdateTimestamp
276         ]);
277     }
278
279     /**
280      * Redirect from a special link url which
281      * uses the page id rather than the name.
282      * @param int $pageId
283      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
284      */
285     public function redirectFromLink($pageId)
286     {
287         $page = $this->entityRepo->getById('page', $pageId);
288         return redirect($page->getUrl());
289     }
290
291     /**
292      * Show the deletion page for the specified page.
293      * @param string $bookSlug
294      * @param string $pageSlug
295      * @return \Illuminate\View\View
296      */
297     public function showDelete($bookSlug, $pageSlug)
298     {
299         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
300         $this->checkOwnablePermission('page-delete', $page);
301         $this->setPageTitle(trans('entities.pages_delete_named', ['pageName'=>$page->getShortName()]));
302         return view('pages/delete', ['book' => $page->book, 'page' => $page, 'current' => $page]);
303     }
304
305
306     /**
307      * Show the deletion page for the specified page.
308      * @param string $bookSlug
309      * @param int $pageId
310      * @return \Illuminate\View\View
311      * @throws NotFoundException
312      */
313     public function showDeleteDraft($bookSlug, $pageId)
314     {
315         $page = $this->entityRepo->getById('page', $pageId, true);
316         $this->checkOwnablePermission('page-update', $page);
317         $this->setPageTitle(trans('entities.pages_delete_draft_named', ['pageName'=>$page->getShortName()]));
318         return view('pages/delete', ['book' => $page->book, 'page' => $page, 'current' => $page]);
319     }
320
321     /**
322      * Remove the specified page from storage.
323      * @param string $bookSlug
324      * @param string $pageSlug
325      * @return Response
326      * @internal param int $id
327      */
328     public function destroy($bookSlug, $pageSlug)
329     {
330         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
331         $book = $page->book;
332         $this->checkOwnablePermission('page-delete', $page);
333         $this->entityRepo->destroyPage($page);
334
335         Activity::addMessage('page_delete', $book->id, $page->name);
336         session()->flash('success', trans('entities.pages_delete_success'));
337         return redirect($book->getUrl());
338     }
339
340     /**
341      * Remove the specified draft page from storage.
342      * @param string $bookSlug
343      * @param int $pageId
344      * @return Response
345      * @throws NotFoundException
346      */
347     public function destroyDraft($bookSlug, $pageId)
348     {
349         $page = $this->entityRepo->getById('page', $pageId, true);
350         $book = $page->book;
351         $this->checkOwnablePermission('page-update', $page);
352         session()->flash('success', trans('entities.pages_delete_draft_success'));
353         $this->entityRepo->destroyPage($page);
354         return redirect($book->getUrl());
355     }
356
357     /**
358      * Shows the last revisions for this page.
359      * @param string $bookSlug
360      * @param string $pageSlug
361      * @return \Illuminate\View\View
362      */
363     public function showRevisions($bookSlug, $pageSlug)
364     {
365         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
366         $this->setPageTitle(trans('entities.pages_revisions_named', ['pageName'=>$page->getShortName()]));
367         return view('pages/revisions', ['page' => $page, 'book' => $page->book, 'current' => $page]);
368     }
369
370     /**
371      * Shows a preview of a single revision
372      * @param string $bookSlug
373      * @param string $pageSlug
374      * @param int $revisionId
375      * @return \Illuminate\View\View
376      */
377     public function showRevision($bookSlug, $pageSlug, $revisionId)
378     {
379         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
380         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
381         if ($revision === null) {
382             abort(404);
383         }
384
385         $page->fill($revision->toArray());
386         $this->setPageTitle(trans('entities.pages_revision_named', ['pageName' => $page->getShortName()]));
387
388         return view('pages/revision', [
389             'page' => $page,
390             'book' => $page->book,
391             'revision' => $revision
392         ]);
393     }
394
395     /**
396      * Shows the changes of a single revision
397      * @param string $bookSlug
398      * @param string $pageSlug
399      * @param int $revisionId
400      * @return \Illuminate\View\View
401      */
402     public function showRevisionChanges($bookSlug, $pageSlug, $revisionId)
403     {
404         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
405         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
406         if ($revision === null) {
407             abort(404);
408         }
409
410         $prev = $revision->getPrevious();
411         $prevContent = ($prev === null) ? '' : $prev->html;
412         $diff = (new Htmldiff)->diff($prevContent, $revision->html);
413
414         $page->fill($revision->toArray());
415         $this->setPageTitle(trans('entities.pages_revision_named', ['pageName'=>$page->getShortName()]));
416
417         return view('pages/revision', [
418             'page' => $page,
419             'book' => $page->book,
420             'diff' => $diff,
421             'revision' => $revision
422         ]);
423     }
424
425     /**
426      * Restores a page using the content of the specified revision.
427      * @param string $bookSlug
428      * @param string $pageSlug
429      * @param int $revisionId
430      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
431      */
432     public function restoreRevision($bookSlug, $pageSlug, $revisionId)
433     {
434         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
435         $this->checkOwnablePermission('page-update', $page);
436         $page = $this->entityRepo->restorePageRevision($page, $page->book, $revisionId);
437         Activity::add($page, 'page_restore', $page->book->id);
438         return redirect($page->getUrl());
439     }
440
441     /**
442      * Exports a page to a PDF.
443      * https://github.com/barryvdh/laravel-dompdf
444      * @param string $bookSlug
445      * @param string $pageSlug
446      * @return \Illuminate\Http\Response
447      */
448     public function exportPdf($bookSlug, $pageSlug)
449     {
450         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
451         $page->html = $this->entityRepo->renderPage($page);
452         $pdfContent = $this->exportService->pageToPdf($page);
453         return response()->make($pdfContent, 200, [
454             'Content-Type'        => 'application/octet-stream',
455             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.pdf'
456         ]);
457     }
458
459     /**
460      * Export a page to a self-contained HTML file.
461      * @param string $bookSlug
462      * @param string $pageSlug
463      * @return \Illuminate\Http\Response
464      */
465     public function exportHtml($bookSlug, $pageSlug)
466     {
467         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
468         $page->html = $this->entityRepo->renderPage($page);
469         $containedHtml = $this->exportService->pageToContainedHtml($page);
470         return response()->make($containedHtml, 200, [
471             'Content-Type'        => 'application/octet-stream',
472             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.html'
473         ]);
474     }
475
476     /**
477      * Export a page to a simple plaintext .txt file.
478      * @param string $bookSlug
479      * @param string $pageSlug
480      * @return \Illuminate\Http\Response
481      */
482     public function exportPlainText($bookSlug, $pageSlug)
483     {
484         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
485         $containedHtml = $this->exportService->pageToPlainText($page);
486         return response()->make($containedHtml, 200, [
487             'Content-Type'        => 'application/octet-stream',
488             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.txt'
489         ]);
490     }
491
492     /**
493      * Show a listing of recently created pages
494      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
495      */
496     public function showRecentlyCreated()
497     {
498         $pages = $this->entityRepo->getRecentlyCreatedPaginated('page', 20)->setPath(baseUrl('/pages/recently-created'));
499         return view('pages/detailed-listing', [
500             'title' => trans('entities.recently_created_pages'),
501             'pages' => $pages
502         ]);
503     }
504
505     /**
506      * Show a listing of recently created pages
507      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
508      */
509     public function showRecentlyUpdated()
510     {
511         $pages = $this->entityRepo->getRecentlyUpdatedPaginated('page', 20)->setPath(baseUrl('/pages/recently-updated'));
512         return view('pages/detailed-listing', [
513             'title' => trans('entities.recently_updated_pages'),
514             'pages' => $pages
515         ]);
516     }
517
518     /**
519      * Show the Restrictions view.
520      * @param string $bookSlug
521      * @param string $pageSlug
522      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
523      */
524     public function showRestrict($bookSlug, $pageSlug)
525     {
526         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
527         $this->checkOwnablePermission('restrictions-manage', $page);
528         $roles = $this->userRepo->getRestrictableRoles();
529         return view('pages/restrictions', [
530             'page'  => $page,
531             'roles' => $roles
532         ]);
533     }
534
535     /**
536      * Show the view to choose a new parent to move a page into.
537      * @param string $bookSlug
538      * @param string $pageSlug
539      * @return mixed
540      * @throws NotFoundException
541      */
542     public function showMove($bookSlug, $pageSlug)
543     {
544         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
545         $this->checkOwnablePermission('page-update', $page);
546         return view('pages/move', [
547             'book' => $page->book,
548             'page' => $page
549         ]);
550     }
551
552     /**
553      * Does the action of moving the location of a page
554      * @param string $bookSlug
555      * @param string $pageSlug
556      * @param Request $request
557      * @return mixed
558      * @throws NotFoundException
559      */
560     public function move($bookSlug, $pageSlug, Request $request)
561     {
562         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
563         $this->checkOwnablePermission('page-update', $page);
564
565         $entitySelection = $request->get('entity_selection', null);
566         if ($entitySelection === null || $entitySelection === '') {
567             return redirect($page->getUrl());
568         }
569
570         $stringExploded = explode(':', $entitySelection);
571         $entityType = $stringExploded[0];
572         $entityId = intval($stringExploded[1]);
573
574
575         try {
576             $parent = $this->entityRepo->getById($entityType, $entityId);
577         } catch (\Exception $e) {
578             session()->flash(trans('entities.selected_book_chapter_not_found'));
579             return redirect()->back();
580         }
581
582         $this->entityRepo->changePageParent($page, $parent);
583         Activity::add($page, 'page_move', $page->book->id);
584         session()->flash('success', trans('entities.pages_move_success', ['parentName' => $parent->name]));
585
586         return redirect($page->getUrl());
587     }
588
589     /**
590      * Set the permissions for this page.
591      * @param string $bookSlug
592      * @param string $pageSlug
593      * @param Request $request
594      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
595      */
596     public function restrict($bookSlug, $pageSlug, Request $request)
597     {
598         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
599         $this->checkOwnablePermission('restrictions-manage', $page);
600         $this->entityRepo->updateEntityPermissionsFromRequest($request, $page);
601         session()->flash('success', trans('entities.pages_permissions_success'));
602         return redirect($page->getUrl());
603     }
604
605 }