]> BookStack Code Mirror - bookstack/blob - app/helpers.php
Added restriction tests and fixed any bugs in the process
[bookstack] / app / helpers.php
1 <?php
2
3 if (!function_exists('versioned_asset')) {
4     /**
5      * Get the path to a versioned file.
6      *
7      * @param  string $file
8      * @return string
9      *
10      * @throws \InvalidArgumentException
11      */
12     function versioned_asset($file)
13     {
14         static $manifest = null;
15
16         if (is_null($manifest)) {
17             $manifest = json_decode(file_get_contents(public_path('build/manifest.json')), true);
18         }
19
20         if (isset($manifest[$file])) {
21             return '/' . $manifest[$file];
22         }
23
24         if (file_exists(public_path($file))) {
25             return '/' . $file;
26         }
27
28         throw new InvalidArgumentException("File {$file} not defined in asset manifest.");
29     }
30 }
31
32 /**
33  * Check if the current user has a permission.
34  * If an ownable element is passed in the permissions are checked against
35  * that particular item.
36  * @param $permission
37  * @param \BookStack\Ownable $ownable
38  * @return mixed
39  */
40 function userCan($permission, \BookStack\Ownable $ownable = null)
41 {
42     if (!auth()->check()) return false;
43     if ($ownable === null) {
44         return auth()->user() && auth()->user()->can($permission);
45     }
46
47     // Check permission on ownable item
48     $permissionBaseName = strtolower($permission) . '-';
49     $hasPermission = false;
50     if (auth()->user()->can($permissionBaseName . 'all')) $hasPermission = true;
51     if (auth()->user()->can($permissionBaseName . 'own') && $ownable->createdBy && $ownable->createdBy->id === auth()->user()->id) $hasPermission = true;
52
53     if (!$ownable instanceof \BookStack\Entity) return $hasPermission;
54
55     // Check restrictions on the entitiy
56     $restrictionService = app('BookStack\Services\RestrictionService');
57     $explodedPermission = explode('-', $permission);
58     $action = end($explodedPermission);
59     $hasAccess = $restrictionService->checkIfEntityRestricted($ownable, $action);
60     return $hasAccess && $hasPermission;
61 }