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