2021-04-11 13:41:47 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace MMK2410\PlausibleAnalytics\Hooks;
|
|
|
|
|
|
|
|
use TYPO3\CMS\Core\Page\AssetCollector;
|
|
|
|
use TYPO3\CMS\Core\Utility\GeneralUtility;
|
2023-05-06 12:55:57 +02:00
|
|
|
use TYPO3\CMS\Core\Context\Context;
|
2021-04-11 13:41:47 +02:00
|
|
|
|
|
|
|
class PageRendererPreProcess
|
|
|
|
{
|
|
|
|
/** @var \TYPO3\CMS\Core\Page\AssetCollector */
|
|
|
|
private $assetCollector;
|
|
|
|
|
|
|
|
/** @var \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController */
|
|
|
|
private $tsfe;
|
|
|
|
|
2023-05-06 12:55:57 +02:00
|
|
|
/** @var Context */
|
|
|
|
private $context;
|
|
|
|
|
2021-04-11 13:41:47 +02:00
|
|
|
public function __construct(AssetCollector $assetCollector = null)
|
|
|
|
{
|
|
|
|
$this->assetCollector = $assetCollector ?? GeneralUtility::makeInstance(AssetCollector::class);
|
2022-08-10 18:46:22 +02:00
|
|
|
$this->tsfe = $GLOBALS['TSFE'] ?? null;
|
2023-05-06 12:55:57 +02:00
|
|
|
$this->context = GeneralUtility::makeInstance(Context::class);
|
2021-04-11 13:41:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public function addLibrary(): void
|
|
|
|
{
|
2023-05-06 12:55:57 +02:00
|
|
|
if (!isset($this->tsfe)|| !isset($this->context)) {
|
2021-05-03 19:48:34 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-04-11 13:41:47 +02:00
|
|
|
$domain = $this->getDomain();
|
|
|
|
$plausible = $this->getPlausibleURL();
|
|
|
|
|
2023-05-06 12:55:57 +02:00
|
|
|
if (
|
|
|
|
isset($domain) &&
|
|
|
|
isset($plausible) &&
|
|
|
|
!$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn')
|
|
|
|
) {
|
2022-08-10 18:48:26 +02:00
|
|
|
$this->assetCollector->addJavaScript(
|
|
|
|
'plausible_analytics',
|
|
|
|
$plausible . '/js/plausible.js',
|
|
|
|
[
|
|
|
|
'async' => 'async',
|
|
|
|
'defer' => 'defer',
|
|
|
|
'data-domain' => $domain
|
|
|
|
],
|
|
|
|
);
|
2021-04-11 13:41:47 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function getPlausibleURL(): ?string
|
|
|
|
{
|
|
|
|
if (!isset($this->tsfe)) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this->tsfe->getSite()->getConfiguration()['plausible_url'] ?? null;
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function getDomain(): ?string
|
|
|
|
{
|
|
|
|
if (!isset($this->tsfe)) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
$domain = $this->tsfe->getSite()->getConfiguration()['plausible_domain'];
|
|
|
|
|
|
|
|
if (!empty($domain)) {
|
|
|
|
return $domain;
|
|
|
|
}
|
|
|
|
|
|
|
|
$base = $this->tsfe->getSite()->getConfiguration()['base'];
|
|
|
|
|
|
|
|
if (!isset($base)) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (strpos($base, 'http://') !== false || strpos($base, 'https://') !== false) {
|
|
|
|
return preg_replace('/https?:\/\/([^\/\n]*).*/', '$1', $base);
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|