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