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