]> BookStack Code Mirror - bookstack/blob - app/Repos/BookRepo.php
Update Ldap.php
[bookstack] / app / Repos / BookRepo.php
1 <?php namespace BookStack\Repos;
2
3 use Alpha\B;
4 use BookStack\Exceptions\NotFoundException;
5 use Illuminate\Database\Eloquent\Collection;
6 use Illuminate\Support\Str;
7 use BookStack\Book;
8 use Views;
9
10 class BookRepo extends EntityRepo
11 {
12     protected $pageRepo;
13     protected $chapterRepo;
14
15     /**
16      * BookRepo constructor.
17      * @param PageRepo $pageRepo
18      * @param ChapterRepo $chapterRepo
19      */
20     public function __construct(PageRepo $pageRepo, ChapterRepo $chapterRepo)
21     {
22         $this->pageRepo = $pageRepo;
23         $this->chapterRepo = $chapterRepo;
24         parent::__construct();
25     }
26
27     /**
28      * Base query for getting books.
29      * Takes into account any restrictions.
30      * @return mixed
31      */
32     private function bookQuery()
33     {
34         return $this->permissionService->enforceBookRestrictions($this->book, 'view');
35     }
36
37     /**
38      * Get the book that has the given id.
39      * @param $id
40      * @return mixed
41      */
42     public function getById($id)
43     {
44         return $this->bookQuery()->findOrFail($id);
45     }
46
47     /**
48      * Get all books, Limited by count.
49      * @param int $count
50      * @return mixed
51      */
52     public function getAll($count = 10)
53     {
54         $bookQuery = $this->bookQuery()->orderBy('name', 'asc');
55         if (!$count) return $bookQuery->get();
56         return $bookQuery->take($count)->get();
57     }
58
59     /**
60      * Get all books paginated.
61      * @param int $count
62      * @return mixed
63      */
64     public function getAllPaginated($count = 10)
65     {
66         return $this->bookQuery()
67             ->orderBy('name', 'asc')->paginate($count);
68     }
69
70
71     /**
72      * Get the latest books.
73      * @param int $count
74      * @return mixed
75      */
76     public function getLatest($count = 10)
77     {
78         return $this->bookQuery()->orderBy('created_at', 'desc')->take($count)->get();
79     }
80
81     /**
82      * Gets the most recently viewed for a user.
83      * @param int $count
84      * @param int $page
85      * @return mixed
86      */
87     public function getRecentlyViewed($count = 10, $page = 0)
88     {
89         return Views::getUserRecentlyViewed($count, $page, $this->book);
90     }
91
92     /**
93      * Gets the most viewed books.
94      * @param int $count
95      * @param int $page
96      * @return mixed
97      */
98     public function getPopular($count = 10, $page = 0)
99     {
100         return Views::getPopular($count, $page, $this->book);
101     }
102
103     /**
104      * Get a book by slug
105      * @param $slug
106      * @return mixed
107      * @throws NotFoundException
108      */
109     public function getBySlug($slug)
110     {
111         $book = $this->bookQuery()->where('slug', '=', $slug)->first();
112         if ($book === null) throw new NotFoundException('Book not found');
113         return $book;
114     }
115
116     /**
117      * Checks if a book exists.
118      * @param $id
119      * @return bool
120      */
121     public function exists($id)
122     {
123         return $this->bookQuery()->where('id', '=', $id)->exists();
124     }
125
126     /**
127      * Get a new book instance from request input.
128      * @param array $input
129      * @return Book
130      */
131     public function createFromInput($input)
132     {
133         $book = $this->book->newInstance($input);
134         $book->slug = $this->findSuitableSlug($book->name);
135         $book->created_by = user()->id;
136         $book->updated_by = user()->id;
137         $book->save();
138         $this->permissionService->buildJointPermissionsForEntity($book);
139         return $book;
140     }
141
142     /**
143      * Update the given book from user input.
144      * @param Book $book
145      * @param $input
146      * @return Book
147      */
148     public function updateFromInput(Book $book, $input)
149     {
150         if ($book->name !== $input['name']) {
151             $book->slug = $this->findSuitableSlug($input['name'], $book->id);
152         }
153         $book->fill($input);
154         $book->updated_by = user()->id;
155         $book->save();
156         $this->permissionService->buildJointPermissionsForEntity($book);
157         return $book;
158     }
159
160     /**
161      * Destroy the given book.
162      * @param Book $book
163      * @throws \Exception
164      */
165     public function destroy(Book $book)
166     {
167         foreach ($book->pages as $page) {
168             $this->pageRepo->destroy($page);
169         }
170         foreach ($book->chapters as $chapter) {
171             $this->chapterRepo->destroy($chapter);
172         }
173         $book->views()->delete();
174         $book->permissions()->delete();
175         $this->permissionService->deleteJointPermissionsForEntity($book);
176         $book->delete();
177     }
178
179     /**
180      * Get the next child element priority.
181      * @param Book $book
182      * @return int
183      */
184     public function getNewPriority($book)
185     {
186         $lastElem = $this->getChildren($book)->pop();
187         return $lastElem ? $lastElem->priority + 1 : 0;
188     }
189
190     /**
191      * @param string $slug
192      * @param bool|false $currentId
193      * @return bool
194      */
195     public function doesSlugExist($slug, $currentId = false)
196     {
197         $query = $this->book->where('slug', '=', $slug);
198         if ($currentId) {
199             $query = $query->where('id', '!=', $currentId);
200         }
201         return $query->count() > 0;
202     }
203
204     /**
205      * Provides a suitable slug for the given book name.
206      * Ensures the returned slug is unique in the system.
207      * @param string $name
208      * @param bool|false $currentId
209      * @return string
210      */
211     public function findSuitableSlug($name, $currentId = false)
212     {
213         $slug = $this->nameToSlug($name);
214         while ($this->doesSlugExist($slug, $currentId)) {
215             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
216         }
217         return $slug;
218     }
219
220     /**
221      * Get all child objects of a book.
222      * Returns a sorted collection of Pages and Chapters.
223      * Loads the book slug onto child elements to prevent access database access for getting the slug.
224      * @param Book $book
225      * @param bool $filterDrafts
226      * @return mixed
227      */
228     public function getChildren(Book $book, $filterDrafts = false)
229     {
230         $pageQuery = $book->pages()->where('chapter_id', '=', 0);
231         $pageQuery = $this->permissionService->enforcePageRestrictions($pageQuery, 'view');
232
233         if ($filterDrafts) {
234             $pageQuery = $pageQuery->where('draft', '=', false);
235         }
236
237         $pages = $pageQuery->get();
238
239         $chapterQuery = $book->chapters()->with(['pages' => function ($query) use ($filterDrafts) {
240             $this->permissionService->enforcePageRestrictions($query, 'view');
241             if ($filterDrafts) $query->where('draft', '=', false);
242         }]);
243         $chapterQuery = $this->permissionService->enforceChapterRestrictions($chapterQuery, 'view');
244         $chapters = $chapterQuery->get();
245         $children = $pages->values();
246         foreach ($chapters as $chapter) {
247             $children->push($chapter);
248         }
249         $bookSlug = $book->slug;
250
251         $children->each(function ($child) use ($bookSlug) {
252             $child->setAttribute('bookSlug', $bookSlug);
253             if ($child->isA('chapter')) {
254                 $child->pages->each(function ($page) use ($bookSlug) {
255                     $page->setAttribute('bookSlug', $bookSlug);
256                 });
257                 $child->pages = $child->pages->sortBy(function ($child, $key) {
258                     $score = $child->priority;
259                     if ($child->draft) $score -= 100;
260                     return $score;
261                 });
262             }
263         });
264
265         // Sort items with drafts first then by priority.
266         return $children->sortBy(function ($child, $key) {
267             $score = $child->priority;
268             if ($child->isA('page') && $child->draft) $score -= 100;
269             return $score;
270         });
271     }
272
273     /**
274      * Get books by search term.
275      * @param $term
276      * @param int $count
277      * @param array $paginationAppends
278      * @return mixed
279      */
280     public function getBySearch($term, $count = 20, $paginationAppends = [])
281     {
282         $terms = $this->prepareSearchTerms($term);
283         $bookQuery = $this->permissionService->enforceBookRestrictions($this->book->fullTextSearchQuery(['name', 'description'], $terms));
284         $bookQuery = $this->addAdvancedSearchQueries($bookQuery, $term);
285         $books = $bookQuery->paginate($count)->appends($paginationAppends);
286         $words = join('|', explode(' ', preg_quote(trim($term), '/')));
287         foreach ($books as $book) {
288             //highlight
289             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $book->getExcerpt(100));
290             $book->searchSnippet = $result;
291         }
292         return $books;
293     }
294
295 }