1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2023 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\Http\Exceptions\HttpException; 25use Fisharebest\Webtrees\Http\ViewResponseTrait; 26use Fisharebest\Webtrees\Log; 27use Fisharebest\Webtrees\Registry; 28use Fisharebest\Webtrees\Services\TreeService; 29use Fisharebest\Webtrees\Site; 30use Fisharebest\Webtrees\Validator; 31use League\Flysystem\FilesystemException; 32use Psr\Http\Message\ResponseInterface; 33use Psr\Http\Message\ServerRequestInterface; 34use Psr\Http\Server\MiddlewareInterface; 35use Psr\Http\Server\RequestHandlerInterface; 36use Throwable; 37 38use function dirname; 39use function error_get_last; 40use function ini_get; 41use function nl2br; 42use function ob_end_clean; 43use function ob_get_level; 44use function register_shutdown_function; 45use function response; 46use function str_replace; 47use function view; 48 49use const E_ERROR; 50use const PHP_EOL; 51 52/** 53 * Middleware to handle and render errors. 54 */ 55class HandleExceptions implements MiddlewareInterface, StatusCodeInterface 56{ 57 use ViewResponseTrait; 58 59 private TreeService $tree_service; 60 61 /** 62 * HandleExceptions constructor. 63 * 64 * @param TreeService $tree_service 65 */ 66 public function __construct(TreeService $tree_service) 67 { 68 $this->tree_service = $tree_service; 69 } 70 71 /** 72 * @param ServerRequestInterface $request 73 * @param RequestHandlerInterface $handler 74 * 75 * @return ResponseInterface 76 * @throws Throwable 77 */ 78 public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface 79 { 80 // Fatal errors. We may be out of memory, so do not create any variables. 81 register_shutdown_function(static function (): void { 82 if (error_get_last() !== null && error_get_last()['type'] & E_ERROR) { 83 // If PHP does not display the error, then we must display it. 84 if (ini_get('display_errors') !== '1') { 85 echo error_get_last()['message'], '<br><br>', error_get_last()['file'], ': ', error_get_last()['line']; 86 } 87 } 88 }); 89 90 try { 91 return $handler->handle($request); 92 } catch (HttpException $exception) { 93 // The router added the tree attribute to the request, and we need it for the error response. 94 if (Registry::container()->has(ServerRequestInterface::class)) { 95 $request = Registry::container()->get(ServerRequestInterface::class); 96 } else { 97 Registry::container()->set(ServerRequestInterface::class, $request); 98 } 99 100 return $this->httpExceptionResponse($request, $exception); 101 } catch (FilesystemException $exception) { 102 // The router added the tree attribute to the request, and we need it for the error response. 103 $request = Registry::container()->get(ServerRequestInterface::class) ?? $request; 104 105 return $this->thirdPartyExceptionResponse($request, $exception); 106 } catch (Throwable $exception) { 107 // Exception thrown while buffering output? 108 while (ob_get_level() > 0) { 109 ob_end_clean(); 110 } 111 112 // The Router middleware may have added a tree attribute to the request. 113 // This might be usable in the error page. 114 if (Registry::container()->has(ServerRequestInterface::class)) { 115 $request = Registry::container()->get(ServerRequestInterface::class); 116 } 117 118 // Show the exception in a standard webtrees page (if we can). 119 try { 120 return $this->unhandledExceptionResponse($request, $exception); 121 } catch (Throwable) { 122 // That didn't work. Try something else. 123 } 124 125 // Show the exception in a tree-less webtrees page (if we can). 126 try { 127 $request = $request->withAttribute('tree', null); 128 129 return $this->unhandledExceptionResponse($request, $exception); 130 } catch (Throwable) { 131 // That didn't work. Try something else. 132 } 133 134 // Show the exception in an error page (if we can). 135 try { 136 $this->layout = 'layouts/error'; 137 138 return $this->unhandledExceptionResponse($request, $exception); 139 } catch (Throwable) { 140 // That didn't work. Try something else. 141 } 142 143 // Show a stack dump. 144 return response(nl2br((string) $exception), StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR); 145 } 146 } 147 148 /** 149 * @param ServerRequestInterface $request 150 * @param HttpException $exception 151 * 152 * @return ResponseInterface 153 */ 154 private function httpExceptionResponse(ServerRequestInterface $request, HttpException $exception): ResponseInterface 155 { 156 $tree = Validator::attributes($request)->treeOptional(); 157 $default = Site::getPreference('DEFAULT_GEDCOM'); 158 $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 = Validator::attributes($request)->treeOptional(); 188 189 $default = Site::getPreference('DEFAULT_GEDCOM'); 190 $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) { 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' => Validator::attributes($request)->treeOptional(), 247 ], StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR); 248 } catch (Throwable) { 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