diff options
author | Anthon Pang <apang@softwaredevelopment.ca> | 2013-02-10 07:58:56 +0400 |
---|---|---|
committer | Anthon Pang <apang@softwaredevelopment.ca> | 2013-02-10 07:58:56 +0400 |
commit | 2ee4124dd67187bb04b17b872a555bb10e2ac712 (patch) | |
tree | 04a124f27483a7543c6e62b95331650016d8d4df /js | |
parent | 090fe54039c6d05d7bda1b144c65d3b335bb1dc7 (diff) |
jslint and coding style changes
* blank line before 'if' and 'return' (unless at start of a block)
* convert tabs to spaces
* redo typeof property !== 'undefined' workaround
* replace .substr() and .substring() with .slice()
* use aliases where possible
Diffstat (limited to 'js')
-rw-r--r-- | js/piwik.js | 276 |
1 files changed, 171 insertions, 105 deletions
diff --git a/js/piwik.js b/js/piwik.js index 4f7f6bb1d7..fdeccd1efd 100644 --- a/js/piwik.js +++ b/js/piwik.js @@ -105,8 +105,10 @@ if (!this.JSON2) { // sequences. escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; + return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; @@ -194,6 +196,7 @@ if (!this.JSON2) { '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; + return v; } @@ -205,6 +208,7 @@ if (!this.JSON2) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); + if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } @@ -217,6 +221,7 @@ if (!this.JSON2) { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); + if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } @@ -231,6 +236,7 @@ if (!this.JSON2) { '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; + return v; } } @@ -268,6 +274,7 @@ if (!this.JSON2) { // Otherwise, throw an error. rep = replacer; + if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { @@ -297,10 +304,12 @@ if (!this.JSON2) { // that modifications can be made. var k, v, value = holder[key]; + if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); + if (v !== undefined) { value[k] = v; } else { @@ -309,6 +318,7 @@ if (!this.JSON2) { } } } + return reviver.call(holder, key, value); } @@ -318,6 +328,7 @@ if (!this.JSON2) { text = String(text); cx.lastIndex = 0; + if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + @@ -372,18 +383,20 @@ if (!this.JSON2) { /*global unescape */ /*global ActiveXObject */ /*global _paq:true */ +/*global Piwik_Overlay_Client */ /*members encodeURIComponent, decodeURIComponent, getElementsByTagName, - shift, unshift, createElement, appendChild, characterSet, charset, + shift, unshift, + createElement, appendChild, characterSet, charset, addEventListener, attachEvent, removeEventListener, detachEvent, disableCookies, cookie, domain, readyState, documentElement, doScroll, title, text, - location, top, document, referrer, parent, links, href, protocol, GearsFactory, + location, top, document, referrer, parent, links, href, protocol, name, GearsFactory, event, which, button, srcElement, type, target, parentNode, tagName, hostname, className, userAgent, cookieEnabled, platform, mimeTypes, enabledPlugin, javaEnabled, XMLHttpRequest, ActiveXObject, open, setRequestHeader, onreadystatechange, send, readyState, status, getTime, getTimeAlias, setTime, toGMTString, getHours, getMinutes, getSeconds, - toLowerCase, charAt, indexOf, lastIndexOf, split, slice, toUpperCase, substring, - onload, src, match, name, + toLowerCase, toUpperCase, charAt, indexOf, lastIndexOf, split, slice, + onload, src, round, random, exec, res, width, height, devicePixelRatio, @@ -407,14 +420,15 @@ if (!this.JSON2) { setHeartBeatTimer, killFrame, redirectFile, setCountPreRendered, trackGoal, trackLink, trackPageView, trackSiteSearch, setEcommerceView, addEcommerceItem, trackEcommerceOrder, trackEcommerceCartUpdate, - addPlugin, getTracker, getAsyncTracker + addPlugin, getTracker, getAsyncTracker, + initialize */ var // asynchronous tracker (or proxy) _paq = _paq || [], // Piwik singleton and namespace - Piwik = Piwik || (function () { + Piwik = Piwik || (function () { "use strict"; /************************************************************ @@ -460,7 +474,9 @@ var */ function isDefined(property) { // workaround https://github.com/douglascrockford/JSLint/commit/24f63ada2f9d7ad65afc90e6d949f631935c2480 - return 'undefined' !== typeof property; + var propertyType = typeof property; + + return propertyType !== 'undefined'; } /* @@ -515,6 +531,7 @@ var function addEventListener(element, eventType, eventHandler, useCapture) { if (element.addEventListener) { element.addEventListener(eventType, eventHandler, useCapture); + return true; } @@ -536,6 +553,7 @@ var for (i in plugins) { if (Object.prototype.hasOwnProperty.call(plugins, i)) { pluginMethod = plugins[i][methodName]; + if (isFunction(pluginMethod)) { result += pluginMethod(callback); } @@ -583,6 +601,7 @@ var registeredOnLoadHandlers[i](); } } + return true; } @@ -612,6 +631,7 @@ var documentAlias.documentElement.doScroll('left'); } catch (error) { setTimeout(ready, 0); + return; } loadHandler(); @@ -651,6 +671,7 @@ var } } } + if (referrer === '') { referrer = documentAlias.referrer; } @@ -703,6 +724,7 @@ var * sha1 * - based on sha1 from http://phpjs.org/functions/sha1:512 (MIT / GPL v2) ************************************************************/ + function sha1(str) { // + original by: Webtoolkit.info (http://www.webtoolkit.info/) // + namespaced by: Michael White (http://getsprink.com) @@ -724,6 +746,7 @@ var v = (val >>> (i * 4)) & 0x0f; str += v.toString(16); } + return str; }, @@ -837,8 +860,10 @@ var } temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4); + return temp.toLowerCase(); } + /************************************************************ * end sha1 ************************************************************/ @@ -847,15 +872,16 @@ var * Fix-up URL when page rendered from search engine cache or translated page */ function urlFixup(hostName, href, referrer) { - if (hostName === 'translate.googleusercontent.com') { // Google + if (hostName === 'translate.googleusercontent.com') { // Google if (referrer === '') { referrer = href; } + href = getParameter(href, 'u'); hostName = getHostName(href); - } else if (hostName === 'cc.bingj.com' || // Bing + } else if (hostName === 'cc.bingj.com' || // Bing hostName === 'webcache.googleusercontent.com' || // Google - hostName.slice(0, 5) === '74.6.') { // Yahoo (via Inktomi 74.6.0.0/16) + hostName.slice(0, 5) === '74.6.') { // Yahoo (via Inktomi 74.6.0.0/16) href = documentAlias.links[0].href; hostName = getHostName(href); } @@ -895,94 +921,110 @@ var title = tmp[0].text; } } + return title; } - /************************************************************ - * Page Overlay - ************************************************************/ - - /* - * check whether this is a page overlay session - */ - function isOverlaySession(configTrackerUrl, configTrackerSiteId) { - var windowName = 'Piwik_Overlay'; - var referrer = documentAlias.referrer; - var testReferrer = configTrackerUrl; - - // remove piwik.php from referrer if present - if(testReferrer.substr(-9) == "piwik.php") { - testReferrer = testReferrer.substring(0, testReferrer.length - 9); - } - - // remove protocol - testReferrer.substring(testReferrer.substring(0, 7) === 'http://' ? 7 : 8, testReferrer.length); - referrer.substring(referrer.substring(0, 7) === 'http://' ? 7 : 8, referrer.length); - - // do a basic match before checking with a regex because the regex is more expensive - // and would be used at every pageview otherwise - if (referrer.substring(0, testReferrer.length) === testReferrer) { - - // build referrer regex to extract parameters - var referrerRegExp = new RegExp('^' + testReferrer - + 'index\\.php\\?module=Overlay&action=startOverlaySession' - + '&idsite=([0-9]+)&period=([^&]+)&date=([^&]+)$'); - - var match = referrer.match(referrerRegExp); - if (match) { - // check idsite - var idsite = match[1]; - if (idsite !== '' + configTrackerSiteId) { - return false; - } - // store overlay session info in window name - var period = match[2]; - var date = match[3]; - window.name = windowName + '###' + period + '###' + date; - } - } - - // retrieve and check data from window name - var windowNameParts = windowAlias.name.split('###'); - return windowNameParts.length === 3 && windowNameParts[0] === windowName; - } - - /* - * inject the script needed for page overlay - */ - function injectOverlayScripts(configTrackerUrl, configTrackerSiteId) { - var windowNameParts = window.name.split('###'); - var root = configTrackerUrl; - if(root.substr(-9) == "piwik.php") { - root = root.substring(0, root.length - 9); // remove piwik.php if present - } - var period = windowNameParts[1]; - var date = windowNameParts[2]; - - var loaded = false; - var onLoad = function () { - if (!loaded) { - loaded = true; - Piwik_Overlay_Client.initialize(root, configTrackerSiteId, period, date); - } - }; - - var script = document.createElement('script'); - script.type = 'text/javascript'; - - script.onreadystatechange = function () { - if (this.readyState === 'loaded' || this.readyState === 'complete') { - onLoad(); - } - }; - script.onload = onLoad; - script.src = root + 'plugins/Overlay/client/client.js?v=1'; - var head = document.getElementsByTagName('head')[0]; - head.appendChild(script); - } - /************************************************************ - * End Page Overlay - ************************************************************/ + /************************************************************ + * Page Overlay + ************************************************************/ + + /* + * Check whether this is a page overlay session + * + * @return boolean + * + * {@internal side-effect: modifies window.name }} + */ + function isOverlaySession(configTrackerUrl, configTrackerSiteId) { + var windowName = 'Piwik_Overlay', + referrer = documentAlias.referrer, + testReferrer = configTrackerUrl; + + // remove piwik.php from referrer if present + if (testReferrer.slice(-9) === 'piwik.php') { + testReferrer = testReferrer.slice(0, testReferrer.length - 9); + } + + // remove protocol + testReferrer.slice(testReferrer.slice(0, 7) === 'http://' ? 7 : 8, testReferrer.length); + referrer.slice(referrer.slice(0, 7) === 'http://' ? 7 : 8, referrer.length); + + // do a basic match before checking with a regex because the regex is more expensive + // and would be used at every pageview otherwise + if (referrer.slice(0, testReferrer.length) === testReferrer) { + + // build referrer regex to extract parameters + var referrerRegExp = new RegExp('^' + testReferrer + + 'index\\.php\\?module=Overlay&action=startOverlaySession' + + '&idsite=([0-9]+)&period=([^&]+)&date=([^&]+)$'); + + var match = referrerRegExp.exec(referrer); + + if (match) { + // check idsite + var idsite = match[1]; + + if (idsite !== String(configTrackerSiteId)) { + return false; + } + + // store overlay session info in window name + var period = match[2], + date = match[3]; + + windowAlias.name = windowName + '###' + period + '###' + date; + } + } + + // retrieve and check data from window name + var windowNameParts = windowAlias.name.split('###'); + + return windowNameParts.length === 3 && windowNameParts[0] === windowName; + } + + /* + * Inject the script needed for page overlay + */ + function injectOverlayScripts(configTrackerUrl, configTrackerSiteId) { + var windowNameParts = windowAlias.name.split('###'), + period = windowNameParts[1], + date = windowNameParts[2], + root = configTrackerUrl; + + if (root.slice(-9) === 'piwik.php') { + root = root.slice(0, root.length - 9); // remove piwik.php if present + } + + var onLoad = function () { + Piwik_Overlay_Client.initialize(root, configTrackerSiteId, period, date); + }; + + var script = documentAlias.createElement('script'); + + script.type = 'text/javascript'; + + if (script.readyState) { + script.onreadystatechange = function () { + if (this.readyState === 'loaded' || this.readyState === 'complete') { + script.onreadystatechange = null; + onLoad(); + } + }; + } else { + script.onload = onLoad; + } + + script.src = root + 'plugins/Overlay/client/client.js?v=1'; + + var head = documentAlias.getElementsByTagName('head')[0]; + + head.appendChild(script); + } + + /************************************************************ + * End Page Overlay + ************************************************************/ /* * Piwik Tracker class @@ -1183,6 +1225,7 @@ var if (configDiscardHashTag) { targetPattern = new RegExp('#.*'); + return url.replace(targetPattern, ''); } @@ -1207,6 +1250,7 @@ var } baseUrl = purify(baseUrl); + if ((i = baseUrl.indexOf('?')) >= 0) { baseUrl = baseUrl.slice(0, i); } @@ -1239,11 +1283,13 @@ var } offset = hostName.length - alias.length; + if ((offset > 0) && (hostName.slice(offset) === alias)) { return true; } } } + return false; } @@ -1350,10 +1396,12 @@ var if (cookie.length) { cookie = JSON2.parse(cookie); + if (isObject(cookie)) { return cookie; } } + return {}; } @@ -1432,6 +1480,7 @@ var '' ]; } + return tmpContainer; } @@ -1460,6 +1509,7 @@ var // Pre 1.3, this cookie was not JSON encoded } } + return [ '', '', @@ -1536,7 +1586,8 @@ var // send charset if document charset is not utf-8. sometimes encoding // of urls will be the same as this and not utf-8, which will cause problems // do not send charset if it is utf8 since it's assumed by default in Piwik - var charSet = document.characterSet || document.charset; + var charSet = documentAlias.characterSet || documentAlias.charset; + if (!charSet || charSet.toLowerCase() === 'utf-8') { charSet = null; } @@ -1561,14 +1612,17 @@ var for (i in configCampaignNameParameters) { if (Object.prototype.hasOwnProperty.call(configCampaignNameParameters, i)) { campaignNameDetected = getParameter(currentUrl, configCampaignNameParameters[i]); + if (campaignNameDetected.length) { break; } } } + for (i in configCampaignKeywordParameters) { if (Object.prototype.hasOwnProperty.call(configCampaignKeywordParameters, i)) { campaignKeywordDetected = getParameter(currentUrl, configCampaignKeywordParameters[i]); + if (campaignKeywordDetected.length) { break; } @@ -1580,6 +1634,7 @@ var // referral URL depends on the first or last referrer attribution currentReferrerHostName = getHostName(configReferrerUrl); originalReferrerHostName = referralUrl.length ? getHostName(referralUrl) : ''; + if (currentReferrerHostName.length && // there is a referrer !isSiteHostName(currentReferrerHostName) && // domain is not the current domain (!configConversionAttributionFirstReferrer || // attribute to last known referrer @@ -1621,6 +1676,7 @@ var // Custom Variables, scope "page" var customVariablesPageStringified = JSON2.stringify(customVariablesPage); + if (customVariablesPageStringified.length > 2) { request += '&cvar=' + encodeWrapper(customVariablesPageStringified); } @@ -1642,6 +1698,7 @@ var // Custom Variables, scope "visit" if (customVariables) { var customVariablesStringified = JSON2.stringify(customVariables); + // Don't sent empty custom variables {} if (customVariablesStringified.length > 2) { request += '&_cvar=' + encodeWrapper(customVariablesStringified); @@ -1874,6 +1931,7 @@ var documentAlias.removeEventListener(prefix + 'visibilitychange', ready, false); callback(); }); + return; } @@ -1958,6 +2016,7 @@ var if (!scriptProtocol.test(sourceHref)) { // track outlinks and all downloads linkType = getLinkType(sourceElement.className, sourceHref, isSiteHostName(sourceHostName)); + if (linkType) { // urldecode %xx sourceHref = urldecode(sourceHref); @@ -2113,6 +2172,7 @@ var registeredHooks[hookName] = hookObj; } + return hookObj; } /*</DEBUG>*/ @@ -2279,9 +2339,11 @@ var */ setCustomVariable: function (index, name, value, scope) { var toRecord; + if (!isDefined(scope)) { scope = 'visit'; } + if (index > 0) { name = isDefined(name) && !isString(name) ? String(name) : name; value = isDefined(value) && !isString(value) ? String(value) : value; @@ -2672,15 +2734,15 @@ var * @param mixed customData */ trackPageView: function (customTitle, customData) { - if (isOverlaySession(configTrackerUrl, configTrackerSiteId)) { - trackCallback(function () { - injectOverlayScripts(configTrackerUrl, configTrackerSiteId); - }); - } else { - trackCallback(function () { - logPageView(customTitle, customData); - }); - } + if (isOverlaySession(configTrackerUrl, configTrackerSiteId)) { + trackCallback(function () { + injectOverlayScripts(configTrackerUrl, configTrackerSiteId); + }); + } else { + trackCallback(function () { + logPageView(customTitle, customData); + }); + } }, /** @@ -2902,21 +2964,25 @@ var // handle Piwik globals option = getOption('tracker_pause'); + if (option) { piwikTracker.setLinkTrackingTimer(option); } option = getOption('download_extensions'); + if (option) { piwikTracker.setDownloadExtensions(option); } option = getOption('hosts_alias'); + if (option) { piwikTracker.setDomains(option); } option = getOption('ignore_classes'); + if (option) { piwikTracker.setIgnoreClasses(option); } |