]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Merge branch 'development' into default-templates
[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         if ($page->book->defaultTemplate) {
140             $page->forceFill([
141                 'html'  => $page->book->defaultTemplate->html,
142             ]);
143         }
144
145         $page->save();
146         $page->refresh()->rebuildPermissions();
147
148         return $page;
149     }
150
151     /**
152      * Publish a draft page to make it a live, non-draft page.
153      */
154     public function publishDraft(Page $draft, array $input): Page
155     {
156         $draft->draft = false;
157         $draft->revision_count = 1;
158         $draft->priority = $this->getNewPriority($draft);
159         $this->updateTemplateStatusAndContentFromInput($draft, $input);
160         $this->baseRepo->update($draft, $input);
161
162         $this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
163         $this->referenceStore->updateForPage($draft);
164         $draft->refresh();
165
166         Activity::add(ActivityType::PAGE_CREATE, $draft);
167
168         return $draft;
169     }
170
171     /**
172      * Update a page in the system.
173      */
174     public function update(Page $page, array $input): Page
175     {
176         // Hold the old details to compare later
177         $oldHtml = $page->html;
178         $oldName = $page->name;
179         $oldMarkdown = $page->markdown;
180
181         $this->updateTemplateStatusAndContentFromInput($page, $input);
182         $this->baseRepo->update($page, $input);
183         $this->referenceStore->updateForPage($page);
184
185         // Update with new details
186         $page->revision_count++;
187         $page->save();
188
189         // Remove all update drafts for this user & page.
190         $this->revisionRepo->deleteDraftsForCurrentUser($page);
191
192         // Save a revision after updating
193         $summary = trim($input['summary'] ?? '');
194         $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
195         $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
196         $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
197         if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
198             $this->revisionRepo->storeNewForPage($page, $summary);
199         }
200
201         Activity::add(ActivityType::PAGE_UPDATE, $page);
202
203         return $page;
204     }
205
206     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
207     {
208         if (isset($input['template']) && userCan('templates-manage')) {
209             $page->template = ($input['template'] === 'true');
210         }
211
212         $pageContent = new PageContent($page);
213         $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
214         $newEditor = $currentEditor;
215
216         $haveInput = isset($input['markdown']) || isset($input['html']);
217         $inputEmpty = empty($input['markdown']) && empty($input['html']);
218
219         if ($haveInput && $inputEmpty) {
220             $pageContent->setNewHTML('', user());
221         } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
222             $newEditor = 'markdown';
223             $pageContent->setNewMarkdown($input['markdown'], user());
224         } elseif (isset($input['html'])) {
225             $newEditor = 'wysiwyg';
226             $pageContent->setNewHTML($input['html'], user());
227         }
228
229         if ($newEditor !== $currentEditor && userCan('editor-change')) {
230             $page->editor = $newEditor;
231         }
232     }
233
234     /**
235      * Save a page update draft.
236      */
237     public function updatePageDraft(Page $page, array $input)
238     {
239         // If the page itself is a draft simply update that
240         if ($page->draft) {
241             $this->updateTemplateStatusAndContentFromInput($page, $input);
242             $page->fill($input);
243             $page->save();
244
245             return $page;
246         }
247
248         // Otherwise, save the data to a revision
249         $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
250         $draft->fill($input);
251
252         if (!empty($input['markdown'])) {
253             $draft->markdown = $input['markdown'];
254             $draft->html = '';
255         } else {
256             $draft->html = $input['html'];
257             $draft->markdown = '';
258         }
259
260         $draft->save();
261
262         return $draft;
263     }
264
265     /**
266      * Destroy a page from the system.
267      *
268      * @throws Exception
269      */
270     public function destroy(Page $page)
271     {
272         $trashCan = new TrashCan();
273         $trashCan->softDestroyPage($page);
274         Activity::add(ActivityType::PAGE_DELETE, $page);
275         $trashCan->autoClearOld();
276     }
277
278     /**
279      * Restores a revision's content back into a page.
280      */
281     public function restoreRevision(Page $page, int $revisionId): Page
282     {
283         $oldUrl = $page->getUrl();
284         $page->revision_count++;
285
286         /** @var PageRevision $revision */
287         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
288
289         $page->fill($revision->toArray());
290         $content = new PageContent($page);
291
292         if (!empty($revision->markdown)) {
293             $content->setNewMarkdown($revision->markdown, user());
294         } else {
295             $content->setNewHTML($revision->html, user());
296         }
297
298         $page->updated_by = user()->id;
299         $page->refreshSlug();
300         $page->save();
301         $page->indexForSearch();
302         $this->referenceStore->updateForPage($page);
303
304         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
305         $this->revisionRepo->storeNewForPage($page, $summary);
306
307         if ($oldUrl !== $page->getUrl()) {
308             $this->referenceUpdater->updateEntityPageReferences($page, $oldUrl);
309         }
310
311         Activity::add(ActivityType::PAGE_RESTORE, $page);
312         Activity::add(ActivityType::REVISION_RESTORE, $revision);
313
314         return $page;
315     }
316
317     /**
318      * Move the given page into a new parent book or chapter.
319      * The $parentIdentifier must be a string of the following format:
320      * 'book:<id>' (book:5).
321      *
322      * @throws MoveOperationException
323      * @throws PermissionsException
324      */
325     public function move(Page $page, string $parentIdentifier): Entity
326     {
327         $parent = $this->findParentByIdentifier($parentIdentifier);
328         if (is_null($parent)) {
329             throw new MoveOperationException('Book or chapter to move page into not found');
330         }
331
332         if (!userCan('page-create', $parent)) {
333             throw new PermissionsException('User does not have permission to create a page within the new parent');
334         }
335
336         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
337         $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
338         $page->changeBook($newBookId);
339         $page->rebuildPermissions();
340
341         Activity::add(ActivityType::PAGE_MOVE, $page);
342
343         return $parent;
344     }
345
346     /**
347      * Find a page parent entity via an identifier string in the format:
348      * {type}:{id}
349      * Example: (book:5).
350      *
351      * @throws MoveOperationException
352      */
353     public function findParentByIdentifier(string $identifier): ?Entity
354     {
355         $stringExploded = explode(':', $identifier);
356         $entityType = $stringExploded[0];
357         $entityId = intval($stringExploded[1]);
358
359         if ($entityType !== 'book' && $entityType !== 'chapter') {
360             throw new MoveOperationException('Pages can only be in books or chapters');
361         }
362
363         $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
364
365         return $parentClass::visible()->where('id', '=', $entityId)->first();
366     }
367
368     /**
369      * Get a new priority for a page.
370      */
371     protected function getNewPriority(Page $page): int
372     {
373         $parent = $page->getParent();
374         if ($parent instanceof Chapter) {
375             /** @var ?Page $lastPage */
376             $lastPage = $parent->pages('desc')->first();
377
378             return $lastPage ? $lastPage->priority + 1 : 0;
379         }
380
381         return (new BookContents($page->book))->getLastPriority() + 1;
382     }
383 }