]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Controller.php
Merge branch 'feature/sort-shelf-books' of git://github.com/guillaumehanotel/BookStac...
[bookstack] / app / Http / Controllers / Controller.php
1 <?php
2
3 namespace BookStack\Http\Controllers;
4
5 use BookStack\Facades\Activity;
6 use BookStack\Interfaces\Loggable;
7 use BookStack\HasCreatorAndUpdater;
8 use BookStack\Model;
9 use Illuminate\Foundation\Bus\DispatchesJobs;
10 use Illuminate\Foundation\Validation\ValidatesRequests;
11 use Illuminate\Http\Exceptions\HttpResponseException;
12 use Illuminate\Http\JsonResponse;
13 use Illuminate\Http\Response;
14 use Illuminate\Routing\Controller as BaseController;
15
16 abstract class Controller extends BaseController
17 {
18     use DispatchesJobs, ValidatesRequests;
19
20     /**
21      * Check if the current user is signed in.
22      */
23     protected function isSignedIn(): bool
24     {
25         return auth()->check();
26     }
27
28     /**
29      * Stops the application and shows a permission error if
30      * the application is in demo mode.
31      */
32     protected function preventAccessInDemoMode()
33     {
34         if (config('app.env') === 'demo') {
35             $this->showPermissionError();
36         }
37     }
38
39     /**
40      * Adds the page title into the view.
41      */
42     public function setPageTitle(string $title)
43     {
44         view()->share('pageTitle', $title);
45     }
46
47     /**
48      * On a permission error redirect to home and display.
49      * the error as a notification.
50      */
51     protected function showPermissionError()
52     {
53         if (request()->wantsJson()) {
54             $response = response()->json(['error' => trans('errors.permissionJson')], 403);
55         } else {
56             $response = redirect('/');
57             $this->showErrorNotification(trans('errors.permission'));
58         }
59
60         throw new HttpResponseException($response);
61     }
62
63     /**
64      * Checks that the current user has the given permission otherwise throw an exception.
65      */
66     protected function checkPermission(string $permission): void
67     {
68         if (!user() || !user()->can($permission)) {
69             $this->showPermissionError();
70         }
71     }
72
73     /**
74      * Check the current user's permissions against an ownable item otherwise throw an exception.
75      */
76     protected function checkOwnablePermission(string $permission, Model $ownable): void
77     {
78         if (!userCan($permission, $ownable)) {
79             $this->showPermissionError();
80         }
81     }
82
83     /**
84      * Check if a user has a permission or bypass the permission
85      * check if the given callback resolves true.
86      */
87     protected function checkPermissionOr(string $permission, callable $callback): void
88     {
89         if ($callback() !== true) {
90             $this->checkPermission($permission);
91         }
92     }
93
94     /**
95      * Check if the current user has a permission or bypass if the provided user
96      * id matches the current user.
97      */
98     protected function checkPermissionOrCurrentUser(string $permission, int $userId): void
99     {
100         $this->checkPermissionOr($permission, function () use ($userId) {
101             return $userId === user()->id;
102         });
103     }
104
105     /**
106      * Send back a json error message.
107      */
108     protected function jsonError(string $messageText = "", int $statusCode = 500): JsonResponse
109     {
110         return response()->json(['message' => $messageText, 'status' => 'error'], $statusCode);
111     }
112
113     /**
114      * Create a response that forces a download in the browser.
115      */
116     protected function downloadResponse(string $content, string $fileName): Response
117     {
118         return response()->make($content, 200, [
119             'Content-Type'        => 'application/octet-stream',
120             'Content-Disposition' => 'attachment; filename="' . $fileName . '"'
121         ]);
122     }
123
124     /**
125      * Show a positive, successful notification to the user on next view load.
126      */
127     protected function showSuccessNotification(string $message): void
128     {
129         session()->flash('success', $message);
130     }
131
132     /**
133      * Show a warning notification to the user on next view load.
134      */
135     protected function showWarningNotification(string $message): void
136     {
137         session()->flash('warning', $message);
138     }
139
140     /**
141      * Show an error notification to the user on next view load.
142      */
143     protected function showErrorNotification(string $message): void
144     {
145         session()->flash('error', $message);
146     }
147
148     /**
149      * Log an activity in the system.
150      * @param string|Loggable
151      */
152     protected function logActivity(string $type, $detail = ''): void
153     {
154         Activity::add($type, $detail);
155     }
156
157     /**
158      * Get the validation rules for image files.
159      */
160     protected function getImageValidationRules(): string
161     {
162         return 'image_extension|mimes:jpeg,png,gif,webp';
163     }
164 }