]> BookStack Code Mirror - bookstack/blob - app/Repos/BookRepo.php
Page Attachments - Improved UI, Now initially complete
[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         $book->fill($input);
151         $book->slug = $this->findSuitableSlug($book->name, $book->id);
152         $book->updated_by = user()->id;
153         $book->save();
154         $this->permissionService->buildJointPermissionsForEntity($book);
155         return $book;
156     }
157
158     /**
159      * Destroy the given book.
160      * @param Book $book
161      * @throws \Exception
162      */
163     public function destroy(Book $book)
164     {
165         foreach ($book->pages as $page) {
166             $this->pageRepo->destroy($page);
167         }
168         foreach ($book->chapters as $chapter) {
169             $this->chapterRepo->destroy($chapter);
170         }
171         $book->views()->delete();
172         $book->permissions()->delete();
173         $this->permissionService->deleteJointPermissionsForEntity($book);
174         $book->delete();
175     }
176
177     /**
178      * Get the next child element priority.
179      * @param Book $book
180      * @return int
181      */
182     public function getNewPriority($book)
183     {
184         $lastElem = $this->getChildren($book)->pop();
185         return $lastElem ? $lastElem->priority + 1 : 0;
186     }
187
188     /**
189      * @param string $slug
190      * @param bool|false $currentId
191      * @return bool
192      */
193     public function doesSlugExist($slug, $currentId = false)
194     {
195         $query = $this->book->where('slug', '=', $slug);
196         if ($currentId) {
197             $query = $query->where('id', '!=', $currentId);
198         }
199         return $query->count() > 0;
200     }
201
202     /**
203      * Provides a suitable slug for the given book name.
204      * Ensures the returned slug is unique in the system.
205      * @param string $name
206      * @param bool|false $currentId
207      * @return string
208      */
209     public function findSuitableSlug($name, $currentId = false)
210     {
211         $slug = Str::slug($name);
212         if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
213         while ($this->doesSlugExist($slug, $currentId)) {
214             $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
215         }
216         return $slug;
217     }
218
219     /**
220      * Get all child objects of a book.
221      * Returns a sorted collection of Pages and Chapters.
222      * Loads the book slug onto child elements to prevent access database access for getting the slug.
223      * @param Book $book
224      * @param bool $filterDrafts
225      * @return mixed
226      */
227     public function getChildren(Book $book, $filterDrafts = false)
228     {
229         $pageQuery = $book->pages()->where('chapter_id', '=', 0);
230         $pageQuery = $this->permissionService->enforcePageRestrictions($pageQuery, 'view');
231
232         if ($filterDrafts) {
233             $pageQuery = $pageQuery->where('draft', '=', false);
234         }
235
236         $pages = $pageQuery->get();
237
238         $chapterQuery = $book->chapters()->with(['pages' => function ($query) use ($filterDrafts) {
239             $this->permissionService->enforcePageRestrictions($query, 'view');
240             if ($filterDrafts) $query->where('draft', '=', false);
241         }]);
242         $chapterQuery = $this->permissionService->enforceChapterRestrictions($chapterQuery, 'view');
243         $chapters = $chapterQuery->get();
244         $children = $pages->values();
245         foreach ($chapters as $chapter) {
246             $children->push($chapter);
247         }
248         $bookSlug = $book->slug;
249
250         $children->each(function ($child) use ($bookSlug) {
251             $child->setAttribute('bookSlug', $bookSlug);
252             if ($child->isA('chapter')) {
253                 $child->pages->each(function ($page) use ($bookSlug) {
254                     $page->setAttribute('bookSlug', $bookSlug);
255                 });
256                 $child->pages = $child->pages->sortBy(function ($child, $key) {
257                     $score = $child->priority;
258                     if ($child->draft) $score -= 100;
259                     return $score;
260                 });
261             }
262         });
263
264         // Sort items with drafts first then by priority.
265         return $children->sortBy(function ($child, $key) {
266             $score = $child->priority;
267             if ($child->isA('page') && $child->draft) $score -= 100;
268             return $score;
269         });
270     }
271
272     /**
273      * Get books by search term.
274      * @param $term
275      * @param int $count
276      * @param array $paginationAppends
277      * @return mixed
278      */
279     public function getBySearch($term, $count = 20, $paginationAppends = [])
280     {
281         $terms = $this->prepareSearchTerms($term);
282         $bookQuery = $this->permissionService->enforceBookRestrictions($this->book->fullTextSearchQuery(['name', 'description'], $terms));
283         $bookQuery = $this->addAdvancedSearchQueries($bookQuery, $term);
284         $books = $bookQuery->paginate($count)->appends($paginationAppends);
285         $words = join('|', explode(' ', preg_quote(trim($term), '/')));
286         foreach ($books as $book) {
287             //highlight
288             $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $book->getExcerpt(100));
289             $book->searchSnippet = $result;
290         }
291         return $books;
292     }
293
294 }