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