]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/PageController.php
Started page transclusion system
[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
160         $this->checkOwnablePermission('page-view', $page);
161
162         $pageContent = $this->entityRepo->renderPage($page);
163         $sidebarTree = $this->entityRepo->getBookChildren($page->book);
164         $pageNav = $this->entityRepo->getPageNav($page);
165         
166         Views::add($page);
167         $this->setPageTitle($page->getShortName());
168         return view('pages/show', [
169             'page' => $page,'book' => $page->book,
170             'current' => $page, 'sidebarTree' => $sidebarTree,
171             'pageNav' => $pageNav, 'pageContent' => $pageContent]);
172     }
173
174     /**
175      * Get page from an ajax request.
176      * @param int $pageId
177      * @return \Illuminate\Http\JsonResponse
178      */
179     public function getPageAjax($pageId)
180     {
181         $page = $this->entityRepo->getById('page', $pageId);
182         return response()->json($page);
183     }
184
185     /**
186      * Show the form for editing the specified page.
187      * @param string $bookSlug
188      * @param string $pageSlug
189      * @return Response
190      */
191     public function edit($bookSlug, $pageSlug)
192     {
193         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
194         $this->checkOwnablePermission('page-update', $page);
195         $this->setPageTitle(trans('entities.pages_editing_named', ['pageName'=>$page->getShortName()]));
196         $page->isDraft = false;
197
198         // Check for active editing
199         $warnings = [];
200         if ($this->entityRepo->isPageEditingActive($page, 60)) {
201             $warnings[] = $this->entityRepo->getPageEditingActiveMessage($page, 60);
202         }
203
204         // Check for a current draft version for this user
205         if ($this->entityRepo->hasUserGotPageDraft($page, $this->currentUser->id)) {
206             $draft = $this->entityRepo->getUserPageDraft($page, $this->currentUser->id);
207             $page->name = $draft->name;
208             $page->html = $draft->html;
209             $page->markdown = $draft->markdown;
210             $page->isDraft = true;
211             $warnings [] = $this->entityRepo->getUserPageDraftMessage($draft);
212         }
213
214         if (count($warnings) > 0) session()->flash('warning', implode("\n", $warnings));
215
216         $draftsEnabled = $this->signedIn;
217         return view('pages/edit', [
218             'page' => $page,
219             'book' => $page->book,
220             'current' => $page,
221             'draftsEnabled' => $draftsEnabled
222         ]);
223     }
224
225     /**
226      * Update the specified page in storage.
227      * @param  Request $request
228      * @param  string $bookSlug
229      * @param  string $pageSlug
230      * @return Response
231      */
232     public function update(Request $request, $bookSlug, $pageSlug)
233     {
234         $this->validate($request, [
235             'name' => 'required|string|max:255'
236         ]);
237         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
238         $this->checkOwnablePermission('page-update', $page);
239         $this->entityRepo->updatePage($page, $page->book->id, $request->all());
240         Activity::add($page, 'page_update', $page->book->id);
241         return redirect($page->getUrl());
242     }
243
244     /**
245      * Save a draft update as a revision.
246      * @param Request $request
247      * @param int $pageId
248      * @return \Illuminate\Http\JsonResponse
249      */
250     public function saveDraft(Request $request, $pageId)
251     {
252         $page = $this->entityRepo->getById('page', $pageId, true);
253         $this->checkOwnablePermission('page-update', $page);
254
255         if (!$this->signedIn) {
256             return response()->json([
257                 'status' => 'error',
258                 'message' => trans('errors.guests_cannot_save_drafts'),
259             ], 500);
260         }
261
262         $draft = $this->entityRepo->updatePageDraft($page, $request->only(['name', 'html', 'markdown']));
263
264         $updateTime = $draft->updated_at->timestamp;
265         $utcUpdateTimestamp = $updateTime + Carbon::createFromTimestamp(0)->offset;
266         return response()->json([
267             'status'    => 'success',
268             'message'   => trans('entities.pages_edit_draft_save_at'),
269             'timestamp' => $utcUpdateTimestamp
270         ]);
271     }
272
273     /**
274      * Redirect from a special link url which
275      * uses the page id rather than the name.
276      * @param int $pageId
277      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
278      */
279     public function redirectFromLink($pageId)
280     {
281         $page = $this->entityRepo->getById('page', $pageId);
282         return redirect($page->getUrl());
283     }
284
285     /**
286      * Show the deletion page for the specified page.
287      * @param string $bookSlug
288      * @param string $pageSlug
289      * @return \Illuminate\View\View
290      */
291     public function showDelete($bookSlug, $pageSlug)
292     {
293         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
294         $this->checkOwnablePermission('page-delete', $page);
295         $this->setPageTitle(trans('entities.pages_delete_named', ['pageName'=>$page->getShortName()]));
296         return view('pages/delete', ['book' => $page->book, 'page' => $page, 'current' => $page]);
297     }
298
299
300     /**
301      * Show the deletion page for the specified page.
302      * @param string $bookSlug
303      * @param int $pageId
304      * @return \Illuminate\View\View
305      * @throws NotFoundException
306      */
307     public function showDeleteDraft($bookSlug, $pageId)
308     {
309         $page = $this->entityRepo->getById('page', $pageId, true);
310         $this->checkOwnablePermission('page-update', $page);
311         $this->setPageTitle(trans('entities.pages_delete_draft_named', ['pageName'=>$page->getShortName()]));
312         return view('pages/delete', ['book' => $page->book, 'page' => $page, 'current' => $page]);
313     }
314
315     /**
316      * Remove the specified page from storage.
317      * @param string $bookSlug
318      * @param string $pageSlug
319      * @return Response
320      * @internal param int $id
321      */
322     public function destroy($bookSlug, $pageSlug)
323     {
324         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
325         $book = $page->book;
326         $this->checkOwnablePermission('page-delete', $page);
327         Activity::addMessage('page_delete', $book->id, $page->name);
328         session()->flash('success', trans('entities.pages_delete_success'));
329         $this->entityRepo->destroyPage($page);
330         return redirect($book->getUrl());
331     }
332
333     /**
334      * Remove the specified draft page from storage.
335      * @param string $bookSlug
336      * @param int $pageId
337      * @return Response
338      * @throws NotFoundException
339      */
340     public function destroyDraft($bookSlug, $pageId)
341     {
342         $page = $this->entityRepo->getById('page', $pageId, true);
343         $book = $page->book;
344         $this->checkOwnablePermission('page-update', $page);
345         session()->flash('success', trans('entities.pages_delete_draft_success'));
346         $this->entityRepo->destroyPage($page);
347         return redirect($book->getUrl());
348     }
349
350     /**
351      * Shows the last revisions for this page.
352      * @param string $bookSlug
353      * @param string $pageSlug
354      * @return \Illuminate\View\View
355      */
356     public function showRevisions($bookSlug, $pageSlug)
357     {
358         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
359         $this->setPageTitle(trans('entities.pages_revisions_named', ['pageName'=>$page->getShortName()]));
360         return view('pages/revisions', ['page' => $page, 'book' => $page->book, 'current' => $page]);
361     }
362
363     /**
364      * Shows a preview of a single revision
365      * @param string $bookSlug
366      * @param string $pageSlug
367      * @param int $revisionId
368      * @return \Illuminate\View\View
369      */
370     public function showRevision($bookSlug, $pageSlug, $revisionId)
371     {
372         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
373         $revision = $this->entityRepo->getById('page_revision', $revisionId, false);
374
375         $page->fill($revision->toArray());
376         $this->setPageTitle(trans('entities.pages_revision_named', ['pageName'=>$page->getShortName()]));
377         
378         return view('pages/revision', [
379             'page' => $page,
380             'book' => $page->book,
381         ]);
382     }
383
384     /**
385      * Shows the changes of a single revision
386      * @param string $bookSlug
387      * @param string $pageSlug
388      * @param int $revisionId
389      * @return \Illuminate\View\View
390      */
391     public function showRevisionChanges($bookSlug, $pageSlug, $revisionId)
392     {
393         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
394         $revision = $this->entityRepo->getById('page_revision', $revisionId);
395
396         $prev = $revision->getPrevious();
397         $prevContent = ($prev === null) ? '' : $prev->html;
398         $diff = (new Htmldiff)->diff($prevContent, $revision->html);
399
400         $page->fill($revision->toArray());
401         $this->setPageTitle(trans('entities.pages_revision_named', ['pageName'=>$page->getShortName()]));
402
403         return view('pages/revision', [
404             'page' => $page,
405             'book' => $page->book,
406             'diff' => $diff,
407         ]);
408     }
409
410     /**
411      * Restores a page using the content of the specified revision.
412      * @param string $bookSlug
413      * @param string $pageSlug
414      * @param int $revisionId
415      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
416      */
417     public function restoreRevision($bookSlug, $pageSlug, $revisionId)
418     {
419         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
420         $this->checkOwnablePermission('page-update', $page);
421         $page = $this->entityRepo->restorePageRevision($page, $page->book, $revisionId);
422         Activity::add($page, 'page_restore', $page->book->id);
423         return redirect($page->getUrl());
424     }
425
426     /**
427      * Exports a page to pdf format using barryvdh/laravel-dompdf wrapper.
428      * https://github.com/barryvdh/laravel-dompdf
429      * @param string $bookSlug
430      * @param string $pageSlug
431      * @return \Illuminate\Http\Response
432      */
433     public function exportPdf($bookSlug, $pageSlug)
434     {
435         $page = $this->entityRepo->getBySlug('page', $pageSlug, $bookSlug);
436         $pdfContent = $this->exportService->pageToPdf($page);
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 }