[TASK] Clean up Routing API
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Middleware / PageResolver.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Frontend\Middleware;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use Psr\Http\Message\ResponseInterface;
19 use Psr\Http\Message\ServerRequestInterface;
20 use Psr\Http\Server\MiddlewareInterface;
21 use Psr\Http\Server\RequestHandlerInterface;
22 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
23 use TYPO3\CMS\Core\Context\Context;
24 use TYPO3\CMS\Core\Context\UserAspect;
25 use TYPO3\CMS\Core\Context\WorkspaceAspect;
26 use TYPO3\CMS\Core\Http\RedirectResponse;
27 use TYPO3\CMS\Core\Routing\PageRouter;
28 use TYPO3\CMS\Core\Routing\RouteResult;
29 use TYPO3\CMS\Core\Site\Entity\Site;
30 use TYPO3\CMS\Core\Site\Entity\SiteInterface;
31 use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
32 use TYPO3\CMS\Core\Type\Bitmask\Permission;
33 use TYPO3\CMS\Core\Utility\GeneralUtility;
34 use TYPO3\CMS\Frontend\Controller\ErrorController;
35 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
36 use TYPO3\CMS\Frontend\Page\PageAccessFailureReasons;
37
38 /**
39 * Process the ID, type and other parameters.
40 * After this point we have an array, TSFE->page, which is the page-record of the current page, $TSFE->id.
41 *
42 * Now, if there is a backend user logged in and he has NO access to this page,
43 * then re-evaluate the id shown!
44 */
45 class PageResolver implements MiddlewareInterface
46 {
47 /**
48 * @var TypoScriptFrontendController
49 */
50 protected $controller;
51
52 public function __construct(TypoScriptFrontendController $controller = null)
53 {
54 $this->controller = $controller ?? $GLOBALS['TSFE'];
55 }
56
57 /**
58 * Resolve the page ID
59 *
60 * @param ServerRequestInterface $request
61 * @param RequestHandlerInterface $handler
62 * @return ResponseInterface
63 */
64 public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
65 {
66 // First, resolve the root page of the site, the Page ID of the current domain
67 if (($site = $request->getAttribute('site', null)) instanceof SiteInterface) {
68 $this->controller->domainStartPage = $site->getRootPageId();
69 }
70 $language = $request->getAttribute('language', null);
71
72 $hasSiteConfiguration = $language instanceof SiteLanguage && $site instanceof Site;
73
74 // Resolve the page ID based on TYPO3's native routing functionality
75 if ($hasSiteConfiguration) {
76 /** @var PageRouter $router */
77 $router = $site->getRouter();
78 /** @var RouteResult $previousResult */
79 $previousResult = $request->getAttribute('routing', new RouteResult($request->getUri(), $site, $language));
80 if (!empty($previousResult->getTail())) {
81 // Check for the route
82 $routeResult = $router->matchRequest($request, $previousResult);
83 $request = $request->withAttribute('routing', $routeResult);
84 if (is_array($routeResult['page'])) {
85 $page = $routeResult['page'];
86 $this->controller->id = (int)($page['l10n_parent'] > 0 ? $page['l10n_parent'] : $page['uid']);
87 $tail = $routeResult->getTail();
88 $requestedUri = $request->getUri();
89 // the request was called with "/my-page" but it's actually called "/my-page/", let's do a redirect
90 if ($tail === '' && substr($requestedUri->getPath(), -1) !== substr($page['slug'], -1)) {
91 $uri = $requestedUri->withPath($requestedUri->getPath() . '/');
92 return new RedirectResponse($uri, 307);
93 }
94 if ($tail === '/') {
95 $uri = $requestedUri->withPath(rtrim($requestedUri->getPath(), '/'));
96 return new RedirectResponse($uri, 307);
97 }
98 if (!empty($tail)) {
99 // @todo: kick in the resolvers for the RouteEnhancers at this point
100 return GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
101 $request,
102 'The requested page does not exist',
103 ['code' => PageAccessFailureReasons::PAGE_NOT_FOUND]
104 );
105 }
106 } else {
107 return GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
108 $request,
109 'The requested page does not exist',
110 ['code' => PageAccessFailureReasons::PAGE_NOT_FOUND]
111 );
112 }
113 // At this point, we later get further route modifiers
114 // for bw-compat we update $GLOBALS[TYPO3_REQUEST] to be used later in TSFE.
115 $GLOBALS['TYPO3_REQUEST'] = $request;
116 }
117 } else {
118 // old-school page resolving for realurl, cooluri etc.
119 $this->controller->siteScript = $request->getAttribute('normalizedParams')->getSiteScript();
120 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'])) {
121 trigger_error('The "checkAlternativeIdMethods-PostProc" hook will be removed in TYPO3 v10.0 in favor of PSR-15. Use a middleware instead.', E_USER_DEPRECATED);
122 $this->checkAlternativeIdMethods($this->controller);
123 }
124 }
125
126 $this->controller->determineId();
127
128 // No access? Then remove user & Re-evaluate the page-id
129 if ($this->controller->isBackendUserLoggedIn() && !$GLOBALS['BE_USER']->doesUserHaveAccess($this->controller->page, Permission::PAGE_SHOW)) {
130 unset($GLOBALS['BE_USER']);
131 // Register an empty backend user as aspect
132 $this->setBackendUserAspect(GeneralUtility::makeInstance(Context::class), null);
133 if (!$hasSiteConfiguration) {
134 $this->checkAlternativeIdMethods($this->controller);
135 }
136 $this->controller->determineId();
137 }
138
139 // Evaluate the cache hash parameter
140 $this->controller->makeCacheHash($request);
141
142 return $handler->handle($request);
143 }
144
145 /**
146 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or Server Rewrites
147 *
148 * Two options:
149 * 1) Use PATH_INFO (also Apache) to extract id and type from that var. Does not require any special modules compiled with apache. (less typical)
150 * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
151 *
152 * @param TypoScriptFrontendController $tsfe
153 */
154 protected function checkAlternativeIdMethods(TypoScriptFrontendController $tsfe)
155 {
156 // Call post processing function for custom URL methods.
157 $_params = ['pObj' => &$tsfe];
158 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] ?? [] as $_funcRef) {
159 GeneralUtility::callUserFunction($_funcRef, $_params, $tsfe);
160 }
161 }
162
163 /**
164 * Register the backend user as aspect
165 *
166 * @param Context $context
167 * @param BackendUserAuthentication $user
168 */
169 protected function setBackendUserAspect(Context $context, BackendUserAuthentication $user = null)
170 {
171 $context->setAspect('backend.user', GeneralUtility::makeInstance(UserAspect::class, $user));
172 $context->setAspect('workspace', GeneralUtility::makeInstance(WorkspaceAspect::class, $user ? $user->workspace : 0));
173 }
174 }