]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Add unit test for ip addess searching
[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::addForEntity($draft, ActivityType::PAGE_CREATE);
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::addForEntity($page, ActivityType::PAGE_UPDATE);
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::addForEntity($page, ActivityType::PAGE_DELETE);
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::addForEntity($page, ActivityType::PAGE_RESTORE);
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 ($parent === null) {
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::addForEntity($page, ActivityType::PAGE_MOVE);
345
346         return $parent;
347     }
348
349     /**
350      * Copy an existing page in the system.
351      * Optionally providing a new parent via string identifier and a new name.
352      *
353      * @throws MoveOperationException
354      * @throws PermissionsException
355      */
356     public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
357     {
358         $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
359         if ($parent === null) {
360             throw new MoveOperationException('Book or chapter to move page into not found');
361         }
362
363         if (!userCan('page-create', $parent)) {
364             throw new PermissionsException('User does not have permission to create a page within the new parent');
365         }
366
367         $copyPage = $this->getNewDraftPage($parent);
368         $pageData = $page->getAttributes();
369
370         // Update name
371         if (!empty($newName)) {
372             $pageData['name'] = $newName;
373         }
374
375         // Copy tags from previous page if set
376         if ($page->tags) {
377             $pageData['tags'] = [];
378             foreach ($page->tags as $tag) {
379                 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
380             }
381         }
382
383         return $this->publishDraft($copyPage, $pageData);
384     }
385
386     /**
387      * Find a page parent entity via a identifier string in the format:
388      * {type}:{id}
389      * Example: (book:5).
390      *
391      * @throws MoveOperationException
392      */
393     protected function findParentByIdentifier(string $identifier): ?Entity
394     {
395         $stringExploded = explode(':', $identifier);
396         $entityType = $stringExploded[0];
397         $entityId = intval($stringExploded[1]);
398
399         if ($entityType !== 'book' && $entityType !== 'chapter') {
400             throw new MoveOperationException('Pages can only be in books or chapters');
401         }
402
403         $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
404
405         return $parentClass::visible()->where('id', '=', $entityId)->first();
406     }
407
408     /**
409      * Change the page's parent to the given entity.
410      */
411     protected function changeParent(Page $page, Entity $parent)
412     {
413         $book = ($parent instanceof Chapter) ? $parent->book : $parent;
414         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
415         $page->save();
416
417         if ($page->book->id !== $book->id) {
418             $page->changeBook($book->id);
419         }
420
421         $page->load('book');
422         $book->rebuildPermissions();
423     }
424
425     /**
426      * Get a page revision to update for the given page.
427      * Checks for an existing revisions before providing a fresh one.
428      */
429     protected function getPageRevisionToUpdate(Page $page): PageRevision
430     {
431         $drafts = $this->getUserDraftQuery($page)->get();
432         if ($drafts->count() > 0) {
433             return $drafts->first();
434         }
435
436         $draft = new PageRevision();
437         $draft->page_id = $page->id;
438         $draft->slug = $page->slug;
439         $draft->book_slug = $page->book->slug;
440         $draft->created_by = user()->id;
441         $draft->type = 'update_draft';
442
443         return $draft;
444     }
445
446     /**
447      * Delete old revisions, for the given page, from the system.
448      */
449     protected function deleteOldRevisions(Page $page)
450     {
451         $revisionLimit = config('app.revision_limit');
452         if ($revisionLimit === false) {
453             return;
454         }
455
456         $revisionsToDelete = PageRevision::query()
457             ->where('page_id', '=', $page->id)
458             ->orderBy('created_at', 'desc')
459             ->skip(intval($revisionLimit))
460             ->take(10)
461             ->get(['id']);
462         if ($revisionsToDelete->count() > 0) {
463             PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
464         }
465     }
466
467     /**
468      * Get a new priority for a page.
469      */
470     protected function getNewPriority(Page $page): int
471     {
472         $parent = $page->getParent();
473         if ($parent instanceof Chapter) {
474             /** @var ?Page $lastPage */
475             $lastPage = $parent->pages('desc')->first();
476
477             return $lastPage ? $lastPage->priority + 1 : 0;
478         }
479
480         return (new BookContents($page->book))->getLastPriority() + 1;
481     }
482
483     /**
484      * Get the query to find the user's draft copies of the given page.
485      */
486     protected function getUserDraftQuery(Page $page)
487     {
488         return PageRevision::query()->where('created_by', '=', user()->id)
489             ->where('type', 'update_draft')
490             ->where('page_id', '=', $page->id)
491             ->orderBy('created_at', 'desc');
492     }
493 }