]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Apply fixes from StyleCI
[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         $revision = PageRevision::query()
73             ->whereHas('page', function (Builder $query) {
74                 $query->visible();
75             })
76             ->where('slug', '=', $pageSlug)
77             ->where('type', '=', 'version')
78             ->where('book_slug', '=', $bookSlug)
79             ->orderBy('created_at', 'desc')
80             ->with('page')
81             ->first();
82
83         return $revision ? $revision->page : null;
84     }
85
86     /**
87      * Get pages that have been marked as a template.
88      */
89     public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
90     {
91         $query = Page::visible()
92             ->where('template', '=', true)
93             ->orderBy('name', 'asc')
94             ->skip(($page - 1) * $count)
95             ->take($count);
96
97         if ($search) {
98             $query->where('name', 'like', '%' . $search . '%');
99         }
100
101         $paginator = $query->paginate($count, ['*'], 'page', $page);
102         $paginator->withPath('/templates');
103
104         return $paginator;
105     }
106
107     /**
108      * Get a parent item via slugs.
109      */
110     public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
111     {
112         if ($chapterSlug !== null) {
113             return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
114         }
115
116         return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
117     }
118
119     /**
120      * Get the draft copy of the given page for the current user.
121      */
122     public function getUserDraft(Page $page): ?PageRevision
123     {
124         $revision = $this->getUserDraftQuery($page)->first();
125
126         return $revision;
127     }
128
129     /**
130      * Get a new draft page belonging to the given parent entity.
131      */
132     public function getNewDraftPage(Entity $parent)
133     {
134         $page = (new Page())->forceFill([
135             'name'       => trans('entities.pages_initial_name'),
136             'created_by' => user()->id,
137             'owned_by'   => user()->id,
138             'updated_by' => user()->id,
139             'draft'      => true,
140         ]);
141
142         if ($parent instanceof Chapter) {
143             $page->chapter_id = $parent->id;
144             $page->book_id = $parent->book_id;
145         } else {
146             $page->book_id = $parent->id;
147         }
148
149         $page->save();
150         $page->refresh()->rebuildPermissions();
151
152         return $page;
153     }
154
155     /**
156      * Publish a draft page to make it a live, non-draft page.
157      */
158     public function publishDraft(Page $draft, array $input): Page
159     {
160         $this->baseRepo->update($draft, $input);
161         $this->updateTemplateStatusAndContentFromInput($draft, $input);
162
163         $draft->draft = false;
164         $draft->revision_count = 1;
165         $draft->priority = $this->getNewPriority($draft);
166         $draft->refreshSlug();
167         $draft->save();
168
169         $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
170         $draft->indexForSearch();
171         $draft->refresh();
172
173         Activity::addForEntity($draft, ActivityType::PAGE_CREATE);
174
175         return $draft;
176     }
177
178     /**
179      * Update a page in the system.
180      */
181     public function update(Page $page, array $input): Page
182     {
183         // Hold the old details to compare later
184         $oldHtml = $page->html;
185         $oldName = $page->name;
186         $oldMarkdown = $page->markdown;
187
188         $this->updateTemplateStatusAndContentFromInput($page, $input);
189         $this->baseRepo->update($page, $input);
190
191         // Update with new details
192         $page->revision_count++;
193         $page->save();
194
195         // Remove all update drafts for this user & page.
196         $this->getUserDraftQuery($page)->delete();
197
198         // Save a revision after updating
199         $summary = trim($input['summary'] ?? '');
200         $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
201         $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
202         $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
203         if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
204             $this->savePageRevision($page, $summary);
205         }
206
207         Activity::addForEntity($page, ActivityType::PAGE_UPDATE);
208
209         return $page;
210     }
211
212     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
213     {
214         if (isset($input['template']) && userCan('templates-manage')) {
215             $page->template = ($input['template'] === 'true');
216         }
217
218         $pageContent = new PageContent($page);
219         if (!empty($input['markdown'] ?? '')) {
220             $pageContent->setNewMarkdown($input['markdown']);
221         } else {
222             $pageContent->setNewHTML($input['html'] ?? '');
223         }
224     }
225
226     /**
227      * Saves a page revision into the system.
228      */
229     protected function savePageRevision(Page $page, string $summary = null): PageRevision
230     {
231         $revision = new PageRevision($page->getAttributes());
232
233         $revision->page_id = $page->id;
234         $revision->slug = $page->slug;
235         $revision->book_slug = $page->book->slug;
236         $revision->created_by = user()->id;
237         $revision->created_at = $page->updated_at;
238         $revision->type = 'version';
239         $revision->summary = $summary;
240         $revision->revision_number = $page->revision_count;
241         $revision->save();
242
243         $this->deleteOldRevisions($page);
244
245         return $revision;
246     }
247
248     /**
249      * Save a page update draft.
250      */
251     public function updatePageDraft(Page $page, array $input)
252     {
253         // If the page itself is a draft simply update that
254         if ($page->draft) {
255             if (isset($input['html'])) {
256                 (new PageContent($page))->setNewHTML($input['html']);
257             }
258             $page->fill($input);
259             $page->save();
260
261             return $page;
262         }
263
264         // Otherwise save the data to a revision
265         $draft = $this->getPageRevisionToUpdate($page);
266         $draft->fill($input);
267         if (setting('app-editor') !== 'markdown') {
268             $draft->markdown = '';
269         }
270
271         $draft->save();
272
273         return $draft;
274     }
275
276     /**
277      * Destroy a page from the system.
278      *
279      * @throws Exception
280      */
281     public function destroy(Page $page)
282     {
283         $trashCan = new TrashCan();
284         $trashCan->softDestroyPage($page);
285         Activity::addForEntity($page, ActivityType::PAGE_DELETE);
286         $trashCan->autoClearOld();
287     }
288
289     /**
290      * Restores a revision's content back into a page.
291      */
292     public function restoreRevision(Page $page, int $revisionId): Page
293     {
294         $page->revision_count++;
295         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
296
297         $page->fill($revision->toArray());
298         $content = new PageContent($page);
299
300         if (!empty($revision->markdown)) {
301             $content->setNewMarkdown($revision->markdown);
302         } else {
303             $content->setNewHTML($revision->html);
304         }
305
306         $page->updated_by = user()->id;
307         $page->refreshSlug();
308         $page->save();
309         $page->indexForSearch();
310
311         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
312         $this->savePageRevision($page, $summary);
313
314         Activity::addForEntity($page, ActivityType::PAGE_RESTORE);
315
316         return $page;
317     }
318
319     /**
320      * Move the given page into a new parent book or chapter.
321      * The $parentIdentifier must be a string of the following format:
322      * 'book:<id>' (book:5).
323      *
324      * @throws MoveOperationException
325      * @throws PermissionsException
326      */
327     public function move(Page $page, string $parentIdentifier): Entity
328     {
329         $parent = $this->findParentByIdentifier($parentIdentifier);
330         if ($parent === null) {
331             throw new MoveOperationException('Book or chapter to move page into not found');
332         }
333
334         if (!userCan('page-create', $parent)) {
335             throw new PermissionsException('User does not have permission to create a page within the new parent');
336         }
337
338         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
339         $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
340         $page->rebuildPermissions();
341
342         Activity::addForEntity($page, ActivityType::PAGE_MOVE);
343
344         return $parent;
345     }
346
347     /**
348      * Copy an existing page in the system.
349      * Optionally providing a new parent via string identifier and a new name.
350      *
351      * @throws MoveOperationException
352      * @throws PermissionsException
353      */
354     public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
355     {
356         $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
357         if ($parent === null) {
358             throw new MoveOperationException('Book or chapter to move page into not found');
359         }
360
361         if (!userCan('page-create', $parent)) {
362             throw new PermissionsException('User does not have permission to create a page within the new parent');
363         }
364
365         $copyPage = $this->getNewDraftPage($parent);
366         $pageData = $page->getAttributes();
367
368         // Update name
369         if (!empty($newName)) {
370             $pageData['name'] = $newName;
371         }
372
373         // Copy tags from previous page if set
374         if ($page->tags) {
375             $pageData['tags'] = [];
376             foreach ($page->tags as $tag) {
377                 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
378             }
379         }
380
381         return $this->publishDraft($copyPage, $pageData);
382     }
383
384     /**
385      * Find a page parent entity via a identifier string in the format:
386      * {type}:{id}
387      * Example: (book:5).
388      *
389      * @throws MoveOperationException
390      */
391     protected function findParentByIdentifier(string $identifier): ?Entity
392     {
393         $stringExploded = explode(':', $identifier);
394         $entityType = $stringExploded[0];
395         $entityId = intval($stringExploded[1]);
396
397         if ($entityType !== 'book' && $entityType !== 'chapter') {
398             throw new MoveOperationException('Pages can only be in books or chapters');
399         }
400
401         $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
402
403         return $parentClass::visible()->where('id', '=', $entityId)->first();
404     }
405
406     /**
407      * Change the page's parent to the given entity.
408      */
409     protected function changeParent(Page $page, Entity $parent)
410     {
411         $book = ($parent instanceof Book) ? $parent : $parent->book;
412         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
413         $page->save();
414
415         if ($page->book->id !== $book->id) {
416             $page->changeBook($book->id);
417         }
418
419         $page->load('book');
420         $book->rebuildPermissions();
421     }
422
423     /**
424      * Get a page revision to update for the given page.
425      * Checks for an existing revisions before providing a fresh one.
426      */
427     protected function getPageRevisionToUpdate(Page $page): PageRevision
428     {
429         $drafts = $this->getUserDraftQuery($page)->get();
430         if ($drafts->count() > 0) {
431             return $drafts->first();
432         }
433
434         $draft = new PageRevision();
435         $draft->page_id = $page->id;
436         $draft->slug = $page->slug;
437         $draft->book_slug = $page->book->slug;
438         $draft->created_by = user()->id;
439         $draft->type = 'update_draft';
440
441         return $draft;
442     }
443
444     /**
445      * Delete old revisions, for the given page, from the system.
446      */
447     protected function deleteOldRevisions(Page $page)
448     {
449         $revisionLimit = config('app.revision_limit');
450         if ($revisionLimit === false) {
451             return;
452         }
453
454         $revisionsToDelete = PageRevision::query()
455             ->where('page_id', '=', $page->id)
456             ->orderBy('created_at', 'desc')
457             ->skip(intval($revisionLimit))
458             ->take(10)
459             ->get(['id']);
460         if ($revisionsToDelete->count() > 0) {
461             PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
462         }
463     }
464
465     /**
466      * Get a new priority for a page.
467      */
468     protected function getNewPriority(Page $page): int
469     {
470         $parent = $page->getParent();
471         if ($parent instanceof Chapter) {
472             $lastPage = $parent->pages('desc')->first();
473
474             return $lastPage ? $lastPage->priority + 1 : 0;
475         }
476
477         return (new BookContents($page->book))->getLastPriority() + 1;
478     }
479
480     /**
481      * Get the query to find the user's draft copies of the given page.
482      */
483     protected function getUserDraftQuery(Page $page)
484     {
485         return PageRevision::query()->where('created_by', '=', user()->id)
486             ->where('type', 'update_draft')
487             ->where('page_id', '=', $page->id)
488             ->orderBy('created_at', 'desc');
489     }
490 }