Skip to content

Commit

Permalink
[FIX] Adjust post / comment controller actions for TYPO3 11
Browse files Browse the repository at this point in the history
* Adjust checks and actions to return response object
* Adjust to changed page caching functionality
* Improve CGL
  • Loading branch information
fnagel committed Mar 12, 2022
1 parent 56204aa commit c4dd85e
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 81 deletions.
42 changes: 16 additions & 26 deletions Classes/Controller/AbstractController.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ abstract class AbstractController extends ActionController
{
use LoggingTrait;

/**
* @var \TYPO3\CMS\Fluid\View\TemplateView
*/
protected $view;

/**
* Injects the Configuration Manager and is initializing the framework settings
* Function is used to override the merge of settings via TS & flexforms
Expand Down Expand Up @@ -70,16 +75,15 @@ public function injectConfigurationManager(ConfigurationManagerInterface $config
$this->settings = $originalSettings;
}

/**
* @inheritdoc
*/
public function processRequest(RequestInterface $request): ResponseInterface
{
try {
return parent::processRequest($request);
$response = parent::processRequest($request);
} catch (\Exception $exception) {
$this->handleKnownExceptionsElseThrowAgain($exception);
}

return $response;
}

protected function handleKnownExceptionsElseThrowAgain(\Throwable $exception)
Expand Down Expand Up @@ -124,10 +128,11 @@ protected function validateTypoScriptConfiguration()
}

/**
* Override getErrorFlashMessage to present
* nice flash error messages.
* Override getErrorFlashMessage to present nice flash error messages.
*
* @return string|false
*/
protected function getErrorFlashMessage(): string
protected function getErrorFlashMessage()
{
$defaultFlashMessage = parent::getErrorFlashMessage();
$locallangKey = sprintf('error.%s.%s', lcfirst($this->request->getControllerName()), $this->actionMethodName);
Expand Down Expand Up @@ -162,26 +167,11 @@ protected function hasFlashMessages(): bool
}

/**
* Clear cache of current page and sends correct header.
* Clear cache of current page.
*/
protected function clearPageCache()
{
if ($this->arguments->hasArgument('post')) {
$flushCacheService = $this->objectManager->get(FlushCacheService::class);
$post = $this->arguments->getArgument('post')->getValue();
$flushCacheService->addCacheTagsToFlush([
'tx_t3blog_post_uid_'.$post->getLocalizedUid(),
]);
} else {
// @todo TYPO3 11: Fix this!
parent::clearCacheOnError();
}

// @todo TYPO3 11: Fix this!
$this->response->setHeader('Cache-Control', 'private', true);
$this->response->setHeader('Expires', '0', true);
$this->response->setHeader('Pragma', 'no-cache', true);
$this->response->sendHeaders();
FlushCacheService::clearPageCache();
}

protected function pageNotFoundAndExit(string $message = 'Entity not found.')
Expand All @@ -191,13 +181,13 @@ protected function pageNotFoundAndExit(string $message = 'Entity not found.')
$message
);

throw new ImmediateResponseException($response, 1576748646637);
throw new ImmediateResponseException($response, 1576748646);
}

