<commit_before><?php
use RoadTest\Utility\Logger\LoggerFactory;

class Analytics_PageTool extends PageTool
{

    const USER_TYPE = "dimension1";
    const BRANDING = "dimension2";
    const ANTI_SPAM = "dimension3";
    private static $CUSTOM_DIMENSION_KEY = "Gt.Analytics.customDimensions";
    private static $EVENT_KEY = "Gt.Analytics.events";
    private static $END_SESSION_KEY = "Gt.Analytics.endSession";

    /**
     * Google Analytics.
     * This simple PageTool doesn't have any functionality in the go() method.
     * Instead, pass the tracking code into the track() method.
     */
    public function go($api, $dom, $template, $tool)
    {
    }

    /**
     * Injects the required JavaScript code where needed to start tracking using
     * Google Analytics.
     *
     * @param string $trackingCode Your Google Analytics account code, looks like
     *                             this: UA-12345678-1
     */
    public function track($trackingCode)
    {
        $logger = LoggerFactory::get($this);
        $responseCode = http_response_code();

        if ($responseCode >= 300 && $responseCode < 400) {
            // don't bother going any further - this is a redirect
            return;
        }

        if (!$this->_dom instanceof Dom) {
            // No dom initialised... can't track.
            return;
        }

        $js = file_get_contents(dirname(__FILE__) . "/Include/Analytics.tool.js");
        if ($js === false) {
            $logger->error("Couldn't find Google Analytics script!");
            return;
        }

        $js = str_replace("{ANALYTICS_CODE}", $trackingCode, $js);

        // enable remarketing
        $js .= "\nga('require', 'displayfeatures');";

        // send any pending events
        if (Session::exists(self::$EVENT_KEY)) {
            $events = Session::get(self::$EVENT_KEY);
            foreach ($events as $event) {
                $js .= "\nga('send', {
                        hitType: 'event',
                        eventCategory: '{$event["eventCategory"]}',
                        eventAction:   '{$event["eventAction"]}',
                        eventLabel:    '{$event["eventLabel"]}',
                        eventValue:    '{$event["eventValue"]}'
                    });
                ";

                $logger->debug(
                    sprintf("Sending GA event: category=%s, action=%s, label=%s, value=%s",
                        $event["eventCategory"],
                        $event["eventAction"],
                        $event["eventLabel"],
                        $event["eventValue"]));
            }
            // delete them now they've been loaded for send
            Session::delete(self::$EVENT_KEY);
        }

        if (!Session::exists(self::$CUSTOM_DIMENSION_KEY)) {
            // this is a new session so add the custom dimension to filter-out spam entries
            $this->customDimension(self::ANTI_SPAM, "true");
        }

        $customDimensions = Session::get(self::$CUSTOM_DIMENSION_KEY);
        foreach ($customDimensions as $key => $value) {
            $js .= "\nga('set', '{$key}', '{$value}');";

            $logger->debug(
                sprintf("Sending GA custom dimension: %s => %s",<commit_msg>Fix GA Pagetool bug which meant anti-spam flag wasn't always sent<commit_after><?php
use RoadTest\Utility\Logger\LoggerFactory;

class Analytics_PageTool extends PageTool
{

    const USER_TYPE = "dimension1";
    const BRANDING = "dimension2";
    const ANTI_SPAM = "dimension3";
    private static $CUSTOM_DIMENSION_KEY = "Gt.Analytics.customDimensions";
    private static $EVENT_KEY = "Gt.Analytics.events";
    private static $END_SESSION_KEY = "Gt.Analytics.endSession";

    /**
     * Google Analytics.
     * This simple PageTool doesn't have any functionality in the go() method.
     * Instead, pass the tracking code into the track() method.
     */
    public function go($api, $dom, $template, $tool)
    {
    }

    /**
     * Injects the required JavaScript code where needed to start tracking using
     * Google Analytics.
     *
     * @param string $trackingCode Your Google Analytics account code, looks like
     *                             this: UA-12345678-1
     */
    public function track($trackingCode)
    {
        $logger = LoggerFactory::get($this);
        $responseCode = http_response_code();

        if ($responseCode >= 300 && $responseCode < 400) {
            // don't bother going any further - this is a redirect
            return;
        }

        if (!$this->_dom instanceof Dom) {
            // No dom initialised... can't track.
            return;
        }

        $js = file_get_contents(dirname(__FILE__) . "/Include/Analytics.tool.js");
        if ($js === false) {
            $logger->error("Couldn't find Google Analytics script!");
            return;
        }

        $js = str_replace("{ANALYTICS_CODE}", $trackingCode, $js);

        // enable remarketing
        $js .= "\nga('require', 'displayfeatures');";

        // send any pending events
        if (Session::exists(self::$EVENT_KEY)) {
            $events = Session::get(self::$EVENT_KEY);
            foreach ($events as $event) {
                $js .= "\nga('send', {
                        hitType: 'event',
                        eventCategory: '{$event["eventCategory"]}',
                        eventAction:   '{$event["eventAction"]}',
                        eventLabel:    '{$event["eventLabel"]}',
                        eventValue:    '{$event["eventValue"]}'
                    });
                ";

                $logger->debug(
                    sprintf("Sending GA event: category=%s, action=%s, label=%s, value=%s",
                        $event["eventCategory"],
                        $event["eventAction"],
                        $event["eventLabel"],
                        $event["eventValue"]));
            }
            // delete them now they've been loaded for send
            Session::delete(self::$EVENT_KEY);
        }

        // make sure the non-spam flag is always set so we can filter out google analytics spam entries
        if(! Session::exists(self::$CUSTOM_DIMENSION_KEY . ".{$name}")) {
            $this->customDimension(self::ANTI_SPAM, "true");
        }

        $customDimensions = Session::get(self::$CUSTOM_DIMENSION_KEY);
        foreach ($customDimensions as $key => $value) {
            $js .= "\nga('set', '{$key}', '{$value}');";

            $logger->debug(
                sprintf("Sending GA custom dimension: %s => %s",
{'fraction_non_alphanumeric': 0.13206397562833205, 'fraction_numerical': 0.0054836252856054835, 'mean_word_length': 1.8810881965774462, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2475709', 'n_tokens_mistral': 1826, 'n_tokens_neox': 1735, 'n_words': 443}