<?php
declare(strict_types = 1);
namespace Aufwind\CookiebotBundle\EventSubscriber;
use Aufwind\CookiebotBundle\CookiebotService;
use Aufwind\CookiebotBundle\Helper\YoutubeFallbackRenderer;
use Aufwind\CookiebotBundle\Service\ConfigManager;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\EnabledTrait;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\PimcoreContextAwareTrait;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\PreviewRequestTrait;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\ResponseInjectionTrait;
use Pimcore\Http\Request\Resolver\PimcoreContextResolver;
use Pimcore\Tool;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PimcoreVideoSubscriber implements EventSubscriberInterface
{
use EnabledTrait;
use ResponseInjectionTrait;
use PimcoreContextAwareTrait;
use PreviewRequestTrait;
public function __construct(
protected ConfigManager $configManager,
protected CookiebotService $cookiebotService,
protected YoutubeFallbackRenderer $youtubeFallbackRenderer,
) {
}
public function onKernelResponse(ResponseEvent $event): void
{
if (!$this->configManager->isAutoInsert()) {
return;
}
if (!$this->isEnabled()) {
return;
}
$request = $event->getRequest();
if (!$event->isMainRequest()) {
return;
}
// only inject tag manager code on non-admin requests
if (!$this->matchesPimcoreContext($request, PimcoreContextResolver::CONTEXT_DEFAULT)) {
return;
}
if (!Tool::useFrontendOutputFilters()) {
return;
}
if ($this->isPreviewRequest($request)) {
return;
}
$response = $event->getResponse();
if (!$this->isHtmlResponse($response)) {
return;
}
if (!$this->cookiebotService->isCookieBotEnabled()) {
return;
}
$content = $response->getContent();
$pattern = "/<iframe(.*?)><\/iframe>/mi";
$matches = [];
if (false === preg_match_all($pattern, $content, $matches)) {
return;
}
$replaced = false;
foreach ($matches[0] as $iframeHtml) {
if (false === strpos($iframeHtml, 'src="https://www.youtube-nocookie.com/') && false === strpos($iframeHtml, 'src="https://www.youtube.com/') && false === strpos($iframeHtml, 'src="https://youtu.be/')) {
continue;
}
$newHtml = preg_replace('/src="/mi', 'data-cookieconsent="marketing" data-cookieblock-src="', $iframeHtml);
if (!empty($newHtml)) {
$replaced = true;
}
$content = str_replace($iframeHtml, $this->youtubeFallbackRenderer->render($newHtml), $content);
}
if ($replaced) {
$css = dirname(__FILE__) . '/../Resources/public/css/cookiebot-draft-video.css';
$css = '<style>' . file_get_contents($css) . '</style>';
$content = str_replace('</head>', $css . '</head>', $content);
}
$response->setContent($content);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => [
['onKernelResponse', -108],
],
];
}
}