]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Controller.php
Merge branch 'master' into 2019-design
[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      * @var bool
23      */
24     protected $signedIn;
25
26     /**
27      * Controller constructor.
28      */
29     public function __construct()
30     {
31         $this->middleware(function ($request, $next) {
32
33             // Get a user instance for the current user
34             $user = user();
35
36             // Share variables with controllers
37             $this->currentUser = $user;
38             $this->signedIn = auth()->check();
39
40             // Share variables with views
41             view()->share('signedIn', $this->signedIn);
42             view()->share('currentUser', $user);
43
44             return $next($request);
45         });
46     }
47
48     /**
49      * Stops the application and shows a permission error if
50      * the application is in demo mode.
51      */
52     protected function preventAccessForDemoUsers()
53     {
54         if (config('app.env') === 'demo') {
55             $this->showPermissionError();
56         }
57     }
58
59     /**
60      * Adds the page title into the view.
61      * @param $title
62      */
63     public function setPageTitle($title)
64     {
65         view()->share('pageTitle', $title);
66     }
67
68     /**
69      * On a permission error redirect to home and display.
70      * the error as a notification.
71      */
72     protected function showPermissionError()
73     {
74         if (request()->wantsJson()) {
75             $response = response()->json(['error' => trans('errors.permissionJson')], 403);
76         } else {
77             $response = redirect('/');
78             session()->flash('error', trans('errors.permission'));
79         }
80
81         throw new HttpResponseException($response);
82     }
83
84     /**
85      * Checks for a permission.
86      * @param string $permissionName
87      * @return bool|\Illuminate\Http\RedirectResponse
88      */
89     protected function checkPermission($permissionName)
90     {
91         if (!user() || !user()->can($permissionName)) {
92             $this->showPermissionError();
93         }
94         return true;
95     }
96
97     /**
98      * Check the current user's permissions against an ownable item.
99      * @param $permission
100      * @param Ownable $ownable
101      * @return bool
102      */
103     protected function checkOwnablePermission($permission, Ownable $ownable)
104     {
105         if (userCan($permission, $ownable)) {
106             return true;
107         }
108         return $this->showPermissionError();
109     }
110
111     /**
112      * Check if a user has a permission or bypass if the callback is true.
113      * @param $permissionName
114      * @param $callback
115      * @return bool
116      */
117     protected function checkPermissionOr($permissionName, $callback)
118     {
119         $callbackResult = $callback();
120         if ($callbackResult === false) {
121             $this->checkPermission($permissionName);
122         }
123         return true;
124     }
125
126     /**
127      * Check if the current user has a permission or bypass if the provided user
128      * id matches the current user.
129      * @param string $permissionName
130      * @param int $userId
131      * @return bool
132      */
133     protected function checkPermissionOrCurrentUser(string $permissionName, int $userId)
134     {
135         return $this->checkPermissionOr($permissionName, function() use ($userId) {
136             return $userId === $this->currentUser->id;
137         });
138     }
139
140     /**
141      * Send back a json error message.
142      * @param string $messageText
143      * @param int $statusCode
144      * @return mixed
145      */
146     protected function jsonError($messageText = "", $statusCode = 500)
147     {
148         return response()->json(['message' => $messageText], $statusCode);
149     }
150
151     /**
152      * Create the response for when a request fails validation.
153      * @param  \Illuminate\Http\Request  $request
154      * @param  array  $errors
155      * @return \Symfony\Component\HttpFoundation\Response
156      */
157     protected function buildFailedValidationResponse(Request $request, array $errors)
158     {
159         if ($request->expectsJson()) {
160             return response()->json(['validation' => $errors], 422);
161         }
162
163         return redirect()->to($this->getRedirectUrl())
164             ->withInput($request->input())
165             ->withErrors($errors, $this->errorBag());
166     }
167
168     /**
169      * Create a response that forces a download in the browser.
170      * @param string $content
171      * @param string $fileName
172      * @return \Illuminate\Http\Response
173      */
174     protected function downloadResponse(string $content, string $fileName)
175     {
176         return response()->make($content, 200, [
177             'Content-Type'        => 'application/octet-stream',
178             'Content-Disposition' => 'attachment; filename="' . $fileName . '"'
179         ]);
180     }
181 }