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