xref: /webtrees/app/Http/Middleware/Router.php (revision 15c4f62c40de0c794536302daf7d5ec0548a1973)
19e5d8e6fSGreg Roach<?php
29e5d8e6fSGreg Roach
39e5d8e6fSGreg Roach/**
49e5d8e6fSGreg Roach * webtrees: online genealogy
5d11be702SGreg Roach * Copyright (C) 2023 webtrees development team
69e5d8e6fSGreg Roach * This program is free software: you can redistribute it and/or modify
79e5d8e6fSGreg Roach * it under the terms of the GNU General Public License as published by
89e5d8e6fSGreg Roach * the Free Software Foundation, either version 3 of the License, or
99e5d8e6fSGreg Roach * (at your option) any later version.
109e5d8e6fSGreg Roach * This program is distributed in the hope that it will be useful,
119e5d8e6fSGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
129e5d8e6fSGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
139e5d8e6fSGreg Roach * GNU General Public License for more details.
149e5d8e6fSGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
169e5d8e6fSGreg Roach */
17fcfa147eSGreg Roach
189e5d8e6fSGreg Roachdeclare(strict_types=1);
199e5d8e6fSGreg Roach
209e5d8e6fSGreg Roachnamespace Fisharebest\Webtrees\Http\Middleware;
219e5d8e6fSGreg Roach
22d8d90d88SGreg Roachuse Aura\Router\Route;
23ee4364daSGreg Roachuse Aura\Router\RouterContainer;
2464c83a78SGreg Roachuse Aura\Router\Rule\Accepts;
2564c83a78SGreg Roachuse Aura\Router\Rule\Allows;
2664c83a78SGreg Roachuse Fig\Http\Message\StatusCodeInterface;
27d8d90d88SGreg Roachuse Fisharebest\Webtrees\Registry;
2882e92bfaSGreg Roachuse Fisharebest\Webtrees\Services\ModuleService;
290c0910bfSGreg Roachuse Fisharebest\Webtrees\Services\TreeService;
30ee4364daSGreg Roachuse Fisharebest\Webtrees\Tree;
31b55cbc6bSGreg Roachuse Fisharebest\Webtrees\Validator;
32785274b8SGreg Roachuse Fisharebest\Webtrees\Webtrees;
33d7de6d4cSGreg Roachuse Middleland\Dispatcher;
349e5d8e6fSGreg Roachuse Psr\Http\Message\ResponseInterface;
359e5d8e6fSGreg Roachuse Psr\Http\Message\ServerRequestInterface;
369e5d8e6fSGreg Roachuse Psr\Http\Server\MiddlewareInterface;
379e5d8e6fSGreg Roachuse Psr\Http\Server\RequestHandlerInterface;
380c0910bfSGreg Roach
39d76bd128SGreg Roachuse function explode;
40d8d90d88SGreg Roachuse function implode;
41dec352c1SGreg Roachuse function str_contains;
429e5d8e6fSGreg Roach
439e5d8e6fSGreg Roach/**
449e5d8e6fSGreg Roach * Simple class to help migrate to a third-party routing library.
459e5d8e6fSGreg Roach */
4671378461SGreg Roachclass Router implements MiddlewareInterface
479e5d8e6fSGreg Roach{
48c4943cffSGreg Roach    private ModuleService $module_service;
4982e92bfaSGreg Roach
50c4943cffSGreg Roach    private RouterContainer $router_container;
513ecf8b4eSGreg Roach
52c4943cffSGreg Roach    private TreeService $tree_service;
530c0910bfSGreg Roach
5482e92bfaSGreg Roach    /**
5582e92bfaSGreg Roach     * @param ModuleService   $module_service
564874f72dSGreg Roach     * @param RouterContainer $router_container
570c0910bfSGreg Roach     * @param TreeService     $tree_service
5882e92bfaSGreg Roach     */
59c4943cffSGreg Roach    public function __construct(
60c4943cffSGreg Roach        ModuleService $module_service,
61c4943cffSGreg Roach        RouterContainer $router_container,
62c4943cffSGreg Roach        TreeService $tree_service
63c4943cffSGreg Roach    ) {
6482e92bfaSGreg Roach        $this->module_service   = $module_service;
653ecf8b4eSGreg Roach        $this->router_container = $router_container;
660c0910bfSGreg Roach        $this->tree_service     = $tree_service;
679e5d8e6fSGreg Roach    }
689e5d8e6fSGreg Roach
699e5d8e6fSGreg Roach    /**
709e5d8e6fSGreg Roach     * @param ServerRequestInterface  $request
719e5d8e6fSGreg Roach     * @param RequestHandlerInterface $handler
729e5d8e6fSGreg Roach     *
739e5d8e6fSGreg Roach     * @return ResponseInterface
749e5d8e6fSGreg Roach     */
759e5d8e6fSGreg Roach    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
769e5d8e6fSGreg Roach    {
778753199aSGreg Roach        // Ugly URLs store the path in a query parameter.
78748dbe15SGreg Roach        $url_route = Validator::queryParams($request)->string('route', '');
79d76bd128SGreg Roach
80d76bd128SGreg Roach        if (Validator::attributes($request)->boolean('rewrite_urls', false)) {
81d76bd128SGreg Roach            // We are creating pretty URLs, but received an ugly one. Probably a search-engine. Redirect it.
82d76bd128SGreg Roach            if ($url_route !== '') {
83d76bd128SGreg Roach                $uri = $request->getUri()
84d76bd128SGreg Roach                    ->withPath($url_route)
85d76bd128SGreg Roach                    ->withQuery(explode('&', $request->getUri()->getQuery(), 2)[1] ?? '');
86d76bd128SGreg Roach
87*15c4f62cSGreg Roach                return Registry::responseFactory()
88*15c4f62cSGreg Roach                    ->redirectUrl($uri, StatusCodeInterface::STATUS_PERMANENT_REDIRECT)
89*15c4f62cSGreg Roach                    ->withHeader('Link', '<' . $uri . '>; rel="canonical"');
90d76bd128SGreg Roach            }
919e4deb3cSGreg Roach
929e4deb3cSGreg Roach            $pretty = $request;
93d76bd128SGreg Roach        } else {
94d76bd128SGreg Roach            // Turn the ugly URL into a pretty one, so the router can parse it.
958753199aSGreg Roach            $uri    = $request->getUri()->withPath($url_route);
969e4deb3cSGreg Roach            $pretty = $request->withUri($uri);
97ee4364daSGreg Roach        }
989e5d8e6fSGreg Roach
993ecf8b4eSGreg Roach        // Match the request to a route.
10064c83a78SGreg Roach        $matcher = $this->router_container->getMatcher();
1019e4deb3cSGreg Roach        $route   = $matcher->match($pretty);
1023ecf8b4eSGreg Roach
10364c83a78SGreg Roach        // No route matched?
10415958f0eSGreg Roach        if ($route === false) {
10564c83a78SGreg Roach            $failed_route = $matcher->getFailedRoute();
10664c83a78SGreg Roach
107d8d90d88SGreg Roach            if ($failed_route instanceof Route) {
108d8d90d88SGreg Roach                if ($failed_route->failedRule === Allows::class) {
10965905dc4SGreg Roach                    return Registry::responseFactory()->response('', StatusCodeInterface::STATUS_METHOD_NOT_ALLOWED, [
11064c83a78SGreg Roach                        'Allow' => implode(', ', $failed_route->allows),
11164c83a78SGreg Roach                    ]);
112d8d90d88SGreg Roach                }
11364c83a78SGreg Roach
114d8d90d88SGreg Roach                if ($failed_route->failedRule === Accepts::class) {
115d8d90d88SGreg Roach                    return Registry::responseFactory()->response('Negotiation failed', StatusCodeInterface::STATUS_NOT_ACCEPTABLE);
116d8d90d88SGreg Roach                }
117d8d90d88SGreg Roach            }
11864c83a78SGreg Roach
11964c83a78SGreg Roach            // Not found
1209e5d8e6fSGreg Roach            return $handler->handle($request);
1219e5d8e6fSGreg Roach        }
1229e5d8e6fSGreg Roach
123f307429bSGreg Roach        // Add the route as attribute of the request
124f307429bSGreg Roach        $request = $request->withAttribute('route', $route);
125f307429bSGreg Roach
1265d3d7b86SGreg Roach        // This middleware cannot run until after the routing, as it needs to know the route.
127f307429bSGreg Roach        $post_routing_middleware = [CheckCsrf::class];
128f307429bSGreg Roach
12982e92bfaSGreg Roach        // Firstly, apply the route middleware
130ee4364daSGreg Roach        $route_middleware = $route->extras['middleware'] ?? [];
1319e5d8e6fSGreg Roach
13282e92bfaSGreg Roach        // Secondly, apply any module middleware
13382e92bfaSGreg Roach        $module_middleware = $this->module_service->findByInterface(MiddlewareInterface::class)->all();
1349e5d8e6fSGreg Roach
13582e92bfaSGreg Roach        // Finally, run the handler using middleware
136aa7265a1SGreg Roach        $handler_middleware = [RequestHandler::class];
13782e92bfaSGreg Roach
138f307429bSGreg Roach        $middleware = array_merge(
139f307429bSGreg Roach            $post_routing_middleware,
140f307429bSGreg Roach            $route_middleware,
141f307429bSGreg Roach            $module_middleware,
142f307429bSGreg Roach            $handler_middleware
143f307429bSGreg Roach        );
144f307429bSGreg Roach
145f307429bSGreg Roach        // Add the matched attributes to the request.
146f307429bSGreg Roach        foreach ($route->attributes as $key => $value) {
147f307429bSGreg Roach            if ($key === 'tree') {
148f307429bSGreg Roach                $value = $this->tree_service->all()->get($value);
149d35568b4SGreg Roach
150d35568b4SGreg Roach                if ($value instanceof Tree) {
151d35568b4SGreg Roach                    Registry::container()->set(Tree::class, $value);
152d35568b4SGreg Roach                }
153f307429bSGreg Roach
154f307429bSGreg Roach                // Missing mandatory parameter? Let the default handler take care of it.
155dec352c1SGreg Roach                if ($value === null && str_contains($route->path, '{tree}')) {
156f307429bSGreg Roach                    return $handler->handle($request);
157f307429bSGreg Roach                }
158f307429bSGreg Roach            }
159f307429bSGreg Roach
160f307429bSGreg Roach            $request = $request->withAttribute((string) $key, $value);
161f307429bSGreg Roach        }
162f307429bSGreg Roach
163cd7ea74aSGreg Roach        // Bind the updated request into the container
164d35568b4SGreg Roach        Registry::container()->set(ServerRequestInterface::class, $request);
16582e92bfaSGreg Roach
166d7de6d4cSGreg Roach        $dispatcher = new Dispatcher($middleware, Registry::container());
167d7de6d4cSGreg Roach
168d7de6d4cSGreg Roach        return $dispatcher->dispatch($request);
1699e5d8e6fSGreg Roach    }
1709e5d8e6fSGreg Roach}
171