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