From 5fe09b03f81b09ed77f05e295d241bf2cd77d67c Mon Sep 17 00:00:00 2001
From: Ere Maijala <ere.maijala@helsinki.fi>
Date: Thu, 6 Oct 2016 10:02:24 +0300
Subject: [PATCH] Avoid duplicate Piwik loading and function conflicts. - Use a
 timestamped init function name in Piwik tracking and load the tracking js
 only once. Fixes an error in lightbox and record tab tracking (Piwik logs to
 console: "A siteId must be given to add a new tracker").

---
 .../src/VuFind/View/Helper/Root/Piwik.php     | 27 ++++++++++++++-----
 1 file changed, 21 insertions(+), 6 deletions(-)

diff --git a/module/VuFind/src/VuFind/View/Helper/Root/Piwik.php b/module/VuFind/src/VuFind/View/Helper/Root/Piwik.php
index 146ba9446df..db7ea75626a 100644
--- a/module/VuFind/src/VuFind/View/Helper/Root/Piwik.php
+++ b/module/VuFind/src/VuFind/View/Helper/Root/Piwik.php
@@ -87,6 +87,14 @@ class Piwik extends \Zend\View\Helper\AbstractHelper
      */
     protected $params;
 
+    /**
+     * A timestamp used to identify the init function to avoid name clashes when
+     * opening lightboxes.
+     *
+     * @var int
+     */
+    protected $timestamp;
+
     /**
      * Constructor
      *
@@ -108,6 +116,7 @@ class Piwik extends \Zend\View\Helper\AbstractHelper
         $this->customVars = $customVars;
         $this->router = $router;
         $this->request = $request;
+        $this->timestamp = round(microtime(true) * 1000);
     }
 
     /**
@@ -389,7 +398,7 @@ class Piwik extends \Zend\View\Helper\AbstractHelper
     {
         return <<<EOT
 
-function initVuFindPiwikTracker(){
+function initVuFindPiwikTracker{$this->timestamp}(){
     var VuFindPiwikTracker = Piwik.getTracker();
 
     VuFindPiwikTracker.setSiteId({$this->siteId});
@@ -432,11 +441,17 @@ EOT;
     VuFindPiwikTracker.enableLinkTracking();
 };
 (function(){
-var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
-    g.type='text/javascript'; g.defer=true; g.async=true;
-    g.src='{$this->url}piwik.js';
-    g.onload=initVuFindPiwikTracker;
-s.parentNode.insertBefore(g,s); })();
+    if (typeof Piwik === 'undefined') {
+        var d=document, g=d.createElement('script'),
+            s=d.getElementsByTagName('script')[0];
+        g.type='text/javascript'; g.defer=true; g.async=true;
+        g.src='{$this->url}piwik.js';
+        g.onload=initVuFindPiwikTracker{$this->timestamp};
+        s.parentNode.insertBefore(g,s);
+    } else {
+        initVuFindPiwikTracker{$this->timestamp}();
+    }
+})();
 EOT;
     }
 
-- 
GitLab