]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/PageController.php
Started work on revisions in image manager
[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      * @throws NotFoundException
149      */
150     public function show($bookSlug, $pageSlug)
151     {
152         try {
153             $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
154         } catch (NotFoundException $e) {
155             $page = $this->entityRepo->getPageByOldSlug($pageSlug, $bookSlug);
156             if ($page === null) {
157                 throw $e;
158             }
159             return redirect($page->getUrl());
160         }
161
162         $this->checkOwnablePermission('page-view', $page);
163
164         $page->html = $this->entityRepo->renderPage($page);
165         $sidebarTree = $this->entityRepo->getBookChildren($page->book);
166         $pageNav = $this->entityRepo->getPageNav($page->html);
167
168         // check if the comment's are enabled
169         $commentsEnabled = !setting('app-disable-comments');
170         if ($commentsEnabled) {
171             $page->load(['comments.createdBy']);
172         }
173
174         Views::add($page);
175         $this->setPageTitle($page->getShortName());
176         return view('pages/show', [
177             'page' => $page,'book' => $page->book,
178             'current' => $page,
179             'sidebarTree' => $sidebarTree,
180             'commentsEnabled' => $commentsEnabled,
181             'pageNav' => $pageNav
182         ]);
183     }
184
185     /**
186      * Get page from an ajax request.
187      * @param int $pageId
188      * @return \Illuminate\Http\JsonResponse
189      */
190     public function getPageAjax($pageId)
191     {
192         $page = $this->entityRepo->getById('page', $pageId);
193         return response()->json($page);
194     }
195
196     /**
197      * Show the form for editing the specified page.
198      * @param string $bookSlug
199      * @param string $pageSlug
200      * @return Response
201      */
202     public function edit($bookSlug, $pageSlug)
203     {
204         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
205         $this->checkOwnablePermission('page-update', $page);
206         $this->setPageTitle(trans('entities.pages_editing_named', ['pageName'=>$page->getShortName()]));
207         $page->isDraft = false;
208
209         // Check for active editing
210         $warnings = [];
211         if ($this->entityRepo->isPageEditingActive($page, 60)) {
212             $warnings[] = $this->entityRepo->getPageEditingActiveMessage($page, 60);
213         }
214
215         // Check for a current draft version for this user
216         if ($this->entityRepo->hasUserGotPageDraft($page, $this->currentUser->id)) {
217             $draft = $this->entityRepo->getUserPageDraft($page, $this->currentUser->id);
218             $page->name = $draft->name;
219             $page->html = $draft->html;
220             $page->markdown = $draft->markdown;
221             $page->isDraft = true;
222             $warnings [] = $this->entityRepo->getUserPageDraftMessage($draft);
223         }
224
225         if (count($warnings) > 0) {
226             session()->flash('warning', implode("\n", $warnings));
227         }
228
229         $draftsEnabled = $this->signedIn;
230         return view('pages/edit', [
231             'page' => $page,
232             'book' => $page->book,
233             'current' => $page,
234             'draftsEnabled' => $draftsEnabled
235         ]);
236     }
237
238     /**
239      * Update the specified page in storage.
240      * @param  Request $request
241      * @param  string $bookSlug
242      * @param  string $pageSlug
243      * @return Response
244      */
245     public function update(Request $request, $bookSlug, $pageSlug)
246     {
247         $this->validate($request, [
248             'name' => 'required|string|max:255'
249         ]);
250         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
251         $this->checkOwnablePermission('page-update', $page);
252         $this->entityRepo->updatePage($page, $page->book->id, $request->all());
253         Activity::add($page, 'page_update', $page->book->id);
254         return redirect($page->getUrl());
255     }
256
257     /**
258      * Save a draft update as a revision.
259      * @param Request $request
260      * @param int $pageId
261      * @return \Illuminate\Http\JsonResponse
262      */
263     public function saveDraft(Request $request, $pageId)
264     {
265         $page = $this->entityRepo->getById('page', $pageId, true);
266         $this->checkOwnablePermission('page-update', $page);
267
268         if (!$this->signedIn) {
269             return response()->json([
270                 'status' => 'error',
271                 'message' => trans('errors.guests_cannot_save_drafts'),
272             ], 500);
273         }
274
275         $draft = $this->entityRepo->updatePageDraft($page, $request->only(['name', 'html', 'markdown']));
276
277         $updateTime = $draft->updated_at->timestamp;
278         return response()->json([
279             'status'    => 'success',
280             'message'   => trans('entities.pages_edit_draft_save_at'),
281             'timestamp' => $updateTime
282         ]);
283     }
284
285     /**
286      * Redirect from a special link url which
287      * uses the page id rather than the name.
288      * @param int $pageId
289      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
290      */
291     public function redirectFromLink($pageId)
292     {
293         $page = $this->entityRepo->getById('page', $pageId);
294         return redirect($page->getUrl());
295     }
296
297     /**
298      * Show the deletion page for the specified page.
299      * @param string $bookSlug
300      * @param string $pageSlug
301      * @return \Illuminate\View\View
302      */
303     public function showDelete($bookSlug, $pageSlug)
304     {
305         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
306         $this->checkOwnablePermission('page-delete', $page);
307         $this->setPageTitle(trans('entities.pages_delete_named', ['pageName'=>$page->getShortName()]));
308         return view('pages/delete', ['book' => $page->book, 'page' => $page, 'current' => $page]);
309     }
310
311
312     /**
313      * Show the deletion page for the specified page.
314      * @param string $bookSlug
315      * @param int $pageId
316      * @return \Illuminate\View\View
317      * @throws NotFoundException
318      */
319     public function showDeleteDraft($bookSlug, $pageId)
320     {
321         $page = $this->entityRepo->getById('page', $pageId, true);
322         $this->checkOwnablePermission('page-update', $page);
323         $this->setPageTitle(trans('entities.pages_delete_draft_named', ['pageName'=>$page->getShortName()]));
324         return view('pages/delete', ['book' => $page->book, 'page' => $page, 'current' => $page]);
325     }
326
327     /**
328      * Remove the specified page from storage.
329      * @param string $bookSlug
330      * @param string $pageSlug
331      * @return Response
332      * @internal param int $id
333      */
334     public function destroy($bookSlug, $pageSlug)
335     {
336         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
337         $book = $page->book;
338         $this->checkOwnablePermission('page-delete', $page);
339         $this->entityRepo->destroyPage($page);
340
341         Activity::addMessage('page_delete', $book->id, $page->name);
342         session()->flash('success', trans('entities.pages_delete_success'));
343         return redirect($book->getUrl());
344     }
345
346     /**
347      * Remove the specified draft page from storage.
348      * @param string $bookSlug
349      * @param int $pageId
350      * @return Response
351      * @throws NotFoundException
352      */
353     public function destroyDraft($bookSlug, $pageId)
354     {
355         $page = $this->entityRepo->getById('page', $pageId, true);
356         $book = $page->book;
357         $this->checkOwnablePermission('page-update', $page);
358         session()->flash('success', trans('entities.pages_delete_draft_success'));
359         $this->entityRepo->destroyPage($page);
360         return redirect($book->getUrl());
361     }
362
363     /**
364      * Shows the last revisions for this page.
365      * @param string $bookSlug
366      * @param string $pageSlug
367      * @return \Illuminate\View\View
368      */
369     public function showRevisions($bookSlug, $pageSlug)
370     {
371         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
372         $this->setPageTitle(trans('entities.pages_revisions_named', ['pageName'=>$page->getShortName()]));
373         return view('pages/revisions', ['page' => $page, 'book' => $page->book, 'current' => $page]);
374     }
375
376     /**
377      * Shows a preview of a single revision
378      * @param string $bookSlug
379      * @param string $pageSlug
380      * @param int $revisionId
381      * @return \Illuminate\View\View
382      */
383     public function showRevision($bookSlug, $pageSlug, $revisionId)
384     {
385         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
386         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
387         if ($revision === null) {
388             abort(404);
389         }
390
391         $page->fill($revision->toArray());
392         $this->setPageTitle(trans('entities.pages_revision_named', ['pageName' => $page->getShortName()]));
393
394         return view('pages/revision', [
395             'page' => $page,
396             'book' => $page->book,
397             'revision' => $revision
398         ]);
399     }
400
401     /**
402      * Shows the changes of a single revision
403      * @param string $bookSlug
404      * @param string $pageSlug
405      * @param int $revisionId
406      * @return \Illuminate\View\View
407      */
408     public function showRevisionChanges($bookSlug, $pageSlug, $revisionId)
409     {
410         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
411         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
412         if ($revision === null) {
413             abort(404);
414         }
415
416         $prev = $revision->getPrevious();
417         $prevContent = ($prev === null) ? '' : $prev->html;
418         $diff = (new Htmldiff)->diff($prevContent, $revision->html);
419
420         $page->fill($revision->toArray());
421         $this->setPageTitle(trans('entities.pages_revision_named', ['pageName'=>$page->getShortName()]));
422
423         return view('pages/revision', [
424             'page' => $page,
425             'book' => $page->book,
426             'diff' => $diff,
427             'revision' => $revision
428         ]);
429     }
430
431     /**
432      * Restores a page using the content of the specified revision.
433      * @param string $bookSlug
434      * @param string $pageSlug
435      * @param int $revisionId
436      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
437      */
438     public function restoreRevision($bookSlug, $pageSlug, $revisionId)
439     {
440         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
441         $this->checkOwnablePermission('page-update', $page);
442         $page = $this->entityRepo->restorePageRevision($page, $page->book, $revisionId);
443         Activity::add($page, 'page_restore', $page->book->id);
444         return redirect($page->getUrl());
445     }
446
447     /**
448      * Exports a page to a PDF.
449      * https://github.com/barryvdh/laravel-dompdf
450      * @param string $bookSlug
451      * @param string $pageSlug
452      * @return \Illuminate\Http\Response
453      */
454     public function exportPdf($bookSlug, $pageSlug)
455     {
456         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
457         $page->html = $this->entityRepo->renderPage($page);
458         $pdfContent = $this->exportService->pageToPdf($page);
459         return response()->make($pdfContent, 200, [
460             'Content-Type'        => 'application/octet-stream',
461             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.pdf'
462         ]);
463     }
464
465     /**
466      * Export a page to a self-contained HTML file.
467      * @param string $bookSlug
468      * @param string $pageSlug
469      * @return \Illuminate\Http\Response
470      */
471     public function exportHtml($bookSlug, $pageSlug)
472     {
473         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
474         $page->html = $this->entityRepo->renderPage($page);
475         $containedHtml = $this->exportService->pageToContainedHtml($page);
476         return response()->make($containedHtml, 200, [
477             'Content-Type'        => 'application/octet-stream',
478             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.html'
479         ]);
480     }
481
482     /**
483      * Export a page to a simple plaintext .txt file.
484      * @param string $bookSlug
485      * @param string $pageSlug
486      * @return \Illuminate\Http\Response
487      */
488     public function exportPlainText($bookSlug, $pageSlug)
489     {
490         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
491         $containedHtml = $this->exportService->pageToPlainText($page);
492         return response()->make($containedHtml, 200, [
493             'Content-Type'        => 'application/octet-stream',
494             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.txt'
495         ]);
496     }
497
498     /**
499      * Show a listing of recently created pages
500      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
501      */
502     public function showRecentlyCreated()
503     {
504         $pages = $this->entityRepo->getRecentlyCreatedPaginated('page', 20)->setPath(baseUrl('/pages/recently-created'));
505         return view('pages/detailed-listing', [
506             'title' => trans('entities.recently_created_pages'),
507             'pages' => $pages
508         ]);
509     }
510
511     /**
512      * Show a listing of recently created pages
513      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
514      */
515     public function showRecentlyUpdated()
516     {
517         $pages = $this->entityRepo->getRecentlyUpdatedPaginated('page', 20)->setPath(baseUrl('/pages/recently-updated'));
518         return view('pages/detailed-listing', [
519             'title' => trans('entities.recently_updated_pages'),
520             'pages' => $pages
521         ]);
522     }
523
524     /**
525      * Show the Restrictions view.
526      * @param string $bookSlug
527      * @param string $pageSlug
528      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
529      */
530     public function showRestrict($bookSlug, $pageSlug)
531     {
532         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
533         $this->checkOwnablePermission('restrictions-manage', $page);
534         $roles = $this->userRepo->getRestrictableRoles();
535         return view('pages/restrictions', [
536             'page'  => $page,
537             'roles' => $roles
538         ]);
539     }
540
541     /**
542      * Show the view to choose a new parent to move a page into.
543      * @param string $bookSlug
544      * @param string $pageSlug
545      * @return mixed
546      * @throws NotFoundException
547      */
548     public function showMove($bookSlug, $pageSlug)
549     {
550         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
551         $this->checkOwnablePermission('page-update', $page);
552         return view('pages/move', [
553             'book' => $page->book,
554             'page' => $page
555         ]);
556     }
557
558     /**
559      * Does the action of moving the location of a page
560      * @param string $bookSlug
561      * @param string $pageSlug
562      * @param Request $request
563      * @return mixed
564      * @throws NotFoundException
565      */
566     public function move($bookSlug, $pageSlug, Request $request)
567     {
568         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
569         $this->checkOwnablePermission('page-update', $page);
570
571         $entitySelection = $request->get('entity_selection', null);
572         if ($entitySelection === null || $entitySelection === '') {
573             return redirect($page->getUrl());
574         }
575
576         $stringExploded = explode(':', $entitySelection);
577         $entityType = $stringExploded[0];
578         $entityId = intval($stringExploded[1]);
579
580
581         try {
582             $parent = $this->entityRepo->getById($entityType, $entityId);
583         } catch (\Exception $e) {
584             session()->flash(trans('entities.selected_book_chapter_not_found'));
585             return redirect()->back();
586         }
587
588         $this->checkOwnablePermission('page-create', $parent);
589
590         $this->entityRepo->changePageParent($page, $parent);
591         Activity::add($page, 'page_move', $page->book->id);
592         session()->flash('success', trans('entities.pages_move_success', ['parentName' => $parent->name]));
593
594         return redirect($page->getUrl());
595     }
596
597     /**
598      * Show the view to copy a page.
599      * @param string $bookSlug
600      * @param string $pageSlug
601      * @return mixed
602      * @throws NotFoundException
603      */
604     public function showCopy($bookSlug, $pageSlug)
605     {
606         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
607         $this->checkOwnablePermission('page-update', $page);
608         session()->flashInput(['name' => $page->name]);
609         return view('pages/copy', [
610             'book' => $page->book,
611             'page' => $page
612         ]);
613     }
614
615     /**
616      * Create a copy of a page within the requested target destination.
617      * @param string $bookSlug
618      * @param string $pageSlug
619      * @param Request $request
620      * @return mixed
621      * @throws NotFoundException
622      */
623     public function copy($bookSlug, $pageSlug, Request $request)
624     {
625         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
626         $this->checkOwnablePermission('page-update', $page);
627
628         $entitySelection = $request->get('entity_selection', null);
629         if ($entitySelection === null || $entitySelection === '') {
630             $parent = $page->chapter ? $page->chapter : $page->book;
631         } else {
632             $stringExploded = explode(':', $entitySelection);
633             $entityType = $stringExploded[0];
634             $entityId = intval($stringExploded[1]);
635
636             try {
637                 $parent = $this->entityRepo->getById($entityType, $entityId);
638             } catch (\Exception $e) {
639                 session()->flash(trans('entities.selected_book_chapter_not_found'));
640                 return redirect()->back();
641             }
642         }
643
644         $this->checkOwnablePermission('page-create', $parent);
645
646         $pageCopy = $this->entityRepo->copyPage($page, $parent, $request->get('name', ''));
647
648         Activity::add($pageCopy, 'page_create', $pageCopy->book->id);
649         session()->flash('success', trans('entities.pages_copy_success'));
650
651         return redirect($pageCopy->getUrl());
652     }
653
654     /**
655      * Set the permissions for this page.
656      * @param string $bookSlug
657      * @param string $pageSlug
658      * @param Request $request
659      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
660      * @throws NotFoundException
661      */
662     public function restrict($bookSlug, $pageSlug, Request $request)
663     {
664         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
665         $this->checkOwnablePermission('restrictions-manage', $page);
666         $this->entityRepo->updateEntityPermissionsFromRequest($request, $page);
667         session()->flash('success', trans('entities.pages_permissions_success'));
668         return redirect($page->getUrl());
669     }
670 }