xref: /webtrees/app/Http/Middleware/HandleExceptions.php (revision 00e28091d5dbdf816443155193c9fd33a0b3dd34)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://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\Localization\Locale\LocaleEnUs;
25use Fisharebest\Webtrees\Http\ViewResponseTrait;
26use Fisharebest\Webtrees\Log;
27use Fisharebest\Webtrees\Services\TreeService;
28use Fisharebest\Webtrees\Site;
29use Psr\Http\Message\ResponseInterface;
30use Psr\Http\Message\ServerRequestInterface;
31use Psr\Http\Server\MiddlewareInterface;
32use Psr\Http\Server\RequestHandlerInterface;
33use Symfony\Component\HttpKernel\Exception\HttpException;
34use Throwable;
35
36use function app;
37use function dirname;
38use function ob_end_clean;
39use function ob_get_level;
40use function response;
41use function str_replace;
42use function view;
43
44use const PHP_EOL;
45
46/**
47 * Middleware to handle and render errors.
48 */
49class HandleExceptions implements MiddlewareInterface, StatusCodeInterface
50{
51    use ViewResponseTrait;
52
53    /** @var TreeService */
54    private $tree_service;
55
56    /**
57     * HandleExceptions constructor.
58     *
59     * @param TreeService $tree_service
60     */
61    public function __construct(TreeService $tree_service)
62    {
63        $this->tree_service = $tree_service;
64    }
65
66    /**
67     * @param ServerRequestInterface  $request
68     * @param RequestHandlerInterface $handler
69     *
70     * @return ResponseInterface
71     * @throws Throwable
72     */
73    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
74    {
75        try {
76            return $handler->handle($request);
77        } catch (HttpException $exception) {
78            // The router added the tree attribute to the request, and we need it for the error response.
79            $request = app(ServerRequestInterface::class) ?? $request;
80
81            return $this->httpExceptionResponse($request, $exception);
82        } catch (Throwable $exception) {
83            // Exception thrown while buffering output?
84            while (ob_get_level() > 0) {
85                ob_end_clean();
86            }
87
88            // The Router middleware may have added a tree attribute to the request.
89            // This might be usable in the error page.
90            if (app()->has(ServerRequestInterface::class)) {
91                $request = app(ServerRequestInterface::class) ?? $request;
92            }
93
94            // No locale set in the request?
95            if ($request->getAttribute('locale') === null) {
96                $request = $request->withAttribute('locale', new LocaleEnUs());
97                app()->instance(ServerRequestInterface::class, $request);
98            }
99
100            // Show the exception in a standard webtrees page (if we can).
101            try {
102                return $this->unhandledExceptionResponse($request, $exception);
103            } catch (Throwable $e) {
104                // That didn't work.  Try something else.
105            }
106
107            // Show the exception in a tree-less webtrees page (if we can).
108            try {
109                $request = $request->withAttribute('tree', null);
110
111                return $this->unhandledExceptionResponse($request, $exception);
112            } catch (Throwable $e) {
113                // That didn't work.  Try something else.
114            }
115
116            // Show the exception in an error page (if we can).
117            try {
118                $this->layout = 'layouts/error';
119
120                return $this->unhandledExceptionResponse($request, $exception);
121            } catch (Throwable $e) {
122                // That didn't work.  Try something else.
123            }
124
125            // Show a stack dump.
126            return response((string) $exception, StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
127        }
128    }
129
130    /**
131     * @param ServerRequestInterface $request
132     * @param HttpException          $exception
133     *
134     * @return ResponseInterface
135     */
136    private function httpExceptionResponse(ServerRequestInterface $request, HttpException $exception): ResponseInterface
137    {
138        $tree = $request->getAttribute('tree');
139
140        $default = Site::getPreference('DEFAULT_GEDCOM');
141        $tree = $tree ?? $this->tree_service->all()[$default] ?? $this->tree_service->all()->first();
142
143        if ($request->getHeaderLine('X-Requested-With') !== '') {
144            $this->layout = 'layouts/ajax';
145        }
146
147        return $this->viewResponse('components/alert-danger', [
148            'alert' => $exception->getMessage(),
149            'title' => $exception->getMessage(),
150            'tree'  => $tree,
151        ], $exception->getStatusCode());
152    }
153
154    /**
155     * @param ServerRequestInterface $request
156     * @param Throwable              $exception
157     *
158     * @return ResponseInterface
159     */
160    private function unhandledExceptionResponse(ServerRequestInterface $request, Throwable $exception): ResponseInterface
161    {
162        $this->layout = 'layouts/default';
163
164        // Create a stack dump for the exception
165        $base_path = dirname(__DIR__, 3);
166        $trace     = $exception->getMessage() . ' ' . $exception->getFile() . ':' . $exception->getLine() . PHP_EOL . $exception->getTraceAsString();
167        $trace     = str_replace($base_path, '…', $trace);
168        $trace     = e($trace);
169        $trace     = preg_replace('/^.*modules_v4.*$/m', '<b>$0</b>', $trace);
170
171        try {
172            Log::addErrorLog($trace);
173        } catch (Throwable $exception) {
174            // Must have been a problem with the database.  Nothing we can do here.
175        }
176
177        if ($request->getHeaderLine('X-Requested-With') !== '') {
178            // If this was a GET request, then we were probably fetching HTML to display, for
179            // example a chart or tab.
180            if ($request->getMethod() === RequestMethodInterface::METHOD_GET) {
181                $status_code = StatusCodeInterface::STATUS_OK;
182            } else {
183                $status_code = StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR;
184            }
185
186            return response(view('components/alert-danger', ['alert' => $trace]), $status_code);
187        }
188
189        return $this->viewResponse('errors/unhandled-exception', [
190            'title'   => 'Error',
191            'error'   => $trace,
192            'request' => $request,
193            'tree'    => null,
194        ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR);
195    }
196}
197