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