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