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