Piwik\Tracker\TrackerCodeGenerator::generate PHP Method

generate() public method

public generate ( integer $idSite, string $piwikUrl, boolean $mergeSubdomains = false, boolean $groupPageTitlesByDomain = false, boolean $mergeAliasUrls = false, array $visitorCustomVariables = null, array $pageCustomVariables = null, string $customCampaignNameQueryParam = null, string $customCampaignKeywordParam = null, boolean $doNotTrack = false, boolean $disableCookies = false, boolean $trackNoScript = false ) : string
$idSite integer
$piwikUrl string http://path/to/piwik/site/
$mergeSubdomains boolean
$groupPageTitlesByDomain boolean
$mergeAliasUrls boolean
$visitorCustomVariables array
$pageCustomVariables array
$customCampaignNameQueryParam string
$customCampaignKeywordParam string
$doNotTrack boolean
$disableCookies boolean
$trackNoScript boolean
return string Javascript code.
    public function generate($idSite, $piwikUrl, $mergeSubdomains = false, $groupPageTitlesByDomain = false, $mergeAliasUrls = false, $visitorCustomVariables = null, $pageCustomVariables = null, $customCampaignNameQueryParam = null, $customCampaignKeywordParam = null, $doNotTrack = false, $disableCookies = false, $trackNoScript = false)
    {
        // changes made to this code should be mirrored in plugins/CoreAdminHome/javascripts/jsTrackingGenerator.js var generateJsCode
        if (substr($piwikUrl, 0, 4) !== 'http') {
            $piwikUrl = 'http://' . $piwikUrl;
        }
        preg_match('~^(http|https)://(.*)$~D', $piwikUrl, $matches);
        $piwikUrl = rtrim(@$matches[2], "/");
        // Build optional parameters to be added to text
        $options = '';
        $optionsBeforeTrackerUrl = '';
        if ($groupPageTitlesByDomain) {
            $options .= '  _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);' . "\n";
        }
        if ($mergeSubdomains || $mergeAliasUrls) {
            $options .= $this->getJavascriptTagOptions($idSite, $mergeSubdomains, $mergeAliasUrls);
        }
        $maxCustomVars = CustomVariables::getNumUsableCustomVariables();
        if ($visitorCustomVariables && count($visitorCustomVariables) > 0) {
            $options .= '  // you can set up to ' . $maxCustomVars . ' custom variables for each visitor' . "\n";
            $index = 1;
            foreach ($visitorCustomVariables as $visitorCustomVariable) {
                if (empty($visitorCustomVariable)) {
                    continue;
                }
                $options .= sprintf('  _paq.push(["setCustomVariable", %d, %s, %s, "visit"]);%s', $index++, json_encode($visitorCustomVariable[0]), json_encode($visitorCustomVariable[1]), "\n");
            }
        }
        if ($pageCustomVariables && count($pageCustomVariables) > 0) {
            $options .= '  // you can set up to ' . $maxCustomVars . ' custom variables for each action (page view, download, click, site search)' . "\n";
            $index = 1;
            foreach ($pageCustomVariables as $pageCustomVariable) {
                if (empty($pageCustomVariable)) {
                    continue;
                }
                $options .= sprintf('  _paq.push(["setCustomVariable", %d, %s, %s, "page"]);%s', $index++, json_encode($pageCustomVariable[0]), json_encode($pageCustomVariable[1]), "\n");
            }
        }
        if ($customCampaignNameQueryParam) {
            $options .= '  _paq.push(["setCampaignNameKey", ' . json_encode($customCampaignNameQueryParam) . ']);' . "\n";
        }
        if ($customCampaignKeywordParam) {
            $options .= '  _paq.push(["setCampaignKeywordKey", ' . json_encode($customCampaignKeywordParam) . ']);' . "\n";
        }
        if ($doNotTrack) {
            $options .= '  _paq.push(["setDoNotTrack", true]);' . "\n";
        }
        if ($disableCookies) {
            $options .= '  _paq.push(["disableCookies"]);' . "\n";
        }
        $codeImpl = array('idSite' => $idSite, 'piwikUrl' => Common::sanitizeInputValue($piwikUrl), 'options' => $options, 'optionsBeforeTrackerUrl' => $optionsBeforeTrackerUrl, 'protocol' => '//', 'loadAsync' => true, 'trackNoScript' => $trackNoScript);
        $parameters = compact('mergeSubdomains', 'groupPageTitlesByDomain', 'mergeAliasUrls', 'visitorCustomVariables', 'pageCustomVariables', 'customCampaignNameQueryParam', 'customCampaignKeywordParam', 'doNotTrack');
        /**
         * Triggered when generating JavaScript tracking code server side. Plugins can use
         * this event to customise the JavaScript tracking code that is displayed to the
         * user.
         *
         * @param array &$codeImpl An array containing snippets of code that the event handler
         *                         can modify. Will contain the following elements:
         *
         *                         - **idSite**: The ID of the site being tracked.
         *                         - **piwikUrl**: The tracker URL to use.
         *                         - **options**: A string of JavaScript code that customises
         *                                        the JavaScript tracker.
         *                         - **optionsBeforeTrackerUrl**: A string of Javascript code that customises
         *                                        the JavaScript tracker inside of anonymous function before
         *                                        adding setTrackerUrl into paq.
         *                         - **protocol**: Piwik url protocol.
         *                         - **loadAsync**: boolean whether piwik.js should be loaded syncronous or asynchronous
         *
         *                         The **httpsPiwikUrl** element can be set if the HTTPS
         *                         domain is different from the normal domain.
         * @param array $parameters The parameters supplied to `TrackerCodeGenerator::generate()`.
         */
        Piwik::postEvent('Piwik.getJavascriptCode', array(&$codeImpl, $parameters));
        $setTrackerUrl = 'var u="' . $codeImpl['protocol'] . '{$piwikUrl}/";';
        if (!empty($codeImpl['httpsPiwikUrl'])) {
            $setTrackerUrl = 'var u=((document.location.protocol === "https:") ? "https://{$httpsPiwikUrl}/" : "http://{$piwikUrl}/");';
            $codeImpl['httpsPiwikUrl'] = rtrim($codeImpl['httpsPiwikUrl'], "/");
        }
        $codeImpl = array('setTrackerUrl' => htmlentities($setTrackerUrl)) + $codeImpl;
        $view = new View('@Morpheus/javascriptCode');
        $view->disableCacheBuster();
        $view->loadAsync = $codeImpl['loadAsync'];
        $view->trackNoScript = $codeImpl['trackNoScript'];
        $jsCode = $view->render();
        $jsCode = htmlentities($jsCode);
        foreach ($codeImpl as $keyToReplace => $replaceWith) {
            $jsCode = str_replace('{$' . $keyToReplace . '}', $replaceWith, $jsCode);
        }
        return $jsCode;
    }

