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 */ 17declare(strict_types=1); 18 19namespace Fisharebest\Webtrees\Http\Middleware; 20 21use Fig\Http\Message\RequestMethodInterface; 22use Fisharebest\Webtrees\Auth; 23use Fisharebest\Webtrees\Http\ViewResponseTrait; 24use Fisharebest\Webtrees\Site; 25use Fisharebest\Webtrees\Tree; 26use Fisharebest\Webtrees\User; 27use Psr\Http\Message\ResponseInterface; 28use Psr\Http\Message\ServerRequestInterface; 29use Psr\Http\Server\MiddlewareInterface; 30use Psr\Http\Server\RequestHandlerInterface; 31use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; 32 33use function redirect; 34use function route; 35 36/** 37 * Middleware to generate a response when no route was matched. 38 */ 39class NoRouteFound implements MiddlewareInterface, RequestMethodInterface 40{ 41 use ViewResponseTrait; 42 43 /** 44 * @param ServerRequestInterface $request 45 * @param RequestHandlerInterface $handler 46 * 47 * @return ResponseInterface 48 */ 49 public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface 50 { 51 if ($request->getMethod() !== self::METHOD_GET) { 52 throw new NotFoundHttpException(); 53 } 54 55 $user = $request->getAttribute('user'); 56 57 // Choose the default tree (if it exists), or the first tree found. 58 $default = Site::getPreference('DEFAULT_GEDCOM'); 59 $tree = Tree::findByName($default) ?? Tree::all()->first(); 60 61 if ($tree instanceof Tree) { 62 if ($tree->getPreference('imported') === '1') { 63 // Logged in? Go to the user's page. 64 if ($user instanceof User) { 65 return redirect(route('user-page', ['tree' => $tree->name()])); 66 } 67 68 // Not logged in? Go to the tree's page. 69 return redirect(route('tree-page', ['ged' => $tree->name()])); 70 } 71 72 return redirect(route('admin-trees', ['ged' => $tree->name()])); 73 } 74 75 // No tree available? Create one. 76 if (Auth::isAdmin($user)) { 77 return redirect(route('admin-trees')); 78 } 79 80 // Logged in, but no access to any tree. 81 if ($user instanceof User) { 82 return $this->viewResponse('errors/no-tree-access', ['title' => '']); 83 } 84 85 // Not logged in. 86 return redirect(route('login', ['url' => $request->getAttribute('request_uri')])); 87 } 88} 89