]> BookStack Code Mirror - bookstack/blob - app/Repos/ChapterRepo.php
Fixed image tests after amends to url system
[bookstack] / app / Repos / ChapterRepo.php
1 <?php namespace BookStack\Repos;
2
3
4 use Activity;
5 use BookStack\Book;
6 use BookStack\Exceptions\NotFoundException;
7 use Illuminate\Support\Str;
8 use BookStack\Chapter;
9
10 class ChapterRepo extends EntityRepo
11 {
12     protected $pageRepo;
13
14     /**
15      * ChapterRepo constructor.
16      * @param $pageRepo
17      */
18     public function __construct(PageRepo $pageRepo)
19     {
20         $this->pageRepo = $pageRepo;
21         parent::__construct();
22     }
23
24     /**
25      * Base query for getting chapters, Takes permissions into account.
26      * @return mixed
27      */
28     private function chapterQuery()
29     {
30         return $this->permissionService->enforceChapterRestrictions($this->chapter, 'view');
31     }
32
33     /**
34      * Check if an id exists.
35      * @param $id
36      * @return bool
37      */
38     public function idExists($id)
39     {
40         return $this->chapterQuery()->where('id', '=', $id)->count() > 0;
41     }
42
43     /**
44      * Get a chapter by a specific id.
45      * @param $id
46      * @return mixed
47      */
48     public function getById($id)
49     {
50         return $this->chapterQuery()->findOrFail($id);
51     }
52
53     /**
54      * Get all chapters.
55      * @return \Illuminate\Database\Eloquent\Collection|static[]
56      */
57     public function getAll()
58     {
59         return $this->chapterQuery()->all();
60     }
61
62     /**
63      * Get a chapter that has the given slug within the given book.
64      * @param $slug
65      * @param $bookId
66      * @return mixed
67      * @throws NotFoundException
68      */
69     public function getBySlug($slug, $bookId)
70     {
71         $chapter = $this->chapterQuery()->where('slug', '=', $slug)->where('book_id', '=', $bookId)->first();
72         if ($chapter === null) throw new NotFoundException('Chapter not found');
73         return $chapter;
74     }
75
76     /**
77      * Get the child items for a chapter
78      * @param Chapter $chapter
79      */
80     public function getChildren(Chapter $chapter)
81     {
82         $pages = $this->permissionService->enforcePageRestrictions($chapter->pages())->get();
83         // Sort items with drafts first then by priority.
84         return $pages->sortBy(function ($child, $key) {
85             $score = $child->priority;
86             if ($child->draft) $score -= 100;
87             return $score;
88         });
89     }
90
91     /**
92      * Create a new chapter from request input.
93      * @param $input
94      * @param Book $book
95      * @return Chapter
96      */
97     public function createFromInput($input, Book $book)
98     {
99         $chapter = $this->chapter->newInstance($input);
100         $chapter->slug = $this->findSuitableSlug($chapter->name, $book->id);
101         $chapter->created_by = auth()->user()->id;
102         $chapter->updated_by = auth()->user()->id;
103         $chapter = $book->chapters()->save($chapter);
104         $this->permissionService->buildJointPermissionsForEntity($chapter);
105         return $chapter;
106     }
107
108     /**
109      * Destroy a chapter and its relations by providing its slug.
110      * @param Chapter $chapter
111      */
112     public function destroy(Chapter $chapter)
113     {
114         if (count($chapter->pages) > 0) {
115             foreach ($chapter->pages as $page) {
116                 $page->chapter_id = 0;
117                 $page->save();
118             }
119         }
120         Activity::removeEntity($chapter);
121         $chapter->views()->delete();
122         $chapter->permissions()->delete();
123         $this->permissionService->deleteJointPermissionsForEntity($chapter);
124         $chapter->delete();
125     }
126
127     /**
128      * Check if a chapter's slug exists.
129      * @param            $slug
130      * @param            $bookId
131      * @param bool|false $currentId
132      * @return bool
133      */
134     public function doesSlugExist($slug, $bookId, $currentId = false)
135     {
136         $query = $this->chapter->where('slug', '=', $slug)->where('book_id', '=', $bookId);
137         if ($currentId) {
138             $query = $query->where('id', '!=', $currentId);
139         }
140         return $query->count() > 0;
141     }
142
143     /**
144      * Finds a suitable slug for the provided name.
145      * Checks database to prevent duplicate slugs.
146      * @param            $name
147      * @param            $bookId
148      * @param bool|false $currentId
149      * @return string
150      */
151     public function findSuitableSlug($name, $bookId, $currentId = false)
152     {
153         $slug = Str::slug($name);
154         if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
155         while ($this->doesSlugExist($slug, $bookId, $currentId)) {
156             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
157         }
158         return $slug;
159     }
160
161     /**
162      * Get a new priority value for a new page to be added
163      * to the given chapter.
164      * @param Chapter $chapter
165      * @return int
166      */
167     public function getNewPriority(Chapter $chapter)
168     {
169         $lastPage = $chapter->pages->last();
170         return $lastPage !== null ? $lastPage->priority + 1 : 0;
171     }
172
173     /**
174      * Get chapters by the given search term.
175      * @param string $term
176      * @param array $whereTerms
177      * @param int $count
178      * @param array $paginationAppends
179      * @return mixed
180      */
181     public function getBySearch($term, $whereTerms = [], $count = 20, $paginationAppends = [])
182     {
183         $terms = $this->prepareSearchTerms($term);
184         $chapterQuery = $this->permissionService->enforceChapterRestrictions($this->chapter->fullTextSearchQuery(['name', 'description'], $terms, $whereTerms));
185         $chapterQuery = $this->addAdvancedSearchQueries($chapterQuery, $term);
186         $chapters = $chapterQuery->paginate($count)->appends($paginationAppends);
187         $words = join('|', explode(' ', preg_quote(trim($term), '/')));
188         foreach ($chapters as $chapter) {
189             //highlight
190             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $chapter->getExcerpt(100));
191             $chapter->searchSnippet = $result;
192         }
193         return $chapters;
194     }
195
196     /**
197      * Changes the book relation of this chapter.
198      * @param $bookId
199      * @param Chapter $chapter
200      * @param bool $rebuildPermissions
201      * @return Chapter
202      */
203     public function changeBook($bookId, Chapter $chapter, $rebuildPermissions = false)
204     {
205         $chapter->book_id = $bookId;
206         // Update related activity
207         foreach ($chapter->activity as $activity) {
208             $activity->book_id = $bookId;
209             $activity->save();
210         }
211         $chapter->slug = $this->findSuitableSlug($chapter->name, $bookId, $chapter->id);
212         $chapter->save();
213         // Update all child pages
214         foreach ($chapter->pages as $page) {
215             $this->pageRepo->changeBook($bookId, $page);
216         }
217
218         // Update permissions if applicable
219         if ($rebuildPermissions) {
220             $chapter->load('book');
221             $this->permissionService->buildJointPermissionsForEntity($chapter->book);
222         }
223
224         return $chapter;
225     }
226
227 }