1 <?php namespace BookStack\Repos;
6 use BookStack\Exceptions\NotFoundException;
8 use BookStack\Services\PermissionService;
9 use BookStack\Services\ViewService;
10 use Illuminate\Database\Eloquent\Builder;
11 use Illuminate\Support\Collection;
32 * Base entity instances keyed by type
38 * @var PermissionService
40 protected $permissionService;
45 protected $viewService;
48 * Acceptable operators to be used in a query
51 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
54 * EntityService constructor.
56 public function __construct()
58 // TODO - Redo this to come via injection
59 $this->book = app(Book::class);
60 $this->chapter = app(Chapter::class);
61 $this->page = app(Page::class);
63 'page' => $this->page,
64 'chapter' => $this->chapter,
67 $this->viewService = app(ViewService::class);
68 $this->permissionService = app(PermissionService::class);
72 * Get an entity instance via type.
76 protected function getEntity($type)
78 return $this->entities[strtolower($type)];
82 * Base query for searching entities via permission system
84 * @param bool $allowDrafts
85 * @return \Illuminate\Database\Query\Builder
87 protected function entityQuery($type, $allowDrafts = false)
89 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type), 'view');
90 if (strtolower($type) === 'page' && !$allowDrafts) {
91 $q = $q->where('draft', '=', false);
97 * Check if an entity with the given id exists.
102 public function exists($type, $id)
104 return $this->entityQuery($type)->where('id', '=', $id)->exists();
108 * Get an entity by ID
109 * @param string $type
111 * @param bool $allowDrafts
114 public function getById($type, $id, $allowDrafts = false)
116 return $this->entityQuery($type, $allowDrafts)->findOrFail($id);
120 * Get an entity by its url slug.
121 * @param string $type
122 * @param string $slug
123 * @param string|bool $bookSlug
125 * @throws NotFoundException
127 public function getBySlug($type, $slug, $bookSlug = false)
129 $q = $this->entityQuery($type)->where('slug', '=', $slug);
130 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
131 $q = $q->where('book_id', '=', function($query) use ($bookSlug) {
133 ->from($this->book->getTable())
134 ->where('slug', '=', $bookSlug)->limit(1);
137 $entity = $q->first();
138 if ($entity === null) throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
143 * Get all entities of a type limited by count unless count if false.
144 * @param string $type
145 * @param integer|bool $count
148 public function getAll($type, $count = 20)
150 $q = $this->entityQuery($type)->orderBy('name', 'asc');
151 if ($count !== false) $q = $q->take($count);
156 * Get all entities in a paginated format
159 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
161 public function getAllPaginated($type, $count = 10)
163 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
167 * Get the most recently created entities of the given type.
168 * @param string $type
171 * @param bool|callable $additionalQuery
173 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
175 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
176 ->orderBy('created_at', 'desc');
177 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
178 if ($additionalQuery !== false && is_callable($additionalQuery)) {
179 $additionalQuery($query);
181 return $query->skip($page * $count)->take($count)->get();
185 * Get the most recently updated entities of the given type.
186 * @param string $type
189 * @param bool|callable $additionalQuery
191 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
193 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
194 ->orderBy('updated_at', 'desc');
195 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
196 if ($additionalQuery !== false && is_callable($additionalQuery)) {
197 $additionalQuery($query);
199 return $query->skip($page * $count)->take($count)->get();
203 * Get the most recently viewed entities.
204 * @param string|bool $type
209 public function getRecentlyViewed($type, $count = 10, $page = 0)
211 $filter = is_bool($type) ? false : $this->getEntity($type);
212 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
216 * Get the most popular entities base on all views.
217 * @param string|bool $type
222 public function getPopular($type, $count = 10, $page = 0)
224 $filter = is_bool($type) ? false : $this->getEntity($type);
225 return $this->viewService->getPopular($count, $page, $filter);
229 * Get draft pages owned by the current user.
233 public function getUserDraftPages($count = 20, $page = 0)
235 return $this->page->where('draft', '=', true)
236 ->where('created_by', '=', user()->id)
237 ->orderBy('updated_at', 'desc')
238 ->skip($count * $page)->take($count)->get();
242 * Updates entity restrictions from a request
244 * @param Entity $entity
246 public function updateEntityPermissionsFromRequest($request, Entity $entity)
248 $entity->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
249 $entity->permissions()->delete();
250 if ($request->has('restrictions')) {
251 foreach ($request->get('restrictions') as $roleId => $restrictions) {
252 foreach ($restrictions as $action => $value) {
253 $entity->permissions()->create([
254 'role_id' => $roleId,
255 'action' => strtolower($action)
261 $this->permissionService->buildJointPermissionsForEntity($entity);
265 * Prepare a string of search terms by turning
266 * it into an array of terms.
267 * Keeps quoted terms together.
271 public function prepareSearchTerms($termString)
273 $termString = $this->cleanSearchTermString($termString);
274 preg_match_all('/(".*?")/', $termString, $matches);
276 if (count($matches[1]) > 0) {
277 foreach ($matches[1] as $match) {
280 $termString = trim(preg_replace('/"(.*?)"/', '', $termString));
282 if (!empty($termString)) $terms = array_merge($terms, explode(' ', $termString));
287 * Removes any special search notation that should not
288 * be used in a full-text search.
292 protected function cleanSearchTermString($termString)
294 // Strip tag searches
295 $termString = preg_replace('/\[.*?\]/', '', $termString);
296 // Reduced multiple spacing into single spacing
297 $termString = preg_replace("/\s{2,}/", " ", $termString);
302 * Get the available query operators as a regex escaped list.
305 protected function getRegexEscapedOperators()
307 $escapedOperators = [];
308 foreach ($this->queryOperators as $operator) {
309 $escapedOperators[] = preg_quote($operator);
311 return join('|', $escapedOperators);
315 * Parses advanced search notations and adds them to the db query.
320 protected function addAdvancedSearchQueries($query, $termString)
322 $escapedOperators = $this->getRegexEscapedOperators();
323 // Look for tag searches
324 preg_match_all("/\[(.*?)((${escapedOperators})(.*?))?\]/", $termString, $tags);
325 if (count($tags[0]) > 0) {
326 $this->applyTagSearches($query, $tags);
333 * Apply extracted tag search terms onto a entity query.
338 protected function applyTagSearches($query, $tags) {
339 $query->where(function($query) use ($tags) {
340 foreach ($tags[1] as $index => $tagName) {
341 $query->whereHas('tags', function($query) use ($tags, $index, $tagName) {
342 $tagOperator = $tags[3][$index];
343 $tagValue = $tags[4][$index];
344 if (!empty($tagOperator) && !empty($tagValue) && in_array($tagOperator, $this->queryOperators)) {
345 if (is_numeric($tagValue) && $tagOperator !== 'like') {
346 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
347 // search the value as a string which prevents being able to do number-based operations
348 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
349 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
350 $query->where('name', '=', $tagName)->whereRaw("value ${tagOperator} ${tagValue}");
352 $query->where('name', '=', $tagName)->where('value', $tagOperator, $tagValue);
355 $query->where('name', '=', $tagName);
364 * Alias method to update the book jointPermissions in the PermissionService.
365 * @param Collection $collection collection on entities
367 public function buildJointPermissions(Collection $collection)
369 $this->permissionService->buildJointPermissionsForEntities($collection);
373 * Format a name as a url slug.
377 protected function nameToSlug($name)
379 $slug = str_replace(' ', '-', strtolower($name));
380 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', $slug);
381 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);