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