]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/PermissionService.php
Remove unnecessary changes
[bookstack] / app / Auth / Permissions / PermissionService.php
1 <?php namespace BookStack\Auth\Permissions;
2
3 use BookStack\Auth\Permissions;
4 use BookStack\Auth\Role;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\EntityProvider;
8 use BookStack\Ownable;
9 use Illuminate\Database\Connection;
10 use Illuminate\Database\Eloquent\Builder;
11 use Illuminate\Database\Query\Builder as QueryBuilder;
12 use Illuminate\Support\Collection;
13
14 class PermissionService
15 {
16
17     protected $currentAction;
18     protected $isAdminUser;
19     protected $userRoles = false;
20     protected $currentUserModel = false;
21
22     /**
23      * @var Connection
24      */
25     protected $db;
26
27     /**
28      * @var JointPermission
29      */
30     protected $jointPermission;
31
32     /**
33      * @var Role
34      */
35     protected $role;
36
37     /**
38      * @var EntityPermission
39      */
40     protected $entityPermission;
41
42     /**
43      * @var EntityProvider
44      */
45     protected $entityProvider;
46
47     protected $entityCache;
48
49     /**
50      * PermissionService constructor.
51      */
52     public function __construct(
53         JointPermission $jointPermission,
54         Permissions\EntityPermission $entityPermission,
55         Role $role,
56         Connection $db,
57         EntityProvider $entityProvider
58     ) {
59         $this->db = $db;
60         $this->jointPermission = $jointPermission;
61         $this->entityPermission = $entityPermission;
62         $this->role = $role;
63         $this->entityProvider = $entityProvider;
64     }
65
66     /**
67      * Set the database connection
68      * @param Connection $connection
69      */
70     public function setConnection(Connection $connection)
71     {
72         $this->db = $connection;
73     }
74
75     /**
76      * Prepare the local entity cache and ensure it's empty
77      * @param \BookStack\Entities\Models\Entity[] $entities
78      */
79     protected function readyEntityCache($entities = [])
80     {
81         $this->entityCache = [];
82
83         foreach ($entities as $entity) {
84             $type = $entity->getType();
85             if (!isset($this->entityCache[$type])) {
86                 $this->entityCache[$type] = collect();
87             }
88             $this->entityCache[$type]->put($entity->id, $entity);
89         }
90     }
91
92     /**
93      * Get a book via ID, Checks local cache
94      * @param $bookId
95      * @return Book
96      */
97     protected function getBook($bookId)
98     {
99         if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
100             return $this->entityCache['book']->get($bookId);
101         }
102
103         $book = $this->entityProvider->book->find($bookId);
104         if ($book === null) {
105             $book = false;
106         }
107
108         return $book;
109     }
110
111     /**
112      * Get a chapter via ID, Checks local cache
113      * @param $chapterId
114      * @return \BookStack\Entities\Models\Book
115      */
116     protected function getChapter($chapterId)
117     {
118         if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
119             return $this->entityCache['chapter']->get($chapterId);
120         }
121
122         $chapter = $this->entityProvider->chapter->find($chapterId);
123         if ($chapter === null) {
124             $chapter = false;
125         }
126
127         return $chapter;
128     }
129
130     /**
131      * Get the roles for the current user;
132      * @return array|bool
133      */
134     protected function getRoles()
135     {
136         if ($this->userRoles !== false) {
137             return $this->userRoles;
138         }
139
140         $roles = [];
141
142         if (auth()->guest()) {
143             $roles[] = $this->role->getSystemRole('public')->id;
144             return $roles;
145         }
146
147
148         foreach ($this->currentUser()->roles as $role) {
149             $roles[] = $role->id;
150         }
151         return $roles;
152     }
153
154     /**
155      * Re-generate all entity permission from scratch.
156      */
157     public function buildJointPermissions()
158     {
159         $this->jointPermission->truncate();
160         $this->readyEntityCache();
161
162         // Get all roles (Should be the most limited dimension)
163         $roles = $this->role->with('permissions')->get()->all();
164
165         // Chunk through all books
166         $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
167             $this->buildJointPermissionsForBooks($books, $roles);
168         });
169
170         // Chunk through all bookshelves
171         $this->entityProvider->bookshelf->newQuery()->withTrashed()->select(['id', 'restricted', 'created_by'])
172             ->chunk(50, function ($shelves) use ($roles) {
173                 $this->buildJointPermissionsForShelves($shelves, $roles);
174             });
175     }
176
177     /**
178      * Get a query for fetching a book with it's children.
179      * @return QueryBuilder
180      */
181     protected function bookFetchQuery()
182     {
183         return $this->entityProvider->book->withTrashed()->newQuery()
184             ->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
185                 $query->withTrashed()->select(['id', 'restricted', 'created_by', 'book_id']);
186             }, 'pages'  => function ($query) {
187                 $query->withTrashed()->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
188             }]);
189     }
190
191     /**
192      * @param Collection $shelves
193      * @param array $roles
194      * @param bool $deleteOld
195      * @throws \Throwable
196      */
197     protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
198     {
199         if ($deleteOld) {
200             $this->deleteManyJointPermissionsForEntities($shelves->all());
201         }
202         $this->createManyJointPermissions($shelves, $roles);
203     }
204
205     /**
206      * Build joint permissions for an array of books
207      * @param Collection $books
208      * @param array $roles
209      * @param bool $deleteOld
210      */
211     protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
212     {
213         $entities = clone $books;
214
215         /** @var Book $book */
216         foreach ($books->all() as $book) {
217             foreach ($book->getRelation('chapters') as $chapter) {
218                 $entities->push($chapter);
219             }
220             foreach ($book->getRelation('pages') as $page) {
221                 $entities->push($page);
222             }
223         }
224
225         if ($deleteOld) {
226             $this->deleteManyJointPermissionsForEntities($entities->all());
227         }
228         $this->createManyJointPermissions($entities, $roles);
229     }
230
231     /**
232      * Rebuild the entity jointPermissions for a particular entity.
233      * @param \BookStack\Entities\Models\Entity $entity
234      * @throws \Throwable
235      */
236     public function buildJointPermissionsForEntity(Entity $entity)
237     {
238         $entities = [$entity];
239         if ($entity->isA('book')) {
240             $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
241             $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
242             return;
243         }
244
245         if ($entity->book) {
246             $entities[] = $entity->book;
247         }
248
249         if ($entity->isA('page') && $entity->chapter_id) {
250             $entities[] = $entity->chapter;
251         }
252
253         if ($entity->isA('chapter')) {
254             foreach ($entity->pages as $page) {
255                 $entities[] = $page;
256             }
257         }
258
259         $this->buildJointPermissionsForEntities(collect($entities));
260     }
261
262     /**
263      * Rebuild the entity jointPermissions for a collection of entities.
264      * @param Collection $entities
265      * @throws \Throwable
266      */
267     public function buildJointPermissionsForEntities(Collection $entities)
268     {
269         $roles = $this->role->newQuery()->get();
270         $this->deleteManyJointPermissionsForEntities($entities->all());
271         $this->createManyJointPermissions($entities, $roles);
272     }
273
274     /**
275      * Build the entity jointPermissions for a particular role.
276      * @param Role $role
277      */
278     public function buildJointPermissionForRole(Role $role)
279     {
280         $roles = [$role];
281         $this->deleteManyJointPermissionsForRoles($roles);
282
283         // Chunk through all books
284         $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
285             $this->buildJointPermissionsForBooks($books, $roles);
286         });
287
288         // Chunk through all bookshelves
289         $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
290             ->chunk(50, function ($shelves) use ($roles) {
291                 $this->buildJointPermissionsForShelves($shelves, $roles);
292             });
293     }
294
295     /**
296      * Delete the entity jointPermissions attached to a particular role.
297      * @param Role $role
298      */
299     public function deleteJointPermissionsForRole(Role $role)
300     {
301         $this->deleteManyJointPermissionsForRoles([$role]);
302     }
303
304     /**
305      * Delete all of the entity jointPermissions for a list of entities.
306      * @param Role[] $roles
307      */
308     protected function deleteManyJointPermissionsForRoles($roles)
309     {
310         $roleIds = array_map(function ($role) {
311             return $role->id;
312         }, $roles);
313         $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
314     }
315
316     /**
317      * Delete the entity jointPermissions for a particular entity.
318      * @param Entity $entity
319      * @throws \Throwable
320      */
321     public function deleteJointPermissionsForEntity(Entity $entity)
322     {
323         $this->deleteManyJointPermissionsForEntities([$entity]);
324     }
325
326     /**
327      * Delete all of the entity jointPermissions for a list of entities.
328      * @param \BookStack\Entities\Models\Entity[] $entities
329      * @throws \Throwable
330      */
331     protected function deleteManyJointPermissionsForEntities($entities)
332     {
333         if (count($entities) === 0) {
334             return;
335         }
336
337         $this->db->transaction(function () use ($entities) {
338
339             foreach (array_chunk($entities, 1000) as $entityChunk) {
340                 $query = $this->db->table('joint_permissions');
341                 foreach ($entityChunk as $entity) {
342                     $query->orWhere(function (QueryBuilder $query) use ($entity) {
343                         $query->where('entity_id', '=', $entity->id)
344                             ->where('entity_type', '=', $entity->getMorphClass());
345                     });
346                 }
347                 $query->delete();
348             }
349         });
350     }
351
352     /**
353      * Create & Save entity jointPermissions for many entities and jointPermissions.
354      * @param Collection $entities
355      * @param array $roles
356      * @throws \Throwable
357      */
358     protected function createManyJointPermissions($entities, $roles)
359     {
360         $this->readyEntityCache($entities);
361         $jointPermissions = [];
362
363         // Fetch Entity Permissions and create a mapping of entity restricted statuses
364         $entityRestrictedMap = [];
365         $permissionFetch = $this->entityPermission->newQuery();
366         foreach ($entities as $entity) {
367             $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
368             $permissionFetch->orWhere(function ($query) use ($entity) {
369                 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
370             });
371         }
372         $permissions = $permissionFetch->get();
373
374         // Create a mapping of explicit entity permissions
375         $permissionMap = [];
376         foreach ($permissions as $permission) {
377             $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
378             $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
379             $permissionMap[$key] = $isRestricted;
380         }
381
382         // Create a mapping of role permissions
383         $rolePermissionMap = [];
384         foreach ($roles as $role) {
385             foreach ($role->permissions as $permission) {
386                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
387             }
388         }
389
390         // Create Joint Permission Data
391         foreach ($entities as $entity) {
392             foreach ($roles as $role) {
393                 foreach ($this->getActions($entity) as $action) {
394                     $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
395                 }
396             }
397         }
398
399         $this->db->transaction(function () use ($jointPermissions) {
400             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
401                 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
402             }
403         });
404     }
405
406
407     /**
408      * Get the actions related to an entity.
409      * @param \BookStack\Entities\Models\Entity $entity
410      * @return array
411      */
412     protected function getActions(Entity $entity)
413     {
414         $baseActions = ['view', 'update', 'delete'];
415         if ($entity->isA('chapter') || $entity->isA('book')) {
416             $baseActions[] = 'page-create';
417         }
418         if ($entity->isA('book')) {
419             $baseActions[] = 'chapter-create';
420         }
421         return $baseActions;
422     }
423
424     /**
425      * Create entity permission data for an entity and role
426      * for a particular action.
427      * @param Entity $entity
428      * @param Role $role
429      * @param string $action
430      * @param array $permissionMap
431      * @param array $rolePermissionMap
432      * @return array
433      */
434     protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
435     {
436         $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
437         $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
438         $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
439         $explodedAction = explode('-', $action);
440         $restrictionAction = end($explodedAction);
441
442         if ($role->system_name === 'admin') {
443             return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
444         }
445
446         if ($entity->restricted) {
447             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
448             return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
449         }
450
451         if ($entity->isA('book') || $entity->isA('bookshelf')) {
452             return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
453         }
454
455         // For chapters and pages, Check if explicit permissions are set on the Book.
456         $book = $this->getBook($entity->book_id);
457         $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
458         $hasPermissiveAccessToParents = !$book->restricted;
459
460         // For pages with a chapter, Check if explicit permissions are set on the Chapter
461         if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
462             $chapter = $this->getChapter($entity->chapter_id);
463             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
464             if ($chapter->restricted) {
465                 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
466             }
467         }
468
469         return $this->createJointPermissionDataArray(
470             $entity,
471             $role,
472             $action,
473             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
474             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
475         );
476     }
477
478     /**
479      * Check for an active restriction in an entity map.
480      * @param $entityMap
481      * @param Entity $entity
482      * @param Role $role
483      * @param $action
484      * @return bool
485      */
486     protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
487     {
488         $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
489         return isset($entityMap[$key]) ? $entityMap[$key] : false;
490     }
491
492     /**
493      * Create an array of data with the information of an entity jointPermissions.
494      * Used to build data for bulk insertion.
495      * @param \BookStack\Entities\Models\Entity $entity
496      * @param Role $role
497      * @param $action
498      * @param $permissionAll
499      * @param $permissionOwn
500      * @return array
501      */
502     protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
503     {
504         return [
505             'role_id'            => $role->getRawAttribute('id'),
506             'entity_id'          => $entity->getRawAttribute('id'),
507             'entity_type'        => $entity->getMorphClass(),
508             'action'             => $action,
509             'has_permission'     => $permissionAll,
510             'has_permission_own' => $permissionOwn,
511             'created_by'         => $entity->getRawAttribute('created_by')
512         ];
513     }
514
515     /**
516      * Checks if an entity has a restriction set upon it.
517      * @param Ownable $ownable
518      * @param $permission
519      * @return bool
520      */
521     public function checkOwnableUserAccess(Ownable $ownable, $permission)
522     {
523         $explodedPermission = explode('-', $permission);
524
525         $baseQuery = $ownable->where('id', '=', $ownable->id);
526         $action = end($explodedPermission);
527         $this->currentAction = $action;
528
529         $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
530
531         // Handle non entity specific jointPermissions
532         if (in_array($explodedPermission[0], $nonJointPermissions)) {
533             $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
534             $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
535             $this->currentAction = 'view';
536             $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
537             return ($allPermission || ($isOwner && $ownPermission));
538         }
539
540         // Handle abnormal create jointPermissions
541         if ($action === 'create') {
542             $this->currentAction = $permission;
543         }
544
545         $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
546         $this->clean();
547         return $q;
548     }
549
550     /**
551      * Checks if a user has the given permission for any items in the system.
552      * Can be passed an entity instance to filter on a specific type.
553      * @param string $permission
554      * @param string $entityClass
555      * @return bool
556      */
557     public function checkUserHasPermissionOnAnything(string $permission, string $entityClass = null)
558     {
559         $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
560         $userId = $this->currentUser()->id;
561
562         $permissionQuery = $this->db->table('joint_permissions')
563             ->where('action', '=', $permission)
564             ->whereIn('role_id', $userRoleIds)
565             ->where(function ($query) use ($userId) {
566                 $query->where('has_permission', '=', 1)
567                     ->orWhere(function ($query2) use ($userId) {
568                         $query2->where('has_permission_own', '=', 1)
569                             ->where('created_by', '=', $userId);
570                     });
571             });
572
573         if (!is_null($entityClass)) {
574             $entityInstance = app()->make($entityClass);
575             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
576         }
577
578         $hasPermission = $permissionQuery->count() > 0;
579         $this->clean();
580         return $hasPermission;
581     }
582
583     /**
584      * Check if an entity has restrictions set on itself or its
585      * parent tree.
586      * @param \BookStack\Entities\Models\Entity $entity
587      * @param $action
588      * @return bool|mixed
589      */
590     public function checkIfRestrictionsSet(Entity $entity, $action)
591     {
592         $this->currentAction = $action;
593         if ($entity->isA('page')) {
594             return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
595         } elseif ($entity->isA('chapter')) {
596             return $entity->restricted || $entity->book->restricted;
597         } elseif ($entity->isA('book')) {
598             return $entity->restricted;
599         }
600     }
601
602     /**
603      * The general query filter to remove all entities
604      * that the current user does not have access to.
605      * @param $query
606      * @return mixed
607      */
608     protected function entityRestrictionQuery($query)
609     {
610         $q = $query->where(function ($parentQuery) {
611             $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
612                 $permissionQuery->whereIn('role_id', $this->getRoles())
613                     ->where('action', '=', $this->currentAction)
614                     ->where(function ($query) {
615                         $query->where('has_permission', '=', true)
616                             ->orWhere(function ($query) {
617                                 $query->where('has_permission_own', '=', true)
618                                     ->where('created_by', '=', $this->currentUser()->id);
619                             });
620                     });
621             });
622         });
623         $this->clean();
624         return $q;
625     }
626
627     /**
628      * Limited the given entity query so that the query will only
629      * return items that the user has permission for the given ability.
630      */
631     public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder
632     {
633         $this->clean();
634         return $query->where(function (Builder $parentQuery) use ($ability) {
635             $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) use ($ability) {
636                 $permissionQuery->whereIn('role_id', $this->getRoles())
637                     ->where('action', '=', $ability)
638                     ->where(function (Builder $query) {
639                         $query->where('has_permission', '=', true)
640                             ->orWhere(function (Builder $query) {
641                                 $query->where('has_permission_own', '=', true)
642                                     ->where('created_by', '=', $this->currentUser()->id);
643                             });
644                     });
645             });
646         });
647     }
648
649     /**
650      * Extend the given page query to ensure draft items are not visible
651      * unless created by the given user.
652      */
653     public function enforceDraftVisiblityOnQuery(Builder $query): Builder
654     {
655         return $query->where(function (Builder $query) {
656             $query->where('draft', '=', false)
657                 ->orWhere(function (Builder $query) {
658                     $query->where('draft', '=', true)
659                         ->where('created_by', '=', $this->currentUser()->id);
660                 });
661         });
662     }
663
664     /**
665      * Add restrictions for a generic entity
666      * @param string $entityType
667      * @param Builder|\BookStack\Entities\Models\Entity $query
668      * @param string $action
669      * @return Builder
670      */
671     public function enforceEntityRestrictions($entityType, $query, $action = 'view')
672     {
673         if (strtolower($entityType) === 'page') {
674             // Prevent drafts being visible to others.
675             $query = $query->where(function ($query) {
676                 $query->where('draft', '=', false)
677                     ->orWhere(function ($query) {
678                         $query->where('draft', '=', true)
679                             ->where('created_by', '=', $this->currentUser()->id);
680                     });
681             });
682         }
683
684         $this->currentAction = $action;
685         return $this->entityRestrictionQuery($query);
686     }
687
688     /**
689      * Filter items that have entities set as a polymorphic relation.
690      * @param $query
691      * @param string $tableName
692      * @param string $entityIdColumn
693      * @param string $entityTypeColumn
694      * @param string $action
695      * @return QueryBuilder
696      */
697     public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
698     {
699
700         $this->currentAction = $action;
701         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
702
703         $q = $query->where(function ($query) use ($tableDetails) {
704             $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
705                 $permissionQuery->select('id')->from('joint_permissions')
706                     ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
707                     ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
708                     ->where('action', '=', $this->currentAction)
709                     ->whereIn('role_id', $this->getRoles())
710                     ->where(function ($query) {
711                         $query->where('has_permission', '=', true)->orWhere(function ($query) {
712                             $query->where('has_permission_own', '=', true)
713                                 ->where('created_by', '=', $this->currentUser()->id);
714                         });
715                     });
716             });
717         });
718         $this->clean();
719         return $q;
720     }
721
722     /**
723      * Add conditions to a query to filter the selection to related entities
724      * where permissions are granted.
725      * @param $entityType
726      * @param $query
727      * @param $tableName
728      * @param $entityIdColumn
729      * @return mixed
730      */
731     public function filterRelatedEntity($entityType, $query, $tableName, $entityIdColumn)
732     {
733         $this->currentAction = 'view';
734         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
735
736         $pageMorphClass = $this->entityProvider->get($entityType)->getMorphClass();
737
738         $q = $query->where(function ($query) use ($tableDetails, $pageMorphClass) {
739             $query->where(function ($query) use (&$tableDetails, $pageMorphClass) {
740                 $query->whereExists(function ($permissionQuery) use (&$tableDetails, $pageMorphClass) {
741                     $permissionQuery->select('id')->from('joint_permissions')
742                         ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
743                         ->where('entity_type', '=', $pageMorphClass)
744                         ->where('action', '=', $this->currentAction)
745                         ->whereIn('role_id', $this->getRoles())
746                         ->where(function ($query) {
747                             $query->where('has_permission', '=', true)->orWhere(function ($query) {
748                                 $query->where('has_permission_own', '=', true)
749                                     ->where('created_by', '=', $this->currentUser()->id);
750                             });
751                         });
752                 });
753             })->orWhere($tableDetails['entityIdColumn'], '=', 0);
754         });
755
756         $this->clean();
757
758         return $q;
759     }
760
761     /**
762      * Get the current user
763      * @return \BookStack\Auth\User
764      */
765     private function currentUser()
766     {
767         if ($this->currentUserModel === false) {
768             $this->currentUserModel = user();
769         }
770
771         return $this->currentUserModel;
772     }
773
774     /**
775      * Clean the cached user elements.
776      */
777     private function clean()
778     {
779         $this->currentUserModel = false;
780         $this->userRoles = false;
781         $this->isAdminUser = null;
782     }
783 }