]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Merge pull request #2436 from BookStackApp/ownership_system
[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             'owned_by' => user()->id,
134             'updated_by' => user()->id,
135             'draft' => true,
136         ]);
137
138         if ($parent instanceof Chapter) {
139             $page->chapter_id = $parent->id;
140             $page->book_id = $parent->book_id;
141         } else {
142             $page->book_id = $parent->id;
143         }
144
145         $page->save();
146         $page->refresh()->rebuildPermissions();
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->baseRepo->update($draft, $input);
156         $this->updateTemplateStatusAndContentFromInput($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->savePageRevision($draft, trans('entities.pages_initial_revision'));
165         $draft->indexForSearch();
166         $draft->refresh();
167
168         Activity::addForEntity($draft, ActivityType::PAGE_CREATE);
169         return $draft;
170     }
171
172     /**
173      * Update a page in the system.
174      */
175     public function update(Page $page, array $input): Page
176     {
177         // Hold the old details to compare later
178         $oldHtml = $page->html;
179         $oldName = $page->name;
180
181         $this->updateTemplateStatusAndContentFromInput($page, $input);
182         $this->baseRepo->update($page, $input);
183
184         // Update with new details
185         $page->revision_count++;
186
187         if (setting('app-editor') !== 'markdown') {
188             $page->markdown = '';
189         }
190
191         $page->save();
192
193         // Remove all update drafts for this user & page.
194         $this->getUserDraftQuery($page)->delete();
195
196         // Save a revision after updating
197         $summary = $input['summary'] ?? null;
198         if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $summary !== null) {
199             $this->savePageRevision($page, $summary);
200         }
201
202         Activity::addForEntity($page, ActivityType::PAGE_UPDATE);
203         return $page;
204     }
205
206     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
207     {
208         if (isset($input['template']) && userCan('templates-manage')) {
209             $page->template = ($input['template'] === 'true');
210         }
211
212         $pageContent = new PageContent($page);
213         if (isset($input['html'])) {
214             $pageContent->setNewHTML($input['html']);
215         } else {
216             $pageContent->setNewMarkdown($input['markdown']);
217         }
218     }
219
220     /**
221      * Saves a page revision into the system.
222      */
223     protected function savePageRevision(Page $page, string $summary = null)
224     {
225         $revision = new PageRevision($page->getAttributes());
226
227         if (setting('app-editor') !== 'markdown') {
228             $revision->markdown = '';
229         }
230
231         $revision->page_id = $page->id;
232         $revision->slug = $page->slug;
233         $revision->book_slug = $page->book->slug;
234         $revision->created_by = user()->id;
235         $revision->created_at = $page->updated_at;
236         $revision->type = 'version';
237         $revision->summary = $summary;
238         $revision->revision_number = $page->revision_count;
239         $revision->save();
240
241         $this->deleteOldRevisions($page);
242         return $revision;
243     }
244
245     /**
246      * Save a page update draft.
247      */
248     public function updatePageDraft(Page $page, array $input)
249     {
250         // If the page itself is a draft simply update that
251         if ($page->draft) {
252             if (isset($input['html'])) {
253                 (new PageContent($page))->setNewHTML($input['html']);
254             }
255             $page->fill($input);
256             $page->save();
257             return $page;
258         }
259
260         // Otherwise save the data to a revision
261         $draft = $this->getPageRevisionToUpdate($page);
262         $draft->fill($input);
263         if (setting('app-editor') !== 'markdown') {
264             $draft->markdown = '';
265         }
266
267         $draft->save();
268         return $draft;
269     }
270
271     /**
272      * Destroy a page from the system.
273      * @throws Exception
274      */
275     public function destroy(Page $page)
276     {
277         $trashCan = new TrashCan();
278         $trashCan->softDestroyPage($page);
279         Activity::addForEntity($page, ActivityType::PAGE_DELETE);
280         $trashCan->autoClearOld();
281     }
282
283     /**
284      * Restores a revision's content back into a page.
285      */
286     public function restoreRevision(Page $page, int $revisionId): Page
287     {
288         $page->revision_count++;
289         $this->savePageRevision($page);
290
291         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
292         $page->fill($revision->toArray());
293         $content = new PageContent($page);
294         $content->setNewHTML($revision->html);
295         $page->updated_by = user()->id;
296         $page->refreshSlug();
297         $page->save();
298
299         $page->indexForSearch();
300         Activity::addForEntity($page, ActivityType::PAGE_RESTORE);
301         return $page;
302     }
303
304     /**
305      * Move the given page into a new parent book or chapter.
306      * The $parentIdentifier must be a string of the following format:
307      * 'book:<id>' (book:5)
308      * @throws MoveOperationException
309      * @throws PermissionsException
310      */
311     public function move(Page $page, string $parentIdentifier): Entity
312     {
313         $parent = $this->findParentByIdentifier($parentIdentifier);
314         if ($parent === null) {
315             throw new MoveOperationException('Book or chapter to move page into not found');
316         }
317
318         if (!userCan('page-create', $parent)) {
319             throw new PermissionsException('User does not have permission to create a page within the new parent');
320         }
321
322         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
323         $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
324         $page->rebuildPermissions();
325
326         Activity::addForEntity($page, ActivityType::PAGE_MOVE);
327         return $parent;
328     }
329
330     /**
331      * Copy an existing page in the system.
332      * Optionally providing a new parent via string identifier and a new name.
333      * @throws MoveOperationException
334      * @throws PermissionsException
335      */
336     public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
337     {
338         $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
339         if ($parent === null) {
340             throw new MoveOperationException('Book or chapter to move page into not found');
341         }
342
343         if (!userCan('page-create', $parent)) {
344             throw new PermissionsException('User does not have permission to create a page within the new parent');
345         }
346
347         $copyPage = $this->getNewDraftPage($parent);
348         $pageData = $page->getAttributes();
349
350         // Update name
351         if (!empty($newName)) {
352             $pageData['name'] = $newName;
353         }
354
355         // Copy tags from previous page if set
356         if ($page->tags) {
357             $pageData['tags'] = [];
358             foreach ($page->tags as $tag) {
359                 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
360             }
361         }
362
363         return $this->publishDraft($copyPage, $pageData);
364     }
365
366     /**
367      * Find a page parent entity via a identifier string in the format:
368      * {type}:{id}
369      * Example: (book:5)
370      * @throws MoveOperationException
371      */
372     protected function findParentByIdentifier(string $identifier): ?Entity
373     {
374         $stringExploded = explode(':', $identifier);
375         $entityType = $stringExploded[0];
376         $entityId = intval($stringExploded[1]);
377
378         if ($entityType !== 'book' && $entityType !== 'chapter') {
379             throw new MoveOperationException('Pages can only be in books or chapters');
380         }
381
382         $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
383         return $parentClass::visible()->where('id', '=', $entityId)->first();
384     }
385
386     /**
387      * Change the page's parent to the given entity.
388      */
389     protected function changeParent(Page $page, Entity $parent)
390     {
391         $book = ($parent instanceof Book) ? $parent : $parent->book;
392         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
393         $page->save();
394
395         if ($page->book->id !== $book->id) {
396             $page->changeBook($book->id);
397         }
398
399         $page->load('book');
400         $book->rebuildPermissions();
401     }
402
403     /**
404      * Get a page revision to update for the given page.
405      * Checks for an existing revisions before providing a fresh one.
406      */
407     protected function getPageRevisionToUpdate(Page $page): PageRevision
408     {
409         $drafts = $this->getUserDraftQuery($page)->get();
410         if ($drafts->count() > 0) {
411             return $drafts->first();
412         }
413
414         $draft = new PageRevision();
415         $draft->page_id = $page->id;
416         $draft->slug = $page->slug;
417         $draft->book_slug = $page->book->slug;
418         $draft->created_by = user()->id;
419         $draft->type = 'update_draft';
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         if ($revisionsToDelete->count() > 0) {
440             PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
441         }
442     }
443
444     /**
445      * Get a new priority for a page
446      */
447     protected function getNewPriority(Page $page): int
448     {
449         $parent = $page->getParent();
450         if ($parent instanceof Chapter) {
451             $lastPage = $parent->pages('desc')->first();
452             return $lastPage ? $lastPage->priority + 1 : 0;
453         }
454
455         return (new BookContents($page->book))->getLastPriority() + 1;
456     }
457
458     /**
459      * Get the query to find the user's draft copies of the given page.
460      */
461     protected function getUserDraftQuery(Page $page)
462     {
463         return PageRevision::query()->where('created_by', '=', user()->id)
464             ->where('type', 'update_draft')
465             ->where('page_id', '=', $page->id)
466             ->orderBy('created_at', 'desc');
467     }
468 }