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