]> BookStack Code Mirror - bookstack/blob - app/App/helpers.php
Search: Added pagination, updated other search uses
[bookstack] / app / App / helpers.php
1 <?php
2
3 use BookStack\App\AppVersion;
4 use BookStack\App\Model;
5 use BookStack\Facades\Theme;
6 use BookStack\Permissions\Permission;
7 use BookStack\Permissions\PermissionApplicator;
8 use BookStack\Settings\SettingService;
9 use BookStack\Users\Models\User;
10
11 /**
12  * Get the path to a versioned file.
13  *
14  * @throws Exception
15  */
16 function versioned_asset(string $file = ''): string
17 {
18     $version = AppVersion::get();
19
20     $additional = '';
21     if (config('app.env') === 'development') {
22         $additional = sha1_file(public_path($file));
23     }
24
25     $path = $file . '?version=' . urlencode($version) . $additional;
26
27     return url($path);
28 }
29
30 /**
31  * Helper method to get the current User.
32  * Defaults to public 'Guest' user if not logged in.
33  */
34 function user(): User
35 {
36     return auth()->user() ?: User::getGuest();
37 }
38
39 /**
40  * Check if the current user has a permission. If an ownable element
41  * is passed in the jointPermissions are checked against that particular item.
42  */
43 function userCan(string|Permission $permission, ?Model $ownable = null): bool
44 {
45     if (is_null($ownable)) {
46         return user()->can($permission);
47     }
48
49     // Check permission on ownable item
50     $permissions = app()->make(PermissionApplicator::class);
51
52     return $permissions->checkOwnableUserAccess($ownable, $permission);
53 }
54
55 /**
56  * Check if the current user can perform the given action on any items in the system.
57  * Can be provided the class name of an entity to filter ability to that specific entity type.
58  */
59 function userCanOnAny(string|Permission $action, string $entityClass = ''): bool
60 {
61     $permissions = app()->make(PermissionApplicator::class);
62
63     return $permissions->checkUserHasEntityPermissionOnAny($action, $entityClass);
64 }
65
66 /**
67  * Helper to access system settings.
68  *
69  * @return mixed|SettingService
70  */
71 function setting(?string $key = null, mixed $default = null): mixed
72 {
73     $settingService = app()->make(SettingService::class);
74
75     if (is_null($key)) {
76         return $settingService;
77     }
78
79     return $settingService->get($key, $default);
80 }
81
82 /**
83  * Get a path to a theme resource.
84  * Returns null if a theme is not configured and
85  * therefore a full path is not available for use.
86  */
87 function theme_path(string $path = ''): ?string
88 {
89     $theme = Theme::getTheme();
90     if (!$theme) {
91         return null;
92     }
93
94     return base_path('themes/' . $theme . ($path ? DIRECTORY_SEPARATOR . $path : $path));
95 }