Skip to content

Commit

Permalink
[FEATURE] Introduce RedirectWasHitEvent
Browse files Browse the repository at this point in the history
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 <typo3@b13.com>
Tested-by: Benni Mack <benni@typo3.org>
Tested-by: Stefan Bürk <stefan@buerk.tech>
Tested-by: Oliver Bartsch <bo@cedev.de>
Reviewed-by: Benni Mack <benni@typo3.org>
Reviewed-by: Stefan Bürk <stefan@buerk.tech>
Reviewed-by: Oliver Bartsch <bo@cedev.de>
  • Loading branch information
o-ba committed Dec 1, 2021
1 parent bbb675a commit 635df9b
Show file tree
Hide file tree
Showing 7 changed files with 370 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
.. 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
77 changes: 77 additions & 0 deletions typo3/sysext/redirects/Classes/Event/RedirectWasHitEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?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;
}
}
57 changes: 57 additions & 0 deletions typo3/sysext/redirects/Classes/EventListener/IncrementHitCount.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?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();
}
}
72 changes: 27 additions & 45 deletions typo3/sysext/redirects/Classes/Http/Middleware/RedirectHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,15 @@

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;

/**
Expand All @@ -36,18 +34,23 @@
*
* @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
Expand All @@ -63,11 +66,12 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
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();
}
}

Expand All @@ -76,31 +80,9 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface

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']);
}
}
5 changes: 5 additions & 0 deletions typo3/sysext/redirects/Configuration/Services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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>
Loading

0 comments on commit 635df9b

Please sign in to comment.