Commit 635df9b7 authored by Oliver Bartsch's avatar Oliver Bartsch
Browse files

[FEATURE] Introduce RedirectWasHitEvent

A new PSR-14 based event "RedirectWasHitEvent" is introduced,
allowing extension authors to further process a matched redirect
and to adjust the PSR-7 Response. It's furthermore possibility
to influence core functionality, e.g. the hit count increment.
This is especially useful for e.g. the use of custom monitoring
tools, which should not increment the hit count while testing
the redirects.

As a side effect, the middleware is cleaned up, since the
increment task is moved into a dedicated event listener.

Resolves: #96147
Releases: main
Change-Id: I146b60d9a347199f7a871edca0845e7d635817df
Reviewed-on: https://review.typo3.org/c/Packages/TYPO3.CMS/+/72437


Tested-by: core-ci's avatarcore-ci <typo3@b13.com>
Tested-by: Benni Mack's avatarBenni Mack <benni@typo3.org>
Tested-by: Stefan Bürk's avatarStefan Bürk <stefan@buerk.tech>
Tested-by: Oliver Bartsch's avatarOliver Bartsch <bo@cedev.de>
Reviewed-by: Benni Mack's avatarBenni Mack <benni@typo3.org>
Reviewed-by: Stefan Bürk's avatarStefan Bürk <stefan@buerk.tech>
Reviewed-by: Oliver Bartsch's avatarOliver Bartsch <bo@cedev.de>
parent bbb675a5
Pipeline #20372 passed with stages
in 52 minutes and 59 seconds
.. include:: ../../Includes.txt
================================================
Feature: #96147 - New PSR-14 RedirectWasHitEvent
================================================
See :issue:`96147`
Description
===========
A new PSR-14 event :php:`\TYPO3\CMS\Redirects\Event\RedirectWasHitEvent`
has been added to TYPO3 Core. This event is fired in the
:php:`\TYPO3\CMS\Redirects\Http\Middleware\RedirectHandler`
middleware and allows extensions to further process the matched
redirect and to adjust the PSR-7 response.
The event features the following methods:
- :php:`getRequest()`: Returns the current PSR-7 Request
- :php:`getResponse()`: Returns the current PSR-7 Response
- :php:`setResponse()`: Can be used to set / update the PSR-7 Response
- :php:`getMatchedRedirect()`: Returns the matched redirect record
- :php:`setMatchedRedirect()`: Can be used to set / update the matched redirect record
- :php:`getTargetUrl()`: Returns the resolved redirect target
TYPO3 already implements the :php:`IncrementHitCount` listener. It is
used to increment the hit count of the matched redirect record, if the
feature is enabled. In case you want to prevent the increment in some
cases, e.g. when the request was initiated by a monitoring tool, you
can either implement your own listener with the same identifier
(:yaml:`redirects-increment-hit-count`) or add your custom listener
before and dynamically set the records :php:`disable_hitcount` flag.
Registration of the Event in your extensions' :file:`Services.yaml`:
.. code-block:: yaml
MyVendor\MyPackage\Redirects\MyEventListener:
tags:
- name: event.listener
identifier: 'my-package/redirects/validate-hit-count'
before: 'redirects-increment-hit-count'
The corresponding event listener class:
.. code-block:: php
use TYPO3\CMS\Redirects\Event\RedirectWasHitEvent;
class MyEventListener {
public function __invoke(RedirectWasHitEvent $event): void
{
$matchedRedirect = $event->getMatchedRedirect();
// This will disable the hit count increment in case the target
// is the page 123 and the request is from the monitoring tool.
if (str_contains($matchedRedirect['target'], 'uid=123')
&& $event->getRequest()->getAttribute('normalizedParams')->getHttpUserAgent() === 'my monitoring tool'
) {
$matchedRedirect['disable_hitcount'] = true;
$event->setMatchedRedirect(
$matchedRedirect
);
// Also add a custom response header
$event->setResponse(
$event->getResponse()->withAddedHeader('X-Custom-Header', 'Hit count increment skipped')
);
}
}
}
Impact
======
This event can be used to further process the matched redirect
and to adjust the PSR-7 Response. It furthermore allows to
influence core functionality, e.g. the hit count increment.
.. index:: PHP-API, ext:redirects
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Redirects\Event;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UriInterface;
/**
* This event is fired when a request matches a configured redirect
*
* This allows to further process the matched redirect and adjusting the PSR-7 response
*/
final class RedirectWasHitEvent
{
private ServerRequestInterface $request;
private ResponseInterface $response;
private array $matchedRedirect;
private UriInterface $targetUrl;
public function __construct(
ServerRequestInterface $request,
ResponseInterface $response,
array $matchedRedirect,
UriInterface $targetUrl
) {
$this->request = $request;
$this->response = $response;
$this->matchedRedirect = $matchedRedirect;
$this->targetUrl = $targetUrl;
}
public function getRequest(): ServerRequestInterface
{
return $this->request;
}
public function getTargetUrl(): UriInterface
{
return $this->targetUrl;
}
public function setMatchedRedirect(array $matchedRedirect): void
{
$this->matchedRedirect = $matchedRedirect;
}
public function getMatchedRedirect(): array
{
return $this->matchedRedirect;
}
public function setResponse(ResponseInterface $response): void
{
$this->response = $response;
}
public function getResponse(): ResponseInterface
{
return $this->response;
}
}
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Redirects\EventListener;
use TYPO3\CMS\Core\Configuration\Features;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Redirects\Event\RedirectWasHitEvent;
/**
* Event listener to increment a matched redirect records' hit count
*/
final class IncrementHitCount
{
protected Features $features;
public function __construct(Features $features)
{
$this->features = $features;
}
public function __invoke(RedirectWasHitEvent $event): void
{
$matchedRedirect = $event->getMatchedRedirect();
if ($matchedRedirect['disable_hitcount']
|| !$this->features->isFeatureEnabled('redirects.hitCount')
) {
// Early return in case hit count is disabled
return;
}
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_redirect');
$queryBuilder
->update('sys_redirect')
->where(
$queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($matchedRedirect['uid'], \PDO::PARAM_INT))
)
->set('hitcount', $queryBuilder->quoteIdentifier('hitcount') . '+1', false)
->set('lasthiton', $GLOBALS['EXEC_TIME'])
->execute();
}
}
......@@ -17,17 +17,15 @@ declare(strict_types=1);
namespace TYPO3\CMS\Redirects\Http\Middleware;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UriInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use TYPO3\CMS\Core\Configuration\Features;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Http\RedirectResponse;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use Psr\Log\LoggerInterface;
use TYPO3\CMS\Core\EventDispatcher\EventDispatcher;
use TYPO3\CMS\Redirects\Event\RedirectWasHitEvent;
use TYPO3\CMS\Redirects\Service\RedirectService;
/**
......@@ -36,18 +34,23 @@ use TYPO3\CMS\Redirects\Service\RedirectService;
*
* @internal
*/
class RedirectHandler implements MiddlewareInterface, LoggerAwareInterface
class RedirectHandler implements MiddlewareInterface
{
use LoggerAwareTrait;
protected RedirectService $redirectService;
protected EventDispatcher $eventDispatcher;
protected ResponseFactoryInterface $responseFactory;
protected LoggerInterface $logger;
/**
* @var RedirectService
*/
protected $redirectService;
public function __construct(RedirectService $redirectService)
{
public function __construct(
RedirectService $redirectService,
EventDispatcher $eventDispatcher,
ResponseFactoryInterface $responseFactory,
LoggerInterface $logger
) {
$this->redirectService = $redirectService;
$this->eventDispatcher = $eventDispatcher;
$this->responseFactory = $responseFactory;
$this->logger = $logger;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
......@@ -63,11 +66,12 @@ class RedirectHandler implements MiddlewareInterface, LoggerAwareInterface
if (is_array($matchedRedirect)) {
$url = $this->redirectService->getTargetUrl($matchedRedirect, $request);
if ($url instanceof UriInterface) {
$this->logger->debug('Redirecting', ['record' => $matchedRedirect, 'uri' => $url]);
$this->logger->debug('Redirecting', ['record' => $matchedRedirect, 'uri' => (string)$url]);
$response = $this->buildRedirectResponse($url, $matchedRedirect);
$this->incrementHitCount($matchedRedirect);
return $response;
// Dispatch event, allowing listeners to execute further tasks and to adjust the PSR-7 response
return $this->eventDispatcher->dispatch(
new RedirectWasHitEvent($request, $response, $matchedRedirect, $url)
)->getResponse();
}
}
......@@ -76,31 +80,9 @@ class RedirectHandler implements MiddlewareInterface, LoggerAwareInterface
protected function buildRedirectResponse(UriInterface $uri, array $redirectRecord): ResponseInterface
{
return new RedirectResponse(
$uri,
(int)$redirectRecord['target_statuscode'],
['X-Redirect-By' => 'TYPO3 Redirect ' . $redirectRecord['uid']]
);
}
/**
* Updates the sys_redirect's hit counter by one
*/
protected function incrementHitCount(array $redirectRecord): void
{
// Track the hit if not disabled
if (!GeneralUtility::makeInstance(Features::class)->isFeatureEnabled('redirects.hitCount') || $redirectRecord['disable_hitcount']) {
return;
}
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('sys_redirect');
$queryBuilder
->update('sys_redirect')
->where(
$queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($redirectRecord['uid'], \PDO::PARAM_INT))
)
->set('hitcount', $queryBuilder->quoteIdentifier('hitcount') . '+1', false)
->set('lasthiton', $GLOBALS['EXEC_TIME'])
->execute();
return $this->responseFactory
->createResponse((int)$redirectRecord['target_statuscode'])
->withHeader('location', (string)$uri)
->withHeader('X-Redirect-By', 'TYPO3 Redirect ' . $redirectRecord['uid']);
}
}
......@@ -36,3 +36,8 @@ services:
- name: event.listener
identifier: 'redirects-enable-hook'
method: 'afterHistoryRollbackFinishedEvent'
TYPO3\CMS\Redirects\EventListener\IncrementHitCount:
tags:
- name: event.listener
identifier: 'redirects-increment-hit-count'
<?xml version="1.0" encoding="utf-8"?>
<dataset>
<sys_redirect>
<uid>12</uid>
<pid>0</pid>
<deleted>0</deleted>
<disabled>0</disabled>
<target>https://example.com/bar</target>
<target_statuscode>307</target_statuscode>
<hitcount>3</hitcount>
<disable_hitcount>0</disable_hitcount>
</sys_redirect>
<sys_redirect>
<uid>13</uid>
<pid>0</pid>
<deleted>0</deleted>
<disabled>0</disabled>
<target>https://example.com/baz</target>
<target_statuscode>307</target_statuscode>
<hitcount>0</hitcount>
<disable_hitcount>1</disable_hitcount>
</sys_redirect>
</dataset>
<?php
declare(strict_types=1);
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Redirects\Tests\Functional\EventListener;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\EventDispatcher\EventDispatcher;
use TYPO3\CMS\Core\Http\RedirectResponse;
use TYPO3\CMS\Core\Http\ServerRequest;
use TYPO3\CMS\Core\Http\Uri;
use TYPO3\CMS\Redirects\Event\RedirectWasHitEvent;
use TYPO3\TestingFramework\Core\Functional\FunctionalTestCase;
class IncrementHitCountTest extends FunctionalTestCase
{
protected $coreExtensionsToLoad = ['redirects'];
protected function setUp(): void
{
parent::setUp();
$this->importDataSet(__DIR__ . '/Fixtures/Redirects.xml');
}
/**
* @test
*/
public function hitCountIsCorrectlyIncremented(): void
{
$matchedRecord = BackendUtility::getRecord('sys_redirect', 12);
// Assert current hit count
self::assertEquals(3, (int)$matchedRecord['hitcount']);
$this->getContainer()->get(EventDispatcher::class)->dispatch(
new RedirectWasHitEvent(
new ServerRequest('https://acme.com'),
new RedirectResponse($matchedRecord['target']),
$matchedRecord,
new Uri($matchedRecord['target'])
)
);
// Assert hit count is not incremented, due to missing feature flag
self::assertEquals(3, (int)(BackendUtility::getRecord('sys_redirect', 12)['hitcount']));
// Set flag
$GLOBALS['TYPO3_CONF_VARS']['SYS']['features']['redirects.hitCount'] = true;
// Use another record, which has "disable_hitcount" set
$matchedRecord = BackendUtility::getRecord('sys_redirect', 13);
// Assert current hit count
self::assertEquals(0, (int)$matchedRecord['hitcount']);
$this->getContainer()->get(EventDispatcher::class)->dispatch(
new RedirectWasHitEvent(
new ServerRequest('https://acme.com'),
new RedirectResponse($matchedRecord['target']),
$matchedRecord,
new Uri($matchedRecord['target'])
)
);
// Assert hit count is not incremented, due to records' disable flag
self::assertEquals(0, (int)(BackendUtility::getRecord('sys_redirect', 13)['hitcount']));
// Check record=12 again, as the feature flag is now enabled and the hit count is not disabled for the record
$matchedRecord = BackendUtility::getRecord('sys_redirect', 12);
// Assert current hit count
self::assertEquals(3, (int)$matchedRecord['hitcount']);
$this->getContainer()->get(EventDispatcher::class)->dispatch(
new RedirectWasHitEvent(
new ServerRequest('https://acme.com'),
new RedirectResponse($matchedRecord['target']),
$matchedRecord,
new Uri($matchedRecord['target'])
)
);
// Assert incremented hit count
self::assertEquals(4, (int)(BackendUtility::getRecord('sys_redirect', 12)['hitcount']));
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment