]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/PageController.php
Merge branch 'master' of https://github.com/BookStackApp/BookStack
[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 = $this->entityRepo->getById('page_revision', $revisionId, false);
373
374         $page->fill($revision->toArray());
375         $this->setPageTitle(trans('entities.pages_revision_named', ['pageName'=>$page->getShortName()]));
376         
377         return view('pages/revision', [
378             'page' => $page,
379             'book' => $page->book,
380         ]);
381     }
382
383     /**
384      * Shows the changes of a single revision
385      * @param string $bookSlug
386      * @param string $pageSlug
387      * @param int $revisionId
388      * @return \Illuminate\View\View
389      */
390     public function showRevisionChanges($bookSlug, $pageSlug, $revisionId)
391     {
392         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
393         $revision = $this->entityRepo->getById('page_revision', $revisionId);
394
395         $prev = $revision->getPrevious();
396         $prevContent = ($prev === null) ? '' : $prev->html;
397         $diff = (new Htmldiff)->diff($prevContent, $revision->html);
398
399         $page->fill($revision->toArray());
400         $this->setPageTitle(trans('entities.pages_revision_named', ['pageName'=>$page->getShortName()]));
401
402         return view('pages/revision', [
403             'page' => $page,
404             'book' => $page->book,
405             'diff' => $diff,
406         ]);
407     }
408
409     /**
410      * Restores a page using the content of the specified revision.
411      * @param string $bookSlug
412      * @param string $pageSlug
413      * @param int $revisionId
414      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
415      */
416     public function restoreRevision($bookSlug, $pageSlug, $revisionId)
417     {
418         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
419         $this->checkOwnablePermission('page-update', $page);
420         $page = $this->entityRepo->restorePageRevision($page, $page->book, $revisionId);
421         Activity::add($page, 'page_restore', $page->book->id);
422         return redirect($page->getUrl());
423     }
424
425     /**
426      * Exports a page to pdf format using barryvdh/laravel-dompdf wrapper.
427      * https://github.com/barryvdh/laravel-dompdf
428      * @param string $bookSlug
429      * @param string $pageSlug
430      * @return \Illuminate\Http\Response
431      */
432     public function exportPdf($bookSlug, $pageSlug)
433     {
434         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
435         $pdfContent = $this->exportService->pageToPdf($page);
436 //        return $pdfContent;
437         return response()->make($pdfContent, 200, [
438             'Content-Type'        => 'application/octet-stream',
439             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.pdf'
440         ]);
441     }
442
443     /**
444      * Export a page to a self-contained HTML file.
445      * @param string $bookSlug
446      * @param string $pageSlug
447      * @return \Illuminate\Http\Response
448      */
449     public function exportHtml($bookSlug, $pageSlug)
450     {
451         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
452         $containedHtml = $this->exportService->pageToContainedHtml($page);
453         return response()->make($containedHtml, 200, [
454             'Content-Type'        => 'application/octet-stream',
455             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.html'
456         ]);
457     }
458
459     /**
460      * Export a page to a simple plaintext .txt file.
461      * @param string $bookSlug
462      * @param string $pageSlug
463      * @return \Illuminate\Http\Response
464      */
465     public function exportPlainText($bookSlug, $pageSlug)
466     {
467         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
468         $containedHtml = $this->exportService->pageToPlainText($page);
469         return response()->make($containedHtml, 200, [
470             'Content-Type'        => 'application/octet-stream',
471             'Content-Disposition' => 'attachment; filename="' . $pageSlug . '.txt'
472         ]);
473     }
474
475     /**
476      * Show a listing of recently created pages
477      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
478      */
479     public function showRecentlyCreated()
480     {
481         $pages = $this->entityRepo->getRecentlyCreatedPaginated('page', 20)->setPath(baseUrl('/pages/recently-created'));
482         return view('pages/detailed-listing', [
483             'title' => trans('entities.recently_created_pages'),
484             'pages' => $pages
485         ]);
486     }
487
488     /**
489      * Show a listing of recently created pages
490      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
491      */
492     public function showRecentlyUpdated()
493     {
494         $pages = $this->entityRepo->getRecentlyUpdatedPaginated('page', 20)->setPath(baseUrl('/pages/recently-updated'));
495         return view('pages/detailed-listing', [
496             'title' => trans('entities.recently_updated_pages'),
497             'pages' => $pages
498         ]);
499     }
500
501     /**
502      * Show the Restrictions view.
503      * @param string $bookSlug
504      * @param string $pageSlug
505      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
506      */
507     public function showRestrict($bookSlug, $pageSlug)
508     {
509         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
510         $this->checkOwnablePermission('restrictions-manage', $page);
511         $roles = $this->userRepo->getRestrictableRoles();
512         return view('pages/restrictions', [
513             'page'  => $page,
514             'roles' => $roles
515         ]);
516     }
517
518     /**
519      * Show the view to choose a new parent to move a page into.
520      * @param string $bookSlug
521      * @param string $pageSlug
522      * @return mixed
523      * @throws NotFoundException
524      */
525     public function showMove($bookSlug, $pageSlug)
526     {
527         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
528         $this->checkOwnablePermission('page-update', $page);
529         return view('pages/move', [
530             'book' => $page->book,
531             'page' => $page
532         ]);
533     }
534
535     /**
536      * Does the action of moving the location of a page
537      * @param string $bookSlug
538      * @param string $pageSlug
539      * @param Request $request
540      * @return mixed
541      * @throws NotFoundException
542      */
543     public function move($bookSlug, $pageSlug, Request $request)
544     {
545         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
546         $this->checkOwnablePermission('page-update', $page);
547
548         $entitySelection = $request->get('entity_selection', null);
549         if ($entitySelection === null || $entitySelection === '') {
550             return redirect($page->getUrl());
551         }
552
553         $stringExploded = explode(':', $entitySelection);
554         $entityType = $stringExploded[0];
555         $entityId = intval($stringExploded[1]);
556
557
558         try {
559             $parent = $this->entityRepo->getById($entityType, $entityId);
560         } catch (\Exception $e) {
561             session()->flash(trans('entities.selected_book_chapter_not_found'));
562             return redirect()->back();
563         }
564
565         $this->entityRepo->changePageParent($page, $parent);
566         Activity::add($page, 'page_move', $page->book->id);
567         session()->flash('success', trans('entities.pages_move_success', ['parentName' => $parent->name]));
568
569         return redirect($page->getUrl());
570     }
571
572     /**
573      * Set the permissions for this page.
574      * @param string $bookSlug
575      * @param string $pageSlug
576      * @param Request $request
577      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
578      */
579     public function restrict($bookSlug, $pageSlug, Request $request)
580     {
581         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
582         $this->checkOwnablePermission('restrictions-manage', $page);
583         $this->entityRepo->updateEntityPermissionsFromRequest($request, $page);
584         session()->flash('success', trans('entities.pages_permissions_success'));
585         return redirect($page->getUrl());
586     }
587
588 }