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