]> BookStack Code Mirror - bookstack/blob - app/Services/PermissionService.php
Updated 404 test to not fail based on random long name
[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, EntityPermission $entityPermission, Role $role, Connection $db,
52         Bookshelf $bookshelf, Book $book, Chapter $chapter, Page $page
53     )
54     {
55         $this->db = $db;
56         $this->jointPermission = $jointPermission;
57         $this->entityPermission = $entityPermission;
58         $this->role = $role;
59         $this->bookshelf = $bookshelf;
60         $this->book = $book;
61         $this->chapter = $chapter;
62         $this->page = $page;
63     }
64
65     /**
66      * Set the database connection
67      * @param Connection $connection
68      */
69     public function setConnection(Connection $connection)
70     {
71         $this->db = $connection;
72     }
73
74     /**
75      * Prepare the local entity cache and ensure it's empty
76      * @param Entity[] $entities
77      */
78     protected function readyEntityCache($entities = [])
79     {
80         $this->entityCache = [];
81
82         foreach ($entities as $entity) {
83             $type = $entity->getType();
84             if (!isset($this->entityCache[$type])) {
85                 $this->entityCache[$type] = collect();
86             }
87             $this->entityCache[$type]->put($entity->id, $entity);
88         }
89     }
90
91     /**
92      * Get a book via ID, Checks local cache
93      * @param $bookId
94      * @return Book
95      */
96     protected function getBook($bookId)
97     {
98         if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
99             return $this->entityCache['book']->get($bookId);
100         }
101
102         $book = $this->book->find($bookId);
103         if ($book === null) {
104             $book = false;
105         }
106
107         return $book;
108     }
109
110     /**
111      * Get a chapter via ID, Checks local cache
112      * @param $chapterId
113      * @return Book
114      */
115     protected function getChapter($chapterId)
116     {
117         if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
118             return $this->entityCache['chapter']->get($chapterId);
119         }
120
121         $chapter = $this->chapter->find($chapterId);
122         if ($chapter === null) {
123             $chapter = false;
124         }
125
126         return $chapter;
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->bookshelf->newQuery()->select(['id', 'restricted', 'created_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->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
183             $query->select(['id', 'restricted', 'created_by', 'book_id']);
184         }, 'pages'  => function ($query) {
185             $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
186         }]);
187     }
188
189     /**
190      * @param Collection $shelves
191      * @param array $roles
192      * @param bool $deleteOld
193      * @throws \Throwable
194      */
195     protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
196     {
197         if ($deleteOld) {
198             $this->deleteManyJointPermissionsForEntities($shelves->all());
199         }
200         $this->createManyJointPermissions($shelves, $roles);
201     }
202
203     /**
204      * Build joint permissions for an array of books
205      * @param Collection $books
206      * @param array $roles
207      * @param bool $deleteOld
208      * @throws \Throwable
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 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->bookshelf->newQuery()->select(['id', 'restricted', 'created_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 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 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->isA('page') && $entity->chapter_id !== 0 && $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 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             'created_by'         => $entity->getRawAttribute('created_by')
511         ];
512     }
513
514     /**
515      * Checks if an entity has a restriction set upon it.
516      * @param Ownable $ownable
517      * @param $permission
518      * @return bool
519      */
520     public function checkOwnableUserAccess(Ownable $ownable, $permission)
521     {
522         $explodedPermission = explode('-', $permission);
523
524         $baseQuery = $ownable->where('id', '=', $ownable->id);
525         $action = end($explodedPermission);
526         $this->currentAction = $action;
527
528         $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
529
530         // Handle non entity specific jointPermissions
531         if (in_array($explodedPermission[0], $nonJointPermissions)) {
532             $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
533             $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
534             $this->currentAction = 'view';
535             $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
536             return ($allPermission || ($isOwner && $ownPermission));
537         }
538
539         // Handle abnormal create jointPermissions
540         if ($action === 'create') {
541             $this->currentAction = $permission;
542         }
543
544         $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
545         $this->clean();
546         return $q;
547     }
548
549     /**
550      * Check if an entity has restrictions set on itself or its
551      * parent tree.
552      * @param Entity $entity
553      * @param $action
554      * @return bool|mixed
555      */
556     public function checkIfRestrictionsSet(Entity $entity, $action)
557     {
558         $this->currentAction = $action;
559         if ($entity->isA('page')) {
560             return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
561         } elseif ($entity->isA('chapter')) {
562             return $entity->restricted || $entity->book->restricted;
563         } elseif ($entity->isA('book')) {
564             return $entity->restricted;
565         }
566     }
567
568     /**
569      * The general query filter to remove all entities
570      * that the current user does not have access to.
571      * @param $query
572      * @return mixed
573      */
574     protected function entityRestrictionQuery($query)
575     {
576         $q = $query->where(function ($parentQuery) {
577             $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
578                 $permissionQuery->whereIn('role_id', $this->getRoles())
579                     ->where('action', '=', $this->currentAction)
580                     ->where(function ($query) {
581                         $query->where('has_permission', '=', true)
582                             ->orWhere(function ($query) {
583                                 $query->where('has_permission_own', '=', true)
584                                     ->where('created_by', '=', $this->currentUser()->id);
585                             });
586                     });
587             });
588         });
589         $this->clean();
590         return $q;
591     }
592
593     /**
594      * Get the children of a book in an efficient single query, Filtered by the permission system.
595      * @param integer $book_id
596      * @param bool $filterDrafts
597      * @param bool $fetchPageContent
598      * @return QueryBuilder
599      */
600     public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
601     {
602         $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
603             $query->where('draft', '=', 0);
604             if (!$filterDrafts) {
605                 $query->orWhere(function ($query) {
606                     $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
607                 });
608             }
609         });
610         $chapterSelect = $this->db->table('chapters')->selectRaw($this->chapter->entityRawQuery())->where('book_id', '=', $book_id);
611         $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
612             ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
613
614         // Add joint permission filter
615         $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
616             ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
617             ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
618             ->where(function ($query) {
619                 $query->where('jp.has_permission', '=', 1)->orWhere(function ($query) {
620                     $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
621                 });
622             });
623         $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
624
625         $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
626         $this->clean();
627         return  $query;
628     }
629
630     /**
631      * Add restrictions for a generic entity
632      * @param string $entityType
633      * @param Builder|Entity $query
634      * @param string $action
635      * @return Builder
636      */
637     public function enforceEntityRestrictions($entityType, $query, $action = 'view')
638     {
639         if (strtolower($entityType) === 'page') {
640             // Prevent drafts being visible to others.
641             $query = $query->where(function ($query) {
642                 $query->where('draft', '=', false);
643                 if ($this->currentUser()) {
644                     $query->orWhere(function ($query) {
645                         $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
646                     });
647                 }
648             });
649         }
650
651         $this->currentAction = $action;
652         return $this->entityRestrictionQuery($query);
653     }
654
655     /**
656      * Filter items that have entities set as a polymorphic relation.
657      * @param $query
658      * @param string $tableName
659      * @param string $entityIdColumn
660      * @param string $entityTypeColumn
661      * @param string $action
662      * @return mixed
663      */
664     public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
665     {
666
667         $this->currentAction = $action;
668         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
669
670         $q = $query->where(function ($query) use ($tableDetails) {
671             $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
672                 $permissionQuery->select('id')->from('joint_permissions')
673                     ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
674                     ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
675                     ->where('action', '=', $this->currentAction)
676                     ->whereIn('role_id', $this->getRoles())
677                     ->where(function ($query) {
678                         $query->where('has_permission', '=', true)->orWhere(function ($query) {
679                             $query->where('has_permission_own', '=', true)
680                                 ->where('created_by', '=', $this->currentUser()->id);
681                         });
682                     });
683             });
684         });
685         $this->clean();
686         return $q;
687     }
688
689     /**
690      * Filters pages that are a direct relation to another item.
691      * @param $query
692      * @param $tableName
693      * @param $entityIdColumn
694      * @return mixed
695      */
696     public function filterRelatedPages($query, $tableName, $entityIdColumn)
697     {
698         $this->currentAction = 'view';
699         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
700
701         $q = $query->where(function ($query) use ($tableDetails) {
702             $query->where(function ($query) use (&$tableDetails) {
703                 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
704                     $permissionQuery->select('id')->from('joint_permissions')
705                         ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
706                         ->where('entity_type', '=', 'Bookstack\\Page')
707                         ->where('action', '=', $this->currentAction)
708                         ->whereIn('role_id', $this->getRoles())
709                         ->where(function ($query) {
710                             $query->where('has_permission', '=', true)->orWhere(function ($query) {
711                                 $query->where('has_permission_own', '=', true)
712                                     ->where('created_by', '=', $this->currentUser()->id);
713                             });
714                         });
715                 });
716             })->orWhere($tableDetails['entityIdColumn'], '=', 0);
717         });
718         $this->clean();
719         return $q;
720     }
721
722     /**
723      * Get the current user
724      * @return User
725      */
726     private function currentUser()
727     {
728         if ($this->currentUserModel === false) {
729             $this->currentUserModel = user();
730         }
731
732         return $this->currentUserModel;
733     }
734
735     /**
736      * Clean the cached user elements.
737      */
738     private function clean()
739     {
740         $this->currentUserModel = false;
741         $this->userRoles = false;
742         $this->isAdminUser = null;
743     }
744 }