├── .github └── workflows │ └── publish.yaml ├── Classes ├── ConfigurationModuleProvider │ └── AppRoutesProvider.php ├── Middleware │ └── AppRoutesMiddleware.php ├── Service │ ├── ResponseCachingService.php │ ├── Router.php │ ├── RoutesConfigurationLoader.php │ └── Tsfe.php └── ViewHelpers │ └── RouteViewHelper.php ├── Configuration ├── RequestMiddlewares.php └── Services.yaml ├── LICENSE ├── Readme.md ├── composer.json └── ext_localconf.php /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | # Taken from: https://github.com/o-ba/tailor_ext/blob/main/.github/workflows/publish.yml 2 | name: publish 3 | 4 | on: 5 | push: 6 | tags: 7 | - "**" 8 | 9 | jobs: 10 | publish: 11 | name: Publish new version to TER 12 | if: startsWith(github.ref, 'refs/tags/') 13 | runs-on: ubuntu-20.04 14 | env: 15 | TYPO3_API_TOKEN: ${{ secrets.TYPO3_API_TOKEN }} 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v3 20 | 21 | - name: Check tag 22 | run: | 23 | if ! [[ ${{ github.ref }} =~ ^refs/tags/[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$ ]]; then 24 | exit 1 25 | fi 26 | 27 | - name: Get version 28 | id: get-version 29 | run: echo "version=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_ENV 30 | 31 | - name: Get comment 32 | id: get-comment 33 | run: | 34 | readonly local comment=$(git tag -n10 -l ${{ env.version }} | sed "s/^[0-9.]*[ ]*//g") 35 | 36 | if [[ -z "${comment// }" ]]; then 37 | echo "comment=Released version ${{ env.version }} of ${{ env.TYPO3_EXTENSION_KEY }}" >> $GITHUB_ENV 38 | else 39 | echo "comment=$comment" >> $GITHUB_ENV 40 | fi 41 | 42 | - name: Setup PHP 43 | uses: shivammathur/setup-php@v2 44 | with: 45 | php-version: 7.4 46 | extensions: intl, mbstring, json, zip, curl 47 | tools: composer:v2 48 | 49 | - name: Install tailor 50 | run: composer global require typo3/tailor --prefer-dist --no-progress 51 | 52 | - name: Publish to TER 53 | run: php ~/.composer/vendor/bin/tailor ter:publish --comment "${{ env.comment }}" ${{ env.version }} 54 | -------------------------------------------------------------------------------- /Classes/ConfigurationModuleProvider/AppRoutesProvider.php: -------------------------------------------------------------------------------- 1 | routesConfigurationLoader = $routesConfigurationLoader; 20 | } 21 | 22 | public function getConfiguration(): array 23 | { 24 | return $this->routesConfigurationLoader->getRoutesConfiguration(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Classes/Middleware/AppRoutesMiddleware.php: -------------------------------------------------------------------------------- 1 | router = $router; 39 | $this->responseCachingService = $responseCachingService; 40 | } 41 | 42 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler = null): ResponseInterface 43 | { 44 | try { 45 | $parameters = $this->router->getUrlMatcher()->match($request->getUri()->getPath()); 46 | } catch (MethodNotAllowedException|ResourceNotFoundException $e) { 47 | // app routes did not match. go on with regular TYPO3 stack. 48 | return $handler->handle($request); 49 | } 50 | $response = $this->handleRequestCached($parameters, $request); 51 | $response = $this->replaceWithNotModifiedResponse($request, $response); 52 | 53 | return $response; 54 | } 55 | 56 | public function handleRequestCached(array $parameters, ServerRequestInterface $request): ResponseInterface 57 | { 58 | $ingredients = [ 59 | 'routeParameters' => $parameters, 60 | 'language' => (int)($request->getAttribute('language')?->getLanguageId() ?? $request->getQueryParams()['L'] ?? 0), 61 | 'site' => $request->getAttribute('site')?->getIdentifier(), 62 | ]; 63 | $cacheKey = 'appRoutes_' . md5(serialize($ingredients)); 64 | if (!empty($parameters['cache']) && $this->responseCachingService->has($cacheKey) && $this->responseCachingService->isCacheable($request)) { 65 | return $this->responseCachingService->serveFromCache($cacheKey); 66 | } 67 | $response = $this->handleWithParameters( 68 | $parameters, 69 | $request->withQueryParams(array_merge( 70 | $request->getQueryParams(), 71 | $parameters 72 | )) 73 | ); 74 | if (!empty($parameters['cache']) && $response->getStatusCode() < 400) { 75 | $response = $this->responseCachingService->storeCacheEntry($request, $response, $cacheKey); 76 | } 77 | return $response; 78 | } 79 | 80 | protected function handleWithParameters(array $parameters, ServerRequestInterface $request): ResponseInterface 81 | { 82 | /** @var SiteInterface $site */ 83 | $site = $request->getAttribute('site'); 84 | if (is_null($site) || $site instanceof NullSite) { 85 | $sites = GeneralUtility::makeInstance(SiteFinder::class)->getAllSites(); 86 | $site = $sites[array_key_first($sites)]; 87 | } 88 | $language = $this->getLanguage($site, $request); 89 | $request = $request->withAttribute('language', $language); 90 | GeneralUtility::makeInstance(Context::class)->setAspect('language', LanguageAspectFactory::createFromSiteLanguage($language)); 91 | 92 | if (empty($parameters['handler'])) { 93 | throw new \Exception('Route must return a handler parameter', 1604066046); 94 | } 95 | $handler = GeneralUtility::makeInstance($parameters['handler']); 96 | if (!$handler instanceof RequestHandlerInterface) { 97 | throw new \Exception('Route must return a handler parameter which implements ' . RequestHandlerInterface::class, 1604066102); 98 | } 99 | if ($parameters['requiresTsfe'] ?? false) { 100 | /** @var FrontendUserAuthentication $feUserAuthentication */ 101 | $feUserAuthentication = $request->getAttribute('frontend.user'); 102 | $request = $this->bootFrontendController($feUserAuthentication, $site, $language, $request); 103 | 104 | if ((new Typo3Version())->getMajorVersion() >= 12) { 105 | $tsfe = $request->getAttribute('frontend.controller'); 106 | $frontendTypoScript = new FrontendTypoScript(new RootNode(), []); 107 | $frontendTypoScript->setSetupTree(new RootNode()); 108 | $frontendTypoScript->setSetupArray($tsfe->tmpl->setup); 109 | $request = $request->withAttribute('frontend.typoscript', $frontendTypoScript); 110 | } 111 | } 112 | 113 | $GLOBALS['TYPO3_REQUEST'] = $request; 114 | 115 | return $handler->handle($request); 116 | } 117 | 118 | protected function replaceWithNotModifiedResponse(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface 119 | { 120 | if ($response->getStatusCode() !== 200) { 121 | return $response; 122 | } 123 | if ($request->hasHeader('If-None-Match') && $response->hasHeader('ETag') && $request->getHeader('If-None-Match')[0] === $response->getHeader('ETag')[0]) { 124 | return $response->withBody(new Stream(fopen('php://temp', 'r+')))->withStatus(304); 125 | } 126 | return $response; 127 | } 128 | 129 | protected function bootFrontendController(FrontendUserAuthentication $frontendUserAuthentication, SiteInterface $site, SiteLanguage $language, ServerRequestInterface $request): ServerRequestInterface 130 | { 131 | if ($this->getTypoScriptFrontendController() instanceof TypoScriptFrontendController) { 132 | return $request; 133 | } 134 | 135 | $tsfeInitializationService = GeneralUtility::makeInstance(Tsfe::class); 136 | $controller = $tsfeInitializationService->getTsfeByPageIdAndLanguageId($site->getRootPageId(), $language->getLanguageId()); 137 | $controller->newCObj($request); 138 | $controller->fe_user = $frontendUserAuthentication; 139 | $GLOBALS['TSFE'] = $controller; 140 | $GLOBALS['TSFE']->sys_page = GeneralUtility::makeInstance(PageRepository::class); 141 | return $request->withAttribute('frontend.controller', $controller); 142 | } 143 | 144 | protected function getLanguage(SiteInterface $site, ServerRequestInterface $request): SiteLanguage 145 | { 146 | $languageUid = (int)($request->getQueryParams()['L'] ?? 0); 147 | foreach ($site->getLanguages() as $siteLanguage) { 148 | if ($siteLanguage->getLanguageId() === $languageUid) { 149 | return $siteLanguage; 150 | } 151 | } 152 | return $site->getDefaultLanguage(); 153 | } 154 | 155 | protected function getTypoScriptFrontendController(): ?TypoScriptFrontendController 156 | { 157 | return $GLOBALS['TSFE'] ?? null; 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /Classes/Service/ResponseCachingService.php: -------------------------------------------------------------------------------- 1 | cache = $cacheManager->getCache('pages'); 23 | } 24 | 25 | public function isCacheable(ServerRequestInterface $request): bool 26 | { 27 | return in_array($request->getMethod(), self::CACHEABLE_REQUEST_METHODS); 28 | } 29 | 30 | public function has(string $cacheKey): bool 31 | { 32 | return $this->cache->has($cacheKey); 33 | } 34 | 35 | public function serveFromCache(string $cacheKey): ResponseInterface 36 | { 37 | $cacheEntry = $this->cache->get($cacheKey); 38 | /** @var ResponseInterface $response */ 39 | $response = $cacheEntry['response']; 40 | $body = new Stream('php://temp', 'rw'); 41 | $body->write($cacheEntry['responseBody']); 42 | $response = $response->withBody($body); 43 | if (!empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug'])) { 44 | $response = $response->withAddedHeader( 45 | 'X-APP-ROUTES-CACHED', 46 | date( 47 | $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], 48 | $cacheEntry['tstamp'] 49 | ) 50 | ); 51 | } 52 | return $response; 53 | } 54 | 55 | public function storeCacheEntry(ServerRequestInterface $request, ResponseInterface $response, string $cacheKey): ResponseInterface 56 | { 57 | if (!in_array($request->getMethod(), self::CACHEABLE_REQUEST_METHODS)) { 58 | if (!empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug'])) { 59 | $response = $response->withAddedHeader('X-APP-ROUTES-UNCACHED', 'uncacheable request method'); 60 | } 61 | return $response; 62 | } 63 | $lifetime = null; // use the default lifetime of the cache 64 | $cacheControlHeaders = $response->getHeader('Cache-Control'); 65 | foreach ($cacheControlHeaders as $cacheControlHeader) { 66 | $valueParts = GeneralUtility::trimExplode(',', $cacheControlHeader); 67 | foreach ($valueParts as $valuePart) { 68 | if ($valuePart === 'no-cache' || $valuePart === 'no-store') { 69 | if (!empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug'])) { 70 | $response = $response->withAddedHeader('X-APP-ROUTES-UNCACHED', 'caching prohibited by Cache-Control header'); 71 | } 72 | return $response; 73 | } 74 | [$key, $value] = GeneralUtility::trimExplode('=', $valuePart); 75 | if ($key === 'max-age') { 76 | $lifetime = $value; 77 | } 78 | } 79 | } 80 | $cacheTags = array_unique($this->getTypoScriptFrontendController() instanceof TypoScriptFrontendController ? $this->getTypoScriptFrontendController()->getPageCacheTags() : []); 81 | $cacheEntry = [ 82 | 'response' => $response, 83 | 'responseBody' => (string)$response->getBody(), 84 | 'tstamp' => $GLOBALS['EXEC_TIME'], 85 | ]; 86 | if (!empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug'])) { 87 | $response = $response->withAddedHeader('X-APP-ROUTES-CACHED', 'now'); 88 | if ($cacheTags !== []) { 89 | $response = $response->withAddedHeader('X-APP-ROUTES-CACHED-WITH-TAGS', implode(',', $cacheTags)); 90 | } 91 | } 92 | $this->cache->set($cacheKey, $cacheEntry, $cacheTags, $lifetime); 93 | return $response; 94 | } 95 | 96 | protected function getTypoScriptFrontendController(): ?TypoScriptFrontendController 97 | { 98 | return $GLOBALS['TSFE'] ?? null; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Classes/Service/Router.php: -------------------------------------------------------------------------------- 1 | getCache()->has($cacheKey)) { 29 | return $this->getCache()->get($cacheKey); 30 | } 31 | $routes = new RouteCollection(); 32 | foreach ($this->routeFilesLoader->getRoutesConfiguration() as $appName => $appRoutesConfiguration) { 33 | $prefix = $appRoutesConfiguration['prefix'] ?? ''; 34 | $routes = $this->populateRouteCollection($routes, $appRoutesConfiguration['routes'], $appName, $prefix); 35 | } 36 | $this->getCache()->set($cacheKey, $routes); 37 | return $routes; 38 | } 39 | 40 | public function getUrlGenerator(): UrlGenerator 41 | { 42 | $context = $this->createRequestContext(); 43 | return new UrlGenerator($this->getRoutes(), $context); 44 | } 45 | 46 | public function getUrlMatcher(): UrlMatcher 47 | { 48 | $context = $this->createRequestContext(); 49 | return new UrlMatcher($this->getRoutes(), $context); 50 | } 51 | 52 | protected function createRequestContext(): RequestContext 53 | { 54 | if (Environment::isCli()) { 55 | return new RequestContext(); 56 | } 57 | 58 | $request = ServerRequestFactory::fromGlobals(); 59 | $host = (string)idn_to_ascii($request->getUri()->getHost()); 60 | return new RequestContext( 61 | '', 62 | $request->getMethod(), 63 | $host, 64 | $request->getUri()->getScheme(), 65 | 80, 66 | 443, 67 | $request->getUri()->getPath() 68 | ); 69 | } 70 | 71 | protected function populateRouteCollection(RouteCollection $routes, array $routesConfiguration, string $namePrefix, string $pathPrefix): RouteCollection 72 | { 73 | foreach ($routesConfiguration as $routeConfiguration) { 74 | $route = new Route( 75 | $pathPrefix . $routeConfiguration['path'], 76 | $routeConfiguration['defaults'] ?? [], 77 | $routeConfiguration['requirements'] ?? [], 78 | $routeConfiguration['options'] ?? [], 79 | $routeConfiguration['host'] ?? '', 80 | $routeConfiguration['schemes'] ?? [], 81 | $routeConfiguration['methods'] ?? [], 82 | $routeConfiguration['condition'] ?? '' 83 | ); 84 | $routes->add($namePrefix . '.' . $routeConfiguration['name'], $route); 85 | } 86 | return $routes; 87 | } 88 | 89 | private function getCache(): FrontendInterface 90 | { 91 | return $this->cacheManager->getCache('runtime'); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Classes/Service/RoutesConfigurationLoader.php: -------------------------------------------------------------------------------- 1 | cache = $cacheManager->getCache('app_routes'); 39 | $this->packageManager = $packageManager; 40 | $this->yamlFileLoader = $yamlFileLoader; 41 | } 42 | 43 | public function getRoutesConfiguration(): array 44 | { 45 | if (!is_array($this->routesConfiguration)) { 46 | $this->loadRoutesConfiguration(); 47 | } 48 | return $this->routesConfiguration; 49 | } 50 | 51 | protected function loadRoutesConfiguration(): void 52 | { 53 | $key = 'appRoutesConfiguration'; 54 | if ($this->cache->has($key)) { 55 | $this->routesConfiguration = $this->cache->get($key); 56 | return; 57 | } 58 | 59 | $routesConfiguration = []; 60 | foreach ($this->findAppRouteYamlFiles() as $yamlFile) { 61 | $routesConfiguration = array_merge_recursive( 62 | $routesConfiguration, 63 | $this->yamlFileLoader->load($yamlFile) 64 | ); 65 | } 66 | $this->routesConfiguration = $routesConfiguration; 67 | $this->cache->set($key, $routesConfiguration); 68 | } 69 | 70 | protected function findAppRouteYamlFiles(): array 71 | { 72 | $paths = []; 73 | foreach ($this->packageManager->getActivePackages() as $package) { 74 | $possiblePath = $package->getPackagePath() . self::APP_ROUTES_YAML_PATH; 75 | if (is_readable($possiblePath)) { 76 | $paths[] = $possiblePath; 77 | } 78 | } 79 | 80 | return $paths; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Classes/Service/Tsfe.php: -------------------------------------------------------------------------------- 1 | siteFinder = $siteFinder ?? GeneralUtility::makeInstance(SiteFinder::class); 49 | } 50 | 51 | /** 52 | * Initializes the TSFE for a given page ID and language. 53 | * 54 | * 55 | * 56 | * @throws Exception\Exception 57 | * @throws SiteNotFoundException 58 | * @throws DBALException 59 | * 60 | * 61 | * @todo: Move whole caching stuff from this method and let return TSFE. 62 | */ 63 | protected function initializeTsfe(int $pageId, int $language = 0, ?int $rootPageId = null): void 64 | { 65 | $cacheIdentifier = $this->getCacheIdentifier($pageId, $language, $rootPageId); 66 | 67 | // Handle spacer and sys-folders, since they are not accessible in frontend, and TSFE can not be fully initialized on them. 68 | // Apart from this, the plugin.tx_solr.index.queue.[indexConfig].additionalPageIds is handled as well. 69 | $pidToUse = $this->getPidToUseForTsfeInitialization($pageId, $rootPageId); 70 | if ($pidToUse !== $pageId) { 71 | $this->initializeTsfe($pidToUse, $language, $rootPageId); 72 | $reusedCacheIdentifier = $this->getCacheIdentifier($pidToUse, $language, $rootPageId); 73 | $this->serverRequestCache[$cacheIdentifier] = $this->serverRequestCache[$reusedCacheIdentifier]; 74 | $this->tsfeCache[$cacheIdentifier] = $this->tsfeCache[$reusedCacheIdentifier]; 75 | // if ($rootPageId === null) { 76 | // // @Todo: Resolve and set TSFE object for $rootPageId. 77 | // } 78 | return; 79 | } 80 | 81 | /** @var Context $context */ 82 | $context = clone GeneralUtility::makeInstance(Context::class); 83 | $site = $this->siteFinder->getSiteByPageId($pageId); 84 | // $siteLanguage and $languageAspect takes the language id into account. 85 | // See: $site->getLanguageById($language); 86 | // Therefore the whole TSFE stack is initialized and must be used as is. 87 | // Note: ServerRequest, Context, Language, cObj of TSFE MUST NOT be changed or touched in any way, 88 | // Otherwise the caching of TSFEs makes no sense anymore. 89 | // If you want something to change in TSFE object, please use cloned one! 90 | $siteLanguage = $site->getLanguageById($language); 91 | $languageAspect = LanguageAspectFactory::createFromSiteLanguage($siteLanguage); 92 | $context->setAspect('language', $languageAspect); 93 | 94 | $serverRequest = $this->serverRequestCache[$cacheIdentifier] ?? null; 95 | if (!isset($this->serverRequestCache[$cacheIdentifier])) { 96 | $serverRequest = GeneralUtility::makeInstance(ServerRequest::class); 97 | $this->serverRequestCache[$cacheIdentifier] = $serverRequest = 98 | $serverRequest->withAttribute('site', $site) 99 | ->withAttribute('language', $siteLanguage) 100 | ->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_FE) 101 | ->withUri($site->getBase()); 102 | } 103 | 104 | if (!isset($this->tsfeCache[$cacheIdentifier])) { 105 | // TYPO3 by default enables a preview mode if a backend user is logged in, 106 | // the VisibilityAspect is configured to show hidden elements. 107 | // Due to this setting hidden relations/translations might be indexed 108 | // when running the Solr indexer via the TYPO3 backend. 109 | // To avoid this, the VisibilityAspect is adapted for indexing. 110 | $context->setAspect( 111 | 'visibility', 112 | GeneralUtility::makeInstance( 113 | VisibilityAspect::class, 114 | false, 115 | false 116 | ) 117 | ); 118 | 119 | /** @var FrontendUserAuthentication $feUser */ 120 | $feUser = GeneralUtility::makeInstance(FrontendUserAuthentication::class); 121 | // for certain situations we need to trick TSFE into granting us 122 | // access to the page in any case to make getPageAndRootline() work 123 | // see http://forge.typo3.org/issues/42122 124 | $pageRecord = BackendUtility::getRecord('pages', $pageId, 'fe_group'); 125 | if (!empty($pageRecord['fe_group'])) { 126 | $userGroups = explode(',', $pageRecord['fe_group']); 127 | } else { 128 | $userGroups = [0, -1]; 129 | } 130 | $feUser->user = ['uid' => 0, 'username' => '', 'usergroup' => implode(',', $userGroups) ]; 131 | $feUser->fetchGroupData($serverRequest); 132 | $context->setAspect('frontend.user', GeneralUtility::makeInstance(UserAspect::class, $feUser, $userGroups)); 133 | 134 | /** @var PageArguments $pageArguments */ 135 | $pageArguments = GeneralUtility::makeInstance(PageArguments::class, $pageId, '0', []); 136 | 137 | /** @var TypoScriptFrontendController $tsfe */ 138 | $tsfe = GeneralUtility::makeInstance(TypoScriptFrontendController::class, $context, $site, $siteLanguage, $pageArguments, $feUser); 139 | 140 | // @extensionScannerIgnoreLine 141 | /** Done in {@link TypoScriptFrontendController::settingLanguage} */ 142 | //$tsfe->sys_page = GeneralUtility::makeInstance(PageRepository::class); 143 | 144 | $template = GeneralUtility::makeInstance(TemplateService::class, $context, null, $tsfe); 145 | $template->tt_track = false; 146 | $tsfe->tmpl = $template; 147 | $context->setAspect('typoscript', GeneralUtility::makeInstance(TypoScriptAspect::class, true)); 148 | $tsfe->no_cache = true; 149 | 150 | $backedUpBackendUser = $GLOBALS['BE_USER'] ?? null; 151 | try { 152 | $serverRequest = $serverRequest->withAttribute('frontend.controller', $tsfe); 153 | $tsfe->determineId($serverRequest); 154 | $tsfe->no_cache = false; 155 | /** @var ServerRequest $serverRequest */ 156 | $serverRequest = $tsfe->getFromCache($serverRequest); 157 | // The manual releasing of locks is low level api and should be avoided in EXT:solr. 158 | $tsfe->releaseLocks(); 159 | 160 | $tsfe->newCObj($serverRequest); 161 | $tsfe->absRefPrefix = self::getAbsRefPrefixFromTSFE($tsfe); 162 | $tsfe->calculateLinkVars([]); 163 | } catch (Throwable $exception) { 164 | // @todo: logging 165 | $this->serverRequestCache[$cacheIdentifier] = null; 166 | $this->tsfeCache[$cacheIdentifier] = null; 167 | // Restore backend user, happens when initializeTsfe() is called from Backend context 168 | if ($backedUpBackendUser) { 169 | $GLOBALS['BE_USER'] = $backedUpBackendUser; 170 | } 171 | return; 172 | } 173 | // Restore backend user, happens when initializeTsfe() is called from Backend context 174 | if ($backedUpBackendUser) { 175 | $GLOBALS['BE_USER'] = $backedUpBackendUser; 176 | } 177 | 178 | $this->serverRequestCache[$cacheIdentifier] = $serverRequest; 179 | $this->tsfeCache[$cacheIdentifier] = $tsfe; 180 | } 181 | 182 | // @todo: Not right place for that action, move on more convenient place: indexing a single item+id+lang. 183 | Locales::setSystemLocaleFromSiteLanguage($siteLanguage); 184 | } 185 | 186 | /** 187 | * Returns TypoScriptFrontendController with sand cast context. 188 | * 189 | * @throws SiteNotFoundException 190 | * @throws Exception\Exception 191 | * @throws DBALException 192 | */ 193 | public function getTsfeByPageIdAndLanguageId(int $pageId, int $language = 0, ?int $rootPageId = null): ?TypoScriptFrontendController 194 | { 195 | $this->assureIsInitialized($pageId, $language, $rootPageId); 196 | return $this->tsfeCache[$this->getCacheIdentifier($pageId, $language, $rootPageId)]; 197 | } 198 | 199 | /** 200 | * Returns TypoScriptFrontendController for first available language id in fallback chain. 201 | * 202 | * Is usable for BE-Modules/CLI-Commands stack only, where the rendered TypoScript configuration 203 | * of EXT:solr* stack is wanted and the language id does not matter. 204 | * 205 | * NOTE: This method MUST NOT be used on indexing context. 206 | * 207 | * @param int ...$languageFallbackChain 208 | */ 209 | public function getTsfeByPageIdAndLanguageFallbackChain(int $pageId, int ...$languageFallbackChain): ?TypoScriptFrontendController 210 | { 211 | foreach ($languageFallbackChain as $languageId) { 212 | try { 213 | $tsfe = $this->getTsfeByPageIdAndLanguageId($pageId, $languageId); 214 | if ($tsfe instanceof TypoScriptFrontendController) { 215 | return $tsfe; 216 | } 217 | } catch (Throwable $e) { 218 | // no needs to log or do anything, the method MUST not return anything if it can't. 219 | continue; 220 | } 221 | } 222 | return null; 223 | } 224 | 225 | /** 226 | * Returns TSFE for first initializable site language. 227 | * 228 | * Is usable for BE-Modules/CLI-Commands stack only, where the rendered TypoScript configuration 229 | * of EXT:solr* stack is wanted and the language id does not matter. 230 | */ 231 | public function getTsfeByPageIdIgnoringLanguage(int $pageId): ?TypoScriptFrontendController 232 | { 233 | try { 234 | $typo3Site = $this->siteFinder->getSiteByPageId($pageId); 235 | } catch (Throwable $e) { 236 | return null; 237 | } 238 | $availableLanguageIds = array_map(static function ($siteLanguage) { 239 | return $siteLanguage->getLanguageId(); 240 | }, $typo3Site->getLanguages()); 241 | 242 | if (empty($availableLanguageIds)) { 243 | return null; 244 | } 245 | return $this->getTsfeByPageIdAndLanguageFallbackChain($pageId, ...$availableLanguageIds); 246 | } 247 | 248 | /** 249 | * Returns TypoScriptFrontendController with sand cast context. 250 | * 251 | * @throws SiteNotFoundException 252 | * @throws Exception\Exception 253 | * @throws DBALException 254 | * 255 | * @noinspection PhpUnused 256 | */ 257 | public function getServerRequestForTsfeByPageIdAndLanguageId(int $pageId, int $language = 0, ?int $rootPageId = null): ?ServerRequest 258 | { 259 | $this->assureIsInitialized($pageId, $language, $rootPageId); 260 | return $this->serverRequestCache[$this->getCacheIdentifier($pageId, $language, $rootPageId)]; 261 | } 262 | 263 | /** 264 | * Initializes the TSFE, ServerRequest, Context if not already done. 265 | * 266 | * 267 | * 268 | * @throws SiteNotFoundException 269 | * @throws Exception\Exception 270 | * @throws DBALException 271 | */ 272 | protected function assureIsInitialized(int $pageId, int $language, ?int $rootPageId = null): void 273 | { 274 | $cacheIdentifier = $this->getCacheIdentifier($pageId, $language, $rootPageId); 275 | if (!array_key_exists($cacheIdentifier, $this->tsfeCache)) { 276 | $this->initializeTsfe($pageId, $language, $rootPageId); 277 | return; 278 | } 279 | if ($this->tsfeCache[$cacheIdentifier] instanceof TypoScriptFrontendController) { 280 | $this->tsfeCache[$cacheIdentifier]->newCObj($this->serverRequestCache[$cacheIdentifier]); 281 | } 282 | } 283 | 284 | /** 285 | * Returns the cache identifier for cached TSFE and ServerRequest objects. 286 | */ 287 | protected function getCacheIdentifier(int $pageId, int $language, ?int $rootPageId = null): string 288 | { 289 | return 'root:' . ($rootPageId ?? 'null') . '|page:' . $pageId . '|lang:' . $language; 290 | } 291 | 292 | /** 293 | * The TSFE can not be initialized for Spacer and sys-folders. 294 | * See: "Spacer and sys folders is not accessible in frontend" on {@link TypoScriptFrontendController::getPageAndRootline} 295 | * 296 | * Note: The requested $pidToUse can be one of configured plugin.tx_solr.index.queue.[indexConfig].additionalPageIds. 297 | * 298 | * @throws Exception\Exception 299 | * @throws DBALException 300 | */ 301 | protected function getPidToUseForTsfeInitialization(int $pidToUse, ?int $rootPageId = null): ?int 302 | { 303 | $incomingPidToUse = $pidToUse; 304 | $incomingRootPageId = $rootPageId; 305 | 306 | // handle plugin.tx_solr.index.queue.[indexConfig].additionalPageIds 307 | if (isset($rootPageId) && !$this->isRequestedPageAPartOfRequestedSite($pidToUse)) { 308 | return $rootPageId; 309 | } 310 | $pageRecord = BackendUtility::getRecord('pages', $pidToUse); 311 | $isSpacerOrSysfolder = ($pageRecord['doktype'] ?? null) == PageRepository::DOKTYPE_SPACER || ($pageRecord['doktype'] ?? null) == PageRepository::DOKTYPE_SYSFOLDER; 312 | if ($isSpacerOrSysfolder === false && $this->isPageAvailableForTSFE($pageRecord)) { 313 | return $pidToUse; 314 | } 315 | // /** @var ConfigurationPageResolver $configurationPageResolver */ 316 | // $configurationPageResolver = GeneralUtility::makeInstance(ConfigurationPageResolver::class); 317 | // $askedPid = $pidToUse; 318 | // $pidToUse = $configurationPageResolver->getClosestPageIdWithActiveTemplate($pidToUse); 319 | // if (!isset($pidToUse) && !isset($rootPageId)) { 320 | // throw new Exception\Exception( 321 | // "The closest page with active template to page \"$askedPid\" could not be resolved and alternative rootPageId is not provided.", 322 | // 1637339439 323 | // ); 324 | // } 325 | if (isset($rootPageId)) { 326 | return $rootPageId; 327 | } 328 | 329 | // Check for recursion that can happen if the root page is a sysfolder with a typoscript template 330 | if ($pidToUse === $incomingPidToUse && $rootPageId === $incomingRootPageId) { 331 | throw new Exception\Exception( 332 | "Infinite recursion detected while looking for the closest page with active template to page \"$askedPid\" . Please note that the page with active template (usually the root page of the current tree) MUST NOT be a sysfolder.", 333 | 1637339476 334 | ); 335 | } 336 | 337 | return $this->getPidToUseForTsfeInitialization($pidToUse, $rootPageId); 338 | } 339 | 340 | /** 341 | * Checks if the page is available for TSFE. 342 | * 343 | * @param array $pageRecord 344 | * @return bool 345 | * @throws \TYPO3\CMS\Core\Context\Exception\AspectNotFoundException 346 | */ 347 | protected function isPageAvailableForTSFE(array $pageRecord): bool 348 | { 349 | $currentTime = GeneralUtility::makeInstance(Context::class)->getPropertyFromAspect('date', 'timestamp'); 350 | return $pageRecord['hidden'] === 0 && 351 | $pageRecord['starttime'] <= $currentTime && 352 | ($pageRecord['endtime'] === 0 || $pageRecord['endtime'] > 0 && $pageRecord['endtime'] > $currentTime) 353 | ; 354 | } 355 | 356 | /** 357 | * Checks if the requested page belongs to site of given root page. 358 | */ 359 | protected function isRequestedPageAPartOfRequestedSite(int $pageId, ?int $rootPageId = null): bool 360 | { 361 | if (!isset($rootPageId)) { 362 | return false; 363 | } 364 | try { 365 | $site = $this->siteFinder->getSiteByPageId($pageId); 366 | } catch (SiteNotFoundException $e) { 367 | return false; 368 | } 369 | return $rootPageId === $site->getRootPageId(); 370 | } 371 | 372 | /** 373 | * Resolves the configured absRefPrefix to a valid value and resolved if absRefPrefix 374 | * is set to "auto". 375 | */ 376 | private function getAbsRefPrefixFromTSFE(TypoScriptFrontendController $TSFE): string 377 | { 378 | $absRefPrefix = ''; 379 | if (empty($TSFE->config['config']['absRefPrefix'])) { 380 | return $absRefPrefix; 381 | } 382 | 383 | $absRefPrefix = trim($TSFE->config['config']['absRefPrefix']); 384 | if ($absRefPrefix === 'auto') { 385 | $absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH'); 386 | } 387 | 388 | return $absRefPrefix; 389 | } 390 | } 391 | -------------------------------------------------------------------------------- /Classes/ViewHelpers/RouteViewHelper.php: -------------------------------------------------------------------------------- 1 | registerArgument('routeName', 'string', '', true); 17 | $this->registerArgument('parameters', 'array', '', false, []); 18 | } 19 | 20 | public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext): string 21 | { 22 | $router = GeneralUtility::makeInstance(Router::class); 23 | return $router->getUrlGenerator()->generate($arguments['routeName'], $arguments['parameters'], UrlGenerator::ABSOLUTE_URL); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Configuration/RequestMiddlewares.php: -------------------------------------------------------------------------------- 1 | [ 5 | 'sinso/app-routes/route' => [ 6 | 'target' => \Sinso\AppRoutes\Middleware\AppRoutesMiddleware::class, 7 | 'after' => [ 8 | 'typo3/cms-frontend/site', 9 | 'typo3/cms-frontend/authentication', 10 | ], 11 | 'before' => [ 12 | 'typo3/cms-frontend/base-redirect-resolver', 13 | ], 14 | ], 15 | ], 16 | ]; 17 | -------------------------------------------------------------------------------- /Configuration/Services.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | _defaults: 3 | autowire: true 4 | autoconfigure: true 5 | public: false 6 | 7 | Sinso\AppRoutes\: 8 | resource: '../Classes/*' 9 | 10 | lowlevel.configuration.module.provider.app_routes: 11 | class: 'Sinso\AppRoutes\ConfigurationModuleProvider\AppRoutesProvider' 12 | tags: 13 | - name: 'lowlevel.configuration.module.provider' 14 | identifier: 'appRoutesConfiguration' 15 | label: 'App Routes' 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # TYPO3 App Routes 2 | 3 | ## Route any URL to your application. 4 | 5 | You use this package if you want to route certain URLs directly to your controllers, completely ignoring the TYPO3 page routing.
6 | This is especially useful to create REST APIs. 7 | 8 | ### Installation 9 | 10 | ```bash 11 | composer req sinso/app-routes 12 | ``` 13 | 14 | ### Configuration 15 | 16 | This package will look for `Configuration/AppRoutes.yaml` files in any loaded extension. Creating this file is all you need to get started: 17 | 18 | ```yaml 19 | myApp: 20 | prefix: /myApi/v2 21 | routes: 22 | - name: orders 23 | path: /orders 24 | defaults: 25 | handler: MyVendor\MyExtension\Api\OrdersEndpoint 26 | - name: order 27 | path: /order/{orderUid} 28 | defaults: 29 | handler: MyVendor\MyExtension\Api\OrderEndpoint 30 | ``` 31 | 32 | The class you provide as `defaults.handler` has to implement `\Psr\Http\Server\RequestHandlerInterface`. 33 | The routing parameters will be available in `$request->getQueryParams()`. 34 | 35 | ### Options 36 | 37 | Under the hood [symfony/routing](https://github.com/symfony/routing) is used. 38 | 39 | Everything that is available as YAML configuration option in `symfony/routing` should work with this package out of the box. 40 | 41 | This package offers these additional options: 42 | 43 | * `defaults.cache: true` - If true, then responses are cached (see more details below). (default: `false`) 44 | * `defaults.requiresTsfe: true` - If true, then `$GLOBALS['TSFE']` will be initialized before your handler is called (default: `false`). 45 | 46 | ### Generate Route URLs 47 | 48 | To generate URLs you can use the `Sinso\AppRoutes\Service\Router`: 49 | 50 | ```php 51 | $router = GeneralUtility::makeInstance(\Sinso\AppRoutes\Service\Router::class); 52 | $url = $router->getUrlGenerator()->generate('myApp.order', ['orderUid' => 42]); 53 | // https://www.example.com/myApi/v2/order/42 54 | ``` 55 | 56 | If you need to generate a URL in a Fluid template, there's also a ViewHelper for that: 57 | 58 | ```html 59 | 63 | 64 | {ar:route(routeName: 'myApp.order', parameters: {orderUid: '42'})} 65 | 66 | 67 | ``` 68 | 69 | ### Configuration Module 70 | 71 | In the configuration module there's an entry "App Routes", that shows all configured routes. 72 | ***Requires TYPO3 v11*** 73 | 74 | ### Server Side Caching 75 | 76 | * Caching can be enabled per route via configuration `defaults.cache: true`. 77 | * The TYPO3 `pages` cache is used to cache API responses. 78 | * Your request handler will not be called at all if the request can be served from cache. 79 | * Only responses for `GET` and `HEAD` requests can be cached. 80 | * The cache key is built from all query parameters that were matched by your route. 81 | * If `$GLOBALS['TSFE']` was involved in handling the request and cache tags were added to it via `$tsfe->addCacheTags($tags)`, those are applied to the cache entry. 82 | * If you have `$GLOBALS['TYPO3_CONF_VARS']['FE']['debug']` enabled, the HTTP response contains headers describing its cache status. 83 | * Responses with `Cache-Control: no-cache` or `Cache-Control: no-store` are not cached. 84 | * Responses with `Cache-Control: max-age=300` overwrite the default TTL of the `pages` cache. 85 | 86 | ### ETag 87 | 88 | Setting an `ETag` header in your response will enable conditional requests, i.e. the client doesn't need to download the response body if it already has the latest version. 89 | 90 | * If your response contains an `ETag` header and it matches the `If-None-Match` header of the request, the response HTTP status will be `304 Not Modified` and the response body will be empty. 91 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sinso/app-routes", 3 | "type": "typo3-cms-extension", 4 | "description": "Easy way to route rest-like URLs to your code", 5 | "license": "GPL-2.0-only", 6 | "require": { 7 | "typo3/cms-core": "^12.4 || ^13.4" 8 | }, 9 | "autoload": { 10 | "psr-4": { 11 | "Sinso\\AppRoutes\\": "Classes" 12 | } 13 | }, 14 | "extra": { 15 | "typo3/cms": { 16 | "extension-key": "app_routes" 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ext_localconf.php: -------------------------------------------------------------------------------- 1 | \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend::class, 7 | 'backend' => \TYPO3\CMS\Core\Cache\Backend\FileBackend::class, 8 | 'options' => [ 9 | 'defaultLifetime' => 60 * 60 * 24 * 7, // route configuration is cached for a week. clear the cache if you change any AppRoute.yaml file 10 | ], 11 | ]; 12 | --------------------------------------------------------------------------------