]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Added testing for our request method overrides
[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         if (setting('app-editor') !== 'markdown') {
267             $draft->markdown = '';
268         }
269
270         $draft->save();
271
272         return $draft;
273     }
274
275     /**
276      * Destroy a page from the system.
277      *
278      * @throws Exception
279      */
280     public function destroy(Page $page)
281     {
282         $trashCan = new TrashCan();
283         $trashCan->softDestroyPage($page);
284         Activity::add(ActivityType::PAGE_DELETE, $page);
285         $trashCan->autoClearOld();
286     }
287
288     /**
289      * Restores a revision's content back into a page.
290      */
291     public function restoreRevision(Page $page, int $revisionId): Page
292     {
293         $page->revision_count++;
294
295         /** @var PageRevision $revision */
296         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
297
298         $page->fill($revision->toArray());
299         $content = new PageContent($page);
300
301         if (!empty($revision->markdown)) {
302             $content->setNewMarkdown($revision->markdown);
303         } else {
304             $content->setNewHTML($revision->html);
305         }
306
307         $page->updated_by = user()->id;
308         $page->refreshSlug();
309         $page->save();
310         $page->indexForSearch();
311
312         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
313         $this->savePageRevision($page, $summary);
314
315         Activity::add(ActivityType::PAGE_RESTORE, $page);
316
317         return $page;
318     }
319
320     /**
321      * Move the given page into a new parent book or chapter.
322      * The $parentIdentifier must be a string of the following format:
323      * 'book:<id>' (book:5).
324      *
325      * @throws MoveOperationException
326      * @throws PermissionsException
327      */
328     public function move(Page $page, string $parentIdentifier): Entity
329     {
330         $parent = $this->findParentByIdentifier($parentIdentifier);
331         if (is_null($parent)) {
332             throw new MoveOperationException('Book or chapter to move page into not found');
333         }
334
335         if (!userCan('page-create', $parent)) {
336             throw new PermissionsException('User does not have permission to create a page within the new parent');
337         }
338
339         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
340         $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
341         $page->changeBook($newBookId);
342         $page->rebuildPermissions();
343
344         Activity::add(ActivityType::PAGE_MOVE, $page);
345
346         return $parent;
347     }
348
349     /**
350      * Find a page parent entity via an identifier string in the format:
351      * {type}:{id}
352      * Example: (book:5).
353      *
354      * @throws MoveOperationException
355      */
356     public function findParentByIdentifier(string $identifier): ?Entity
357     {
358         $stringExploded = explode(':', $identifier);
359         $entityType = $stringExploded[0];
360         $entityId = intval($stringExploded[1]);
361
362         if ($entityType !== 'book' && $entityType !== 'chapter') {
363             throw new MoveOperationException('Pages can only be in books or chapters');
364         }
365
366         $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
367
368         return $parentClass::visible()->where('id', '=', $entityId)->first();
369     }
370
371     /**
372      * Change the page's parent to the given entity.
373      */
374     protected function changeParent(Page $page, Entity $parent)
375     {
376         $book = ($parent instanceof Chapter) ? $parent->book : $parent;
377         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
378         $page->save();
379
380         if ($page->book->id !== $book->id) {
381             $page->changeBook($book->id);
382         }
383
384         $page->load('book');
385         $book->rebuildPermissions();
386     }
387
388     /**
389      * Get a page revision to update for the given page.
390      * Checks for an existing revisions before providing a fresh one.
391      */
392     protected function getPageRevisionToUpdate(Page $page): PageRevision
393     {
394         $drafts = $this->getUserDraftQuery($page)->get();
395         if ($drafts->count() > 0) {
396             return $drafts->first();
397         }
398
399         $draft = new PageRevision();
400         $draft->page_id = $page->id;
401         $draft->slug = $page->slug;
402         $draft->book_slug = $page->book->slug;
403         $draft->created_by = user()->id;
404         $draft->type = 'update_draft';
405
406         return $draft;
407     }
408
409     /**
410      * Delete old revisions, for the given page, from the system.
411      */
412     protected function deleteOldRevisions(Page $page)
413     {
414         $revisionLimit = config('app.revision_limit');
415         if ($revisionLimit === false) {
416             return;
417         }
418
419         $revisionsToDelete = PageRevision::query()
420             ->where('page_id', '=', $page->id)
421             ->orderBy('created_at', 'desc')
422             ->skip(intval($revisionLimit))
423             ->take(10)
424             ->get(['id']);
425         if ($revisionsToDelete->count() > 0) {
426             PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
427         }
428     }
429
430     /**
431      * Get a new priority for a page.
432      */
433     protected function getNewPriority(Page $page): int
434     {
435         $parent = $page->getParent();
436         if ($parent instanceof Chapter) {
437             /** @var ?Page $lastPage */
438             $lastPage = $parent->pages('desc')->first();
439
440             return $lastPage ? $lastPage->priority + 1 : 0;
441         }
442
443         return (new BookContents($page->book))->getLastPriority() + 1;
444     }
445
446     /**
447      * Get the query to find the user's draft copies of the given page.
448      */
449     protected function getUserDraftQuery(Page $page)
450     {
451         return PageRevision::query()->where('created_by', '=', user()->id)
452             ->where('type', 'update_draft')
453             ->where('page_id', '=', $page->id)
454             ->orderBy('created_at', 'desc');
455     }
456 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.