xref: /webtrees/app/Http/Middleware/HandleExceptions.php (revision 4a213054c13c5caf2ed7b812a0d260527e167ef6)
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\NotSupportedException;
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    /** @var TreeService */
58    private $tree_service;
59
60    /**
61     * HandleExceptions constructor.
62     *
63     * @param TreeService $tree_service
64     */
65    public function __construct(TreeService $tree_service)
66    {
67        $this->tree_service = $tree_service;
68    }
69
70    /**
71     * @param ServerRequestInterface  $request
72     * @param RequestHandlerInterface $handler
73     *
74     * @return ResponseInterface
75     * @throws Throwable
76     */
77    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
78    {
79        // Fatal errors.  We may be out of memory, so do not create any variables.
80        register_shutdown_function(static function (): void {
81            if (error_get_last() !== null && error_get_last()['type'] & E_ERROR) {
82                // If PHP does not display the error, then we must display it.
83                if (ini_get('display_errors') !== '1') {
84                    echo error_get_last()['message'], '<br><br>', error_get_last()['file'] , ': ', error_get_last()['line'];
85                }
86            }
87        });
88
89        try {
90            return $handler->handle($request);
91        } catch (HttpException $exception) {
92            // The router added the tree attribute to the request, and we need it for the error response.
93            if (app()->has(ServerRequestInterface::class)) {
94                $request = app(ServerRequestInterface::class);
95            } else {
96                app()->instance(ServerRequestInterface::class, $request);
97            }
98
99            return $this->httpExceptionResponse($request, $exception);
100        } catch (NotSupportedException $exception) {
101            // The router added the tree attribute to the request, and we need it for the error response.
102            $request = app(ServerRequestInterface::class) ?? $request;
103
104            return $this->thirdPartyExceptionResponse($request, $exception);
105        } catch (Throwable $exception) {
106            // Exception thrown while buffering output?
107            while (ob_get_level() > 0) {
108                ob_end_clean();
109            }
110
111            // The Router middleware may have added a tree attribute to the request.
112            // This might be usable in the error page.
113            if (app()->has(ServerRequestInterface::class)) {
114                $request = app(ServerRequestInterface::class) ?? $request;
115            }
116
117            // Show the exception in a standard webtrees page (if we can).
118            try {
119                return $this->unhandledExceptionResponse($request, $exception);
120            } catch (Throwable $ignore) {
121                // That didn't work.  Try something else.
122            }
123
124            // Show the exception in a tree-less webtrees page (if we can).
125            try {
126                $request = $request->withAttribute('tree', null);
127
128                return $this->unhandledExceptionResponse($request, $exception);
129            } catch (Throwable $ignore) {
130                // That didn't work.  Try something else.
131            }
132
133            // Show the exception in an error page (if we can).
134            try {
135                $this->layout = 'layouts/error';
136
137                return $this->unhandledExceptionResponse($request, $exception);
138            } catch (Throwable $ignore) {
139                // That didn't work.  Try something else.
140            }
141
142            // Show a stack dump.
143            return response((string) $exception, StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
144        }
145    }
146
147    /**
148     * @param ServerRequestInterface $request
149     * @param HttpException          $exception
150     *
151     * @return ResponseInterface
152     */
153    private function httpExceptionResponse(ServerRequestInterface $request, HttpException $exception): ResponseInterface
154    {
155        $tree = $request->getAttribute('tree');
156
157        $default = Site::getPreference('DEFAULT_GEDCOM');
158        $tree = $tree ?? $this->tree_service->all()[$default] ?? $this->tree_service->all()->first();
159
160        $status_code = $exception->getCode();
161
162        // If this was a GET request, then we were probably fetching HTML to display, for
163        // example a chart or tab.
164        if (
165            $request->getHeaderLine('X-Requested-With') !== '' &&
166            $request->getMethod() === RequestMethodInterface::METHOD_GET
167        ) {
168            $this->layout = 'layouts/ajax';
169            $status_code = StatusCodeInterface::STATUS_OK;
170        }
171
172        return $this->viewResponse('components/alert-danger', [
173            'alert' => $exception->getMessage(),
174            'title' => $exception->getMessage(),
175            'tree'  => $tree,
176        ], $status_code);
177    }
178
179    /**
180     * @param ServerRequestInterface $request
181     * @param Throwable              $exception
182     *
183     * @return ResponseInterface
184     */
185    private function thirdPartyExceptionResponse(ServerRequestInterface $request, Throwable $exception): ResponseInterface
186    {
187        $tree = $request->getAttribute('tree');
188
189        $default = Site::getPreference('DEFAULT_GEDCOM');
190        $tree = $tree ?? $this->tree_service->all()[$default] ?? $this->tree_service->all()->first();
191
192        if ($request->getHeaderLine('X-Requested-With') !== '') {
193            $this->layout = 'layouts/ajax';
194        }
195
196        return $this->viewResponse('components/alert-danger', [
197            'alert' => $exception->getMessage(),
198            'title' => $exception->getMessage(),
199            'tree'  => $tree,
200        ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
201    }
202
203    /**
204     * @param ServerRequestInterface $request
205     * @param Throwable              $exception
206     *
207     * @return ResponseInterface
208     */
209    private function unhandledExceptionResponse(ServerRequestInterface $request, Throwable $exception): ResponseInterface
210    {
211        $this->layout = 'layouts/default';
212
213        // Create a stack dump for the exception
214        $base_path = dirname(__DIR__, 3);
215        $trace     = $exception->getMessage() . ' ' . $exception->getFile() . ':' . $exception->getLine() . PHP_EOL . $exception->getTraceAsString();
216        $trace     = str_replace($base_path, '…', $trace);
217        // User data may contain non UTF-8 characters.
218        $trace     = mb_convert_encoding($trace, 'UTF-8', 'UTF-8');
219        $trace     = e($trace);
220        $trace     = preg_replace('/^.*modules_v4.*$/m', '<b>$0</b>', $trace);
221
222        try {
223            Log::addErrorLog($trace);
224        } catch (Throwable $ignore) {
225            // Must have been a problem with the database.  Nothing we can do here.
226        }
227
228        if ($request->getHeaderLine('X-Requested-With') !== '') {
229            // If this was a GET request, then we were probably fetching HTML to display, for
230            // example a chart or tab.
231            if ($request->getMethod() === RequestMethodInterface::METHOD_GET) {
232                $status_code = StatusCodeInterface::STATUS_OK;
233            } else {
234                $status_code = StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR;
235            }
236
237            return response(view('components/alert-danger', ['alert' => $trace]), $status_code);
238        }
239
240        try {
241            // Try with a full header/menu
242            return $this->viewResponse('errors/unhandled-exception', [
243                'title'   => 'Error',
244                'error'   => $trace,
245                'request' => $request,
246                'tree'    => $request->getAttribute('tree'),
247            ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
248        } catch (Throwable $ignore) {
249            // Try with a minimal header/menu
250            return $this->viewResponse('errors/unhandled-exception', [
251                'title'   => 'Error',
252                'error'   => $trace,
253                'request' => $request,
254                'tree'    => null,
255            ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
256        }
257    }
258}
259