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