| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <?php
- namespace Opentalent\OtStats\Middleware;
- use Opentalent\OtCore\Website\OtPageRepository;
- use Opentalent\OtStats\Settings\StatsSettingsRepository;
- use Psr\Http\Message\ResponseInterface;
- use Psr\Http\Message\ServerRequestInterface;
- use Psr\Http\Server\MiddlewareInterface;
- use Psr\Http\Server\RequestHandlerInterface;
- use TYPO3\CMS\Core\Http\Stream;
- use TYPO3\CMS\Core\Utility\GeneralUtility;
- use TYPO3\CMS\Extbase\Object\ObjectManager;
- use TYPO3\CMS\Fluid\View\StandaloneView;
- /**
- * Hooks into the frontend request to add the matomo script into
- * the request's header
- *
- * @internal
- */
- class RequestHandler implements MiddlewareInterface
- {
- const TEMPLATES_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Templates';
- const PARTIALS_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Partials';
- const LAYOUTS_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Layouts';
- const TEMPLATE_FILE = self::TEMPLATES_ROOT_PATHS . '/Header/Include.html';
- public function __construct() {}
- /**
- * Process the frontend request to insert the matomo script in the header
- * if the stats module is activated
- *
- * @param ServerRequestInterface $request
- * @param RequestHandlerInterface $handler
- * @return ResponseInterface
- */
- public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
- {
- // Retrieve the current matomo site's id if set
- $otPageRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(OtPageRepository::class);
- $rootPageUid = $otPageRepository->getCurrentSiteRootPageUid();
- $statsSettingsRepository = GeneralUtility::makeInstance(ObjectManager::class)->get(StatsSettingsRepository::class);
- $matomoSiteId = $statsSettingsRepository->getMatomoSiteId($rootPageUid);
- if (!$matomoSiteId > 0) {
- // stats are not enabled, continue
- return $handler->handle($request);
- }
- // render view
- $view = GeneralUtility::makeInstance(StandaloneView::class);
- $view->setTemplateRootPaths([self::TEMPLATES_ROOT_PATHS]);
- $view->setPartialRootPaths([self::PARTIALS_ROOT_PATHS]);
- $view->setLayoutRootPaths([self::LAYOUTS_ROOT_PATHS]);
- $view->setTemplatePathAndFilename(
- GeneralUtility::getFileAbsFileName(self::TEMPLATE_FILE)
- );
- // Build the response
- $response = $handler->handle($request);
- // insert the rendered view in the body, just before the closing </html> tag
- $newSection = $view->render();
- $bodyContent = (string)$response->getBody();
- $bodyContent = str_replace('</head>', $newSection . '</head>', $bodyContent);
- $newBody = new Stream('php://temp', 'wb+');
- $newBody->write($bodyContent);
- $newBody->rewind();
- $response = $response->withBody($newBody);
- return $response;
- }
- }
|