3 namespace BookStack\Http\Controllers;
5 use BookStack\Exceptions\NotifyException;
6 use BookStack\Facades\Activity;
7 use BookStack\Interfaces\Loggable;
9 use BookStack\Util\WebSafeMimeSniffer;
10 use Illuminate\Foundation\Bus\DispatchesJobs;
11 use Illuminate\Foundation\Validation\ValidatesRequests;
12 use Illuminate\Http\JsonResponse;
13 use Illuminate\Http\Response;
14 use Illuminate\Routing\Controller as BaseController;
15 use Symfony\Component\HttpFoundation\StreamedResponse;
17 abstract class Controller extends BaseController
20 use ValidatesRequests;
23 * Check if the current user is signed in.
25 protected function isSignedIn(): bool
27 return auth()->check();
31 * Stops the application and shows a permission error if
32 * the application is in demo mode.
34 protected function preventAccessInDemoMode()
36 if (config('app.env') === 'demo') {
37 $this->showPermissionError();
42 * Adds the page title into the view.
44 public function setPageTitle(string $title)
46 view()->share('pageTitle', $title);
50 * On a permission error redirect to home and display.
51 * the error as a notification.
55 protected function showPermissionError()
57 $message = request()->wantsJson() ? trans('errors.permissionJson') : trans('errors.permission');
59 throw new NotifyException($message, '/', 403);
63 * Checks that the current user has the given permission otherwise throw an exception.
65 protected function checkPermission(string $permission): void
67 if (!user() || !user()->can($permission)) {
68 $this->showPermissionError();
73 * Check the current user's permissions against an ownable item otherwise throw an exception.
75 protected function checkOwnablePermission(string $permission, Model $ownable): void
77 if (!userCan($permission, $ownable)) {
78 $this->showPermissionError();
83 * Check if a user has a permission or bypass the permission
84 * check if the given callback resolves true.
86 protected function checkPermissionOr(string $permission, callable $callback): void
88 if ($callback() !== true) {
89 $this->checkPermission($permission);
94 * Check if the current user has a permission or bypass if the provided user
95 * id matches the current user.
97 protected function checkPermissionOrCurrentUser(string $permission, int $userId): void
99 $this->checkPermissionOr($permission, function () use ($userId) {
100 return $userId === user()->id;
105 * Send back a json error message.
107 protected function jsonError(string $messageText = '', int $statusCode = 500): JsonResponse
109 return response()->json(['message' => $messageText, 'status' => 'error'], $statusCode);
113 * Create a response that forces a download in the browser.
115 protected function downloadResponse(string $content, string $fileName): Response
117 return response()->make($content, 200, [
118 'Content-Type' => 'application/octet-stream',
119 'Content-Disposition' => 'attachment; filename="' . str_replace('"', '', $fileName) . '"',
120 'X-Content-Type-Options' => 'nosniff',
125 * Create a response that forces a download, from a given stream of content.
127 protected function streamedDownloadResponse($stream, string $fileName): StreamedResponse
129 return response()->stream(function () use ($stream) {
131 // End & flush the output buffer, if we're in one, otherwise we still use memory.
132 // Output buffer may or may not exist depending on PHP `output_buffering` setting.
133 // Ignore in testing since output buffers are used to gather a response.
134 if (!empty(ob_get_status()) && !app()->runningUnitTests()) {
141 'Content-Type' => 'application/octet-stream',
142 'Content-Disposition' => 'attachment; filename="' . str_replace('"', '', $fileName) . '"',
143 'X-Content-Type-Options' => 'nosniff',
148 * Create a file download response that provides the file with a content-type
149 * correct for the file, in a way so the browser can show the content in browser.
151 protected function inlineDownloadResponse(string $content, string $fileName): Response
153 $mime = (new WebSafeMimeSniffer())->sniff($content);
155 return response()->make($content, 200, [
156 'Content-Type' => $mime,
157 'Content-Disposition' => 'inline; filename="' . str_replace('"', '', $fileName) . '"',
158 'X-Content-Type-Options' => 'nosniff',
163 * Create a file download response that provides the file with a content-type
164 * correct for the file, in a way so the browser can show the content in browser,
165 * for a given content stream.
167 protected function streamedInlineDownloadResponse($stream, string $fileName): StreamedResponse
169 $sniffContent = fread($stream, 1000);
170 $mime = (new WebSafeMimeSniffer())->sniff($sniffContent);
172 return response()->stream(function () use ($sniffContent, $stream) {
177 'Content-Type' => $mime,
178 'Content-Disposition' => 'inline; filename="' . str_replace('"', '', $fileName) . '"',
179 'X-Content-Type-Options' => 'nosniff',
184 * Show a positive, successful notification to the user on next view load.
186 protected function showSuccessNotification(string $message): void
188 session()->flash('success', $message);
192 * Show a warning notification to the user on next view load.
194 protected function showWarningNotification(string $message): void
196 session()->flash('warning', $message);
200 * Show an error notification to the user on next view load.
202 protected function showErrorNotification(string $message): void
204 session()->flash('error', $message);
208 * Log an activity in the system.
210 * @param string|Loggable $detail
212 protected function logActivity(string $type, $detail = ''): void
214 Activity::add($type, $detail);
218 * Get the validation rules for image files.
220 protected function getImageValidationRules(): array
222 return ['image_extension', 'mimes:jpeg,png,gif,webp,svg', 'max:' . (config('app.upload_limit') * 1000)];