<?PHP
#
#   FILE:  GoogleAnalytics.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2014 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

/**
* Plugin to add Google Analytics tracking code to the HTML header.  The code
* is inserted via the EVENT_IN_HTML_HEADER event, so that event must be
* signaled in the active user interface for the plugin to work correctly.
*/
class GoogleAnalytics extends Plugin {

    # ---- STANDARD PLUGIN INTERFACE -----------------------------------------

    /**
    * Set plugin attributes.
    */
    function Register()
    {
        $this->Name = "Google Analytics";
        $this->Version = "1.0.1";
        $this->Description = "Add Google Analytics tracking code to the HTML"
                ." page header.";
        $this->Author = "Internet Scout";
        $this->Url = "http://scout.wisc.edu/cwis/";
        $this->Email = "scout@scout.wisc.edu";
        $this->Requires = array(
                "CWISCore" => "3.1.0");
        $this->EnabledByDefault = FALSE;

        $this->CfgSetup["TrackingId"] = array(
                "Type" => "Text",
                "Label" => "Tracking ID",
                "Help" => "Your Google Analytics tracking ID (should be in"
                        ." the form <i>UA-NNNNNNNN-N</i>).",
                "Size" => 20);
        $this->CfgSetup["EnhancedLinkAttribution"] = array(
                "Type" => "Flag",
                "Label" => "Use Enhanced Link Attribution",
                "Help" => "Whether to include code for Enhanced Link"
                        ." Attribution.",
                "Default" => TRUE);
        $this->CfgSetup["SiteVerificationCode"] = array(
                "Type" => "Text",
                "Label" => "Site Verification Code",
                "Help" => "A verification code used by Google to confirm"
                        ." your ownership of the site.",
                "Size" => 40,
                "MaxLength" => 100);
    }

    /**
    * Initialize the plugin.  This is called (if the plugin is enabled) after
    * all plugins have been loaded but before any methods for this plugin
    * (other than Register()) have been called.
    * @return NULL if initialization was successful, otherwise a string containing
    *       an error message indicating why initialization failed.
    */
    function Initialize()
    {
        # if we do not have a GA tracking ID
        if ((strlen($this->ConfigSetting("TrackingId")) == 0)
                && (strlen($this->ConfigSetting("SiteVerificationCode")) == 0))
        {
            # return error message about no tracking ID
            return "Either a Google Analytics tracking ID or a Google"
                    ." verification code has not been set.";
        }
        # else if GA tracking ID does not look valid
        elseif (strlen($this->ConfigSetting("TrackingId"))
                && (!preg_match("/^UA-[0-9]+-[0-9]{1,3}$/",
                        $this->ConfigSetting("TrackingId"))))
        {
            # return error message about invalid tracking ID
            return "The Google Analytics tracking ID appears to be invalid.";
        }

        # report successful initialization
        return NULL;
    }

    /**
    * Hook methods to be called when specific events occur.
    * For events declared by other plugins the name string should start with
    * the plugin base (class) name followed by "::" and then the event name.
    * @return Array of method names to hook indexed by the event constants
    *       or names to hook them to.
    */
    function HookEvents()
    {
        return array("EVENT_IN_HTML_HEADER" => "PrintTrackingCode");
    }


    # ---- HOOKED METHODS ----------------------------------------------------

    /**
    * HOOKED METHOD: PrintTrackingCode
    * Write the code for Google Analytics tracking to output.
    */
    function PrintTrackingCode()
    {
        if (strlen($this->ConfigSetting("TrackingId")))
        {
            ?>
            <!-- Google Analytics (start) -->
            <script>
                (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
                ga('create', '<?PHP  print $this->ConfigSetting("TrackingId");  ?>', 'auto');
                <?PHP  if ($this->ConfigSetting("EnhancedLinkAttribution")) {  ?>
                ga('require', 'linkid', 'linkid.js');
                <?PHP  }  ?>
                ga('send', 'pageview');
            </script>
            <!-- Google Analytics (end) --><?PHP
        }
        if (strlen($this->ConfigSetting("SiteVerificationCode")))
        {
            ?>
            <meta name="google-site-verification" content="<?PHP
                    print $this->ConfigSetting("SiteVerificationCode");
                    ?>" /><?PHP
        }
    }


    # ---- CALLABLE METHODS --------------------------------------------------


    # ---- PRIVATE INTERFACE -------------------------------------------------

}
