1bfa47fb6SAlex<?php 2bfa47fb6SAlex 3fea4b096SAlexander Lehmannuse dokuwiki\Extension\ActionPlugin; 4fea4b096SAlexander Lehmannuse dokuwiki\Extension\EventHandler; 5fea4b096SAlexander Lehmann 6fea4b096SAlexander Lehmannclass action_plugin_googletagmanager extends ActionPlugin 7737086b3SAlexander Lehmann{ 8737086b3SAlexander Lehmann public const GTMID = 'GTMID'; 931d01fc3SNickeau 10bfa47fb6SAlex /** 11bfa47fb6SAlex * Register its handlers with the DokuWiki's event controller 12bfa47fb6SAlex */ 13fea4b096SAlexander Lehmann public function register(EventHandler $controller) 14737086b3SAlexander Lehmann { 158b69576fSAlexander Lehmann $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'addHeaders'); 16bfa47fb6SAlex } 17bfa47fb6SAlex 18737086b3SAlexander Lehmann public function addHeaders(&$event, $param) 19737086b3SAlexander Lehmann { 208b69576fSAlexander Lehmann $GTMID = $this->getConf(self::GTMID); 218b69576fSAlexander Lehmann if (!$GTMID) return; 2231d01fc3SNickeau 238b69576fSAlexander Lehmann $is_AW_tag = substr($GTMID, 0, 3) == 'AW-'; 240fc69df8SAlexander Lehmann 250fc69df8SAlexander Lehmann if ($is_AW_tag) { 26*c93bcb92SAlexander Lehmann $script1 = "https://www.googletagmanager.com/gtag/js?id={$GTMID}"; 27*c93bcb92SAlexander Lehmann $script2 = <<<EOT 28*c93bcb92SAlexander Lehmann window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} 29*c93bcb92SAlexander Lehmann gtag('js', new Date()); gtag('config', '{$GTMID}');"; 30*c93bcb92SAlexander Lehmann EOT; 31*c93bcb92SAlexander Lehmann 32*c93bcb92SAlexander Lehmann $event->data['script'][] = ['src' => $script1]; 33*c93bcb92SAlexander Lehmann $event->data['script'][] = ['type' => 'text/javascript', '_data' => $script2]; 340fc69df8SAlexander Lehmann } else { 35*c93bcb92SAlexander Lehmann $iframe = <<<EOT 36*c93bcb92SAlexander Lehmann <iframe src="https://www.googletagmanager.com/ns.html?id={$GTMID}" 37*c93bcb92SAlexander Lehmann height="0" width="0" style="display:none;visibility:hidden"></iframe> 38*c93bcb92SAlexander Lehmann EOT; 39*c93bcb92SAlexander Lehmann 40*c93bcb92SAlexander Lehmann $script = <<<EOT 41*c93bcb92SAlexander Lehmann (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': 42bfa47fb6SAlex new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], 43bfa47fb6SAlex j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 448b69576fSAlexander Lehmann 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); 45*c93bcb92SAlexander Lehmann })(window,document,'script','dataLayer','{$GTMID}'); 46*c93bcb92SAlexander Lehmann EOT; 47*c93bcb92SAlexander Lehmann 48*c93bcb92SAlexander Lehmann $event->data['noscript'][] = ['_data' => $iframe]; 49*c93bcb92SAlexander Lehmann $event->data['script'][] = ['type' => 'text/javascript', '_data' => $script]; 50bfa47fb6SAlex } 51bfa47fb6SAlex } 520fc69df8SAlexander Lehmann} 53