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