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