]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Update sponsor image URLs in readme
[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\Queries\EntityQueries;
12 use BookStack\Entities\Tools\BookContents;
13 use BookStack\Entities\Tools\PageContent;
14 use BookStack\Entities\Tools\PageEditorData;
15 use BookStack\Entities\Tools\TrashCan;
16 use BookStack\Exceptions\MoveOperationException;
17 use BookStack\Exceptions\PermissionsException;
18 use BookStack\Facades\Activity;
19 use BookStack\References\ReferenceStore;
20 use BookStack\References\ReferenceUpdater;
21 use Exception;
22
23 class PageRepo
24 {
25     public function __construct(
26         protected BaseRepo $baseRepo,
27         protected RevisionRepo $revisionRepo,
28         protected EntityQueries $entityQueries,
29         protected ReferenceStore $referenceStore,
30         protected ReferenceUpdater $referenceUpdater,
31         protected TrashCan $trashCan,
32     ) {
33     }
34
35     /**
36      * Get a new draft page belonging to the given parent entity.
37      */
38     public function getNewDraftPage(Entity $parent)
39     {
40         $page = (new Page())->forceFill([
41             'name'       => trans('entities.pages_initial_name'),
42             'created_by' => user()->id,
43             'owned_by'   => user()->id,
44             'updated_by' => user()->id,
45             'draft'      => true,
46         ]);
47
48         if ($parent instanceof Chapter) {
49             $page->chapter_id = $parent->id;
50             $page->book_id = $parent->book_id;
51         } else {
52             $page->book_id = $parent->id;
53         }
54
55         $defaultTemplate = $page->chapter->defaultTemplate ?? $page->book->defaultTemplate;
56         if ($defaultTemplate && userCan('view', $defaultTemplate)) {
57             $page->forceFill([
58                 'html'  => $defaultTemplate->html,
59                 'markdown' => $defaultTemplate->markdown,
60             ]);
61         }
62
63         $page->save();
64         $page->refresh()->rebuildPermissions();
65
66         return $page;
67     }
68
69     /**
70      * Publish a draft page to make it a live, non-draft page.
71      */
72     public function publishDraft(Page $draft, array $input): Page
73     {
74         $draft->draft = false;
75         $draft->revision_count = 1;
76         $draft->priority = $this->getNewPriority($draft);
77         $this->updateTemplateStatusAndContentFromInput($draft, $input);
78         $this->baseRepo->update($draft, $input);
79
80         $summary = trim($input['summary'] ?? '') ?: trans('entities.pages_initial_revision');
81         $this->revisionRepo->storeNewForPage($draft, $summary);
82         $draft->refresh();
83
84         Activity::add(ActivityType::PAGE_CREATE, $draft);
85
86         return $draft;
87     }
88
89     /**
90      * Update a page in the system.
91      */
92     public function update(Page $page, array $input): Page
93     {
94         // Hold the old details to compare later
95         $oldHtml = $page->html;
96         $oldName = $page->name;
97         $oldMarkdown = $page->markdown;
98
99         $this->updateTemplateStatusAndContentFromInput($page, $input);
100         $this->baseRepo->update($page, $input);
101
102         // Update with new details
103         $page->revision_count++;
104         $page->save();
105
106         // Remove all update drafts for this user & page.
107         $this->revisionRepo->deleteDraftsForCurrentUser($page);
108
109         // Save a revision after updating
110         $summary = trim($input['summary'] ?? '');
111         $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
112         $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
113         $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
114         if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
115             $this->revisionRepo->storeNewForPage($page, $summary);
116         }
117
118         Activity::add(ActivityType::PAGE_UPDATE, $page);
119
120         return $page;
121     }
122
123     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
124     {
125         if (isset($input['template']) && userCan('templates-manage')) {
126             $page->template = ($input['template'] === 'true');
127         }
128
129         $pageContent = new PageContent($page);
130         $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
131         $newEditor = $currentEditor;
132
133         $haveInput = isset($input['markdown']) || isset($input['html']);
134         $inputEmpty = empty($input['markdown']) && empty($input['html']);
135
136         if ($haveInput && $inputEmpty) {
137             $pageContent->setNewHTML('', user());
138         } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
139             $newEditor = 'markdown';
140             $pageContent->setNewMarkdown($input['markdown'], user());
141         } elseif (isset($input['html'])) {
142             $newEditor = 'wysiwyg';
143             $pageContent->setNewHTML($input['html'], user());
144         }
145
146         if ($newEditor !== $currentEditor && userCan('editor-change')) {
147             $page->editor = $newEditor;
148         }
149     }
150
151     /**
152      * Save a page update draft.
153      */
154     public function updatePageDraft(Page $page, array $input)
155     {
156         // If the page itself is a draft simply update that
157         if ($page->draft) {
158             $this->updateTemplateStatusAndContentFromInput($page, $input);
159             $page->fill($input);
160             $page->save();
161
162             return $page;
163         }
164
165         // Otherwise, save the data to a revision
166         $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
167         $draft->fill($input);
168
169         if (!empty($input['markdown'])) {
170             $draft->markdown = $input['markdown'];
171             $draft->html = '';
172         } else {
173             $draft->html = $input['html'];
174             $draft->markdown = '';
175         }
176
177         $draft->save();
178
179         return $draft;
180     }
181
182     /**
183      * Destroy a page from the system.
184      *
185      * @throws Exception
186      */
187     public function destroy(Page $page)
188     {
189         $this->trashCan->softDestroyPage($page);
190         Activity::add(ActivityType::PAGE_DELETE, $page);
191         $this->trashCan->autoClearOld();
192     }
193
194     /**
195      * Restores a revision's content back into a page.
196      */
197     public function restoreRevision(Page $page, int $revisionId): Page
198     {
199         $oldUrl = $page->getUrl();
200         $page->revision_count++;
201
202         /** @var PageRevision $revision */
203         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
204
205         $page->fill($revision->toArray());
206         $content = new PageContent($page);
207
208         if (!empty($revision->markdown)) {
209             $content->setNewMarkdown($revision->markdown, user());
210         } else {
211             $content->setNewHTML($revision->html, user());
212         }
213
214         $page->updated_by = user()->id;
215         $page->refreshSlug();
216         $page->save();
217         $page->indexForSearch();
218         $this->referenceStore->updateForEntity($page);
219
220         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
221         $this->revisionRepo->storeNewForPage($page, $summary);
222
223         if ($oldUrl !== $page->getUrl()) {
224             $this->referenceUpdater->updateEntityReferences($page, $oldUrl);
225         }
226
227         Activity::add(ActivityType::PAGE_RESTORE, $page);
228         Activity::add(ActivityType::REVISION_RESTORE, $revision);
229
230         return $page;
231     }
232
233     /**
234      * Move the given page into a new parent book or chapter.
235      * The $parentIdentifier must be a string of the following format:
236      * 'book:<id>' (book:5).
237      *
238      * @throws MoveOperationException
239      * @throws PermissionsException
240      */
241     public function move(Page $page, string $parentIdentifier): Entity
242     {
243         $parent = $this->entityQueries->findVisibleByStringIdentifier($parentIdentifier);
244         if (!$parent instanceof Chapter && !$parent instanceof Book) {
245             throw new MoveOperationException('Book or chapter to move page into not found');
246         }
247
248         if (!userCan('page-create', $parent)) {
249             throw new PermissionsException('User does not have permission to create a page within the new parent');
250         }
251
252         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
253         $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
254         $page->changeBook($newBookId);
255         $page->rebuildPermissions();
256
257         Activity::add(ActivityType::PAGE_MOVE, $page);
258
259         return $parent;
260     }
261
262     /**
263      * Get a new priority for a page.
264      */
265     protected function getNewPriority(Page $page): int
266     {
267         $parent = $page->getParent();
268         if ($parent instanceof Chapter) {
269             /** @var ?Page $lastPage */
270             $lastPage = $parent->pages('desc')->first();
271
272             return $lastPage ? $lastPage->priority + 1 : 0;
273         }
274
275         return (new BookContents($page->book))->getLastPriority() + 1;
276     }
277 }