]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Added additional testing for editor switching permissions
[bookstack] / app / Entities / Repos / PageRepo.php
1 <?php
2
3 namespace BookStack\Entities\Repos;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Entities\Models\PageRevision;
11 use BookStack\Entities\Tools\BookContents;
12 use BookStack\Entities\Tools\PageContent;
13 use BookStack\Entities\Tools\PageEditorData;
14 use BookStack\Entities\Tools\TrashCan;
15 use BookStack\Exceptions\MoveOperationException;
16 use BookStack\Exceptions\NotFoundException;
17 use BookStack\Exceptions\PermissionsException;
18 use BookStack\Facades\Activity;
19 use Exception;
20 use Illuminate\Database\Eloquent\Builder;
21 use Illuminate\Pagination\LengthAwarePaginator;
22
23 class PageRepo
24 {
25     protected $baseRepo;
26
27     /**
28      * PageRepo constructor.
29      */
30     public function __construct(BaseRepo $baseRepo)
31     {
32         $this->baseRepo = $baseRepo;
33     }
34
35     /**
36      * Get a page by ID.
37      *
38      * @throws NotFoundException
39      */
40     public function getById(int $id, array $relations = ['book']): Page
41     {
42         $page = Page::visible()->with($relations)->find($id);
43
44         if (!$page) {
45             throw new NotFoundException(trans('errors.page_not_found'));
46         }
47
48         return $page;
49     }
50
51     /**
52      * Get a page its book and own slug.
53      *
54      * @throws NotFoundException
55      */
56     public function getBySlug(string $bookSlug, string $pageSlug): Page
57     {
58         $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
59
60         if (!$page) {
61             throw new NotFoundException(trans('errors.page_not_found'));
62         }
63
64         return $page;
65     }
66
67     /**
68      * Get a page by its old slug but checking the revisions table
69      * for the last revision that matched the given page and book slug.
70      */
71     public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
72     {
73         /** @var ?PageRevision $revision */
74         $revision = PageRevision::query()
75             ->whereHas('page', function (Builder $query) {
76                 $query->scopes('visible');
77             })
78             ->where('slug', '=', $pageSlug)
79             ->where('type', '=', 'version')
80             ->where('book_slug', '=', $bookSlug)
81             ->orderBy('created_at', 'desc')
82             ->with('page')
83             ->first();
84
85         return $revision->page ?? null;
86     }
87
88     /**
89      * Get pages that have been marked as a template.
90      */
91     public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
92     {
93         $query = Page::visible()
94             ->where('template', '=', true)
95             ->orderBy('name', 'asc')
96             ->skip(($page - 1) * $count)
97             ->take($count);
98
99         if ($search) {
100             $query->where('name', 'like', '%' . $search . '%');
101         }
102
103         $paginator = $query->paginate($count, ['*'], 'page', $page);
104         $paginator->withPath('/templates');
105
106         return $paginator;
107     }
108
109     /**
110      * Get a parent item via slugs.
111      */
112     public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
113     {
114         if ($chapterSlug !== null) {
115             return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
116         }
117
118         return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
119     }
120
121     /**
122      * Get the draft copy of the given page for the current user.
123      */
124     public function getUserDraft(Page $page): ?PageRevision
125     {
126         $revision = $this->getUserDraftQuery($page)->first();
127
128         return $revision;
129     }
130
131     /**
132      * Get a new draft page belonging to the given parent entity.
133      */
134     public function getNewDraftPage(Entity $parent)
135     {
136         $page = (new Page())->forceFill([
137             'name'       => trans('entities.pages_initial_name'),
138             'created_by' => user()->id,
139             'owned_by'   => user()->id,
140             'updated_by' => user()->id,
141             'draft'      => true,
142         ]);
143
144         if ($parent instanceof Chapter) {
145             $page->chapter_id = $parent->id;
146             $page->book_id = $parent->book_id;
147         } else {
148             $page->book_id = $parent->id;
149         }
150
151         $page->save();
152         $page->refresh()->rebuildPermissions();
153
154         return $page;
155     }
156
157     /**
158      * Publish a draft page to make it a live, non-draft page.
159      */
160     public function publishDraft(Page $draft, array $input): Page
161     {
162         $this->updateTemplateStatusAndContentFromInput($draft, $input);
163         $this->baseRepo->update($draft, $input);
164
165         $draft->draft = false;
166         $draft->revision_count = 1;
167         $draft->priority = $this->getNewPriority($draft);
168         $draft->refreshSlug();
169         $draft->save();
170
171         $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
172         $draft->indexForSearch();
173         $draft->refresh();
174
175         Activity::add(ActivityType::PAGE_CREATE, $draft);
176
177         return $draft;
178     }
179
180     /**
181      * Update a page in the system.
182      */
183     public function update(Page $page, array $input): Page
184     {
185         // Hold the old details to compare later
186         $oldHtml = $page->html;
187         $oldName = $page->name;
188         $oldMarkdown = $page->markdown;
189
190         $this->updateTemplateStatusAndContentFromInput($page, $input);
191         $this->baseRepo->update($page, $input);
192
193         // Update with new details
194         $page->revision_count++;
195         $page->save();
196
197         // Remove all update drafts for this user & page.
198         $this->getUserDraftQuery($page)->delete();
199
200         // Save a revision after updating
201         $summary = trim($input['summary'] ?? '');
202         $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
203         $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
204         $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
205         if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
206             $this->savePageRevision($page, $summary);
207         }
208
209         Activity::add(ActivityType::PAGE_UPDATE, $page);
210
211         return $page;
212     }
213
214     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
215     {
216         if (isset($input['template']) && userCan('templates-manage')) {
217             $page->template = ($input['template'] === 'true');
218         }
219
220         $pageContent = new PageContent($page);
221         $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
222         $newEditor = $currentEditor;
223
224         $haveInput = isset($input['markdown']) || isset($input['html']);
225         $inputEmpty = empty($input['markdown']) && empty($input['html']);
226
227         if ($haveInput && $inputEmpty) {
228             $pageContent->setNewHTML('');
229         } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
230             $newEditor = 'markdown';
231             $pageContent->setNewMarkdown($input['markdown']);
232         } elseif (isset($input['html'])) {
233             $newEditor = 'wysiwyg';
234             $pageContent->setNewHTML($input['html']);
235         }
236
237         if ($newEditor !== $currentEditor && userCan('editor-change')) {
238             $page->editor = $newEditor;
239         }
240     }
241
242     /**
243      * Saves a page revision into the system.
244      */
245     protected function savePageRevision(Page $page, string $summary = null): PageRevision
246     {
247         $revision = new PageRevision();
248
249         $revision->name = $page->name;
250         $revision->html = $page->html;
251         $revision->markdown = $page->markdown;
252         $revision->text = $page->text;
253         $revision->page_id = $page->id;
254         $revision->slug = $page->slug;
255         $revision->book_slug = $page->book->slug;
256         $revision->created_by = user()->id;
257         $revision->created_at = $page->updated_at;
258         $revision->type = 'version';
259         $revision->summary = $summary;
260         $revision->revision_number = $page->revision_count;
261         $revision->save();
262
263         $this->deleteOldRevisions($page);
264
265         return $revision;
266     }
267
268     /**
269      * Save a page update draft.
270      */
271     public function updatePageDraft(Page $page, array $input)
272     {
273         // If the page itself is a draft simply update that
274         if ($page->draft) {
275             $this->updateTemplateStatusAndContentFromInput($page, $input);
276             $page->fill($input);
277             $page->save();
278
279             return $page;
280         }
281
282         // Otherwise, save the data to a revision
283         $draft = $this->getPageRevisionToUpdate($page);
284         $draft->fill($input);
285
286         if (!empty($input['markdown'])) {
287             $draft->markdown = $input['markdown'];
288             $draft->html = '';
289         } else {
290             $draft->html = $input['html'];
291             $draft->markdown = '';
292         }
293
294         $draft->save();
295
296         return $draft;
297     }
298
299     /**
300      * Destroy a page from the system.
301      *
302      * @throws Exception
303      */
304     public function destroy(Page $page)
305     {
306         $trashCan = new TrashCan();
307         $trashCan->softDestroyPage($page);
308         Activity::add(ActivityType::PAGE_DELETE, $page);
309         $trashCan->autoClearOld();
310     }
311
312     /**
313      * Restores a revision's content back into a page.
314      */
315     public function restoreRevision(Page $page, int $revisionId): Page
316     {
317         $page->revision_count++;
318
319         /** @var PageRevision $revision */
320         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
321
322         $page->fill($revision->toArray());
323         $content = new PageContent($page);
324
325         if (!empty($revision->markdown)) {
326             $content->setNewMarkdown($revision->markdown);
327         } else {
328             $content->setNewHTML($revision->html);
329         }
330
331         $page->updated_by = user()->id;
332         $page->refreshSlug();
333         $page->save();
334         $page->indexForSearch();
335
336         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
337         $this->savePageRevision($page, $summary);
338
339         Activity::add(ActivityType::PAGE_RESTORE, $page);
340
341         return $page;
342     }
343
344     /**
345      * Move the given page into a new parent book or chapter.
346      * The $parentIdentifier must be a string of the following format:
347      * 'book:<id>' (book:5).
348      *
349      * @throws MoveOperationException
350      * @throws PermissionsException
351      */
352     public function move(Page $page, string $parentIdentifier): Entity
353     {
354         $parent = $this->findParentByIdentifier($parentIdentifier);
355         if (is_null($parent)) {
356             throw new MoveOperationException('Book or chapter to move page into not found');
357         }
358
359         if (!userCan('page-create', $parent)) {
360             throw new PermissionsException('User does not have permission to create a page within the new parent');
361         }
362
363         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
364         $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
365         $page->changeBook($newBookId);
366         $page->rebuildPermissions();
367
368         Activity::add(ActivityType::PAGE_MOVE, $page);
369
370         return $parent;
371     }
372
373     /**
374      * Find a page parent entity via an identifier string in the format:
375      * {type}:{id}
376      * Example: (book:5).
377      *
378      * @throws MoveOperationException
379      */
380     public function findParentByIdentifier(string $identifier): ?Entity
381     {
382         $stringExploded = explode(':', $identifier);
383         $entityType = $stringExploded[0];
384         $entityId = intval($stringExploded[1]);
385
386         if ($entityType !== 'book' && $entityType !== 'chapter') {
387             throw new MoveOperationException('Pages can only be in books or chapters');
388         }
389
390         $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
391
392         return $parentClass::visible()->where('id', '=', $entityId)->first();
393     }
394
395     /**
396      * Change the page's parent to the given entity.
397      */
398     protected function changeParent(Page $page, Entity $parent)
399     {
400         $book = ($parent instanceof Chapter) ? $parent->book : $parent;
401         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
402         $page->save();
403
404         if ($page->book->id !== $book->id) {
405             $page->changeBook($book->id);
406         }
407
408         $page->load('book');
409         $book->rebuildPermissions();
410     }
411
412     /**
413      * Get a page revision to update for the given page.
414      * Checks for an existing revisions before providing a fresh one.
415      */
416     protected function getPageRevisionToUpdate(Page $page): PageRevision
417     {
418         $drafts = $this->getUserDraftQuery($page)->get();
419         if ($drafts->count() > 0) {
420             return $drafts->first();
421         }
422
423         $draft = new PageRevision();
424         $draft->page_id = $page->id;
425         $draft->slug = $page->slug;
426         $draft->book_slug = $page->book->slug;
427         $draft->created_by = user()->id;
428         $draft->type = 'update_draft';
429
430         return $draft;
431     }
432
433     /**
434      * Delete old revisions, for the given page, from the system.
435      */
436     protected function deleteOldRevisions(Page $page)
437     {
438         $revisionLimit = config('app.revision_limit');
439         if ($revisionLimit === false) {
440             return;
441         }
442
443         $revisionsToDelete = PageRevision::query()
444             ->where('page_id', '=', $page->id)
445             ->orderBy('created_at', 'desc')
446             ->skip(intval($revisionLimit))
447             ->take(10)
448             ->get(['id']);
449         if ($revisionsToDelete->count() > 0) {
450             PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
451         }
452     }
453
454     /**
455      * Get a new priority for a page.
456      */
457     protected function getNewPriority(Page $page): int
458     {
459         $parent = $page->getParent();
460         if ($parent instanceof Chapter) {
461             /** @var ?Page $lastPage */
462             $lastPage = $parent->pages('desc')->first();
463
464             return $lastPage ? $lastPage->priority + 1 : 0;
465         }
466
467         return (new BookContents($page->book))->getLastPriority() + 1;
468     }
469
470     /**
471      * Get the query to find the user's draft copies of the given page.
472      */
473     protected function getUserDraftQuery(Page $page)
474     {
475         return PageRevision::query()->where('created_by', '=', user()->id)
476             ->where('type', 'update_draft')
477             ->where('page_id', '=', $page->id)
478             ->orderBy('created_at', 'desc');
479     }
480 }