]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Added core editor switching functionality
[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\TrashCan;
14 use BookStack\Exceptions\MoveOperationException;
15 use BookStack\Exceptions\NotFoundException;
16 use BookStack\Exceptions\PermissionsException;
17 use BookStack\Facades\Activity;
18 use Exception;
19 use Illuminate\Database\Eloquent\Builder;
20 use Illuminate\Pagination\LengthAwarePaginator;
21
22 class PageRepo
23 {
24     protected $baseRepo;
25
26     /**
27      * PageRepo constructor.
28      */
29     public function __construct(BaseRepo $baseRepo)
30     {
31         $this->baseRepo = $baseRepo;
32     }
33
34     /**
35      * Get a page by ID.
36      *
37      * @throws NotFoundException
38      */
39     public function getById(int $id, array $relations = ['book']): Page
40     {
41         $page = Page::visible()->with($relations)->find($id);
42
43         if (!$page) {
44             throw new NotFoundException(trans('errors.page_not_found'));
45         }
46
47         return $page;
48     }
49
50     /**
51      * Get a page its book and own slug.
52      *
53      * @throws NotFoundException
54      */
55     public function getBySlug(string $bookSlug, string $pageSlug): Page
56     {
57         $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
58
59         if (!$page) {
60             throw new NotFoundException(trans('errors.page_not_found'));
61         }
62
63         return $page;
64     }
65
66     /**
67      * Get a page by its old slug but checking the revisions table
68      * for the last revision that matched the given page and book slug.
69      */
70     public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
71     {
72         /** @var ?PageRevision $revision */
73         $revision = PageRevision::query()
74             ->whereHas('page', function (Builder $query) {
75                 $query->scopes('visible');
76             })
77             ->where('slug', '=', $pageSlug)
78             ->where('type', '=', 'version')
79             ->where('book_slug', '=', $bookSlug)
80             ->orderBy('created_at', 'desc')
81             ->with('page')
82             ->first();
83
84         return $revision->page ?? null;
85     }
86
87     /**
88      * Get pages that have been marked as a template.
89      */
90     public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
91     {
92         $query = Page::visible()
93             ->where('template', '=', true)
94             ->orderBy('name', 'asc')
95             ->skip(($page - 1) * $count)
96             ->take($count);
97
98         if ($search) {
99             $query->where('name', 'like', '%' . $search . '%');
100         }
101
102         $paginator = $query->paginate($count, ['*'], 'page', $page);
103         $paginator->withPath('/templates');
104
105         return $paginator;
106     }
107
108     /**
109      * Get a parent item via slugs.
110      */
111     public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
112     {
113         if ($chapterSlug !== null) {
114             return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
115         }
116
117         return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
118     }
119
120     /**
121      * Get the draft copy of the given page for the current user.
122      */
123     public function getUserDraft(Page $page): ?PageRevision
124     {
125         $revision = $this->getUserDraftQuery($page)->first();
126
127         return $revision;
128     }
129
130     /**
131      * Get a new draft page belonging to the given parent entity.
132      */
133     public function getNewDraftPage(Entity $parent)
134     {
135         $page = (new Page())->forceFill([
136             'name'       => trans('entities.pages_initial_name'),
137             'created_by' => user()->id,
138             'owned_by'   => user()->id,
139             'updated_by' => user()->id,
140             'draft'      => true,
141         ]);
142
143         if ($parent instanceof Chapter) {
144             $page->chapter_id = $parent->id;
145             $page->book_id = $parent->book_id;
146         } else {
147             $page->book_id = $parent->id;
148         }
149
150         $page->save();
151         $page->refresh()->rebuildPermissions();
152
153         return $page;
154     }
155
156     /**
157      * Publish a draft page to make it a live, non-draft page.
158      */
159     public function publishDraft(Page $draft, array $input): Page
160     {
161         $this->updateTemplateStatusAndContentFromInput($draft, $input);
162         $this->baseRepo->update($draft, $input);
163
164         $draft->draft = false;
165         $draft->revision_count = 1;
166         $draft->priority = $this->getNewPriority($draft);
167         $draft->refreshSlug();
168         $draft->save();
169
170         $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
171         $draft->indexForSearch();
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
192         // Update with new details
193         $page->revision_count++;
194         $page->save();
195
196         // Remove all update drafts for this user & page.
197         $this->getUserDraftQuery($page)->delete();
198
199         // Save a revision after updating
200         $summary = trim($input['summary'] ?? '');
201         $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
202         $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
203         $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
204         if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
205             $this->savePageRevision($page, $summary);
206         }
207
208         Activity::add(ActivityType::PAGE_UPDATE, $page);
209
210         return $page;
211     }
212
213     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
214     {
215         if (isset($input['template']) && userCan('templates-manage')) {
216             $page->template = ($input['template'] === 'true');
217         }
218
219         $pageContent = new PageContent($page);
220         if (!empty($input['markdown'] ?? '')) {
221             $pageContent->setNewMarkdown($input['markdown']);
222         } elseif (isset($input['html'])) {
223             $pageContent->setNewHTML($input['html']);
224         }
225     }
226
227     /**
228      * Saves a page revision into the system.
229      */
230     protected function savePageRevision(Page $page, string $summary = null): PageRevision
231     {
232         $revision = new PageRevision($page->getAttributes());
233
234         $revision->page_id = $page->id;
235         $revision->slug = $page->slug;
236         $revision->book_slug = $page->book->slug;
237         $revision->created_by = user()->id;
238         $revision->created_at = $page->updated_at;
239         $revision->type = 'version';
240         $revision->summary = $summary;
241         $revision->revision_number = $page->revision_count;
242         $revision->save();
243
244         $this->deleteOldRevisions($page);
245
246         return $revision;
247     }
248
249     /**
250      * Save a page update draft.
251      */
252     public function updatePageDraft(Page $page, array $input)
253     {
254         // If the page itself is a draft simply update that
255         if ($page->draft) {
256             $this->updateTemplateStatusAndContentFromInput($page, $input);
257             $page->fill($input);
258             $page->save();
259
260             return $page;
261         }
262
263         // Otherwise, save the data to a revision
264         $draft = $this->getPageRevisionToUpdate($page);
265         $draft->fill($input);
266
267         if (!empty($input['markdown'])) {
268             $draft->markdown = $input['markdown'];
269             $draft->html = '';
270         } else {
271             $draft->html = $input['html'];
272             $draft->markdown = '';
273         }
274
275         $draft->save();
276
277         return $draft;
278     }
279
280     /**
281      * Destroy a page from the system.
282      *
283      * @throws Exception
284      */
285     public function destroy(Page $page)
286     {
287         $trashCan = new TrashCan();
288         $trashCan->softDestroyPage($page);
289         Activity::add(ActivityType::PAGE_DELETE, $page);
290         $trashCan->autoClearOld();
291     }
292
293     /**
294      * Restores a revision's content back into a page.
295      */
296     public function restoreRevision(Page $page, int $revisionId): Page
297     {
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
317         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
318         $this->savePageRevision($page, $summary);
319
320         Activity::add(ActivityType::PAGE_RESTORE, $page);
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      * Change the page's parent to the given entity.
378      */
379     protected function changeParent(Page $page, Entity $parent)
380     {
381         $book = ($parent instanceof Chapter) ? $parent->book : $parent;
382         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
383         $page->save();
384
385         if ($page->book->id !== $book->id) {
386             $page->changeBook($book->id);
387         }
388
389         $page->load('book');
390         $book->rebuildPermissions();
391     }
392
393     /**
394      * Get a page revision to update for the given page.
395      * Checks for an existing revisions before providing a fresh one.
396      */
397     protected function getPageRevisionToUpdate(Page $page): PageRevision
398     {
399         $drafts = $this->getUserDraftQuery($page)->get();
400         if ($drafts->count() > 0) {
401             return $drafts->first();
402         }
403
404         $draft = new PageRevision();
405         $draft->page_id = $page->id;
406         $draft->slug = $page->slug;
407         $draft->book_slug = $page->book->slug;
408         $draft->created_by = user()->id;
409         $draft->type = 'update_draft';
410
411         return $draft;
412     }
413
414     /**
415      * Delete old revisions, for the given page, from the system.
416      */
417     protected function deleteOldRevisions(Page $page)
418     {
419         $revisionLimit = config('app.revision_limit');
420         if ($revisionLimit === false) {
421             return;
422         }
423
424         $revisionsToDelete = PageRevision::query()
425             ->where('page_id', '=', $page->id)
426             ->orderBy('created_at', 'desc')
427             ->skip(intval($revisionLimit))
428             ->take(10)
429             ->get(['id']);
430         if ($revisionsToDelete->count() > 0) {
431             PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
432         }
433     }
434
435     /**
436      * Get a new priority for a page.
437      */
438     protected function getNewPriority(Page $page): int
439     {
440         $parent = $page->getParent();
441         if ($parent instanceof Chapter) {
442             /** @var ?Page $lastPage */
443             $lastPage = $parent->pages('desc')->first();
444
445             return $lastPage ? $lastPage->priority + 1 : 0;
446         }
447
448         return (new BookContents($page->book))->getLastPriority() + 1;
449     }
450
451     /**
452      * Get the query to find the user's draft copies of the given page.
453      */
454     protected function getUserDraftQuery(Page $page)
455     {
456         return PageRevision::query()->where('created_by', '=', user()->id)
457             ->where('type', 'update_draft')
458             ->where('page_id', '=', $page->id)
459             ->orderBy('created_at', 'desc');
460     }
461 }