]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Images: Prevented base64 extraction without permission
[bookstack] / app / Entities / Repos / PageRepo.php
1 <?php
2
3 namespace BookStack\Entities\Repos;
4
5 use BookStack\Activity\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 BookStack\References\ReferenceStore;
20 use BookStack\References\ReferenceUpdater;
21 use Exception;
22 use Illuminate\Pagination\LengthAwarePaginator;
23
24 class PageRepo
25 {
26     public function __construct(
27         protected BaseRepo $baseRepo,
28         protected RevisionRepo $revisionRepo,
29         protected ReferenceStore $referenceStore,
30         protected ReferenceUpdater $referenceUpdater
31     ) {
32     }
33
34     /**
35      * Get a page by ID.
36      *
37      * @throws NotFoundException
38      */
39     public function getById(int $id, array $relations = ['book']): Page
40     {
41         /** @var Page $page */
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         $revision = $this->revisionRepo->getBySlugs($bookSlug, $pageSlug);
74
75         return $revision->page ?? null;
76     }
77
78     /**
79      * Get pages that have been marked as a template.
80      */
81     public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
82     {
83         $query = Page::visible()
84             ->where('template', '=', true)
85             ->orderBy('name', 'asc')
86             ->skip(($page - 1) * $count)
87             ->take($count);
88
89         if ($search) {
90             $query->where('name', 'like', '%' . $search . '%');
91         }
92
93         $paginator = $query->paginate($count, ['*'], 'page', $page);
94         $paginator->withPath('/templates');
95
96         return $paginator;
97     }
98
99     /**
100      * Get a parent item via slugs.
101      */
102     public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
103     {
104         if ($chapterSlug !== null) {
105             return Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
106         }
107
108         return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
109     }
110
111     /**
112      * Get the draft copy of the given page for the current user.
113      */
114     public function getUserDraft(Page $page): ?PageRevision
115     {
116         return $this->revisionRepo->getLatestDraftForCurrentUser($page);
117     }
118
119     /**
120      * Get a new draft page belonging to the given parent entity.
121      */
122     public function getNewDraftPage(Entity $parent)
123     {
124         $page = (new Page())->forceFill([
125             'name'       => trans('entities.pages_initial_name'),
126             'created_by' => user()->id,
127             'owned_by'   => user()->id,
128             'updated_by' => user()->id,
129             'draft'      => true,
130         ]);
131
132         if ($parent instanceof Chapter) {
133             $page->chapter_id = $parent->id;
134             $page->book_id = $parent->book_id;
135         } else {
136             $page->book_id = $parent->id;
137         }
138
139         $page->save();
140         $page->refresh()->rebuildPermissions();
141
142         return $page;
143     }
144
145     /**
146      * Publish a draft page to make it a live, non-draft page.
147      */
148     public function publishDraft(Page $draft, array $input): Page
149     {
150         $draft->draft = false;
151         $draft->revision_count = 1;
152         $draft->priority = $this->getNewPriority($draft);
153         $this->updateTemplateStatusAndContentFromInput($draft, $input);
154         $this->baseRepo->update($draft, $input);
155
156         $this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
157         $this->referenceStore->updateForPage($draft);
158         $draft->refresh();
159
160         Activity::add(ActivityType::PAGE_CREATE, $draft);
161
162         return $draft;
163     }
164
165     /**
166      * Update a page in the system.
167      */
168     public function update(Page $page, array $input): Page
169     {
170         // Hold the old details to compare later
171         $oldHtml = $page->html;
172         $oldName = $page->name;
173         $oldMarkdown = $page->markdown;
174
175         $this->updateTemplateStatusAndContentFromInput($page, $input);
176         $this->baseRepo->update($page, $input);
177         $this->referenceStore->updateForPage($page);
178
179         // Update with new details
180         $page->revision_count++;
181         $page->save();
182
183         // Remove all update drafts for this user & page.
184         $this->revisionRepo->deleteDraftsForCurrentUser($page);
185
186         // Save a revision after updating
187         $summary = trim($input['summary'] ?? '');
188         $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
189         $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
190         $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
191         if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
192             $this->revisionRepo->storeNewForPage($page, $summary);
193         }
194
195         Activity::add(ActivityType::PAGE_UPDATE, $page);
196
197         return $page;
198     }
199
200     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
201     {
202         if (isset($input['template']) && userCan('templates-manage')) {
203             $page->template = ($input['template'] === 'true');
204         }
205
206         $pageContent = new PageContent($page);
207         $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
208         $newEditor = $currentEditor;
209
210         $haveInput = isset($input['markdown']) || isset($input['html']);
211         $inputEmpty = empty($input['markdown']) && empty($input['html']);
212
213         if ($haveInput && $inputEmpty) {
214             $pageContent->setNewHTML('', user());
215         } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
216             $newEditor = 'markdown';
217             $pageContent->setNewMarkdown($input['markdown'], user());
218         } elseif (isset($input['html'])) {
219             $newEditor = 'wysiwyg';
220             $pageContent->setNewHTML($input['html'], user());
221         }
222
223         if ($newEditor !== $currentEditor && userCan('editor-change')) {
224             $page->editor = $newEditor;
225         }
226     }
227
228     /**
229      * Save a page update draft.
230      */
231     public function updatePageDraft(Page $page, array $input)
232     {
233         // If the page itself is a draft simply update that
234         if ($page->draft) {
235             $this->updateTemplateStatusAndContentFromInput($page, $input);
236             $page->fill($input);
237             $page->save();
238
239             return $page;
240         }
241
242         // Otherwise, save the data to a revision
243         $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
244         $draft->fill($input);
245
246         if (!empty($input['markdown'])) {
247             $draft->markdown = $input['markdown'];
248             $draft->html = '';
249         } else {
250             $draft->html = $input['html'];
251             $draft->markdown = '';
252         }
253
254         $draft->save();
255
256         return $draft;
257     }
258
259     /**
260      * Destroy a page from the system.
261      *
262      * @throws Exception
263      */
264     public function destroy(Page $page)
265     {
266         $trashCan = new TrashCan();
267         $trashCan->softDestroyPage($page);
268         Activity::add(ActivityType::PAGE_DELETE, $page);
269         $trashCan->autoClearOld();
270     }
271
272     /**
273      * Restores a revision's content back into a page.
274      */
275     public function restoreRevision(Page $page, int $revisionId): Page
276     {
277         $oldUrl = $page->getUrl();
278         $page->revision_count++;
279
280         /** @var PageRevision $revision */
281         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
282
283         $page->fill($revision->toArray());
284         $content = new PageContent($page);
285
286         if (!empty($revision->markdown)) {
287             $content->setNewMarkdown($revision->markdown, user());
288         } else {
289             $content->setNewHTML($revision->html, user());
290         }
291
292         $page->updated_by = user()->id;
293         $page->refreshSlug();
294         $page->save();
295         $page->indexForSearch();
296         $this->referenceStore->updateForPage($page);
297
298         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
299         $this->revisionRepo->storeNewForPage($page, $summary);
300
301         if ($oldUrl !== $page->getUrl()) {
302             $this->referenceUpdater->updateEntityPageReferences($page, $oldUrl);
303         }
304
305         Activity::add(ActivityType::PAGE_RESTORE, $page);
306         Activity::add(ActivityType::REVISION_RESTORE, $revision);
307
308         return $page;
309     }
310
311     /**
312      * Move the given page into a new parent book or chapter.
313      * The $parentIdentifier must be a string of the following format:
314      * 'book:<id>' (book:5).
315      *
316      * @throws MoveOperationException
317      * @throws PermissionsException
318      */
319     public function move(Page $page, string $parentIdentifier): Entity
320     {
321         $parent = $this->findParentByIdentifier($parentIdentifier);
322         if (is_null($parent)) {
323             throw new MoveOperationException('Book or chapter to move page into not found');
324         }
325
326         if (!userCan('page-create', $parent)) {
327             throw new PermissionsException('User does not have permission to create a page within the new parent');
328         }
329
330         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
331         $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
332         $page->changeBook($newBookId);
333         $page->rebuildPermissions();
334
335         Activity::add(ActivityType::PAGE_MOVE, $page);
336
337         return $parent;
338     }
339
340     /**
341      * Find a page parent entity via an identifier string in the format:
342      * {type}:{id}
343      * Example: (book:5).
344      *
345      * @throws MoveOperationException
346      */
347     public function findParentByIdentifier(string $identifier): ?Entity
348     {
349         $stringExploded = explode(':', $identifier);
350         $entityType = $stringExploded[0];
351         $entityId = intval($stringExploded[1]);
352
353         if ($entityType !== 'book' && $entityType !== 'chapter') {
354             throw new MoveOperationException('Pages can only be in books or chapters');
355         }
356
357         $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
358
359         return $parentClass::visible()->where('id', '=', $entityId)->first();
360     }
361
362     /**
363      * Get a new priority for a page.
364      */
365     protected function getNewPriority(Page $page): int
366     {
367         $parent = $page->getParent();
368         if ($parent instanceof Chapter) {
369             /** @var ?Page $lastPage */
370             $lastPage = $parent->pages('desc')->first();
371
372             return $lastPage ? $lastPage->priority + 1 : 0;
373         }
374
375         return (new BookContents($page->book))->getLastPriority() + 1;
376     }
377 }