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