]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Controller.php
Refactored notification showing and global view data
[bookstack] / app / Http / Controllers / Controller.php
1 <?php
2
3 namespace BookStack\Http\Controllers;
4
5 use BookStack\Auth\User;
6 use BookStack\Ownable;
7 use Illuminate\Foundation\Bus\DispatchesJobs;
8 use Illuminate\Foundation\Validation\ValidatesRequests;
9 use Illuminate\Http\Exceptions\HttpResponseException;
10 use Illuminate\Http\Request;
11 use Illuminate\Routing\Controller as BaseController;
12
13 abstract class Controller extends BaseController
14 {
15     use DispatchesJobs, ValidatesRequests;
16
17     /**
18      * @var User static
19      */
20     protected $currentUser;
21
22     /**
23      * @var bool
24      */
25     protected $signedIn;
26
27     /**
28      * Controller constructor.
29      */
30     public function __construct()
31     {
32         $this->currentUser = user();
33         $this->signedIn = auth()->check();
34     }
35
36     /**
37      * Stops the application and shows a permission error if
38      * the application is in demo mode.
39      */
40     protected function preventAccessInDemoMode()
41     {
42         if (config('app.env') === 'demo') {
43             $this->showPermissionError();
44         }
45     }
46
47     /**
48      * Adds the page title into the view.
49      * @param $title
50      */
51     public function setPageTitle($title)
52     {
53         view()->share('pageTitle', $title);
54     }
55
56     /**
57      * On a permission error redirect to home and display.
58      * the error as a notification.
59      */
60     protected function showPermissionError()
61     {
62         if (request()->wantsJson()) {
63             $response = response()->json(['error' => trans('errors.permissionJson')], 403);
64         } else {
65             $response = redirect('/');
66             $this->showErrorNotification( trans('errors.permission'));
67         }
68
69         throw new HttpResponseException($response);
70     }
71
72     /**
73      * Checks for a permission.
74      * @param string $permissionName
75      * @return bool|\Illuminate\Http\RedirectResponse
76      */
77     protected function checkPermission($permissionName)
78     {
79         if (!user() || !user()->can($permissionName)) {
80             $this->showPermissionError();
81         }
82         return true;
83     }
84
85     /**
86      * Check the current user's permissions against an ownable item.
87      * @param $permission
88      * @param Ownable $ownable
89      * @return bool
90      */
91     protected function checkOwnablePermission($permission, Ownable $ownable)
92     {
93         if (userCan($permission, $ownable)) {
94             return true;
95         }
96         return $this->showPermissionError();
97     }
98
99     /**
100      * Check if a user has a permission or bypass if the callback is true.
101      * @param $permissionName
102      * @param $callback
103      * @return bool
104      */
105     protected function checkPermissionOr($permissionName, $callback)
106     {
107         $callbackResult = $callback();
108         if ($callbackResult === false) {
109             $this->checkPermission($permissionName);
110         }
111         return true;
112     }
113
114     /**
115      * Check if the current user has a permission or bypass if the provided user
116      * id matches the current user.
117      * @param string $permissionName
118      * @param int $userId
119      * @return bool
120      */
121     protected function checkPermissionOrCurrentUser(string $permissionName, int $userId)
122     {
123         return $this->checkPermissionOr($permissionName, function () use ($userId) {
124             return $userId === $this->currentUser->id;
125         });
126     }
127
128     /**
129      * Send back a json error message.
130      * @param string $messageText
131      * @param int $statusCode
132      * @return mixed
133      */
134     protected function jsonError($messageText = "", $statusCode = 500)
135     {
136         return response()->json(['message' => $messageText], $statusCode);
137     }
138
139     /**
140      * Create the response for when a request fails validation.
141      * @param  \Illuminate\Http\Request  $request
142      * @param  array  $errors
143      * @return \Symfony\Component\HttpFoundation\Response
144      */
145     protected function buildFailedValidationResponse(Request $request, array $errors)
146     {
147         if ($request->expectsJson()) {
148             return response()->json(['validation' => $errors], 422);
149         }
150
151         return redirect()->to($this->getRedirectUrl())
152             ->withInput($request->input())
153             ->withErrors($errors, $this->errorBag());
154     }
155
156     /**
157      * Create a response that forces a download in the browser.
158      * @param string $content
159      * @param string $fileName
160      * @return \Illuminate\Http\Response
161      */
162     protected function downloadResponse(string $content, string $fileName)
163     {
164         return response()->make($content, 200, [
165             'Content-Type'        => 'application/octet-stream',
166             'Content-Disposition' => 'attachment; filename="' . $fileName . '"'
167         ]);
168     }
169
170     /**
171      * Show a positive, successful notification to the user on next view load.
172      * @param string $message
173      */
174     protected function showSuccessNotification(string $message)
175     {
176         session()->flash('success', $message);
177     }
178
179     /**
180      * Show a warning notification to the user on next view load.
181      * @param string $message
182      */
183     protected function showWarningNotification(string $message)
184     {
185         session()->flash('warning', $message);
186     }
187
188     /**
189      * Show an error notification to the user on next view load.
190      * @param string $message
191      */
192     protected function showErrorNotification(string $message)
193     {
194         session()->flash('error', $message);
195     }
196 }