]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Queries: Update API to align data with previous versions
[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         $this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
81         $draft->refresh();
82
83         Activity::add(ActivityType::PAGE_CREATE, $draft);
84
85         return $draft;
86     }
87
88     /**
89      * Update a page in the system.
90      */
91     public function update(Page $page, array $input): Page
92     {
93         // Hold the old details to compare later
94         $oldHtml = $page->html;
95         $oldName = $page->name;
96         $oldMarkdown = $page->markdown;
97
98         $this->updateTemplateStatusAndContentFromInput($page, $input);
99         $this->baseRepo->update($page, $input);
100
101         // Update with new details
102         $page->revision_count++;
103         $page->save();
104
105         // Remove all update drafts for this user & page.
106         $this->revisionRepo->deleteDraftsForCurrentUser($page);
107
108         // Save a revision after updating
109         $summary = trim($input['summary'] ?? '');
110         $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
111         $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
112         $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
113         if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
114             $this->revisionRepo->storeNewForPage($page, $summary);
115         }
116
117         Activity::add(ActivityType::PAGE_UPDATE, $page);
118
119         return $page;
120     }
121
122     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
123     {
124         if (isset($input['template']) && userCan('templates-manage')) {
125             $page->template = ($input['template'] === 'true');
126         }
127
128         $pageContent = new PageContent($page);
129         $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
130         $newEditor = $currentEditor;
131
132         $haveInput = isset($input['markdown']) || isset($input['html']);
133         $inputEmpty = empty($input['markdown']) && empty($input['html']);
134
135         if ($haveInput && $inputEmpty) {
136             $pageContent->setNewHTML('', user());
137         } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
138             $newEditor = 'markdown';
139             $pageContent->setNewMarkdown($input['markdown'], user());
140         } elseif (isset($input['html'])) {
141             $newEditor = 'wysiwyg';
142             $pageContent->setNewHTML($input['html'], user());
143         }
144
145         if ($newEditor !== $currentEditor && userCan('editor-change')) {
146             $page->editor = $newEditor;
147         }
148     }
149
150     /**
151      * Save a page update draft.
152      */
153     public function updatePageDraft(Page $page, array $input)
154     {
155         // If the page itself is a draft simply update that
156         if ($page->draft) {
157             $this->updateTemplateStatusAndContentFromInput($page, $input);
158             $page->fill($input);
159             $page->save();
160
161             return $page;
162         }
163
164         // Otherwise, save the data to a revision
165         $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
166         $draft->fill($input);
167
168         if (!empty($input['markdown'])) {
169             $draft->markdown = $input['markdown'];
170             $draft->html = '';
171         } else {
172             $draft->html = $input['html'];
173             $draft->markdown = '';
174         }
175
176         $draft->save();
177
178         return $draft;
179     }
180
181     /**
182      * Destroy a page from the system.
183      *
184      * @throws Exception
185      */
186     public function destroy(Page $page)
187     {
188         $this->trashCan->softDestroyPage($page);
189         Activity::add(ActivityType::PAGE_DELETE, $page);
190         $this->trashCan->autoClearOld();
191     }
192
193     /**
194      * Restores a revision's content back into a page.
195      */
196     public function restoreRevision(Page $page, int $revisionId): Page
197     {
198         $oldUrl = $page->getUrl();
199         $page->revision_count++;
200
201         /** @var PageRevision $revision */
202         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
203
204         $page->fill($revision->toArray());
205         $content = new PageContent($page);
206
207         if (!empty($revision->markdown)) {
208             $content->setNewMarkdown($revision->markdown, user());
209         } else {
210             $content->setNewHTML($revision->html, user());
211         }
212
213         $page->updated_by = user()->id;
214         $page->refreshSlug();
215         $page->save();
216         $page->indexForSearch();
217         $this->referenceStore->updateForEntity($page);
218
219         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
220         $this->revisionRepo->storeNewForPage($page, $summary);
221
222         if ($oldUrl !== $page->getUrl()) {
223             $this->referenceUpdater->updateEntityReferences($page, $oldUrl);
224         }
225
226         Activity::add(ActivityType::PAGE_RESTORE, $page);
227         Activity::add(ActivityType::REVISION_RESTORE, $revision);
228
229         return $page;
230     }
231
232     /**
233      * Move the given page into a new parent book or chapter.
234      * The $parentIdentifier must be a string of the following format:
235      * 'book:<id>' (book:5).
236      *
237      * @throws MoveOperationException
238      * @throws PermissionsException
239      */
240     public function move(Page $page, string $parentIdentifier): Entity
241     {
242         $parent = $this->entityQueries->findVisibleByStringIdentifier($parentIdentifier);
243         if (!$parent instanceof Chapter && !$parent instanceof Book) {
244             throw new MoveOperationException('Book or chapter to move page into not found');
245         }
246
247         if (!userCan('page-create', $parent)) {
248             throw new PermissionsException('User does not have permission to create a page within the new parent');
249         }
250
251         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
252         $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
253         $page->changeBook($newBookId);
254         $page->rebuildPermissions();
255
256         Activity::add(ActivityType::PAGE_MOVE, $page);
257
258         return $parent;
259     }
260
261     /**
262      * Get a new priority for a page.
263      */
264     protected function getNewPriority(Page $page): int
265     {
266         $parent = $page->getParent();
267         if ($parent instanceof Chapter) {
268             /** @var ?Page $lastPage */
269             $lastPage = $parent->pages('desc')->first();
270
271             return $lastPage ? $lastPage->priority + 1 : 0;
272         }
273
274         return (new BookContents($page->book))->getLastPriority() + 1;
275     }
276 }