/**
* Persist all records to database.
*/
protected function persistAllEntities(): string
protected function persistAllEntities(): void
{
/* @var $persistenceManager PersistenceManager */
$persistenceManager = $this->objectManager->get(PersistenceManager::class);
Expand Down
62 changes: 31 additions & 31 deletions Classes/Controller/CommentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,9 @@ public function showAction(Post $post)
/**
* action new.
*
* @param Post $post The post the comment is related to
* @param Comment $newComment
* @param Post $post The post the comment is related to
* @param Comment|null $newComment
* @return ResponseInterface
* @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("newComment")
*/
public function newAction(Post $post, Comment $newComment = null): ResponseInterface
Expand All @@ -130,8 +131,16 @@ public function newAction(Post $post, Comment $newComment = null): ResponseInter
*/
public function createAction(Post $post, Comment $newComment)
{
$this->checkIfCommentIsAllowed($post);
$this->checkSpamPoints($newComment);
$commentAllowedResult = $this->checkIfCommentIsAllowed($post);
if ($commentAllowedResult instanceof ResponseInterface) {
return $commentAllowedResult;
}

$spamPointResult = $this->checkSpamPoints($newComment);
if ($spamPointResult instanceof ResponseInterface) {
return $spamPointResult;
}

$this->sanitizeComment($newComment);

if ($this->settings['blogsystem']['comments']['approvedByDefault']) {
Expand All @@ -154,55 +163,45 @@ public function createAction(Post $post, Comment $newComment)

if (!$this->hasFlashMessages()) {
if ($newComment->isApproved()) {
$this->addFlashMessageByKey('created', FlashMessage::OK);
$this->addFlashMessageByKey('created');
} else {
$this->addFlashMessageByKey('createdDisapproved', FlashMessage::NOTICE);
}

$this->clearPageCache();
}

$this->redirect('show', 'Post', null, $post->getLinkParameter());
}

/**
* @inheritDoc
*/
protected function clearCacheOnError()
{
$this->clearPageCache();
}

/**
* Checks if a new comment could be created.
*
* @param Post $post The post the comment is related to
*/
protected function checkIfCommentIsAllowed(Post $post)
protected function checkIfCommentIsAllowed(Post $post): ?ResponseInterface
{
$settings = $this->settings['blogsystem']['comments'];

if (!$settings['allowed'] || $post->getAllowComments() === Post::ALLOW_COMMENTS_NOBODY) {
$this->addFlashMessageByKey('notAllowed', FlashMessage::ERROR);
$this->errorAction();
return $this->errorAction();
}

if ($post->getAllowComments() === Post::ALLOW_COMMENTS_LOGIN && !GeneralUtility::isUserLoggedIn()
) {
if ($post->getAllowComments() === Post::ALLOW_COMMENTS_LOGIN && !GeneralUtility::isUserLoggedIn()) {
$this->addFlashMessageByKey('notLoggedIn', FlashMessage::ERROR);
$this->errorAction();
return $this->errorAction();
}

if ($settings['allowedUntil'] && $post->isExpired(trim($settings['allowedUntil']))) {
$this->addFlashMessageByKey('commentsClosed', FlashMessage::ERROR);
$this->errorAction();
return $this->errorAction();
}

return null;
}

/**
* Process comment request.
*
* @param Comment $comment The comment to be deleted
*/
protected function checkSpamPoints(Comment $comment)
protected function checkSpamPoints(Comment $comment): ?ResponseInterface
{
$settings = $this->settings['blogsystem']['comments']['spamCheck'];
$comment->setSpamPoints($this->spamCheckService->process($settings));
Expand All @@ -221,17 +220,15 @@ protected function checkSpamPoints(Comment $comment)
null,
null,
$settings['redirect']['arguments'],
(int)$settings['redirect']['pid'],
0,
403
(int)$settings['redirect']['pid']
);
}

// block comment and show message
if ($threshold['block'] > 0 && $comment->getSpamPoints() >= (int) $threshold['block']) {
$this->getLog()->notice('New comment blocked because of SPAM.', $logData);
$this->addFlashMessageByKey('blockedAsSpam', FlashMessage::ERROR);
$this->errorAction();
return $this->errorAction();
}

// mark as spam
Expand All @@ -240,11 +237,12 @@ protected function checkSpamPoints(Comment $comment)
$comment->markAsSpam();
$this->addFlashMessageByKey('markedAsSpam', FlashMessage::NOTICE);
}

return null;
}

