PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/javascript/index.php

https://github.com/CodeYellowBV/piwik
PHP | 1287 lines | 987 code | 234 blank | 66 comment | 70 complexity | ffc108e668e073b9b32ec482b311f2e5 MD5 | raw file
Possible License(s): LGPL-3.0, JSON, MIT, GPL-3.0, LGPL-2.1, GPL-2.0, AGPL-1.0, BSD-2-Clause, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. ?><!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <title>piwik.js: Unit Tests</title>
  7. <?php
  8. require_once(dirname(__FILE__).'/SQLite.php');
  9. if(file_exists("stub.tpl")) {
  10. echo file_get_contents("stub.tpl");
  11. }
  12. ?>
  13. <script type="text/javascript">
  14. function getToken() {
  15. return "<?php $token = md5(uniqid(mt_rand(), true)); echo $token; ?>";
  16. }
  17. <?php
  18. $sqlite = false;
  19. if (file_exists("enable_sqlite")) {
  20. if (class_exists('SQLite')) {
  21. $sqlite = true;
  22. }
  23. }
  24. if(!$sqlite) {
  25. echo 'alert("WARNING: Javascript integration tests require sqlite, \n1) ensure this PHP extension is enabled to make sure you run all tests \napt-get install php5-sqlite \n2) Then please create an empty file enable_sqlite in tests/javascript/enable_sqlite \n3) Re-execute this page and make sure this popup does not display ");';
  26. }
  27. if ($sqlite) {
  28. echo '
  29. var _paq = _paq || [];
  30. function testCallingTrackPageViewBeforeSetTrackerUrlWorks() {
  31. _paq.push(["setCustomData", { "token" : getToken() }]);
  32. _paq.push(["trackPageView", "Asynchronous Tracker ONE"]);
  33. _paq.push(["setSiteId", 1]);
  34. _paq.push(["setTrackerUrl", "piwik.php"]);
  35. }
  36. function testTrackPageViewAsync() {
  37. _paq.push(["trackPageView", "Asynchronous tracking TWO"]);
  38. }
  39. testCallingTrackPageViewBeforeSetTrackerUrlWorks();
  40. testTrackPageViewAsync();
  41. ';
  42. }
  43. ?>
  44. </script>
  45. <script src="../../js/piwik.js" type="text/javascript"></script>
  46. <script src="../../plugins/Overlay/client/urlnormalizer.js" type="text/javascript"></script>
  47. <script src="piwiktest.js" type="text/javascript"></script>
  48. <link rel="stylesheet" href="assets/qunit.css" type="text/css" media="screen" />
  49. <link rel="stylesheet" href="jash/Jash.css" type="text/css" media="screen" />
  50. <script src="assets/qunit.js" type="text/javascript"></script>
  51. <script src="jslint/jslint.js" type="text/javascript"></script>
  52. <script type="text/javascript">
  53. function _e(id){
  54. if (document.getElementById)
  55. return document.getElementById(id);
  56. if (document.layers)
  57. return document[id];
  58. if (document.all)
  59. return document.all[id];
  60. }
  61. function loadJash() {
  62. var jashDiv = _e('jashDiv');
  63. jashDiv.innerHTML = '';
  64. document.body.appendChild(document.createElement('script')).src='jash/Jash.js';
  65. }
  66. function dropCookie(cookieName, path, domain) {
  67. var expiryDate = new Date();
  68. expiryDate.setTime(expiryDate.getTime() - 3600);
  69. document.cookie = cookieName + '=;expires=' + expiryDate.toGMTString() +
  70. ';path=' + (path ? path : '') +
  71. (domain ? ';domain=' + domain : '');
  72. document.cookie = cookieName + ';expires=' + expiryDate.toGMTString() +
  73. ';path=' + (path ? path : '') +
  74. (domain ? ';domain=' + domain : '');
  75. }
  76. function deleteCookies() {
  77. // aggressively delete cookies
  78. // 1. get all cookies
  79. var
  80. cookies = (document.cookie).split(';'),
  81. aCookie,
  82. cookiePattern = new RegExp('^ *([^=]*)='),
  83. cookieMatch,
  84. cookieName,
  85. domain,
  86. domains = [],
  87. path,
  88. paths = [];
  89. cookies.push( '=' );
  90. // 2. construct list of domains
  91. domain = document.domain;
  92. if (domain.substring(0, 1) !== '.') {
  93. domain = '.' + domain;
  94. }
  95. domains.push( domain );
  96. while ((i = domain.indexOf('.')) >= 0) {
  97. domain = domain.substring(i+1);
  98. domains.push( domain );
  99. }
  100. domains.push( '' );
  101. domains.push( null );
  102. // 3. construct list of paths
  103. path = window.location.pathname;
  104. while ((i = path.lastIndexOf('/')) >= 0) {
  105. paths.push(path + '/');
  106. paths.push(path);
  107. path = path.substring(0, i);
  108. }
  109. paths.push( '/' );
  110. paths.push( '' );
  111. paths.push( null );
  112. // 4. iterate through cookies
  113. for (aCookie in cookies) {
  114. if (Object.prototype.hasOwnProperty.call(cookies, aCookie)) {
  115. // 5. extract cookie name
  116. cookieMatch = cookiePattern.exec(cookies[aCookie]);
  117. if (cookieMatch) {
  118. cookieName = cookieMatch[1];
  119. // 6. iterate through domains
  120. for (i = 0; i < domains.length; i++) {
  121. // 7. iterate through paths
  122. for (j = 0; j < paths.length; j++) {
  123. // 8. drop cookie
  124. dropCookie(cookieName, paths[j], domains[i]);
  125. }
  126. }
  127. }
  128. }
  129. }
  130. }
  131. </script>
  132. </head>
  133. <body>
  134. <div style="display:none;"><a href="http://piwik.org/qa">First anchor link</a></div>
  135. <h1 id="qunit-header">piwik.js: Unit Tests</h1>
  136. <h2 id="qunit-banner"></h2>
  137. <div id="qunit-testrunner-toolbar"></div>
  138. <h2 id="qunit-userAgent"></h2>
  139. <div id="other" style="display:none;">
  140. <div id="div1"></div>
  141. <iframe name="iframe2"></iframe>
  142. <iframe name="iframe3"></iframe>
  143. <iframe name="iframe4"></iframe>
  144. <iframe name="iframe5"></iframe>
  145. <iframe name="iframe6"></iframe>
  146. <iframe name="iframe7"></iframe>
  147. <ul>
  148. <li><a id="click1" href="javascript:_e('div1').innerHTML='&lt;iframe src=&quot;http://click.example.com&quot;&gt;&lt;/iframe&gt;';void(0)" class="clicktest">ignore: implicit (JavaScript href)</a></li>
  149. <li><a id="click2" href="http://example.org" target="iframe2" class="piwik_ignore clicktest">ignore: explicit</a></li>
  150. <li><a id="click3" href="example.php" target="iframe3" class="clicktest">ignore: implicit (localhost)</a></li>
  151. <li><a id="click4" href="http://example.net" target="iframe4" class="clicktest">outlink: implicit (outbound URL)</a></li>
  152. <li><a id="click5" href="example.html" target="iframe5" class="piwik_link clicktest">outlink: explicit (localhost)</a></li>
  153. <li><a id="click6" href="example.pdf" target="iframe6" class="clicktest">download: implicit (file extension)</a></li>
  154. <li><a id="click7" href="example.word" target="iframe7" class="piwik_download clicktest">download: explicit</a></li>
  155. <li><a id="click8" href="example.exe" target="iframe8" class="clicktest">no click handler</a></li>
  156. </ul>
  157. <div id="clickDiv"></div>
  158. </div>
  159. <ol id="qunit-tests"></ol>
  160. <div id="main" style="display:none;"></div>
  161. <script>
  162. var hasLoaded = false;
  163. function PiwikTest() {
  164. hasLoaded = true;
  165. module('externals');
  166. test("JSLint", function() {
  167. expect(1);
  168. var src = '<?php
  169. $src = file_get_contents('../../js/piwik.js');
  170. $src = strtr($src, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
  171. echo "$src"; ?>';
  172. ok( JSLINT(src), "JSLint" );
  173. // alert(JSLINT.report(true));
  174. });
  175. test("JSON", function() {
  176. expect(49);
  177. var tracker = Piwik.getTracker(), dummy;
  178. equal( typeof JSON2.stringify, 'function', 'JSON.stringify function' );
  179. equal( typeof JSON2.stringify(dummy), 'undefined', 'undefined' );
  180. equal( JSON2.stringify(null), 'null', 'null' );
  181. equal( JSON2.stringify(true), 'true', 'true' );
  182. equal( JSON2.stringify(false), 'false', 'false' );
  183. ok( JSON2.stringify(0) === '0', 'Number 0' );
  184. ok( JSON2.stringify(1) === '1', 'Number 1' );
  185. ok( JSON2.stringify(-1) === '-1', 'Number -1' );
  186. ok( JSON2.stringify(42) === '42', 'Number 42' );
  187. ok( JSON2.stringify(1.0) === '1.0'
  188. || JSON2.stringify(1.0) === '1', 'float 1.0' );
  189. equal( JSON2.stringify(1.1), '1.1', 'float 1.1' );
  190. equal( JSON2.stringify(""), '""', 'empty string' );
  191. equal( JSON2.stringify('"'), '"' + '\\' + '"' + '"', 'string "' );
  192. equal( JSON2.stringify('\\'), '"' + '\\\\' + '"', 'string \\' );
  193. equal( JSON2.stringify("1"), '"1"', 'string "1"' );
  194. equal( JSON2.stringify("ABC"), '"ABC"', 'string ABC' );
  195. equal( JSON2.stringify("\x40\x41\x42\x43"), '"@ABC"', '\\x hex string @ABC' );
  196. ok( JSON2.stringify("\u60a8\u597d") == '"您好"'
  197. || JSON2.stringify("\u60a8\u597d") == '"\\u60a8\\u597d"', '\\u Unicode string 您好' );
  198. ok( JSON2.stringify("ßéàêö您好") == '"ßéàêö您好"'
  199. || JSON2.stringify("ßéàêö您好") == '"\\u00df\\u00e9\\u00e0\\u00ea\\u00f6\\u60a8\\u597d"', 'string non-ASCII text' );
  200. equal( JSON2.stringify("20060228T08:00:00"), '"20060228T08:00:00"', 'string "20060228T08:00:00"' );
  201. var d = new Date();
  202. d.setTime(1240013340000);
  203. ok( JSON2.stringify(d) === '"2009-04-18T00:09:00Z"'
  204. || JSON2.stringify(d) === '"2009-04-18T00:09:00.000Z"', 'Date');
  205. equal( JSON2.stringify([1, 2, 3]), '[1,2,3]', 'Array of numbers' );
  206. equal( JSON2.stringify({'key' : 'value'}), '{"key":"value"}', 'Object (members)' );
  207. equal( JSON2.stringify(
  208. [ {'domains' : ['example.com', 'example.ca']},
  209. {'names' : ['Sean', 'Cathy'] } ]
  210. ), '[{"domains":["example.com","example.ca"]},{"names":["Sean","Cathy"]}]', 'Nested members' );
  211. equal( typeof eval('('+dummy+')'), 'undefined', 'eval undefined' );
  212. equal( typeof JSON2.parse, 'function', 'JSON.parse function' );
  213. // these throw a SyntaxError
  214. // equal( typeof JSON2.parse('undefined'), 'undefined', 'undefined' );
  215. // equal( typeof JSON2.parse(dummy), 'undefined', 'undefined' );
  216. // equal( JSON2.parse('undefined'), dummy, 'undefined' );
  217. // equal( JSON2.parse('undefined'), undefined, 'undefined' );
  218. strictEqual( JSON2.parse('null'), null, 'null' );
  219. strictEqual( JSON2.parse('true'), true, 'true' );
  220. strictEqual( JSON2.parse('false'), false, 'false' );
  221. equal( JSON2.parse('0'), 0, 'Number 0' );
  222. equal( JSON2.parse('1'), 1, 'Number 1' );
  223. equal( JSON2.parse('-1'), -1, 'Number -1' );
  224. equal( JSON2.parse('42'), 42, 'Number 42' );
  225. ok( JSON2.parse('1.0') === 1.0
  226. || JSON2.parse('1.0') === 1, 'float 1.0' );
  227. equal( JSON2.parse('1.1'), 1.1, 'float 1.1' );
  228. equal( JSON2.parse('""'), "", 'empty string' );
  229. equal( JSON2.parse('"' + '\\' + '"' + '"'), '"', 'string "' );
  230. equal( JSON2.parse('"\\\\"'), '\\', 'string \\' );
  231. equal( JSON2.parse('"1"'), "1", 'string "1"' );
  232. equal( JSON2.parse('"ABC"'), "ABC", 'string ABC' );
  233. equal( JSON2.parse('"@ABC"'), "\x40\x41\x42\x43", 'Hex string @ABC' );
  234. ok( JSON2.parse('"您好"') == "\u60a8\u597d"
  235. && JSON2.parse('"\\u60a8\\u597d"') == "您好", 'Unicode string 您好' );
  236. ok( JSON2.parse('"ßéàêö您好"') == "ßéàêö您好"
  237. && JSON2.parse('"\\u00df\\u00e9\\u00e0\\u00ea\\u00f6\\u60a8\\u597d"') == "ßéàêö您好", 'string non-ASCII text' );
  238. equal( JSON2.parse('"20060228T08:00:00"'), "20060228T08:00:00", 'string "20060228T08:00:00"' );
  239. // these aren't converted back to Date objects
  240. equal( JSON2.parse('"2009-04-18T00:09:00Z"'), "2009-04-18T00:09:00Z", 'string "2009-04-18T00:09:00Z"' );
  241. equal( JSON2.parse('"2009-04-18T00:09:00.000Z"'), "2009-04-18T00:09:00.000Z", 'string "2009-04-18T00:09:00.000Z"' );
  242. deepEqual( JSON2.parse('[1,2,3]'), [1, 2, 3], 'Array of numbers' );
  243. deepEqual( JSON2.parse('{"key":"value"}'), {'key' : 'value'}, 'Object (members)' );
  244. deepEqual( JSON2.parse('[{"domains":["example.com","example.ca"]},{"names":["Sean","Cathy"]}]'),
  245. [ {'domains' : ['example.com', 'example.ca']}, {'names' : ['Sean', 'Cathy'] } ], 'Nested members' );
  246. });
  247. module("core");
  248. test("Basic requirements", function() {
  249. expect(3);
  250. equal( typeof encodeURIComponent, 'function', 'encodeURIComponent' );
  251. ok( RegExp, "RegExp" );
  252. ok( Piwik, "Piwik" );
  253. });
  254. test("Test API - addPlugin(), getTracker(), getHook(), and hook", function() {
  255. expect(6);
  256. ok( Piwik.addPlugin, "Piwik.addPlugin" );
  257. var tracker = Piwik.getTracker();
  258. equal( typeof tracker, 'object', "Piwik.getTracker()" );
  259. equal( typeof tracker.getHook, 'function', "test Tracker getHook" );
  260. equal( typeof tracker.hook, 'object', "test Tracker hook" );
  261. equal( typeof tracker.getHook('test'), 'object', "test Tracker getHook('test')" );
  262. equal( typeof tracker.hook.test, 'object', "test Tracker hook.test" );
  263. });
  264. test("API methods", function() {
  265. expect(54);
  266. equal( typeof Piwik.addPlugin, 'function', 'addPlugin' );
  267. equal( typeof Piwik.getTracker, 'function', 'getTracker' );
  268. equal( typeof Piwik.getAsyncTracker, 'function', 'getAsyncTracker' );
  269. var tracker;
  270. tracker = Piwik.getAsyncTracker();
  271. ok(tracker instanceof Object, 'getAsyncTracker');
  272. tracker = Piwik.getTracker();
  273. ok(tracker instanceof Object, 'getTracker');
  274. equal( typeof tracker.getVisitorId, 'function', 'getVisitorId' );
  275. equal( typeof tracker.getVisitorInfo, 'function', 'getVisitorInfo' );
  276. equal( typeof tracker.getAttributionInfo, 'function', 'getAttributionInfo' );
  277. equal( typeof tracker.getAttributionReferrerTimestamp, 'function', 'getAttributionReferrerTimestamp' );
  278. equal( typeof tracker.getAttributionReferrerUrl, 'function', 'getAttributionReferrerUrl' );
  279. equal( typeof tracker.getAttributionCampaignName, 'function', 'getAttributionCampaignName' );
  280. equal( typeof tracker.getAttributionCampaignKeyword, 'function', 'getAttributionCampaignKeyword' );
  281. equal( typeof tracker.setTrackerUrl, 'function', 'setTrackerUrl' );
  282. equal( typeof tracker.getRequest, 'function', 'getRequest' );
  283. equal( typeof tracker.setSiteId, 'function', 'setSiteId' );
  284. equal( typeof tracker.setCustomData, 'function', 'setCustomData' );
  285. equal( typeof tracker.getCustomData, 'function', 'getCustomData' );
  286. equal( typeof tracker.setCustomVariable, 'function', 'setCustomVariable' );
  287. equal( typeof tracker.getCustomVariable, 'function', 'getCustomVariable' );
  288. equal( typeof tracker.deleteCustomVariable, 'function', 'deleteCustomVariable' );
  289. equal( typeof tracker.setLinkTrackingTimer, 'function', 'setLinkTrackingTimer' );
  290. equal( typeof tracker.setDownloadExtensions, 'function', 'setDownloadExtensions' );
  291. equal( typeof tracker.addDownloadExtensions, 'function', 'addDownloadExtensions' );
  292. equal( typeof tracker.setDomains, 'function', 'setDomains' );
  293. equal( typeof tracker.setIgnoreClasses, 'function', 'setIgnoreClasses' );
  294. equal( typeof tracker.setRequestMethod, 'function', 'setRequestMethod' );
  295. equal( typeof tracker.setReferrerUrl, 'function', 'setReferrerUrl' );
  296. equal( typeof tracker.setCustomUrl, 'function', 'setCustomUrl' );
  297. equal( typeof tracker.setDocumentTitle, 'function', 'setDocumentTitle' );
  298. equal( typeof tracker.setDownloadClasses, 'function', 'setDownloadClasses' );
  299. equal( typeof tracker.setLinkClasses, 'function', 'setLinkClasses' );
  300. equal( typeof tracker.setCampaignNameKey, 'function', 'setCampaignNameKey' );
  301. equal( typeof tracker.setCampaignKeywordKey, 'function', 'setCampaignKeywordKey' );
  302. equal( typeof tracker.discardHashTag, 'function', 'discardHashTag' );
  303. equal( typeof tracker.setCookieNamePrefix, 'function', 'setCookieNamePrefix' );
  304. equal( typeof tracker.setCookieDomain, 'function', 'setCookieDomain' );
  305. equal( typeof tracker.setCookiePath, 'function', 'setCookiePath' );
  306. equal( typeof tracker.setVisitorCookieTimeout, 'function', 'setVisitorCookieTimeout' );
  307. equal( typeof tracker.setSessionCookieTimeout, 'function', 'setSessionCookieTimeout' );
  308. equal( typeof tracker.setReferralCookieTimeout, 'function', 'setReferralCookieTimeout' );
  309. equal( typeof tracker.setConversionAttributionFirstReferrer, 'function', 'setConversionAttributionFirstReferrer' );
  310. equal( typeof tracker.addListener, 'function', 'addListener' );
  311. equal( typeof tracker.enableLinkTracking, 'function', 'enableLinkTracking' );
  312. equal( typeof tracker.setHeartBeatTimer, 'function', 'setHeartBeatTimer' );
  313. equal( typeof tracker.killFrame, 'function', 'killFrame' );
  314. equal( typeof tracker.redirectFile, 'function', 'redirectFile' );
  315. equal( typeof tracker.setCountPreRendered, 'function', 'setCountPreRendered' );
  316. equal( typeof tracker.trackGoal, 'function', 'trackGoal' );
  317. equal( typeof tracker.trackLink, 'function', 'trackLink' );
  318. equal( typeof tracker.trackPageView, 'function', 'trackPageView' );
  319. // ecommerce
  320. equal( typeof tracker.setEcommerceView, 'function', 'setEcommerceView' );
  321. equal( typeof tracker.addEcommerceItem, 'function', 'addEcommerceItem' );
  322. equal( typeof tracker.trackEcommerceOrder, 'function', 'trackEcommerceOrder' );
  323. equal( typeof tracker.trackEcommerceCartUpdate, 'function', 'trackEcommerceCartUpdate' );
  324. });
  325. module("API and internals");
  326. test("Tracker is_a functions", function() {
  327. expect(22);
  328. var tracker = Piwik.getTracker();
  329. equal( typeof tracker.hook.test._isDefined, 'function', 'isDefined' );
  330. ok( tracker.hook.test._isDefined(tracker), 'isDefined true' );
  331. ok( tracker.hook.test._isDefined(tracker.hook), 'isDefined(obj.exists) true' );
  332. ok( !tracker.hook.test._isDefined(tracker.non_existant_property), 'isDefined(obj.missing) false' );
  333. equal( typeof tracker.hook.test._isFunction, 'function', 'isFunction' );
  334. ok( tracker.hook.test._isFunction(tracker.hook.test._isFunction), 'isFunction(isFunction)' );
  335. ok( tracker.hook.test._isFunction(function () { }), 'isFunction(function)' );
  336. equal( typeof tracker.hook.test._isObject, 'function', 'isObject' );
  337. ok( tracker.hook.test._isObject(null), 'isObject(null)' ); // null is an object!
  338. ok( tracker.hook.test._isObject(new Object), 'isObject(Object)' );
  339. ok( tracker.hook.test._isObject(window), 'isObject(window)' );
  340. ok( !tracker.hook.test._isObject('string'), 'isObject("string")' );
  341. ok( tracker.hook.test._isObject(new String), 'isObject(String)' ); // String is an object!
  342. equal( typeof tracker.hook.test._isString, 'function', 'isString' );
  343. ok( tracker.hook.test._isString(''), 'isString(emptyString)' );
  344. ok( tracker.hook.test._isString('abc'), 'isString("abc")' );
  345. ok( tracker.hook.test._isString('123'), 'isString("123")' );
  346. ok( !tracker.hook.test._isString(123), 'isString(123)' );
  347. ok( !tracker.hook.test._isString(null), 'isString(null)' );
  348. ok( !tracker.hook.test._isString(window), 'isString(window)' );
  349. ok( !tracker.hook.test._isString(function () { }), 'isString(function)' );
  350. ok( tracker.hook.test._isString(new String), 'isString(String)' ); // String is a string
  351. });
  352. test("AnalyticsTracker alias", function() {
  353. expect(1);
  354. var tracker = AnalyticsTracker.getTracker();
  355. equal( typeof tracker.hook.test._encode, 'function', 'encodeWrapper' );
  356. });
  357. test("Tracker encode, decode, urldecode wrappers", function() {
  358. expect(6);
  359. var tracker = Piwik.getTracker();
  360. equal( typeof tracker.hook.test._encode, 'function', 'encodeWrapper' );
  361. equal( typeof tracker.hook.test._decode, 'function', 'decodeWrapper' );
  362. equal( typeof tracker.hook.test._urldecode, 'function', 'urldecodeWrapper' );
  363. equal( tracker.hook.test._encode("&=?;/#"), '%26%3D%3F%3B%2F%23', 'encodeWrapper()' );
  364. equal( tracker.hook.test._decode("%26%3D%3F%3B%2F%23"), '&=?;/#', 'decodeWrapper()' );
  365. equal( tracker.hook.test._urldecode("mailto:%69%6e%66%6f@%65%78%61%6d%70%6c%65.%63%6f%6d"), 'mailto:info@example.com', 'decodeWrapper()' );
  366. });
  367. test("Tracker getHostName(), getParameter(), urlFixup(), domainFixup(), titleFixup() and purify()", function() {
  368. expect(57);
  369. var tracker = Piwik.getTracker();
  370. equal( typeof tracker.hook.test._getHostName, 'function', 'getHostName' );
  371. equal( typeof tracker.hook.test._getParameter, 'function', 'getParameter' );
  372. equal( tracker.hook.test._getHostName('http://example.com'), 'example.com', 'http://example.com');
  373. equal( tracker.hook.test._getHostName('http://example.com/'), 'example.com', 'http://example.com/');
  374. equal( tracker.hook.test._getHostName('http://example.com/index'), 'example.com', 'http://example.com/index');
  375. equal( tracker.hook.test._getHostName('http://example.com/index?q=xyz'), 'example.com', 'http://example.com/index?q=xyz');
  376. equal( tracker.hook.test._getHostName('http://example.com/?q=xyz'), 'example.com', 'http://example.com/?q=xyz');
  377. equal( tracker.hook.test._getHostName('http://example.com/?q=xyz#hash'), 'example.com', 'http://example.com/?q=xyz#hash');
  378. equal( tracker.hook.test._getHostName('http://example.com#hash'), 'example.com', 'http://example.com#hash');
  379. equal( tracker.hook.test._getHostName('http://example.com/#hash'), 'example.com', 'http://example.com/#hash');
  380. equal( tracker.hook.test._getHostName('http://example.com:80'), 'example.com', 'http://example.com:80');
  381. equal( tracker.hook.test._getHostName('http://example.com:80/'), 'example.com', 'http://example.com:80/');
  382. equal( tracker.hook.test._getHostName('https://example.com/'), 'example.com', 'https://example.com/');
  383. equal( tracker.hook.test._getHostName('http://user@example.com/'), 'example.com', 'http://user@example.com/');
  384. equal( tracker.hook.test._getHostName('http://user:password@example.com/'), 'example.com', 'http://user:password@example.com/');
  385. equal( tracker.hook.test._getParameter('http://piwik.org/', 'q'), '', 'no query');
  386. equal( tracker.hook.test._getParameter('http://piwik.org/?q=test', 'q'), 'test', '?q');
  387. equal( tracker.hook.test._getParameter('http://piwik.org/?q=test#aq=not', 'q'), 'test', '?q');
  388. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2', 'q'), 'test2', '&q');
  389. // getParameter in hash tag
  390. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#aq=not', 'q'), 'test2', '&q');
  391. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#aq=not', 'aq'), 'not', '#aq');
  392. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'bq'), 'yes', '#bq');
  393. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#pk_campaign=campaign', 'pk_campaign'), 'campaign', '#pk_campaign');
  394. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'q'), 'test2', '#q');
  395. // URL decoded
  396. equal( tracker.hook.test._getParameter('http://piwik.org/?q=http%3a%2f%2flocalhost%2f%3fr%3d1%26q%3dfalse', 'q'), 'http://localhost/?r=1&q=false', 'url');
  397. equal( tracker.hook.test._getParameter('http://piwik.org/?q=http%3a%2f%2flocalhost%2f%3fr%3d1%26q%3dfalse&notq=not', 'q'), 'http://localhost/?r=1&q=false', 'url');
  398. // non existing parameters
  399. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'bqq'), "", '#q');
  400. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'bq='), "", '#q');
  401. equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'sp='), "", '#q');
  402. equal( typeof tracker.hook.test._urlFixup, 'function', 'urlFixup' );
  403. deepEqual( tracker.hook.test._urlFixup( 'webcache.googleusercontent.com', 'http://webcache.googleusercontent.com/search?q=cache:CD2SncROLs4J:piwik.org/blog/2010/04/piwik-0-6-security-advisory/+piwik+security&cd=1&hl=en&ct=clnk', '' ),
  404. ['piwik.org', 'http://piwik.org/qa', ''], 'webcache.googleusercontent.com' );
  405. deepEqual( tracker.hook.test._urlFixup( 'cc.bingj.com', 'http://cc.bingj.com/cache.aspx?q=web+analytics&d=5020318678516316&mkt=en-CA&setlang=en-CA&w=6ea8ea88,ff6c44df', '' ),
  406. ['piwik.org', 'http://piwik.org/qa', ''], 'cc.bingj.com' );
  407. deepEqual( tracker.hook.test._urlFixup( '74.6.239.185', 'http://74.6.239.185/search/srpcache?ei=UTF-8&p=piwik&fr=yfp-t-964&fp_ip=ca&u=http://cc.bingj.com/cache.aspx?q=piwik&d=4770519086662477&mkt=en-US&setlang=en-US&w=f4bc05d8,8c8af2e3&icp=1&.intl=us&sig=PXmPDNqapxSQ.scsuhIpZA--', '' ),
  408. ['piwik.org', 'http://piwik.org/qa', ''], 'yahoo cache (1)' );
  409. deepEqual( tracker.hook.test._urlFixup( '74.6.239.84', 'http://74.6.239.84/search/srpcache?ei=UTF-8&p=web+analytics&fr=yfp-t-715&u=http://cc.bingj.com/cache.aspx?q=web+analytics&d=5020318680482405&mkt=en-CA&setlang=en-CA&w=a68d7af0,873cfeb0&icp=1&.intl=ca&sig=x6MgjtrDYvsxi8Zk2ZX.tw--', '' ),
  410. ['piwik.org', 'http://piwik.org/qa', ''], 'yahoo cache (2)' );
  411. deepEqual( tracker.hook.test._urlFixup( 'translate.googleusercontent.com', 'http://translate.googleusercontent.com/translate_c?hl=en&ie=UTF-8&sl=en&tl=fr&u=http://piwik.org/&prev=_t&rurl=translate.google.com&twu=1&usg=ALkJrhirI_ijXXT7Ja_aDGndEJbE7pJqpQ', '' ),
  412. ['piwik.org', 'http://piwik.org/', 'http://translate.googleusercontent.com/translate_c?hl=en&ie=UTF-8&sl=en&tl=fr&u=http://piwik.org/&prev=_t&rurl=translate.google.com&twu=1&usg=ALkJrhirI_ijXXT7Ja_aDGndEJbE7pJqpQ'], 'translate.googleusercontent.com' );
  413. equal( typeof tracker.hook.test._domainFixup, 'function', 'domainFixup' );
  414. equal( tracker.hook.test._domainFixup( 'localhost' ), 'localhost', 'domainFixup: localhost' );
  415. equal( tracker.hook.test._domainFixup( 'localhost.' ), 'localhost', 'domainFixup: localhost.' );
  416. equal( tracker.hook.test._domainFixup( 'localhost.localdomain' ), 'localhost.localdomain', 'domainFixup: localhost.localdomain' );
  417. equal( tracker.hook.test._domainFixup( 'localhost.localdomain.' ), 'localhost.localdomain', 'domainFixup: localhost.localdomain.' );
  418. equal( tracker.hook.test._domainFixup( '127.0.0.1' ), '127.0.0.1', 'domainFixup: 127.0.0.1' );
  419. equal( tracker.hook.test._domainFixup( 'www.example.com' ), 'www.example.com', 'domainFixup: www.example.com' );
  420. equal( tracker.hook.test._domainFixup( 'www.example.com.' ), 'www.example.com', 'domainFixup: www.example.com.' );
  421. equal( tracker.hook.test._domainFixup( '.example.com' ), '.example.com', 'domainFixup: .example.com' );
  422. equal( tracker.hook.test._domainFixup( '.example.com.' ), '.example.com', 'domainFixup: .example.com.' );
  423. equal( tracker.hook.test._domainFixup( '*.example.com' ), '.example.com', 'domainFixup: *.example.com' );
  424. equal( tracker.hook.test._domainFixup( '*.example.com.' ), '.example.com', 'domainFixup: *.example.com.' );
  425. equal( typeof tracker.hook.test._titleFixup, 'function', 'titleFixup' );
  426. equal( tracker.hook.test._titleFixup( 'hello' ), 'hello', 'hello string' );
  427. equal( tracker.hook.test._titleFixup( document.title ), 'piwik.js: Unit Tests', 'hello string' );
  428. equal( typeof tracker.hook.test._purify, 'function', 'purify' );
  429. equal( tracker.hook.test._purify('http://example.com'), 'http://example.com', 'http://example.com');
  430. equal( tracker.hook.test._purify('http://example.com#hash'), 'http://example.com#hash', 'http://example.com#hash');
  431. equal( tracker.hook.test._purify('http://example.com/?q=xyz#hash'), 'http://example.com/?q=xyz#hash', 'http://example.com/?q=xyz#hash');
  432. tracker.discardHashTag(true);
  433. equal( tracker.hook.test._purify('http://example.com'), 'http://example.com', 'http://example.com');
  434. equal( tracker.hook.test._purify('http://example.com#hash'), 'http://example.com', 'http://example.com#hash');
  435. equal( tracker.hook.test._purify('http://example.com/?q=xyz#hash'), 'http://example.com/?q=xyz', 'http://example.com/?q=xyz#hash');
  436. });
  437. // support for setCustomUrl( relativeURI )
  438. test("getProtocolScheme and resolveRelativeReference", function() {
  439. expect(27);
  440. var tracker = Piwik.getTracker();
  441. equal( typeof tracker.hook.test._getProtocolScheme, 'function', "getProtocolScheme" );
  442. ok( tracker.hook.test._getProtocolScheme('http://example.com') === 'http', 'http://' );
  443. ok( tracker.hook.test._getProtocolScheme('https://example.com') === 'https', 'https://' );
  444. ok( tracker.hook.test._getProtocolScheme('file://somefile.txt') === 'file', 'file://' );
  445. ok( tracker.hook.test._getProtocolScheme('mailto:somebody@example.com') === 'mailto', 'mailto:' );
  446. ok( tracker.hook.test._getProtocolScheme('javascript:alert(document.cookie)') === 'javascript', 'javascript:' );
  447. ok( tracker.hook.test._getProtocolScheme('') === null, 'empty string' );
  448. ok( tracker.hook.test._getProtocolScheme(':') === null, 'unspecified scheme' );
  449. ok( tracker.hook.test._getProtocolScheme('scheme') === null, 'missing colon' );
  450. equal( typeof tracker.hook.test._resolveRelativeReference, 'function', 'resolveRelativeReference' );
  451. var i, j, data = [
  452. // unsupported
  453. // ['http://example.com/index.php/pathinfo?query', 'test.php', 'http://example.com/test.php'],
  454. // ['http://example.com/subdir/index.php', '../test.php', 'http://example.com/test.php'],
  455. // already absolute
  456. ['http://example.com/', 'http://example.com', 'http://example.com'],
  457. ['http://example.com/', 'https://example.com/', 'https://example.com/'],
  458. ['http://example.com/', 'http://example.com/index', 'http://example.com/index'],
  459. // relative to root
  460. ['http://example.com/', '', 'http://example.com/'],
  461. ['http://example.com/', '/', 'http://example.com/'],
  462. ['http://example.com/', '/test.php', 'http://example.com/test.php'],
  463. ['http://example.com/index', '/test.php', 'http://example.com/test.php'],
  464. ['http://example.com/index?query=x', '/test.php', 'http://example.com/test.php'],
  465. ['http://example.com/index?query=x#hash', '/test.php', 'http://example.com/test.php'],
  466. ['http://example.com/?query', '/test.php', 'http://example.com/test.php'],
  467. ['http://example.com/#hash', '/test.php', 'http://example.com/test.php'],
  468. // relative to current document
  469. ['http://example.com/subdir/', 'test.php', 'http://example.com/subdir/test.php'],
  470. ['http://example.com/subdir/index', 'test.php', 'http://example.com/subdir/test.php'],
  471. ['http://example.com/subdir/index?query=x', 'test.php', 'http://example.com/subdir/test.php'],
  472. ['http://example.com/subdir/index?query=x#hash', 'test.php', 'http://example.com/subdir/test.php'],
  473. ['http://example.com/subdir/?query', 'test.php', 'http://example.com/subdir/test.php'],
  474. ['http://example.com/subdir/#hash', 'test.php', 'http://example.com/subdir/test.php']
  475. ];
  476. for (i = 0; i < data.length; i++) {
  477. j = data[i];
  478. equal( tracker.hook.test._resolveRelativeReference(j[0], j[1]), j[2], j[2] );
  479. }
  480. });
  481. test("Tracker setDomains() and isSiteHostName()", function() {
  482. expect(13);
  483. var tracker = Piwik.getTracker();
  484. equal( typeof tracker.hook.test._isSiteHostName, 'function', "isSiteHostName" );
  485. // test wildcards
  486. tracker.setDomains( ['*.Example.com'] );
  487. // skip test if testing on localhost
  488. ok( window.location.hostname != 'localhost' ? !tracker.hook.test._isSiteHostName('localhost') : true, '!isSiteHostName("localhost")' );
  489. ok( !tracker.hook.test._isSiteHostName('google.com'), '!isSiteHostName("google.com")' );
  490. ok( tracker.hook.test._isSiteHostName('example.com'), 'isSiteHostName("example.com")' );
  491. ok( tracker.hook.test._isSiteHostName('www.example.com'), 'isSiteHostName("www.example.com")' );
  492. ok( tracker.hook.test._isSiteHostName('www.sub.example.com'), 'isSiteHostName("www.sub.example.com")' );
  493. tracker.setDomains( 'dev.piwik.org' );
  494. ok( !tracker.hook.test._isSiteHostName('piwik.org'), '!isSiteHostName("piwik.org")' );
  495. ok( tracker.hook.test._isSiteHostName('dev.piwik.org'), 'isSiteHostName("dev.piwik.org")' );
  496. ok( !tracker.hook.test._isSiteHostName('piwik.example.org'), '!isSiteHostName("piwik.example.org")');
  497. ok( !tracker.hook.test._isSiteHostName('dev.piwik.org.com'), '!isSiteHostName("dev.piwik.org.com")');
  498. tracker.setDomains( '.piwik.org' );
  499. ok( tracker.hook.test._isSiteHostName('piwik.org'), 'isSiteHostName("piwik.org")' );
  500. ok( tracker.hook.test._isSiteHostName('dev.piwik.org'), 'isSiteHostName("dev.piwik.org")' );
  501. ok( !tracker.hook.test._isSiteHostName('piwik.org.com'), '!isSiteHostName("piwik.org.com")');
  502. });
  503. test("Tracker getClassesRegExp()", function() {
  504. expect(3);
  505. var tracker = Piwik.getTracker();
  506. equal( typeof tracker.hook.test._getClassesRegExp, 'function', "getClassesRegExp" );
  507. var download = tracker.hook.test._getClassesRegExp([], 'download');
  508. ok( download.test('piwik_download'), 'piwik_download (default)' );
  509. var outlink = tracker.hook.test._getClassesRegExp([], 'link');
  510. ok( outlink.test('piwik_link'), 'piwik_link (default)' );
  511. });
  512. test("Tracker setIgnoreClasses() and getClassesRegExp(ignore)", function() {
  513. expect(14);
  514. var tracker = Piwik.getTracker();
  515. var ignore = tracker.hook.test._getClassesRegExp([], 'ignore');
  516. ok( ignore.test('piwik_ignore'), '[1] piwik_ignore' );
  517. ok( !ignore.test('pk_ignore'), '[1] !pk_ignore' );
  518. ok( !ignore.test('apiwik_ignore'), '!apiwik_ignore' );
  519. ok( !ignore.test('piwik_ignorez'), '!piwik_ignorez' );
  520. ok( ignore.test('abc piwik_ignore xyz'), 'abc piwik_ignore xyz' );
  521. tracker.setIgnoreClasses( 'my_download' );
  522. ignore = tracker.hook.test._getClassesRegExp(['my_download'], 'ignore');
  523. ok( ignore.test('piwik_ignore'), '[2] piwik_ignore' );
  524. ok( !ignore.test('pk_ignore'), '[2] !pk_ignore' );
  525. ok( ignore.test('my_download'), 'my_download' );
  526. ok( ignore.test('abc piwik_ignore xyz'), 'abc piwik_ignore xyz' );
  527. ok( ignore.test('abc my_download xyz'), 'abc my_download xyz' );
  528. tracker.setIgnoreClasses( ['my_download', 'my_outlink'] );
  529. ignore = tracker.hook.test._getClassesRegExp(['my_download','my_outlink'], 'ignore');
  530. ok( ignore.test('piwik_ignore'), '[3] piwik_ignore' );
  531. ok( !ignore.test('pk_ignore'), '[3] !pk_ignore' );
  532. ok( ignore.test('my_download'), 'my_download' );
  533. ok( ignore.test('my_outlink'), 'my_outlink' );
  534. });
  535. test("Tracker hasCookies(), getCookie(), setCookie()", function() {
  536. expect(2);
  537. var tracker = Piwik.getTracker();
  538. ok( tracker.hook.test._hasCookies() == '1', 'hasCookies()' );
  539. var cookieName = '_pk_test_harness' + Math.random(),
  540. expectedValue = String(Math.random());
  541. tracker.hook.test._setCookie( cookieName, expectedValue );
  542. equal( tracker.hook.test._getCookie( cookieName ), expectedValue, 'getCookie(), setCookie()' );
  543. });
  544. test("Tracker setDownloadExtensions(), addDownloadExtensions(), setDownloadClasses(), setLinkClasses(), and getLinkType()", function() {
  545. expect(25);
  546. var tracker = Piwik.getTracker();
  547. equal( typeof tracker.hook.test._getLinkType, 'function', 'getLinkType' );
  548. equal( tracker.hook.test._getLinkType('something', 'goofy.html', false), 'link', 'implicit link' );
  549. equal( tracker.hook.test._getLinkType('something', 'goofy.pdf', false), 'download', 'external PDF files are downloads' );
  550. equal( tracker.hook.test._getLinkType('something', 'goofy.pdf', true), 'download', 'local PDF are downloads' );
  551. equal( tracker.hook.test._getLinkType('something', 'goofy-with-dash.pdf', true), 'download', 'local PDF are downloads' );
  552. equal( tracker.hook.test._getLinkType('piwik_download', 'piwiktest.ext', true), 'download', 'piwik_download' );
  553. equal( tracker.hook.test._getLinkType('abc piwik_download xyz', 'piwiktest.ext', true), 'download', 'abc piwik_download xyz' );
  554. equal( tracker.hook.test._getLinkType('piwik_link', 'piwiktest.asp', true), 'link', 'piwik_link' );
  555. equal( tracker.hook.test._getLinkType('abc piwik_link xyz', 'piwiktest.asp', true), 'link', 'abc piwik_link xyz' );
  556. equal( tracker.hook.test._getLinkType('something', 'piwiktest.txt', true), 'download', 'download extension' );
  557. equal( tracker.hook.test._getLinkType('something', 'piwiktest.ext', true), 0, '[1] link (default)' );
  558. equal( tracker.hook.test._getLinkType('something', 'file.zip', true), 'download', 'download file.zip' );
  559. equal( tracker.hook.test._getLinkType('something', 'index.php?name=file.zip#anchor', true), 'download', 'download file.zip (anchor)' );
  560. equal( tracker.hook.test._getLinkType('something', 'index.php?name=file.zip&redirect=yes', true), 'download', 'download file.zip (is param)' );
  561. equal( tracker.hook.test._getLinkType('something', 'file.zip?mirror=true', true), 'download', 'download file.zip (with param)' );
  562. tracker.setDownloadExtensions('pk');
  563. equal( tracker.hook.test._getLinkType('something', 'piwiktest.pk', true), 'download', '[1] .pk == download extension' );
  564. equal( tracker.hook.test._getLinkType('something', 'piwiktest.txt', true), 0, '.txt =! download extension' );
  565. tracker.addDownloadExtensions('xyz');
  566. equal( tracker.hook.test._getLinkType('something', 'piwiktest.pk', true), 'download', '[2] .pk == download extension' );
  567. equal( tracker.hook.test._getLinkType('something', 'piwiktest.xyz', true), 'download', '.xyz == download extension' );
  568. tracker.setDownloadClasses(['a', 'b']);
  569. equal( tracker.hook.test._getLinkType('abc piwik_download', 'piwiktest.ext', true), 'download', 'download (default)' );
  570. equal( tracker.hook.test._getLinkType('abc a', 'piwiktest.ext', true), 'download', 'download (a)' );
  571. equal( tracker.hook.test._getLinkType('b abc', 'piwiktest.ext', true), 'download', 'download (b)' );
  572. tracker.setLinkClasses(['c', 'd']);
  573. equal( tracker.hook.test._getLinkType('abc piwik_link', 'piwiktest.ext', true), 'link', 'link (default)' );
  574. equal( tracker.hook.test._getLinkType('abc c', 'piwiktest.ext', true), 'link', 'link (c)' );
  575. equal( tracker.hook.test._getLinkType('d abc', 'piwiktest.ext', true), 'link', 'link (d)' );
  576. });
  577. test("utf8_encode(), sha1()", function() {
  578. expect(6);
  579. var tracker = Piwik.getTracker();
  580. equal( typeof tracker.hook.test._utf8_encode, 'function', 'utf8_encode' );
  581. equal( tracker.hook.test._utf8_encode('hello world'), '<?php echo utf8_encode("hello world"); ?>', 'utf8_encode("hello world")' );
  582. equal( tracker.hook.test._utf8_encode('Gesamtgröße'), '<?php echo utf8_encode("Gesamtgröße"); ?>', 'utf8_encode("Gesamtgröße")' );
  583. equal( tracker.hook.test._utf8_encode('您好'), '<?php echo utf8_encode("您好"); ?>', 'utf8_encode("您好")' );
  584. equal( typeof tracker.hook.test._sha1, 'function', 'sha1' );
  585. equal( tracker.hook.test._sha1('hello world'), '<?php echo sha1("hello world"); ?>', 'sha1("hello world")' );
  586. });
  587. test("getRequest()", function() {
  588. expect(1);
  589. var tracker = Piwik.getTracker();
  590. tracker.setCustomData("key is X", "value is Y");
  591. equal( tracker.getRequest('hello=world').indexOf('hello=world&idsite=&rec=1&r='), 0);
  592. });
  593. test("prefixPropertyName()", function() {
  594. expect(3);
  595. var tracker = Piwik.getTracker();
  596. equal( typeof tracker.hook.test._prefixPropertyName, 'function', 'prefixPropertyName' );
  597. equal( tracker.hook.test._prefixPropertyName('', 'hidden'), 'hidden', 'no prefix' );
  598. equal( tracker.hook.test._prefixPropertyName('webkit', 'hidden'), 'webkitHidden', 'webkit prefix' );
  599. });
  600. test("Internal timers and setLinkTrackingTimer()", function() {
  601. expect(5);
  602. var tracker = Piwik.getTracker();
  603. ok( ! ( _paq instanceof Array ), "async tracker proxy not an array" );
  604. equal( typeof tracker, typeof _paq, "async tracker proxy" );
  605. var startTime, stopTime;
  606. equal( typeof tracker.hook.test._beforeUnloadHandler, 'function', 'beforeUnloadHandler' );
  607. startTime = new Date();
  608. tracker.hook.test._beforeUnloadHandler();
  609. stopTime = new Date();
  610. ok( (stopTime.getTime() - startTime.getTime()) < 500, 'beforeUnloadHandler()' );
  611. tracker.setLinkTrackingTimer(2000);
  612. startTime = new Date();
  613. tracker.trackPageView();
  614. tracker.hook.test._beforeUnloadHandler();
  615. stopTime = new Date();
  616. ok( (stopTime.getTime() - startTime.getTime()) >= 2000, 'setLinkTrackingTimer()' );
  617. });
  618. test("Overlay URL Normalizer", function() {
  619. expect(11);
  620. var test = function(testCases) {
  621. for (var i = 0; i < testCases.length; i++) {
  622. var observed = Piwik_Overlay_UrlNormalizer.normalize(testCases[i][0]);
  623. var expected = testCases[i][1];
  624. equal(observed, expected, testCases[i][0]);
  625. }
  626. };
  627. Piwik_Overlay_UrlNormalizer.initialize();
  628. Piwik_Overlay_UrlNormalizer.setExcludedParameters(['excluded1', 'excluded2', 'excluded3']);
  629. Piwik_Overlay_UrlNormalizer.setBaseHref(false);
  630. Piwik_Overlay_UrlNormalizer.setCurrentDomain('example.com');
  631. Piwik_Overlay_UrlNormalizer.setCurrentUrl('https://www.example.com/current/test.html?asdfasdf');
  632. test([
  633. [
  634. 'relative/path/',
  635. 'example.com/current/relative/path/'
  636. ], [
  637. 'http://www.example2.com/path/foo.html',
  638. 'example2.com/path/foo.html'
  639. ]
  640. ]);
  641. Piwik_Overlay_UrlNormalizer.setCurrentDomain('www.example3.com');
  642. Piwik_Overlay_UrlNormalizer.setCurrentUrl('http://example3.com/current/folder/');
  643. test([[
  644. 'relative.html',
  645. 'example3.com/current/folder/relative.html'
  646. ]]);
  647. Piwik_Overlay_UrlNormalizer.setBaseHref('http://example.com/base/');
  648. test([
  649. [
  650. 'http://www.example2.com/my/test/path.html?id=2&excluded2=foo#MyAnchor',
  651. 'example2.com/my/test/path.html?id=2#MyAnchor'
  652. ], [
  653. '/my/test/foo/../path.html?excluded1=foo&excluded2=foo&excluded3=foo',
  654. 'example3.com/my/test/path.html'
  655. ], [
  656. 'path/./test//test///foo.bar?excluded2=foo&id=3',
  657. 'example.com/base/path/test/test/foo.bar?id=3'
  658. ], [
  659. 'path/./test//test///foo.bar?excluded2=foo#Anchor',
  660. 'example.com/base/path/test/test/foo.bar#Anchor'
  661. ], [
  662. 'https://example2.com//test.html?id=3&excluded1=foo&bar=baz#asdf',
  663. 'example2.com/test.html?id=3&bar=baz#asdf'
  664. ], [
  665. '#',
  666. ''
  667. ], [
  668. '#Anchor',
  669. ''
  670. ], [
  671. '/',
  672. 'example3.com/'
  673. ]
  674. ]);
  675. });
  676. <?php
  677. if ($sqlite) {
  678. ?>
  679. module("request", {
  680. setup: function () {
  681. ok(true, "request.setup");
  682. deleteCookies();
  683. ok(document.cookie === "", "deleteCookies");
  684. },
  685. teardown: function () {
  686. ok(true, "request.teardown");
  687. }
  688. });
  689. test("tracking", function() {
  690. expect(97);
  691. /*
  692. * Prevent Opera and HtmlUnit from performing the default action (i.e., load the href URL)
  693. */
  694. var stopEvent = function (evt) {
  695. evt = evt || window.event;
  696. // evt.cancelBubble = true;
  697. evt.returnValue = false;
  698. if (evt.preventDefault)
  699. evt.preventDefault();
  700. // if (evt.stopPropagation)
  701. // evt.stopPropagation();
  702. // return false;
  703. };
  704. var tracker = Piwik.getTracker();
  705. tracker.setTrackerUrl("piwik.php");
  706. tracker.setSiteId(1);
  707. function wait(msecs)
  708. {
  709. var start = new Date().getTime();
  710. var cur = start
  711. while(cur - start < msecs)
  712. {
  713. cur = new Date().getTime();
  714. }
  715. }
  716. var visitorIdStart = tracker.getVisitorId();
  717. // need to wait at least 1 second so that the cookie would be different, if it wasnt persisted
  718. wait(2000);
  719. var visitorIdStart2 = tracker.getVisitorId();
  720. ok( visitorIdStart == visitorIdStart2, "getVisitorId() same when called twice with more than 1 second delay");
  721. var customUrl = "http://localhost.localdomain/?utm_campaign=YEAH&utm_term=RIGHT!";
  722. tracker.setCustomUrl(customUrl);
  723. tracker.setCustomData({ "token" : getToken() });
  724. var data = tracker.getCustomData();
  725. ok( getToken() != "" && data.token == data["token"] && data.token == getToken(), "setCustomData() , getCustomData()" );
  726. // Custom variables with integer/float values
  727. tracker.setCustomVariable(1, 1, 2, "visit");
  728. deepEqual( tracker.getCustomVariable(1, "visit"), ["1", "2"], "setCustomVariable() with integer name/value" );
  729. tracker.setCustomVariable(1, 1, 0, "visit");
  730. deepEqual( tracker.getCustomVariable(1, "visit"), ["1", "0"], "setCustomVariable() with integer name/value" );
  731. tracker.setCustomVariable(2, 1.05, 2.11, "visit");
  732. deepEqual( tracker.getCustomVariable(2, "visit"), ["1.05", "2.11"], "setCustomVariable() with integer name/value" );
  733. // custom variables with undefined names or values
  734. tracker.setCustomVariable(5);// setting a custom variable with no name and no value should not error
  735. deepEqual( tracker.getCustomVariable(5), false, "getting a custom variable with no name nor value" );
  736. deepEqual( tracker.getCustomVariable(55), false, "getting a custom variable with no name nor value" );
  737. tracker.setCustomVariable(5, "new name");
  738. deepEqual( tracker.getCustomVariable(5), ["new name", ""], "getting a custom variable with no value" );
  739. tracker.deleteCustomVariable(5);
  740. tracker.setDocumentTitle("PiwikTest");
  741. var referrerUrl = "http://referrer.example.com/page/sub?query=test&test2=test3";
  742. tracker.setReferrerUrl(referrerUrl);
  743. referrerTimestamp = Math.round(new Date().getTime() / 1000);
  744. tracker.trackPageView();
  745. tracker.trackPageView("CustomTitleTest");
  746. var customUrlShouldNotChangeCampaign = "http://localhost.localdomain/?utm_campaign=NONONONONONONO&utm_term=PLEASE NO!";
  747. tracker.setCustomUrl(customUrl);
  748. tracker.trackPageView();
  749. tracker.trackLink("http://example.ca", "link", { "token" : getToken() });
  750. // async tracker proxy
  751. _paq.push(["trackLink", "http://example.fr/async.zip", "download", { "token" : getToken() }]);
  752. // push function
  753. _paq.push([ function(t) {
  754. tracker.trackLink("http://example.de", "link", { "token" : t });
  755. }, getToken() ]);
  756. tracker.setRequestMethod("POST");
  757. tracker.trackGoal(42, 69, { "token" : getToken(), "boy" : "Michael", "girl" : "Mandy"});
  758. piwik_log("CompatibilityLayer", 1, "piwik.php", { "token" : getToken() });
  759. tracker.hook.test._addEventListener(_e("click8"), "click", stopEvent);
  760. QUnit.triggerEvent( _e("click8"), "click" );
  761. tracker.enableLinkTracking();
  762. tracker.setRequestMethod("GET");
  763. var buttons = new Array("click1", "click2", "click3", "click4", "click5", "click6", "click7");
  764. for (var i=0; i < buttons.length; i++) {
  765. tracker.hook.test._addEventListener(_e(buttons[i]), "click", stopEvent);
  766. QUnit.triggerEvent( _e(buttons[i]), "click" );
  767. }
  768. var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() :
  769. window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") :
  770. null;
  771. var clickDiv = _e("clickDiv"),
  772. anchor = document.createElement("a");
  773. anchor.id = "click9";
  774. anchor.href = "http://example.us";
  775. clickDiv.innerHTML = "";
  776. clickDiv.appendChild(anchor);
  777. tracker.addListener(anchor);
  778. tracker.hook.test._addEventListener(anchor, "click", stopEvent);
  779. QUnit.triggerEvent( _e("click9"), "click" );
  780. var visitorId1, visitorId2;
  781. _paq.push([ function() {
  782. visitorId1 = Piwik.getAsyncTracker().getVisitorId();
  783. }]);
  784. visitorId2 = tracker.getVisitorId();
  785. ok( visitorId1 && visitorId1 != "" && visitorId2 && visitorId2 != "" && (visitorId1 == visitorId2), "getVisitorId()" );
  786. var visitorInfo1, visitorInfo2;
  787. // Visitor INFO + Attribution INFO tests
  788. tracker.setReferrerUrl(referrerUrl);
  789. _paq.push([ function() {
  790. visitorInfo1 = Piwik.getAsyncTracker().getVisitorInfo();
  791. attributionInfo1 = Piwik.getAsyncTracker().getAttributionInfo();
  792. referrer1 = Piwik.getAsyncTracker().getAttributionReferrerUrl();
  793. }]);
  794. visitorInfo2 = tracker.getVisitorInfo();
  795. ok( visitorInfo1 && visitorInfo2 && visitorInfo1.length == visitorInfo2.length, "getVisitorInfo()" );
  796. for (var i = 0; i < 6; i++) {
  797. ok( visitorInfo1[i] == visitorInfo2[i], "(loadVisitorId())["+i+"]" );
  798. }
  799. attributionInfo2 = tracker.getAttributionInfo();
  800. ok( attributionInfo1 && attributionInfo2 && attributionInfo1.length == attributionInfo2.length, "getAttributionInfo()" );
  801. referrer2 = tracker.getAttributionReferrerUrl();
  802. ok( referrer2 == referrerUrl, "getAttributionReferrerUrl()" );
  803. ok( referrer1 == referrerUrl, "async getAttributionReferrerUrl()" );
  804. referrerTimestamp2 = tracker.getAttributionReferrerTimestamp();
  805. ok( referrerTimestamp2 == referrerTimestamp, "tracker.getAttributionReferrerTimestamp()" );
  806. campaignName2 = tracker.getAttributionCampaignName();
  807. campaignKeyword2 = tracker.getAttributionCampaignKeyword();
  808. ok( campaignName2 == "YEAH", "getAttributionCampaignName()");
  809. ok( campaignKeyword2 == "RIGHT!", "getAttributionCampaignKeyword()");
  810. // Test visitor ID at the start is the same at the end
  811. var visitorIdEnd = tracker.getVisitorId();
  812. ok( visitorIdStart == visitorIdEnd, "tracker.getVisitorId() same at the start and end of process");
  813. // Custom variables
  814. tracker.setCookieNamePrefix("PREFIX");
  815. tracker.setCustomVariable(1, "cookiename", "cookievalue");
  816. deepEqual( tracker.getCustomVariable(1), ["cookiename", "cookievalue"], "setCustomVariable(cvarExists), getCustomVariable()" );
  817. tracker.setCustomVariable(2, "cookiename2", "cookievalue2", "visit");
  818. deepEqual( tracker.getCustomVariable(2), ["cookiename2", "cookievalue2"], "setCustomVariable(cvarExists), getCustomVariable()" );
  819. deepEqual( tracker.getCustomVariable(2, "visit"), ["cookiename2", "cookievalue2"], "setCustomVariable(cvarExists), getCustomVariable()" );
  820. deepEqual( tracker.getCustomVariable(2, 2), ["cookiename2", "cookievalue2"], "GA compability - setCustomVariable(cvarExists), getCustomVariable()" );
  821. tracker.setCustomVariable(2, "cookiename2PAGE", "cookievalue2PAGE", "page");
  822. deepEqual( tracker.getCustomVariable(2, "page"), ["cookiename2PAGE", "cookievalue2PAGE"], "setCustomVariable(cvarExists), getCustomVariable()" );
  823. deepEqual( tracker.getCustomVariable(2, 3), ["cookiename2PAGE", "cookievalue2PAGE"], "GA compability - setCustomVariable(cvarExists), getCustomVariable()" );
  824. tracker.setCustomVariable(2, "cookiename2EVENT", "cookievalue2EVENT", "event");
  825. deepEqual( tracker.getCustomVariable(2, "event"), ["cookiename2EVENT", "cookievalue2EVENT"], "CustomVariable and event scope" );
  826. tracker.trackPageView("SaveCustomVariableCookie");
  827. // test Site Search
  828. tracker.trackSiteSearch("No result keyword éà", "Search cat", 0);
  829. tracker.trackSiteSearch("Keyword with 10 results", false, 10);
  830. tracker.trackSiteSearch("search Keyword");
  831. // Testing Custom events
  832. tracker.setCustomVariable(1, "cvarEventName", "cvarEventValue", "event");
  833. tracker.trackEvent("Event Category", "Event Action");
  834. tracker.trackEvent("Event Category2", "Event Action2", "Event Name2");
  835. tracker.trackEvent("Event Category3", "Event Action3", "Event Name3", 3.333);
  836. //Ecommerce views
  837. tracker.setEcommerceView( "", false, ["CATEGORY1","CATEGORY2"] );
  838. deepEqual( tracker.getCustomVariable(3, "page"), false, "Ecommerce view SKU");
  839. tracker.setEcommerceView( "SKUMultiple", false, ["CATEGORY1","CATEGORY2"] );
  840. deepEqual( tracker.getCustomVariable(4, "page"), ["_pkn",""], "Ecommerce view Name");
  841. deepEqual( tracker.getCustomVariable(5, "page"), ["_pkc","[\"CATEGORY1\",\"CATEGORY2\"]"], "Ecommerce view Category");
  842. tracker.trackPageView("MultipleCategories");
  843. var tracker2 = Piwik.getTracker();
  844. tracker2.setTrackerUrl("piwik.php");
  845. tracker2.setSiteId(1);
  846. tracker2.setCustomData({ "token" : getToken() });
  847. tracker2.setCookieNamePrefix("PREFIX");
  848. deepEqual( tracker2.getCustomVariable(1), ["cookiename", "cookievalue"], "getCustomVariable(cvarExists) from cookie" );
  849. ok( /PREFIX/.test( document.cookie ), "setCookieNamePrefix()" );
  850. tracker2.deleteCustomVariable(1);
  851. //console.log(tracker2.getCustomVariable(1));
  852. ok( tracker2.getCustomVariable(1) === false, "VISIT deleteCustomVariable(), getCustomVariable() === false" );
  853. tracker2.deleteCustomVariable(2, "page");
  854. //console.log(tracker2.getCustomVariable(2, "page"));
  855. ok( tracker2.getCustomVariable(2, "page") === false, "PAGE deleteCustomVariable(), getCustomVariable() === false" );
  856. tracker2.trackPageView("DeleteCustomVariableCookie");
  857. var tracker3 = Piwik.getTracker();
  858. tracker3.setTrackerUrl("piwik.php");
  859. tracker3.setSiteId(1);
  860. track

Large files files are truncated, but you can click here to view the full file