]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Code cleanup, bug squashing
[bookstack] / app / Entities / Repos / PageRepo.php
1 <?php namespace BookStack\Entities\Repos;
2
3 use BookStack\Actions\ActivityType;
4 use BookStack\Entities\Models\Book;
5 use BookStack\Entities\Models\Chapter;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\Tools\BookContents;
8 use BookStack\Entities\Tools\PageContent;
9 use BookStack\Entities\Tools\TrashCan;
10 use BookStack\Entities\Models\Page;
11 use BookStack\Entities\Models\PageRevision;
12 use BookStack\Exceptions\MoveOperationException;
13 use BookStack\Exceptions\NotFoundException;
14 use BookStack\Exceptions\PermissionsException;
15 use BookStack\Facades\Activity;
16 use Exception;
17 use Illuminate\Database\Eloquent\Builder;
18 use Illuminate\Pagination\LengthAwarePaginator;
19 use Illuminate\Support\Collection;
20
21 class PageRepo
22 {
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      * @throws NotFoundException
37      */
38     public function getById(int $id, array $relations = ['book']): Page
39     {
40         $page = Page::visible()->with($relations)->find($id);
41
42         if (!$page) {
43             throw new NotFoundException(trans('errors.page_not_found'));
44         }
45
46         return $page;
47     }
48
49     /**
50      * Get a page its book and own slug.
51      * @throws NotFoundException
52      */
53     public function getBySlug(string $bookSlug, string $pageSlug): Page
54     {
55         $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
56
57         if (!$page) {
58             throw new NotFoundException(trans('errors.page_not_found'));
59         }
60
61         return $page;
62     }
63
64     /**
65      * Get a page by its old slug but checking the revisions table
66      * for the last revision that matched the given page and book slug.
67      */
68     public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
69     {
70         $revision = PageRevision::query()
71             ->whereHas('page', function (Builder $query) {
72                 $query->visible();
73             })
74             ->where('slug', '=', $pageSlug)
75             ->where('type', '=', 'version')
76             ->where('book_slug', '=', $bookSlug)
77             ->orderBy('created_at', 'desc')
78             ->with('page')
79             ->first();
80         return $revision ? $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 = 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         $revision = $this->getUserDraftQuery($page)->first();
122         return $revision;
123     }
124
125     /**
126      * Get a new draft page belonging to the given parent entity.
127      */
128     public function getNewDraftPage(Entity $parent)
129     {
130         $page = (new Page())->forceFill([
131             'name' => trans('entities.pages_initial_name'),
132             'created_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         return $page;
147     }
148
149     /**
150      * Publish a draft page to make it a live, non-draft page.
151      */
152     public function publishDraft(Page $draft, array $input): Page
153     {
154         $this->baseRepo->update($draft, $input);
155         $this->updateTemplateStatusAndContentFromInput($draft, $input);
156
157         $draft->draft = false;
158         $draft->revision_count = 1;
159         $draft->priority = $this->getNewPriority($draft);
160         $draft->refreshSlug();
161         $draft->save();
162
163         $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
164         $draft->indexForSearch();
165         $draft->refresh();
166
167         Activity::addForEntity($draft, ActivityType::PAGE_CREATE);
168         return $draft;
169     }
170
171     /**
172      * Update a page in the system.
173      */
174     public function update(Page $page, array $input): Page
175     {
176         // Hold the old details to compare later
177         $oldHtml = $page->html;
178         $oldName = $page->name;
179
180         $this->updateTemplateStatusAndContentFromInput($page, $input);
181         $this->baseRepo->update($page, $input);
182
183         // Update with new details
184         $page->revision_count++;
185
186         if (setting('app-editor') !== 'markdown') {
187             $page->markdown = '';
188         }
189
190         $page->save();
191
192         // Remove all update drafts for this user & page.
193         $this->getUserDraftQuery($page)->delete();
194
195         // Save a revision after updating
196         $summary = $input['summary'] ?? null;
197         if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $summary !== null) {
198             $this->savePageRevision($page, $summary);
199         }
200
201         Activity::addForEntity($page, ActivityType::PAGE_UPDATE);
202         return $page;
203     }
204
205     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
206     {
207         if (isset($input['template']) && userCan('templates-manage')) {
208             $page->template = ($input['template'] === 'true');
209         }
210
211         $pageContent = new PageContent($page);
212         if (isset($input['html'])) {
213             $pageContent->setNewHTML($input['html']);
214         } else {
215             $pageContent->setNewMarkdown($input['markdown']);
216         }
217     }
218
219     /**
220      * Saves a page revision into the system.
221      */
222     protected function savePageRevision(Page $page, string $summary = null)
223     {
224         $revision = new PageRevision($page->getAttributes());
225
226         if (setting('app-editor') !== 'markdown') {
227             $revision->markdown = '';
228         }
229
230         $revision->page_id = $page->id;
231         $revision->slug = $page->slug;
232         $revision->book_slug = $page->book->slug;
233         $revision->created_by = user()->id;
234         $revision->created_at = $page->updated_at;
235         $revision->type = 'version';
236         $revision->summary = $summary;
237         $revision->revision_number = $page->revision_count;
238         $revision->save();
239
240         $this->deleteOldRevisions($page);
241         return $revision;
242     }
243
244     /**
245      * Save a page update draft.
246      */
247     public function updatePageDraft(Page $page, array $input)
248     {
249         // If the page itself is a draft simply update that
250         if ($page->draft) {
251             if (isset($input['html'])) {
252                 (new PageContent($page))->setNewHTML($input['html']);
253             }
254             $page->fill($input);
255             $page->save();
256             return $page;
257         }
258
259         // Otherwise save the data to a revision
260         $draft = $this->getPageRevisionToUpdate($page);
261         $draft->fill($input);
262         if (setting('app-editor') !== 'markdown') {
263             $draft->markdown = '';
264         }
265
266         $draft->save();
267         return $draft;
268     }
269
270     /**
271      * Destroy a page from the system.
272      * @throws Exception
273      */
274     public function destroy(Page $page)
275     {
276         $trashCan = new TrashCan();
277         $trashCan->softDestroyPage($page);
278         Activity::addForEntity($page, ActivityType::PAGE_DELETE);
279         $trashCan->autoClearOld();
280     }
281
282     /**
283      * Restores a revision's content back into a page.
284      */
285     public function restoreRevision(Page $page, int $revisionId): Page
286     {
287         $page->revision_count++;
288         $this->savePageRevision($page);
289
290         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
291         $page->fill($revision->toArray());
292         $content = new PageContent($page);
293         $content->setNewHTML($revision->html);
294         $page->updated_by = user()->id;
295         $page->refreshSlug();
296         $page->save();
297
298         $page->indexForSearch();
299         Activity::addForEntity($page, ActivityType::PAGE_RESTORE);
300         return $page;
301     }
302
303     /**
304      * Move the given page into a new parent book or chapter.
305      * The $parentIdentifier must be a string of the following format:
306      * 'book:<id>' (book:5)
307      * @throws MoveOperationException
308      * @throws PermissionsException
309      */
310     public function move(Page $page, string $parentIdentifier): Entity
311     {
312         $parent = $this->findParentByIdentifier($parentIdentifier);
313         if ($parent === null) {
314             throw new MoveOperationException('Book or chapter to move page into not found');
315         }
316
317         if (!userCan('page-create', $parent)) {
318             throw new PermissionsException('User does not have permission to create a page within the new parent');
319         }
320
321         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
322         $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
323         $page->rebuildPermissions();
324
325         Activity::addForEntity($page, ActivityType::PAGE_MOVE);
326         return $parent;
327     }
328
329     /**
330      * Copy an existing page in the system.
331      * Optionally providing a new parent via string identifier and a new name.
332      * @throws MoveOperationException
333      * @throws PermissionsException
334      */
335     public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
336     {
337         $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
338         if ($parent === null) {
339             throw new MoveOperationException('Book or chapter to move page into not found');
340         }
341
342         if (!userCan('page-create', $parent)) {
343             throw new PermissionsException('User does not have permission to create a page within the new parent');
344         }
345
346         $copyPage = $this->getNewDraftPage($parent);
347         $pageData = $page->getAttributes();
348
349         // Update name
350         if (!empty($newName)) {
351             $pageData['name'] = $newName;
352         }
353
354         // Copy tags from previous page if set
355         if ($page->tags) {
356             $pageData['tags'] = [];
357             foreach ($page->tags as $tag) {
358                 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
359             }
360         }
361
362         return $this->publishDraft($copyPage, $pageData);
363     }
364
365     /**
366      * Find a page parent entity via a identifier string in the format:
367      * {type}:{id}
368      * Example: (book:5)
369      * @throws MoveOperationException
370      */
371     protected function findParentByIdentifier(string $identifier): ?Entity
372     {
373         $stringExploded = explode(':', $identifier);
374         $entityType = $stringExploded[0];
375         $entityId = intval($stringExploded[1]);
376
377         if ($entityType !== 'book' && $entityType !== 'chapter') {
378             throw new MoveOperationException('Pages can only be in books or chapters');
379         }
380
381         $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
382         return $parentClass::visible()->where('id', '=', $entityId)->first();
383     }
384
385     /**
386      * Update the permissions of a page.
387      */
388     public function updatePermissions(Page $page, bool $restricted, Collection $permissions = null)
389     {
390         $this->baseRepo->updatePermissions($page, $restricted, $permissions);
391     }
392
393     /**
394      * Change the page's parent to the given entity.
395      */
396     protected function changeParent(Page $page, Entity $parent)
397     {
398         $book = ($parent instanceof Book) ? $parent : $parent->book;
399         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
400         $page->save();
401
402         if ($page->book->id !== $book->id) {
403             $page->changeBook($book->id);
404         }
405
406         $page->load('book');
407         $book->rebuildPermissions();
408     }
409
410     /**
411      * Get a page revision to update for the given page.
412      * Checks for an existing revisions before providing a fresh one.
413      */
414     protected function getPageRevisionToUpdate(Page $page): PageRevision
415     {
416         $drafts = $this->getUserDraftQuery($page)->get();
417         if ($drafts->count() > 0) {
418             return $drafts->first();
419         }
420
421         $draft = new PageRevision();
422         $draft->page_id = $page->id;
423         $draft->slug = $page->slug;
424         $draft->book_slug = $page->book->slug;
425         $draft->created_by = user()->id;
426         $draft->type = 'update_draft';
427         return $draft;
428     }
429
430     /**
431      * Delete old revisions, for the given page, from the system.
432      */
433     protected function deleteOldRevisions(Page $page)
434     {
435         $revisionLimit = config('app.revision_limit');
436         if ($revisionLimit === false) {
437             return;
438         }
439
440         $revisionsToDelete = PageRevision::query()
441             ->where('page_id', '=', $page->id)
442             ->orderBy('created_at', 'desc')
443             ->skip(intval($revisionLimit))
444             ->take(10)
445             ->get(['id']);
446         if ($revisionsToDelete->count() > 0) {
447             PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
448         }
449     }
450
451     /**
452      * Get a new priority for a page
453      */
454     protected function getNewPriority(Page $page): int
455     {
456         $parent = $page->getParent();
457         if ($parent instanceof Chapter) {
458             $lastPage = $parent->pages('desc')->first();
459             return $lastPage ? $lastPage->priority + 1 : 0;
460         }
461
462         return (new BookContents($page->book))->getLastPriority() + 1;
463     }
464
465     /**
466      * Get the query to find the user's draft copies of the given page.
467      */
468     protected function getUserDraftQuery(Page $page)
469     {
470         return PageRevision::query()->where('created_by', '=', user()->id)
471             ->where('type', 'update_draft')
472             ->where('page_id', '=', $page->id)
473             ->orderBy('created_at', 'desc');
474     }
475 }