xref: /webtrees/app/Http/Middleware/Router.php (revision b1331e2ee95636c32070e430b0bcc725662cb8b9)
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 Aura\Router\Route;
23use Aura\Router\RouterContainer;
24use Aura\Router\Rule\Accepts;
25use Aura\Router\Rule\Allows;
26use Fig\Http\Message\StatusCodeInterface;
27use Fisharebest\Webtrees\Registry;
28use Fisharebest\Webtrees\Services\ModuleService;
29use Fisharebest\Webtrees\Services\TreeService;
30use Fisharebest\Webtrees\Tree;
31use Fisharebest\Webtrees\Validator;
32use Fisharebest\Webtrees\Webtrees;
33use Middleland\Dispatcher;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36use Psr\Http\Server\MiddlewareInterface;
37use Psr\Http\Server\RequestHandlerInterface;
38
39use function explode;
40use function implode;
41use function str_contains;
42
43/**
44 * Simple class to help migrate to a third-party routing library.
45 */
46class Router implements MiddlewareInterface
47{
48    private ModuleService $module_service;
49
50    private RouterContainer $router_container;
51
52    private TreeService $tree_service;
53
54    /**
55     * @param ModuleService   $module_service
56     * @param RouterContainer $router_container
57     * @param TreeService     $tree_service
58     */
59    public function __construct(
60        ModuleService $module_service,
61        RouterContainer $router_container,
62        TreeService $tree_service
63    ) {
64        $this->module_service   = $module_service;
65        $this->router_container = $router_container;
66        $this->tree_service     = $tree_service;
67    }
68
69    /**
70     * @param ServerRequestInterface  $request
71     * @param RequestHandlerInterface $handler
72     *
73     * @return ResponseInterface
74     */
75    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
76    {
77        // Ugly URLs store the path in a query parameter.
78        $url_route = Validator::queryParams($request)->string('route', '');
79
80        if (Validator::attributes($request)->boolean('rewrite_urls', false)) {
81            // We are creating pretty URLs, but received an ugly one. Probably a search-engine. Redirect it.
82            if ($url_route !== '') {
83                $uri = $request->getUri()
84                    ->withPath($url_route)
85                    ->withQuery(explode('&', $request->getUri()->getQuery(), 2)[1] ?? '');
86
87                return Registry::responseFactory()->redirectUrl($uri, StatusCodeInterface::STATUS_PERMANENT_REDIRECT);
88            }
89
90            $pretty = $request;
91        } else {
92            // Turn the ugly URL into a pretty one, so the router can parse it.
93            $uri    = $request->getUri()->withPath($url_route);
94            $pretty = $request->withUri($uri);
95        }
96
97        // Match the request to a route.
98        $matcher = $this->router_container->getMatcher();
99        $route   = $matcher->match($pretty);
100
101        // No route matched?
102        if ($route === false) {
103            $failed_route = $matcher->getFailedRoute();
104
105            if ($failed_route instanceof Route) {
106                if ($failed_route->failedRule === Allows::class) {
107                    return Registry::responseFactory()->response('', StatusCodeInterface::STATUS_METHOD_NOT_ALLOWED, [
108                        'Allow' => implode(', ', $failed_route->allows),
109                    ]);
110                }
111
112                if ($failed_route->failedRule === Accepts::class) {
113                    return Registry::responseFactory()->response('Negotiation failed', StatusCodeInterface::STATUS_NOT_ACCEPTABLE);
114                }
115            }
116
117            // Not found
118            return $handler->handle($request);
119        }
120
121        // Add the route as attribute of the request
122        $request = $request->withAttribute('route', $route);
123
124        // This middleware cannot run until after the routing, as it needs to know the route.
125        $post_routing_middleware = [CheckCsrf::class];
126
127        // Firstly, apply the route middleware
128        $route_middleware = $route->extras['middleware'] ?? [];
129
130        // Secondly, apply any module middleware
131        $module_middleware = $this->module_service->findByInterface(MiddlewareInterface::class)->all();
132
133        // Finally, run the handler using middleware
134        $handler_middleware = [RequestHandler::class];
135
136        $middleware = array_merge(
137            $post_routing_middleware,
138            $route_middleware,
139            $module_middleware,
140            $handler_middleware
141        );
142
143        // Add the matched attributes to the request.
144        foreach ($route->attributes as $key => $value) {
145            if ($key === 'tree') {
146                $value = $this->tree_service->all()->get($value);
147
148                if ($value instanceof Tree) {
149                    Registry::container()->set(Tree::class, $value);
150                }
151
152                // Missing mandatory parameter? Let the default handler take care of it.
153                if ($value === null && str_contains($route->path, '{tree}')) {
154                    return $handler->handle($request);
155                }
156            }
157
158            $request = $request->withAttribute((string) $key, $value);
159        }
160
161        // Bind the updated request into the container
162        Registry::container()->set(ServerRequestInterface::class, $request);
163
164        $dispatcher = new Dispatcher($middleware, Registry::container());
165
166        return $dispatcher->dispatch($request);
167    }
168}
169