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