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