xref: /webtrees/app/Http/Middleware/HandleExceptions.php (revision 3d9e70a53ebdea3db408ada1769711840cc7d14c)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\Middleware;
21
22use Fig\Http\Message\RequestMethodInterface;
23use Fig\Http\Message\StatusCodeInterface;
24use Fisharebest\Webtrees\Exceptions\HttpException;
25use Fisharebest\Webtrees\Http\ViewResponseTrait;
26use Fisharebest\Webtrees\Log;
27use Fisharebest\Webtrees\Services\TreeService;
28use Fisharebest\Webtrees\Site;
29use League\Flysystem\FilesystemException;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use Psr\Http\Server\MiddlewareInterface;
33use Psr\Http\Server\RequestHandlerInterface;
34use Throwable;
35
36use function app;
37use function dirname;
38use function error_get_last;
39use function ini_get;
40use function ob_end_clean;
41use function ob_get_level;
42use function register_shutdown_function;
43use function response;
44use function str_replace;
45use function view;
46
47use const E_ERROR;
48use const PHP_EOL;
49
50/**
51 * Middleware to handle and render errors.
52 */
53class HandleExceptions implements MiddlewareInterface, StatusCodeInterface
54{
55    use ViewResponseTrait;
56
57    private TreeService $tree_service;
58
59    /**
60     * HandleExceptions constructor.
61     *
62     * @param TreeService $tree_service
63     */
64    public function __construct(TreeService $tree_service)
65    {
66        $this->tree_service = $tree_service;
67    }
68
69    /**
70     * @param ServerRequestInterface  $request
71     * @param RequestHandlerInterface $handler
72     *
73     * @return ResponseInterface
74     * @throws Throwable
75     */
76    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
77    {
78        // Fatal errors.  We may be out of memory, so do not create any variables.
79        register_shutdown_function(static function (): void {
80            if (error_get_last() !== null && error_get_last()['type'] & E_ERROR) {
81                // If PHP does not display the error, then we must display it.
82                if (ini_get('display_errors') !== '1') {
83                    echo error_get_last()['message'], '<br><br>', error_get_last()['file'] , ': ', error_get_last()['line'];
84                }
85            }
86        });
87
88        try {
89            return $handler->handle($request);
90        } catch (HttpException $exception) {
91            // The router added the tree attribute to the request, and we need it for the error response.
92            if (app()->has(ServerRequestInterface::class)) {
93                $request = app(ServerRequestInterface::class);
94            } else {
95                app()->instance(ServerRequestInterface::class, $request);
96            }
97
98            return $this->httpExceptionResponse($request, $exception);
99        } catch (FilesystemException $exception) {
100            // The router added the tree attribute to the request, and we need it for the error response.
101            $request = app(ServerRequestInterface::class) ?? $request;
102
103            return $this->thirdPartyExceptionResponse($request, $exception);
104        } catch (Throwable $exception) {
105            // Exception thrown while buffering output?
106            while (ob_get_level() > 0) {
107                ob_end_clean();
108            }
109
110            // The Router middleware may have added a tree attribute to the request.
111            // This might be usable in the error page.
112            if (app()->has(ServerRequestInterface::class)) {
113                $request = app(ServerRequestInterface::class) ?? $request;
114            }
115
116            // Show the exception in a standard webtrees page (if we can).
117            try {
118                return $this->unhandledExceptionResponse($request, $exception);
119            } catch (Throwable $ignore) {
120                // That didn't work.  Try something else.
121            }
122
123            // Show the exception in a tree-less webtrees page (if we can).
124            try {
125                $request = $request->withAttribute('tree', null);
126
127                return $this->unhandledExceptionResponse($request, $exception);
128            } catch (Throwable $ignore) {
129                // That didn't work.  Try something else.
130            }
131
132            // Show the exception in an error page (if we can).
133            try {
134                $this->layout = 'layouts/error';
135
136                return $this->unhandledExceptionResponse($request, $exception);
137            } catch (Throwable $ignore) {
138                // That didn't work.  Try something else.
139            }
140
141            // Show a stack dump.
142            return response((string) $exception, StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
143        }
144    }
145
146    /**
147     * @param ServerRequestInterface $request
148     * @param HttpException          $exception
149     *
150     * @return ResponseInterface
151     */
152    private function httpExceptionResponse(ServerRequestInterface $request, HttpException $exception): ResponseInterface
153    {
154        $tree = $request->getAttribute('tree');
155
156        $default = Site::getPreference('DEFAULT_GEDCOM');
157        $tree = $tree ?? $this->tree_service->all()[$default] ?? $this->tree_service->all()->first();
158
159        $status_code = $exception->getCode();
160
161        // If this was a GET request, then we were probably fetching HTML to display, for
162        // example a chart or tab.
163        if (
164            $request->getHeaderLine('X-Requested-With') !== '' &&
165            $request->getMethod() === RequestMethodInterface::METHOD_GET
166        ) {
167            $this->layout = 'layouts/ajax';
168            $status_code = StatusCodeInterface::STATUS_OK;
169        }
170
171        return $this->viewResponse('components/alert-danger', [
172            'alert' => $exception->getMessage(),
173            'title' => $exception->getMessage(),
174            'tree'  => $tree,
175        ], $status_code);
176    }
177
178    /**
179     * @param ServerRequestInterface $request
180     * @param Throwable              $exception
181     *
182     * @return ResponseInterface
183     */
184    private function thirdPartyExceptionResponse(ServerRequestInterface $request, Throwable $exception): ResponseInterface
185    {
186        $tree = $request->getAttribute('tree');
187
188        $default = Site::getPreference('DEFAULT_GEDCOM');
189        $tree = $tree ?? $this->tree_service->all()[$default] ?? $this->tree_service->all()->first();
190
191        if ($request->getHeaderLine('X-Requested-With') !== '') {
192            $this->layout = 'layouts/ajax';
193        }
194
195        return $this->viewResponse('components/alert-danger', [
196            'alert' => $exception->getMessage(),
197            'title' => $exception->getMessage(),
198            'tree'  => $tree,
199        ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
200    }
201
202    /**
203     * @param ServerRequestInterface $request
204     * @param Throwable              $exception
205     *
206     * @return ResponseInterface
207     */
208    private function unhandledExceptionResponse(ServerRequestInterface $request, Throwable $exception): ResponseInterface
209    {
210        $this->layout = 'layouts/default';
211
212        // Create a stack dump for the exception
213        $base_path = dirname(__DIR__, 3);
214        $trace     = $exception->getMessage() . ' ' . $exception->getFile() . ':' . $exception->getLine() . PHP_EOL . $exception->getTraceAsString();
215        $trace     = str_replace($base_path, '…', $trace);
216        // User data may contain non UTF-8 characters.
217        $trace     = mb_convert_encoding($trace, 'UTF-8', 'UTF-8');
218        $trace     = e($trace);
219        $trace     = preg_replace('/^.*modules_v4.*$/m', '<b>$0</b>', $trace);
220
221        try {
222            Log::addErrorLog($trace);
223        } catch (Throwable $ignore) {
224            // Must have been a problem with the database.  Nothing we can do here.
225        }
226
227        if ($request->getHeaderLine('X-Requested-With') !== '') {
228            // If this was a GET request, then we were probably fetching HTML to display, for
229            // example a chart or tab.
230            if ($request->getMethod() === RequestMethodInterface::METHOD_GET) {
231                $status_code = StatusCodeInterface::STATUS_OK;
232            } else {
233                $status_code = StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR;
234            }
235
236            return response(view('components/alert-danger', ['alert' => $trace]), $status_code);
237        }
238
239        try {
240            // Try with a full header/menu
241            return $this->viewResponse('errors/unhandled-exception', [
242                'title'   => 'Error',
243                'error'   => $trace,
244                'request' => $request,
245                'tree'    => $request->getAttribute('tree'),
246            ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
247        } catch (Throwable $ignore) {
248            // Try with a minimal header/menu
249            return $this->viewResponse('errors/unhandled-exception', [
250                'title'   => 'Error',
251                'error'   => $trace,
252                'request' => $request,
253                'tree'    => null,
254            ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
255        }
256    }
257}
258