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