Usage Example

    public function testStringsAreEscaped()
    {
        $generator = new TrackerCodeGenerator();
        $jsTag = $generator->generate($idSite = 1, $piwikUrl = 'abc"def', $mergeSubdomains = true, $groupPageTitlesByDomain = true, $mergeAliasUrls = true, $visitorCustomVariables = array(array('abc"def', 'abc"def')), $pageCustomVariables = array(array('abc"def', 'abc"def')), $customCampaignNameQueryParam = 'abc"def', $customCampaignKeywordParam = 'abc"def');
        $expected = '<!-- Piwik -->
<script type="text/javascript">
  var _paq = _paq || [];
  _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
  // you can set up to 5 custom variables for each visitor
  _paq.push(["setCustomVariable", 1, "abc\\"def", "abc\\"def", "visit"]);
  // you can set up to 5 custom variables for each action (page view, download, click, site search)
  _paq.push(["setCustomVariable", 1, "abc\\"def", "abc\\"def", "page"]);
  _paq.push(["setCampaignNameKey", "abc\\"def"]);
  _paq.push(["setCampaignKeywordKey", "abc\\"def"]);
  _paq.push([\'trackPageView\']);
  _paq.push([\'enableLinkTracking\']);
  (function() {
    var u="//abc"def/";
    _paq.push([\'setTrackerUrl\', u+\'piwik.php\']);
    _paq.push([\'setSiteId\', \'1\']);
    var d=document, g=d.createElement(\'script\'), s=d.getElementsByTagName(\'script\')[0];
    g.type=\'text/javascript\'; g.async=true; g.defer=true; g.src=u+\'piwik.js\'; s.parentNode.insertBefore(g,s);
  })();
</script>
<noscript><p><img src="//abc"def/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
';
        $this->assertEquals($expected, $jsTag);
    }
All Usage Examples Of Piwik\Tracker\TrackerCodeGenerator::generate