/**
* Sanitize comment content.
*
*/
protected function sanitizeComment(Comment $comment)
{
Expand All @@ -264,8 +262,10 @@ protected function sanitizeComment(Comment $comment)

/**
* Disable error flash message.
*
* @return string|false
*/
protected function getErrorFlashMessage(): string
protected function getErrorFlashMessage()
{
return false;
}
Expand Down
24 changes: 15 additions & 9 deletions Classes/Service/FlushCacheService.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Service\CacheService;

/**
* Handles email sending and templating.
Expand All @@ -23,7 +24,6 @@ class FlushCacheService implements SingletonInterface
*/
protected $cacheTagsToFlush = [];


public function initializeObject()
{
// Clear cache on shutdown
Expand All @@ -33,7 +33,7 @@ public function initializeObject()
/**
* Clear all added cache tags. Called on shutdown.
*/
public function flushFrontendCache()
protected function flushFrontendCache()
{
static::flushFrontendCacheByTags($this->cacheTagsToFlush);
}
Expand All @@ -42,8 +42,6 @@ public function flushFrontendCache()
* Add a cache tag to flush.
*
* @param string|array $cacheTagsToFlush
*
* @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
*/
public function addCacheTagsToFlush($cacheTagsToFlush)
{
Expand All @@ -60,12 +58,8 @@ public function addCacheTagsToFlush($cacheTagsToFlush)

/**
* Clear frontend page cache by tags.
*
* @param $cacheTagsToFlush
*
* @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
*/
public static function flushFrontendCacheByTags($cacheTagsToFlush)
public static function flushFrontendCacheByTags(array $cacheTagsToFlush)
{
if (count($cacheTagsToFlush) < 1) {
return;
Expand All @@ -79,4 +73,16 @@ public static function flushFrontendCacheByTags($cacheTagsToFlush)
$cacheManager->getCache('cache_pagesection')->flushByTag($cacheTag);
}
}

/**
* Clear current frontend page cache.
*/
public static function clearPageCache()
{
$pageUid = \FelixNagel\T3extblog\Utility\GeneralUtility::getPageUid();

/** @var $cacheService CacheService */
$cacheService = GeneralUtility::makeInstance(CacheService::class);
$cacheService->clearPageCache([$pageUid]);
}
}
31 changes: 16 additions & 15 deletions Classes/Utility/GeneralUtility.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility as CoreGeneralUtility;
use TYPO3\CMS\Core\Core\Bootstrap;
use TYPO3\CMS\Core\Http\ApplicationType;

/**
Expand All @@ -26,7 +25,6 @@ class GeneralUtility implements SingletonInterface
{
/**
* Get TypoScript frontend controller.
*
*/
public static function getTsFe(): \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
{
Expand All @@ -37,31 +35,32 @@ public static function getTsFe(): \TYPO3\CMS\Frontend\Controller\TypoScriptFront
return $GLOBALS['TSFE'];
}

/**
* Get FE page UID.
*/
public static function getPageUid(): int
{
return static::getTsFe()->id;
}

/**
* Get FE language UID.
*
*/
public static function getLanguageUid(): int
{
$languageAspect = CoreGeneralUtility::makeInstance(Context::class)->getAspect('language');

return $languageAspect->getId();
return static::getContext()->getAspect('language')->getId();
}

/**
* CAUTION: disables whole FE cache!
*
*/
public static function disableFrontendCache(): void
{
if (isset($GLOBALS['TSFE'])) {
$GLOBALS['TSFE']->no_cache = true;
}
static::getTsFe()->set_no_cache('EXT:t3extblog', true);
}

/**
* Get page renderer.
*
*/
public static function getPageRenderer(): PageRenderer
{
Expand All @@ -70,13 +69,10 @@ public static function getPageRenderer(): PageRenderer

/**
* Check if FE user is logged in
*
*/
public static function isUserLoggedIn(): bool
{
$context = CoreGeneralUtility::makeInstance(Context::class);

return (bool)$context->getPropertyFromAspect('frontend.user', 'isLoggedIn');
return (bool)static::getContext()->getPropertyFromAspect('frontend.user', 'isLoggedIn');
}

/**
Expand All @@ -86,4 +82,9 @@ public static function isValidBackendUser(): bool
{
return static::getTsFe()->isBackendUserLoggedIn();
}

protected static function getContext(): Context
{
return CoreGeneralUtility::makeInstance(Context::class);
}
}

0 comments on commit c4dd85e

Please sign in to comment.