1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
|
<?php
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>piwik.js: Unit Tests</title>
<?php
require_once(dirname(__FILE__).'/SQLite.php');
if(file_exists("stub.tpl")) {
echo file_get_contents("stub.tpl");
}
?>
<script type="text/javascript">
function getToken() {
return "<?php $token = md5(uniqid(mt_rand(), true)); echo $token; ?>";
}
function getContentToken() {
return "<?php $token = md5(uniqid(mt_rand(), true)); echo $token; ?>";
}
<?php
$sqlite = false;
if (file_exists("enable_sqlite")) {
if (class_exists('SQLite')) {
$sqlite = true;
}
}
if(!$sqlite) {
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 ");';
}
if ($sqlite) {
echo '
var _paq = _paq || [];
function testCallingTrackPageViewBeforeSetTrackerUrlWorks() {
_paq.push(["setCustomData", { "token" : getToken() }]);
_paq.push(["trackPageView", "Asynchronous Tracker ONE"]);
_paq.push(["setSiteId", 1]);
_paq.push(["setTrackerUrl", "piwik.php"]);
}
function testTrackPageViewAsync() {
_paq.push(["trackPageView", "Asynchronous tracking TWO"]);
}
testCallingTrackPageViewBeforeSetTrackerUrlWorks();
testTrackPageViewAsync();
';
}
?>
</script>
<script src="../../js/piwik.js?rand=<?php echo md5(uniqid(mt_rand(), true)) ?>" type="text/javascript"></script>
<script src="../../plugins/Overlay/client/urlnormalizer.js" type="text/javascript"></script>
<script src="piwiktest.js" type="text/javascript"></script>
<link rel="stylesheet" href="assets/qunit.css" type="text/css" media="screen" />
<link rel="stylesheet" href="jash/Jash.css" type="text/css" media="screen" />
<style>
.assertSize {
height: 1px;
width: 1px;
}
.hideY {
overflow-x: hidden !important;
}
#contenttest {
position: absolute;
left: 0px;
right: 0px;
top: 0px;
bottom: 0px;
}
</style>
<script src="../../libs/bower_components/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="assets/qunit.js" type="text/javascript"></script>
<script src="jslint/jslint.js" type="text/javascript"></script>
<script type="text/javascript">
QUnit.config.reorder = false;
function _e(id){
if (document.getElementById)
return document.getElementById(id);
if (document.layers)
return document[id];
if (document.all)
return document.all[id];
}
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
function _s(selector) { // select node within content test scope
$nodes = $('#contenttest ' + selector);
if ($nodes.length) {
return $nodes[0];
} else {
ok(false, 'selector not found but should: #contenttest ' + selector);
}
}
// Polyfill for IndexOf for IE6-IE8
function indexOfArray(theArray, searchElement)
{
if (theArray && theArray.indexOf) {
return theArray.indexOf(searchElement);
}
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (!isDefined(theArray) || theArray === null) {
return -1;
}
if (!theArray.length) {
return -1;
}
var len = theArray.length;
if (len === 0) {
return -1;
}
var k = 0;
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (theArray[k] === searchElement) {
return k;
}
k++;
}
return -1;
}
function getOrigin()
{
if (window.location.origin) {
return window.location.origin;
}
return window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
function encodeWrapper(url)
{
return window.encodeURIComponent(url);
}
function toEncodedAbsoluteUrl(url)
{
return encodeWrapper(toAbsoluteUrl(url));
}
function toAbsoluteUrl(url)
{
var origin = getOrigin();
var path = toAbsolutePath(url);
var absoluteUrl = origin + path;
return absoluteUrl;
}
function toEncodedAbsolutePath(url)
{
return encodeWrapper(toAbsolutePath(url));
}
function toAbsolutePath(url)
{
var path = '';
if (0 !== url.indexOf('/')) {
path += location.pathname;
if (!path.match(/\/$/)) {
path += '/';
}
}
var absolutePath = path + url;
return absolutePath;
}
function loadJash() {
var jashDiv = _e('jashDiv');
jashDiv.innerHTML = '';
document.body.appendChild(document.createElement('script')).src='jash/Jash.js';
}
function scrollToTop()
{
window.scroll(0, 0);
}
function triggerEvent(element, type) {
if ( document.createEvent ) {
var event = document.createEvent( "MouseEvents" );
event.initMouseEvent(type, true, true, element.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
element.dispatchEvent( event );
} else if ( element.fireEvent ) {
element.fireEvent( "on" + type );
}
}
function wait(msecs)
{
var start = new Date().getTime();
var cur = start
while(cur - start < msecs)
{
cur = new Date().getTime();
}
}
function fetchTrackedRequests(token)
{
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() :
window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") :
null;
xhr.open("GET", "piwik.php?requests=" + token, false);
xhr.send(null);
return xhr.responseText;
}
function dropCookie(cookieName, path, domain) {
var expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() - 3600);
document.cookie = cookieName + '=;expires=' + expiryDate.toGMTString() +
';path=' + (path ? path : '') +
(domain ? ';domain=' + domain : '');
document.cookie = cookieName + ';expires=' + expiryDate.toGMTString() +
';path=' + (path ? path : '') +
(domain ? ';domain=' + domain : '');
}
function deleteCookies() {
// aggressively delete cookies
// 1. get all cookies
var
cookies = (document.cookie).split(';'),
aCookie,
cookiePattern = new RegExp('^ *([^=]*)='),
cookieMatch,
cookieName,
domain,
domains = [],
path,
paths = [];
cookies.push( '=' );
// 2. construct list of domains
domain = document.domain;
if (domain.substring(0, 1) !== '.') {
domain = '.' + domain;
}
domains.push( domain );
while ((i = domain.indexOf('.')) >= 0) {
domain = domain.substring(i+1);
domains.push( domain );
}
domains.push( '' );
domains.push( null );
// 3. construct list of paths
path = window.location.pathname;
while ((i = path.lastIndexOf('/')) >= 0) {
paths.push(path + '/');
paths.push(path);
path = path.substring(0, i);
}
paths.push( '/' );
paths.push( '' );
paths.push( null );
// 4. iterate through cookies
for (aCookie in cookies) {
if (Object.prototype.hasOwnProperty.call(cookies, aCookie)) {
// 5. extract cookie name
cookieMatch = cookiePattern.exec(cookies[aCookie]);
if (cookieMatch) {
cookieName = cookieMatch[1];
// 6. iterate through domains
for (i = 0; i < domains.length; i++) {
// 7. iterate through paths
for (j = 0; j < paths.length; j++) {
// 8. drop cookie
dropCookie(cookieName, paths[j], domains[i]);
}
}
}
}
}
}
var contentTestHtml = {};
function removeContentTrackingFixture()
{
$('#contenttest').remove();
}
function setupContentTrackingFixture(name, targetNode) {
var url = 'content-fixtures/' + name + '.html'
if (!contentTestHtml[name]) {
$.ajax({
url: url,
success: function( content ) { contentTestHtml[name] = content; },
dataType: 'html',
async: false
});
}
var newNode = $('<div id="contenttest">' + contentTestHtml[name] + '</div>');
removeContentTrackingFixture();
if (targetNode) {
$(targetNode).prepend(newNode);
} else {
$('#other').append(newNode);
}
}
</script>
</head>
<body>
<div style="display:none;"><a id="firstLink" href="http://piwik.org/qa">First anchor link</a></div>
<h1 id="qunit-header">piwik.js: Unit Tests</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<div id="other" style="display:none;">
<div id="div1"></div>
<iframe name="iframe2"></iframe>
<iframe name="iframe3"></iframe>
<iframe name="iframe4"></iframe>
<iframe name="iframe5"></iframe>
<iframe name="iframe6"></iframe>
<iframe name="iframe7"></iframe>
<img id="image1" src=""/> <!-- Test require this empty source attribute before image2!! -->
<img id="image2" data-content-piece src="img.jpg"/>
<ul>
<li><a id="click1" href="javascript:_e('div1').innerHTML='<iframe src="http://click.example.com"></iframe>';void(0)" class="clicktest">ignore: implicit (JavaScript href)</a></li>
<li><a id="click2" href="http://example.org" target="iframe2" class="piwik_ignore clicktest">ignore: explicit</a></li>
<li><a id="click3" href="example.php" target="iframe3" class="clicktest">ignore: implicit (localhost)</a></li>
<li><a id="click4" href="http://example.net" target="iframe4" class="clicktest">outlink: implicit (outbound URL)</a></li>
<li><a id="click5" href="example.html" target="iframe5" class="piwik_link clicktest">outlink: explicit (localhost)</a></li>
<li><a id="click6" href="example.pdf" target="iframe6" class="clicktest">download: implicit (file extension)</a></li>
<li><a id="click7" href="example.word" target="iframe7" class="piwik_download clicktest">download: explicit</a></li>
<li><a id="click8" href="example.exe" target="iframe8" class="clicktest">no click handler</a></li>
</ul>
<div id="clickDiv"></div>
</div>
<map name="map">
<area id="area1" shape="rect" coords="0,0,10,10" href="img.jpg" alt="Piwik">
<area shape="circle" coords="10,10,10,20" href="img2.jpg" alt="Piwik2">
</map>
<ol id="qunit-tests"></ol>
<div id="main" style="display:none;"></div>
<script>
if (isIE()) {
(function () {
// otherwise because of position:absolute some nodes will be visible but should not... it will show scroll bars in IE
function fixWidthNode(tagName){
var node = document.getElementsByTagName(tagName)[0];
node.className = node.className + ' hideY ie';
}
fixWidthNode('html');
fixWidthNode('body');
})();
}
var hasLoaded = false;
function PiwikTest() {
hasLoaded = true;
module('externals');
test("JSLint", function() {
expect(1);
var src = '<?php
$src = file_get_contents('../../js/piwik.js');
$src = strtr($src, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
echo "$src"; ?>';
var result = JSLINT(src);
ok( result, "JSLint" );
// alert(JSLINT.report(true));
});
test("JSON", function() {
expect(49);
var tracker = Piwik.getTracker(), dummy;
equal( typeof JSON2.stringify, 'function', 'JSON.stringify function' );
equal( typeof JSON2.stringify(dummy), 'undefined', 'undefined' );
equal( JSON2.stringify(null), 'null', 'null' );
equal( JSON2.stringify(true), 'true', 'true' );
equal( JSON2.stringify(false), 'false', 'false' );
ok( JSON2.stringify(0) === '0', 'Number 0' );
ok( JSON2.stringify(1) === '1', 'Number 1' );
ok( JSON2.stringify(-1) === '-1', 'Number -1' );
ok( JSON2.stringify(42) === '42', 'Number 42' );
ok( JSON2.stringify(1.0) === '1.0'
|| JSON2.stringify(1.0) === '1', 'float 1.0' );
equal( JSON2.stringify(1.1), '1.1', 'float 1.1' );
equal( JSON2.stringify(""), '""', 'empty string' );
equal( JSON2.stringify('"'), '"' + '\\' + '"' + '"', 'string "' );
equal( JSON2.stringify('\\'), '"' + '\\\\' + '"', 'string \\' );
equal( JSON2.stringify("1"), '"1"', 'string "1"' );
equal( JSON2.stringify("ABC"), '"ABC"', 'string ABC' );
equal( JSON2.stringify("\x40\x41\x42\x43"), '"@ABC"', '\\x hex string @ABC' );
ok( JSON2.stringify("\u60a8\u597d") == '"您好"'
|| JSON2.stringify("\u60a8\u597d") == '"\\u60a8\\u597d"', '\\u Unicode string 您好' );
ok( JSON2.stringify("ßéàêö您好") == '"ßéàêö您好"'
|| JSON2.stringify("ßéàêö您好") == '"\\u00df\\u00e9\\u00e0\\u00ea\\u00f6\\u60a8\\u597d"', 'string non-ASCII text' );
equal( JSON2.stringify("20060228T08:00:00"), '"20060228T08:00:00"', 'string "20060228T08:00:00"' );
var d = new Date();
d.setTime(1240013340000);
ok( JSON2.stringify(d) === '"2009-04-18T00:09:00Z"'
|| JSON2.stringify(d) === '"2009-04-18T00:09:00.000Z"', 'Date');
equal( JSON2.stringify([1, 2, 3]), '[1,2,3]', 'Array of numbers' );
equal( JSON2.stringify({'key' : 'value'}), '{"key":"value"}', 'Object (members)' );
equal( JSON2.stringify(
[ {'domains' : ['example.com', 'example.ca']},
{'names' : ['Sean', 'Cathy'] } ]
), '[{"domains":["example.com","example.ca"]},{"names":["Sean","Cathy"]}]', 'Nested members' );
equal( typeof eval('('+dummy+')'), 'undefined', 'eval undefined' );
equal( typeof JSON2.parse, 'function', 'JSON.parse function' );
// these throw a SyntaxError
// equal( typeof JSON2.parse('undefined'), 'undefined', 'undefined' );
// equal( typeof JSON2.parse(dummy), 'undefined', 'undefined' );
// equal( JSON2.parse('undefined'), dummy, 'undefined' );
// equal( JSON2.parse('undefined'), undefined, 'undefined' );
strictEqual( JSON2.parse('null'), null, 'null' );
strictEqual( JSON2.parse('true'), true, 'true' );
strictEqual( JSON2.parse('false'), false, 'false' );
equal( JSON2.parse('0'), 0, 'Number 0' );
equal( JSON2.parse('1'), 1, 'Number 1' );
equal( JSON2.parse('-1'), -1, 'Number -1' );
equal( JSON2.parse('42'), 42, 'Number 42' );
ok( JSON2.parse('1.0') === 1.0
|| JSON2.parse('1.0') === 1, 'float 1.0' );
equal( JSON2.parse('1.1'), 1.1, 'float 1.1' );
equal( JSON2.parse('""'), "", 'empty string' );
equal( JSON2.parse('"' + '\\' + '"' + '"'), '"', 'string "' );
equal( JSON2.parse('"\\\\"'), '\\', 'string \\' );
equal( JSON2.parse('"1"'), "1", 'string "1"' );
equal( JSON2.parse('"ABC"'), "ABC", 'string ABC' );
equal( JSON2.parse('"@ABC"'), "\x40\x41\x42\x43", 'Hex string @ABC' );
ok( JSON2.parse('"您好"') == "\u60a8\u597d"
&& JSON2.parse('"\\u60a8\\u597d"') == "您好", 'Unicode string 您好' );
ok( JSON2.parse('"ßéàêö您好"') == "ßéàêö您好"
&& JSON2.parse('"\\u00df\\u00e9\\u00e0\\u00ea\\u00f6\\u60a8\\u597d"') == "ßéàêö您好", 'string non-ASCII text' );
equal( JSON2.parse('"20060228T08:00:00"'), "20060228T08:00:00", 'string "20060228T08:00:00"' );
// these aren't converted back to Date objects
equal( JSON2.parse('"2009-04-18T00:09:00Z"'), "2009-04-18T00:09:00Z", 'string "2009-04-18T00:09:00Z"' );
equal( JSON2.parse('"2009-04-18T00:09:00.000Z"'), "2009-04-18T00:09:00.000Z", 'string "2009-04-18T00:09:00.000Z"' );
deepEqual( JSON2.parse('[1,2,3]'), [1, 2, 3], 'Array of numbers' );
deepEqual( JSON2.parse('{"key":"value"}'), {'key' : 'value'}, 'Object (members)' );
deepEqual( JSON2.parse('[{"domains":["example.com","example.ca"]},{"names":["Sean","Cathy"]}]'),
[ {'domains' : ['example.com', 'example.ca']}, {'names' : ['Sean', 'Cathy'] } ], 'Nested members' );
});
module("core", {
setup: function () {
Piwik.getTracker().clearTrackedContentImpressions();
},
teardown: function () {
$('#other #content').remove();
}
});
test("Query", function() {
var tracker = Piwik.getTracker();
var query = tracker.getQuery();
var actual;
actual = query.hasNodeCssClass();
strictEqual(actual, false, "hasNodeCssClass, no element set");
actual = query.hasNodeCssClass(_e('clickDiv'));
strictEqual(actual, false, "hasNodeCssClass, no classname set");
actual = query.hasNodeCssClass(_e('clickDiv'), 'anyClass');
strictEqual(actual, false, "hasNodeCssClass, element has no class at all");
actual = query.hasNodeCssClass(_e('click3'), 'anyClass');
strictEqual(actual, false, "hasNodeCssClass, element has one classes and it does not match");
actual = query.hasNodeCssClass(_e('click3'), 'clicktest');
strictEqual(actual, true, "hasNodeCssClass, element has one classes and it matches");
actual = query.hasNodeCssClass(_e('click7'), 'anyClass');
strictEqual(actual, false, "hasNodeCssClass, element has many classes but not this one");
actual = query.hasNodeCssClass(_e('click7'), 'piwik_download');
strictEqual(actual, true, "hasNodeCssClass, element has many classes and it matches");
actual = query.findNodesHavingCssClass();
propEqual(actual, [], "findNodesHavingCssClass, no node set");
actual = query.findNodesHavingCssClass(document.body);
propEqual(actual, [], "findNodesHavingCssClass, no classname set");
actual = query.findNodesHavingCssClass(document.body, 'piwik_ignore');
propEqual(actual, [_e('click2')], "findNodesHavingCssClass, find matching within body");
actual = query.findNodesHavingCssClass(_e('other'), 'piwik_ignore');
propEqual(actual, [_e('click2')], "findNodesHavingCssClass, ffind matching within div");
actual = query.findNodesHavingCssClass(_e('other'), 'piwik_download');
propEqual(actual, [_e('click7')], "findNodesHavingCssClass, find matching within div different class");
actual = query.findNodesHavingCssClass(_e('other'), 'clicktest');
propEqual(actual, [_e('click1'), _e('click2'), _e('click3'), _e('click4'), _e('click5'), _e('click6'), _e('click7'), _e('click8')], "findNodesHavingCssClass, find many matching within div");
actual = query.findNodesHavingCssClass(_e('click7'), 'piwik_download');
propEqual(actual, [], "findNodesHavingCssClass, should not find if passed node has class itself");
actual = query.findNodesHavingCssClass(_e('clickDiv'), 'clicktest');
if (_e('clickDiv').children) {
ok(_e('clickDiv').children.length === 0, "clickDiv should not have any children");
}
propEqual(actual, [], "findNodesHavingCssClass, should not find anything");
actual = query.findFirstNodeHavingClass();
strictEqual(actual, undefined, "findFirstNodeHavingClass, no node set");
actual = query.findFirstNodeHavingClass(document.body);
strictEqual(actual, undefined, "findFirstNodeHavingClass, no classname set");
actual = query.findFirstNodeHavingClass(document.body, 'notExistingClass');
strictEqual(actual, undefined, "findFirstNodeHavingClass, no such classname exists");
actual = query.findFirstNodeHavingClass(document.body, 'piwik_ignore');
strictEqual(actual, _e('click2'), "findFirstNodeHavingClass, find matching within body");
actual = query.findFirstNodeHavingClass(_e('other'), 'clicktest');
strictEqual(actual, _e('click1'), "findFirstNodeHavingClass, find matching within node");
actual = query.findFirstNodeHavingClass(_e('click1'), 'clicktest');
strictEqual(actual, _e('click1'), "findFirstNodeHavingClass, passed node has class itself");
actual = query.hasNodeAttribute();
strictEqual(actual, false, "hasNodeAttribute, no element set");
actual = query.hasNodeAttribute(_e('clickDiv'));
strictEqual(actual, false, "hasNodeAttribute, no attribute set");
actual = query.hasNodeAttribute(document.body, 'anyAttribute');
strictEqual(actual, false, "hasNodeAttribute, element has no attribute at all");
actual = query.hasNodeAttribute(_e('click2'), 'anyAttribute');
strictEqual(actual, false, "hasNodeAttribute, element has attributes and it does not match");
actual = query.hasNodeAttribute(_e('click2'), 'href');
strictEqual(actual, true, "hasNodeAttribute, element has attributes and it does match");
actual = query.hasNodeAttribute(_e('image1'), 'src');
strictEqual(actual, true, "hasNodeAttribute, element has attributes and it does match other attribute");
actual = query.hasNodeAttribute(_e('image2'), 'data-content-piece');
strictEqual(actual, true, "hasNodeAttribute, element has attribute and no value");
actual = query.hasNodeAttributeWithValue();
strictEqual(actual, false, "hasNodeAttributeWithValue, no element set");
actual = query.hasNodeAttributeWithValue(_e('clickDiv'));
strictEqual(actual, false, "hasNodeAttributeWithValue, no attribute set");
actual = query.hasNodeAttributeWithValue(document.body, 'anyAttribute');
strictEqual(actual, false, "hasNodeAttributeWithValue, element has no attribute at all");
actual = query.hasNodeAttributeWithValue(_e('click2'), 'anyAttribute');
strictEqual(actual, false, "hasNodeAttributeWithValue, element has attributes but not this one");
actual = query.hasNodeAttributeWithValue(_e('click2'), 'href');
strictEqual(actual, true, "hasNodeAttributeWithValue, element has attribute and value");
actual = query.hasNodeAttributeWithValue(_e('image1'), 'src');
strictEqual(actual, false, "hasNodeAttributeWithValue, element has attribute but no value");
actual = query.hasNodeAttributeWithValue(_e('image2'), 'data-content-piece');
strictEqual(actual, false, "hasNodeAttributeWithValue, element has attribute but no value");
actual = query.getAttributeValueFromNode();
strictEqual(actual, undefined, "getAttributeValueFromNode, no element set");
actual = query.getAttributeValueFromNode(_e('clickDiv'));
strictEqual(actual, undefined, "getAttributeValueFromNode, no attribute set");
actual = query.getAttributeValueFromNode(document.body, 'anyAttribute');
strictEqual(actual, undefined, "getAttributeValueFromNode, element has no attribute at all");
actual = query.getAttributeValueFromNode(_e('click2'), 'anyAttribute');
strictEqual(actual, undefined, "getAttributeValueFromNode, element has attributes but not this one");
actual = query.getAttributeValueFromNode(_e('click2'), 'href');
strictEqual(actual, 'http://example.org', "getAttributeValueFromNode, element has attribute and value");
actual = query.getAttributeValueFromNode(_e('image1'), 'src');
strictEqual(actual, '', "getAttributeValueFromNode, element has attribute but no value");
actual = query.getAttributeValueFromNode(_e('image2'), 'data-content-piece');
strictEqual(actual, '', "getAttributeValueFromNode, element has attribute but no value");
actual = query.getAttributeValueFromNode(_e('click2'), 'class');
strictEqual(actual, 'piwik_ignore clicktest', "getAttributeValueFromNode, element has attribute class and value");
actual = query.findNodesHavingAttribute();
propEqual(actual, [], "findNodesHavingAttribute, no node set");
actual = query.findNodesHavingAttribute(document.body);
propEqual(actual, [], "findNodesHavingAttribute, no attribute set");
actual = query.findNodesHavingAttribute(document.body, 'anyAttribute');
propEqual(actual, [], "findNodesHavingAttribute, should not find any such attribute within body");
actual = query.findNodesHavingAttribute(document.body, 'style');
strictEqual(actual.length, 3, "findNodesHavingAttribute, should find a few");
actual = query.findNodesHavingAttribute(_e('click1'), 'href');
propEqual(actual, [], "findNodesHavingAttribute, should not find itself if the passed element has the attribute");
actual = query.findNodesHavingAttribute(_e('clickDiv'), 'id');
if (_e('clickDiv').children) {
ok(_e('clickDiv').children.length === 0, "clickDiv should not have any children");
}
propEqual(actual, [], "findNodesHavingAttribute, this element does not have children");
actual = query.findNodesHavingAttribute(document.body, 'href');
ok(actual.length > 11, "findNodesHavingAttribute, should find many elements within body");
actual = query.findNodesHavingAttribute(_e('other'), 'href');
propEqual(actual, [_e('click1'), _e('click2'), _e('click3'), _e('click4'), _e('click5'), _e('click6'), _e('click7'), _e('click8')], "findNodesHavingAttribute, should find many elements within node");
actual = query.findNodesHavingAttribute(_e('other'), 'anyAttribute');
propEqual(actual, [], "findNodesHavingAttribute, should not find any such attribute within div");
// TODO it is a bit confusing that findNodesHavingAttribute/CssClass does not include the passed node in the search but findFirstNodeHavingAttribute/CssClass does
actual = query.findFirstNodeHavingAttribute();
strictEqual(actual, undefined, "findFirstNodeHavingAttribute, no node set");
actual = query.findFirstNodeHavingAttribute(document.body);
strictEqual(actual, undefined, "findFirstNodeHavingAttribute, no attribute set");
actual = query.findFirstNodeHavingAttribute(document.body, 'anyAttribute');
strictEqual(actual, undefined, "findFirstNodeHavingAttribute, should not find any such attribute within body");
actual = query.findFirstNodeHavingAttribute(_e('click1'), 'href');
strictEqual(actual, _e('click1'), "findFirstNodeHavingAttribute, element has the attribute itself and not a children");
actual = query.findFirstNodeHavingAttribute(_e('clickDiv'), 'anyAttribute');
strictEqual(actual, undefined, "findFirstNodeHavingAttribute, this element does not have children");
actual = query.findFirstNodeHavingAttribute(document.body, 'href');
strictEqual(actual, _e('firstLink'), "findFirstNodeHavingAttribute, should find first link within body");
actual = query.findFirstNodeHavingAttribute(_e('other'), 'href');
strictEqual(actual, _e('click1'), "findFirstNodeHavingAttribute, should find fist link within node");
actual = query.findFirstNodeHavingAttributeWithValue();
strictEqual(actual, undefined, "findFirstNodeHavingAttributeWithValue, no node set");
actual = query.findFirstNodeHavingAttributeWithValue(document.body);
strictEqual(actual, undefined, "findFirstNodeHavingAttributeWithValue, no attribute set");
actual = query.findFirstNodeHavingAttributeWithValue(document.body, 'anyAttribute');
strictEqual(actual, undefined, "findFirstNodeHavingAttributeWithValue, should not find any such attribute within body");
actual = query.findFirstNodeHavingAttributeWithValue(_e('click2'), 'href');
strictEqual(actual, _e('click2'), "findFirstNodeHavingAttributeWithValue, element has the attribute itself and not a children");
actual = query.findFirstNodeHavingAttributeWithValue(_e('clickDiv'), 'anyAttribute');
strictEqual(actual, undefined, "findFirstNodeHavingAttributeWithValue, this element does not have children");
actual = query.findFirstNodeHavingAttributeWithValue(document.body, 'href');
strictEqual(actual, _e('firstLink'), "findFirstNodeHavingAttributeWithValue, should find first link within body");
actual = query.findFirstNodeHavingAttributeWithValue(document.body, 'src');
strictEqual(actual, _e('image2'), "findFirstNodeHavingAttributeWithValue, should not return first image which has empty src attribute");
actual = query.htmlCollectionToArray();
propEqual(actual, [], "htmlCollectionToArray, should always return an array even if nothing given");
actual = query.htmlCollectionToArray(5);
propEqual(actual, [], "htmlCollectionToArray, should always return an array even if interger given"); // would still parse string to an array but we can live with that
var htmlCollection = document.getElementsByTagName('a');
actual = query.htmlCollectionToArray(htmlCollection);
ok($.isArray(actual), 'htmlCollectionToArray, should convert to array');
ok(actual.length === htmlCollection.length, 'htmlCollectionToArray should have same amount of elements as before');
ok(actual.length > 10, 'htmlCollectionToArray, just make sure there are many a elements found. otherwise test is useless');
ok(-1 !== indexOfArray(actual, _e('click1')), 'htmlCollectionToArray, random check to make sure it contains a link');
actual = query.isLinkElement();
strictEqual(actual, false, "isLinkElement, no element set");
actual = query.isLinkElement(_e('div1'));
strictEqual(actual, false, "isLinkElement, a div is not a link element");
actual = query.isLinkElement(document.createTextNode('ff'));
strictEqual(actual, false, "isLinkElement, a text node is not a link element");
actual = query.isLinkElement(document.createComment('tt'));
strictEqual(actual, false, "isLinkElement, a comment is not a link element");
actual = query.isLinkElement(_e('area1'));
strictEqual(actual, true, "isLinkElement, an area element is a link element");
actual = query.isLinkElement(_e('click1'));
strictEqual(actual, true, "isLinkElement, an a element is a link element");
actual = query.find();
propEqual(actual, [], "find, no selector passed should return an empty array");
actual = query.find('[data-content-piece]');
propEqual(actual, [_e('image2')], "find, should find elements by attribute");
actual = query.find('.piwik_link');
propEqual(actual, [_e('click5')], "find, should find elements by class");
actual = query.find('#image1');
propEqual(actual, [_e('image1')], "find, should find elements by id");
actual = query.find('[href]');
ok(actual.length > 10, "find, should find many elements by attribute");
ok(-1 !== indexOfArray(actual, _e('click1')), 'find, random check to make sure it contains a link');
actual = query.find('.clicktest');
ok(actual.length === 8, "find, should find many elements by class");
ok(-1 !== indexOfArray(actual, _e('click1')), 'find, random check to make sure it contains a link');
actual = query.findMultiple();
propEqual(actual, [], "findMultiple, no selectors passed should return an empty array");
actual = query.findMultiple([]);
propEqual(actual, [], "findMultiple, empty selectors passed should return an empty array");
actual = query.findMultiple(['.piwik_link']);
propEqual(actual, [_e('click5')], "findMultiple, only one selector passed");
actual = query.findMultiple(['.piwik_link', '[data-content-piece]']);
propEqual(actual, [_e('image2'), _e('click5')], "findMultiple, two selectors passed");
actual = query.findMultiple(['.piwik_link', '[data-content-piece]', '#image2', '#div1']);
propEqual(actual, [_e('div1'), _e('image2'), _e('click5')], "findMultiple, should make nodes unique in case we select the same multiple times");
actual = query.findNodesByTagName();
propEqual(actual, [], "findNodesByTagName, no element and no tag name set");
actual = query.findNodesByTagName(document.body);
propEqual(actual, [], "findNodesByTagName, no tag name set");
actual = query.findNodesByTagName(document.body, 'notExistingOne');
propEqual(actual, [], "findNodesByTagName, should not find any such element");
actual = query.findNodesByTagName(document.body, 'a');
ok($.isArray(actual), "findNodesByTagName, should always return an array");
actual = query.findNodesByTagName(document.body, 'h1');
propEqual(actual, [_e('qunit-header')], "findNodesByTagName, find exactly one");
actual = query.findNodesByTagName(document.body, 'a');
ok(actual.length > 10, "findNodesByTagName, find many, even nested ones");
ok(indexOfArray(actual, _e('click1')), "findNodesByTagName, just a random test to make sure it actually contains a link");
});
test("contentFindContentBlock", function() {
var tracker = Piwik.getTracker();
var content = tracker.getContent();
var actual, expected;
actual = content.findContentNodes();
propEqual(actual, [], "findContentNodes, should not find any content node when there is none");
actual = content.findContentNodesWithinNode();
propEqual(actual, [], "findContentNodesWithinNode, should not find any content node when no node passed");
actual = content.findContentNodesWithinNode(_e('other'));
ok(_e('other'), "if we do not get an element here test is not useful");
propEqual(actual, [], "findContentNodesWithinNode, should not find any content node when there is none");
actual = content.findParentContentNode(_e('click1'));
ok(_e('click1'), "if we do not get an element here test is not useful");
strictEqual(actual, undefined, "findParentContentNode, should not find any content node when there is none");
setupContentTrackingFixture('findContentBlockTest');
var isOneWithClass = _s('#isOneWithClass');
var isOneWithAttr = _s('#isOneWithAttribute');
var isHrefUrl = _s('[href="http://www.example.com"]');
var containsOneWithAttr = _s('#containsOneWithAttribute [data-track-content]');
expected = [containsOneWithAttr, isOneWithAttr, isHrefUrl, isOneWithClass];
actual = content.findContentNodes();
propEqual(actual, expected, "findContentNodes, should find all content blocks within the DOM");
actual = content.findContentNodesWithinNode(_s(''));
propEqual(actual, expected, "findContentNodesWithinNode, should find all content blocks within the DOM");
actual = content.findContentNodesWithinNode(_s('#containsOneWithAttribute'));
propEqual(actual, [containsOneWithAttr], "findContentNodesWithinNode, should find content blocks within a node");
actual = content.findContentNodesWithinNode(isOneWithClass);
propEqual(actual, [isOneWithClass], "findContentNodesWithinNode, should find one content block in the node itself");
actual = content.findParentContentNode(_s('#isOneWithClass'));
strictEqual(actual, isOneWithClass, "findParentContentNode, should find itself in case the passed node is a content block with class");
actual = content.findParentContentNode(_s('#isOneWithAttribute'));
strictEqual(actual, isOneWithAttr, "findParentContentNode, should find itself in case the passed node is a content block with attribute");
actual = content.findParentContentNode(_s('#innerNode'));
strictEqual(actual, isHrefUrl, "findParentContentNode, should find parent content block");
});
test("contentFindContentNodes", function() {
function ex(testNumber) { // select node within content test scope
$nodes = $('#contenttest #ex' + testNumber);
if ($nodes.length) {
return $nodes[0];
} else {
ok(false, 'selector was not found but should be "#contenttest #ex' + selector + '"')
}
}
var tracker = Piwik.getTracker();
var content = tracker.getContent();
var actual;
var unrelatedNode = _e('other');
ok(unrelatedNode, 'Make sure this element exists');
actual = content.findTargetNodeNoDefault();
strictEqual(actual, undefined, "findTargetNodeNoDefault, should not find anything if no node set");
actual = content.findTargetNode();
strictEqual(actual, undefined, "findTargetNode, should not find anything if no node set");
actual = content.findPieceNode();
strictEqual(actual, undefined, "findPieceNode, should not find anything if no node set");
setupContentTrackingFixture('findContentNodesTest');
var example1 = ex(1);
ok(example1, 'Make sure this element exists to verify setup');
ok("test fall back to content block node");
actual = content.findTargetNodeNoDefault(example1);
strictEqual(actual, undefined, "findTargetNodeNoDefault, should return nothing as no target set");
actual = content.findTargetNode(example1);
strictEqual(actual, example1, "findTargetNode, should fall back to content block node as no target set");
actual = content.findPieceNode(example1);
strictEqual(actual, example1, "findPieceNode, should not find anything if no node set");
ok("test actually detects the attributes within a content block");
actual = content.findTargetNodeNoDefault(ex(3));
ok(undefined !== $(actual).attr(content.CONTENT_TARGET_ATTR), "findTargetNodeNoDefault, should have the attribute");
strictEqual(actual, ex('3 a'), "findTargetNodeNoDefault, should find actual target node via attribute");
actual = content.findTargetNode(ex(3));
ok(undefined !== $(actual).attr(content.CONTENT_TARGET_ATTR), "findTargetNode, should have the attribute");
strictEqual(actual, ex('3 a'), "findTargetNode, should find actual target node via attribute");
actual = content.findPieceNode(ex(3));
ok(undefined !== $(actual).attr(content.CONTENT_PIECE_ATTR), "findPieceNode, should have the attribute");
strictEqual(actual, ex('3 img'), "findPieceNode, should find actual target piece via attribute");
ok("test actually detects the CSS class within a content block");
actual = content.findTargetNodeNoDefault(ex(4));
ok($(actual).hasClass(content.CONTENT_TARGET_CLASS), "findTargetNodeNoDefault, should have the CSS class");
strictEqual(actual, ex('4 a'), "findTargetNodeNoDefault, should find actual target node via class");
actual = content.findTargetNode(ex(4));
ok($(actual).hasClass(content.CONTENT_TARGET_CLASS), "findTargetNode, should have the CSS class");
strictEqual(actual, ex('4 a'), "findTargetNode, should find actual target node via class");
actual = content.findPieceNode(ex(4));
ok($(actual).hasClass(content.CONTENT_PIECE_CLASS), "findPieceNode, should have the CSS class");
strictEqual(actual, ex('4 img'), "findPieceNode, should find actual target piece via class");
ok("test actually attributes takes precendence over class");
actual = content.findTargetNodeNoDefault(ex(5));
ok(undefined !== $(actual).attr(content.CONTENT_TARGET_ATTR), "findTargetNodeNoDefault, should have the attribute");
strictEqual(actual.textContent, 'Target with attribute', "findTargetNodeNoDefault, should igonre node with class and pick attribute node");
actual = content.findTargetNode(ex(5));
ok(undefined !== $(actual).attr(content.CONTENT_TARGET_ATTR), "findTargetNode, should have the attribute");
strictEqual(actual.textContent, 'Target with attribute', "findTargetNode, should igonre node with class and pick attribute node");
actual = content.findPieceNode(ex(5));
ok(undefined !== $(actual).attr(content.CONTENT_PIECE_ATTR), "findPieceNode, should have the attribute");
strictEqual(actual.textContent, 'Piece with attribute', "findPieceNode, should igonre node with class and pick attribute node");
ok("make sure it picks always the first one with multiple nodes have same class or same attribute");
actual = content.findTargetNode(ex(6));
ok($(actual).hasClass(content.CONTENT_TARGET_CLASS), "findTargetNode, should have the CSS class");
strictEqual(actual.textContent, 'Target with class1', "findTargetNode, should igonre node with class and pick attribute node");
actual = content.findPieceNode(ex(6));
ok($(actual).hasClass(content.CONTENT_PIECE_CLASS), "findPieceNode, should have the CSS class");
strictEqual(actual.textContent, 'Piece with class1', "findPieceNode, should igonre node with class and pick attribute node");
actual = content.findTargetNode(ex(7));
ok(undefined !== $(actual).attr(content.CONTENT_TARGET_ATTR), "findTargetNode, should have the attribute");
strictEqual(actual.textContent, 'Target with attribute1', "findTargetNode, should igonre node with class and pick attribute node");
actual = content.findPieceNode(ex(7));
ok(undefined !== $(actual).attr(content.CONTENT_PIECE_ATTR), "findPieceNode, should have the attribute");
strictEqual(actual.textContent, 'Piece with attribute1', "findPieceNode, should igonre node with class and pick attribute node");
});
test("contentUtilities", function() {
var tracker = Piwik.getTracker();
var content = tracker.getContent();
var query = tracker.getQuery();
content.setLocation(); // clear possible previous location
var actual, expected;
function assertTrimmed(value, expected, message)
{
strictEqual(content.trim(value), expected, message);
}
function assertRemoveDomainKeepsValueUntouched(value, message)
{
strictEqual(content.removeDomainIfIsInLink(value), value, message);
}
function assertIsSameDomain(url, message)
{
strictEqual(content.isSameDomain(url), true, message);
}
function assertIsNotSameDomain(url, message)
{
strictEqual(content.isSameDomain(url), false, 'isSameDomain, ' + message);
}
function assertDomainWillBeRemoved(url, expected, message)
{
strictEqual(content.removeDomainIfIsInLink(url), expected, message);
}
function assertBuildsAbsoluteUrl(url, expected, message)
{
strictEqual(content.toAbsoluteUrl(url), expected, message);
}
function assertImpressionRequestParams(name, piece, target, expected, message) {
strictEqual(content.buildImpressionRequestParams(name, piece, target), expected, message);
}
function assertInteractionRequestParams(interaction, name, piece, target, expected, message) {
strictEqual(content.buildInteractionRequestParams(interaction, name, piece, target), expected, message);
}
function assertShouldIgnoreInteraction(id, message) {
var node = content.findTargetNode(_e(id));
strictEqual(content.shouldIgnoreInteraction(node), true, message);
ok($(node).hasClass(content.CONTENT_IGNOREINTERACTION_CLASS) || undefined !== $(node).attr(content.CONTENT_IGNOREINTERACTION_ATTR), "needs to have either attribute or class");
}
function assertShouldNotIgnoreInteraction(id, message) {
var node = content.findTargetNode(_e(id));
strictEqual(content.shouldIgnoreInteraction(node), false, message);
}
function assertNodeAuthorizedToTriggerInteraction(contentNode, interactedNode, message) {
strictEqual(tracker.isNodeAuthorizedToTriggerInteraction(_s(contentNode), _s(interactedNode)), true, message);
}
function assertNodeNotAuthorizedToTriggerInteraction(contentNode, interactedNode, message) {
strictEqual(tracker.isNodeAuthorizedToTriggerInteraction(_s(contentNode), _s(interactedNode)), false, message);
}
function assertFoundMediaUrl(id, expected, message) {
var node = content.findPieceNode(_e(id));
strictEqual(content.findMediaUrlInNode(node), expected, message);
}
function assertIsUrlToCurrentDomain(url, message) {
strictEqual(content.isUrlToCurrentDomain(url), true, message);
}
function assertNotUrlToCurrentDomain(url, message) {
strictEqual(content.isUrlToCurrentDomain(url), false, message);
}
var locationAlias = $.extend({}, window.location);
var origin = getOrigin();
var host = locationAlias.host;
ok("test trim(text)");
strictEqual(undefined, content.trim(), 'should not fail if nothing set / is undefined');
assertTrimmed(null, null, 'should not trim if null');
assertTrimmed(5, 5, 'should not trim a number');
assertTrimmed('', '', 'should not change an empty string');
assertTrimmed(' ', '', 'should remove all whitespace');
assertTrimmed(' xxxx', 'xxxx', 'should remove left whitespace');
assertTrimmed(' xxxx ', 'xxxx', 'should remove left and right whitespace');
assertTrimmed(" \t xxxx \t", 'xxxx', 'should remove tabs and whitespace');
assertTrimmed(' xx xx ', 'xx xx', 'should keep whitespace between text untouched');
ok("test isSameDomain(url)");
assertIsNotSameDomain(undefined, 'no url given');
assertIsNotSameDomain(5, 'a number, not a url');
assertIsNotSameDomain('foo bar', 'not a url');
assertIsNotSameDomain('http://example.com', 'not same domain');
assertIsNotSameDomain('https://www.example.com', 'not same domain and different protocol');
assertIsNotSameDomain('http://www.example.com:8080', 'not same domain and different port');
assertIsNotSameDomain('http://www.example.com/path/img.jpg', 'not same domain with path');
assertIsSameDomain(origin, 'same protocol and same domain');
assertIsSameDomain(origin + '/path/img.jpg', 'same protocol and same domain with path');
assertIsSameDomain('https://' + host + '/path/img.jpg', 'different protocol is still same domain');
assertIsSameDomain('http://' + host + ':8080/path/img.jpg', 'different port is still same domain');
ok("test removeDomainIfIsInLink(url)");
strictEqual(content.removeDomainIfIsInLink(), undefined, 'should not fail if nothing set / is undefined');
assertRemoveDomainKeepsValueUntouched(null, 'should keep null untouched');
assertRemoveDomainKeepsValueUntouched(5, 'should keep number untouched');
assertRemoveDomainKeepsValueUntouched('', 'should keep empty string untouched');
assertRemoveDomainKeepsValueUntouched('Any Text', 'should keep string untouched that is not a url');
assertRemoveDomainKeepsValueUntouched('/path/img.jpg', 'should keep string untouched that looks like a path');
assertRemoveDomainKeepsValueUntouched('ftp://path/img.jpg', 'should keep string untouched that looks like a path');
assertRemoveDomainKeepsValueUntouched('http://www.example.com', 'should keep string untouched as it is different domain');
assertRemoveDomainKeepsValueUntouched('http://www.example.com/', 'should keep string untouched as it is different domain');
assertRemoveDomainKeepsValueUntouched('https://www.example.com/', 'should keep string untouched as it is different domain');
assertRemoveDomainKeepsValueUntouched('http://www.example.com/path/img.jpg', 'should keep string untouched as it is different domain, this time with path');
assertRemoveDomainKeepsValueUntouched('http://www.example.com:8080/path/img.jpg', 'should keep string untouched as it is different domain, this time with port');
assertDomainWillBeRemoved(origin + '/path/img.jpg?x=y', '/path/img.jpg?x=y', 'should trim http domain with path that is the same as the current');
assertDomainWillBeRemoved('https://' + host + '/path/img.jpg?x=y', '/path/img.jpg?x=y', 'should trim https domain with path that is the same as the current');
assertDomainWillBeRemoved(origin, '/', 'should trim http domain without path that is the same as the current');
assertDomainWillBeRemoved('https://' + host, '/', 'should trim https domain without path that is the same as the current');
assertDomainWillBeRemoved('https://' + host + ':8080', '/', 'should trim https domain with port that is the same as the current');
ok("test isUrlToCurrentDomain(url)");
strictEqual(content.removeDomainIfIsInLink(), undefined, 'should not fail if nothing set / is undefined');
assertNotUrlToCurrentDomain(null, ' null is not a urls');
assertNotUrlToCurrentDomain(5, '5 is not a url');
assertIsUrlToCurrentDomain('', 'empty string is same as current url so same domain');
assertIsUrlToCurrentDomain('Any Text', 'relative url, same domain');
assertIsUrlToCurrentDomain('/path/img.jpg', 'absolute url same domain');
assertNotUrlToCurrentDomain('ftp://path/img.jpg', 'different protocol');
assertNotUrlToCurrentDomain('http://www.example.com', 'different domain');
assertNotUrlToCurrentDomain('http://www.example.com/', 'different domain with root path');
assertNotUrlToCurrentDomain('https://www.example.com/', 'different domain and protocol');
assertNotUrlToCurrentDomain('http://www.example.com/path/img.jpg', 'different domain, this time with path');
assertNotUrlToCurrentDomain('http://www.example.com:8080/path/img.jpg', 'different domain, this time with port');
assertIsUrlToCurrentDomain(origin + '/path/img.jpg?x=y', 'same domain with path');
assertIsUrlToCurrentDomain(origin + '?x=y', 'same domain with question mark');
assertNotUrlToCurrentDomain('https://' + host + '/path/img.jpg?x=y', 'different protocol and path is different url');
assertIsUrlToCurrentDomain(origin, '/', 'same domain with root path');
assertNotUrlToCurrentDomain('https://' + host, 'same domain but different protocol');
assertNotUrlToCurrentDomain('https://' + host + ':5959', 'different protocol and port');
assertNotUrlToCurrentDomain('http://' + host + ':5959', 'different protocol and port');
ok("test toAbsoluteUrl(url) we need a lot of tests for this method as this will generate the redirect url");
strictEqual(undefined, content.toAbsoluteUrl(), 'should not fail if nothing set / is undefined');
assertBuildsAbsoluteUrl(null, null, 'null should be untouched');
assertBuildsAbsoluteUrl(5, 5, 'number should be untouched');
assertBuildsAbsoluteUrl('', locationAlias.href, 'an empty string should generate the same URL as it is currently');
assertBuildsAbsoluteUrl('/', origin + '/', 'root path');
assertBuildsAbsoluteUrl('/test', origin + '/test', 'absolute url');
assertBuildsAbsoluteUrl('/test/', origin + '/test/', 'absolute url');
assertBuildsAbsoluteUrl('?x=5', toAbsoluteUrl('?x=5'), 'absolute url');
assertBuildsAbsoluteUrl('path', toAbsoluteUrl('path'), 'relative path');
assertBuildsAbsoluteUrl('path/x?p=5', toAbsoluteUrl('path/x?p=5'), 'relative path');
assertBuildsAbsoluteUrl('#test', toAbsoluteUrl('#test'), 'anchor url');
assertBuildsAbsoluteUrl('//' + locationAlias.host + '/test/img.jpg', origin + '/test/img.jpg', 'inherit protocol url');
assertBuildsAbsoluteUrl('mailto:test@example.com', 'mailto:test@example.com', 'mailto pseudo-protocol url');
assertBuildsAbsoluteUrl('javascript:void 0', 'javascript:void 0', 'javascript pseudo-protocol url');
assertBuildsAbsoluteUrl('tel:0123456789', 'tel:0123456789', 'tel pseudo-protocol url');
assertBuildsAbsoluteUrl('anythinggggggggg:test', toAbsoluteUrl('anythinggggggggg:test'), 'we do not treat this one as pseudo-protocol url as there are too many characters before colon');
assertBuildsAbsoluteUrl('k1dm:test', toAbsoluteUrl('k1dm:test'), 'we do not treat this one as pseudo-protocol url as it contains a number');
locationAlias.pathname = '/test/';
content.setLocation(locationAlias);
assertBuildsAbsoluteUrl('?x=5', origin + '/test/?x=5', 'should add query param');
assertBuildsAbsoluteUrl('link2', origin + '/test/link2', 'relative url in existing path');
locationAlias.pathname = '/test';
content.setLocation(locationAlias);
assertBuildsAbsoluteUrl('?x=5', origin + '/test?x=5', 'should add query param');
assertBuildsAbsoluteUrl('link2', origin + '/link2', 'relative url replaces other relative url');
ok("test buildImpressionRequestParams(name, piece, target)");
assertImpressionRequestParams('name', 'piece', 'target', 'c_n=name&c_p=piece&c_t=target', "all parameters set");
assertImpressionRequestParams('name', 'piece', null, 'c_n=name&c_p=piece', "no target set");
assertImpressionRequestParams('http://example.com.com', '/?x=1', '&target=1', 'c_n=http%3A%2F%2Fexample.com.com&c_p=%2F%3Fx%3D1&c_t=%26target%3D1', "should encode values");
ok("test buildInteractionRequestParams(interaction, name, piece, target)");
assertInteractionRequestParams(null, null, null, null, '', "nothing set");
assertInteractionRequestParams('interaction', null, null, null, 'c_i=interaction', "only interaction set");
assertInteractionRequestParams('interaction', 'name', null, null, 'c_i=interaction&c_n=name', "no piece and no target set");
assertInteractionRequestParams('interaction', 'name', 'piece', null, 'c_i=interaction&c_n=name&c_p=piece', "no target set");
assertInteractionRequestParams('interaction', 'name', 'piece', 'target', 'c_i=interaction&c_n=name&c_p=piece&c_t=target', "all parameters set");
assertInteractionRequestParams(null, 'name', 'piece', null, 'c_n=name&c_p=piece', "only name and piece set");
assertInteractionRequestParams('http://', 'http://example.com.com', '/?x=1', '&target=1', 'c_i=http%3A%2F%2F&c_n=http%3A%2F%2Fexample.com.com&c_p=%2F%3Fx%3D1&c_t=%26target%3D1', "should encode values");
setupContentTrackingFixture('contentUtilities');
ok("test shouldIgnoreInteraction(targetNode)");
assertShouldIgnoreInteraction('ignoreInteraction1', 'should be ignored because of CSS class');
assertShouldIgnoreInteraction('ignoreInteraction2', 'should be ignored because of Attribute');
assertShouldIgnoreInteraction('ignoreInteraction3', 'should be ignored because of CSS class');
assertShouldIgnoreInteraction('ignoreInteraction4', 'should be ignored because of Attribute');
assertShouldNotIgnoreInteraction('notIgnoreInteraction1', 'should not be ignored');
assertShouldNotIgnoreInteraction('notIgnoreInteraction2', 'should not be ignored as set in wrong element');
ok("test isNodeAuthorizedToTriggerInteraction(targetNode)");
strictEqual(tracker.isNodeAuthorizedToTriggerInteraction(), false, 'nothing set');
strictEqual(tracker.isNodeAuthorizedToTriggerInteraction('#ignoreInteraction2'), false, 'no interacted node set');
var notAuthIgnoreNode = '#ignoreInteraction2 a';
assertNodeNotAuthorizedToTriggerInteraction(notAuthIgnoreNode, notAuthIgnoreNode, 'node has to be ignored');
$(_s(notAuthIgnoreNode)).attr('data-content-ignoreinteraction', null);
// node no longer ignored and it should be authorized!
assertNodeAuthorizedToTriggerInteraction(notAuthIgnoreNode, notAuthIgnoreNode, 'node no longer has to be ignored');
$(_s(notAuthIgnoreNode)).attr('data-content-ignoreinteraction', ''); // reset changed attribute
assertNodeAuthorizedToTriggerInteraction('#authorized1', '#authorized1', 'interacted with target node which is content block');
assertNodeAuthorizedToTriggerInteraction('#authorized1', '#authorized1_1', 'interacted with child of target node which is content block');
assertNodeAuthorizedToTriggerInteraction('#authorized2', '#authorized2_1', 'interacted with target node');
assertNodeAuthorizedToTriggerInteraction('#authorized2', '#authorized2_2', 'interacted with children of target node');
assertNodeNotAuthorizedToTriggerInteraction('#authorized3', '#authorized3', 'interacted with content block but it is not target node');
assertNodeNotAuthorizedToTriggerInteraction('#authorized3', '#authorized3_1', 'interacted with children of content block but not children of target node');
assertNodeAuthorizedToTriggerInteraction('#authorized3', '#authorized3_2', 'interacted with target node to make sure auth3 is not ignored');
ok("test setHrefAttribute(node, url)");
var aElement = _e('aLinkToBeChanged');
content.setHrefAttribute(); // should not fail if no arguments
strictEqual(query.getAttributeValueFromNode(aElement, 'href'), 'http://www.example.com', 'setHrefAttribute, check initial link value');
content.setHrefAttribute(aElement);
content.setHrefAttribute(aElement, '');
strictEqual(query.getAttributeValueFromNode(aElement, 'href'), 'http://www.example.com', 'setHrefAttribute, an empty URL should not be set');
content.setHrefAttribute(aElement, '/test');
strictEqual(query.getAttributeValueFromNode(aElement, 'href'), '/test', 'setHrefAttribute, link should be changed now');
strictEqual(content.findMediaUrlInNode(), undefined, 'should not fail if no node passed');
ok(_e('click1') && _e('mediaDiv'), 'make sure both nodes exist otherwise following two assertions to not test what we want');
assertFoundMediaUrl('click1', undefined, 'should not find anything in a link as it is not a media');
assertFoundMediaUrl('mediaDiv', undefined, 'should not find anything in a non media element even if it defines a src attribute');
assertFoundMediaUrl('mediaImg', 'test/img.jpg', 'should find url of image');
assertFoundMediaUrl('mediaVideo', 'movie.mp4', 'should find url of video, first one should be used');
assertFoundMediaUrl('mediaAudio', 'audio.ogg', 'should find url of audio, first one should be used');
assertFoundMediaUrl('mediaEmbed', 'embed.swf', 'should find url of embed element');
assertFoundMediaUrl('mediaObjectSimple', 'objectSimple.swf', 'should find url of a simple object element');
assertFoundMediaUrl('mediaObjectParam', 'movie_param1.swf', 'should find url of a simple object element');
assertFoundMediaUrl('mediaObjectPdf', 'document.pdf', 'should find url of an object that contains non flash resources such as pdf');
assertFoundMediaUrl('mediaObjectEmbed', 'document2.pdf', 'should fallback to an embed in an object');
});
test("contentVisibleNodeTests", function() {
var tracker = Piwik.getTracker();
var content = tracker.getContent();
var actual;
function _ex(testnumber) { // select node within content test scope
return _s('#ex' + testnumber);
}
function assertContentNodeVisible(node, message)
{
scrollToTop(); // make sure content nodes are actually in view port
if (!message) {
message = '';
}
strictEqual(content.isNodeVisible(node), true, 'isNodeVisible, ' + message);
}
function assertContentNodeNotVisible(node, message)
{
scrollToTop(); // make sure content nodes are actually in view port
if (!message) {
message = '';
}
strictEqual(content.isNodeVisible(node), false, 'isNodeVisible, ' + message);
}
function assertInternalNodeVisible(node, message)
{
scrollToTop(); // make sure content nodes are actually in view port
if (!message) {
message = '';
}
strictEqual(tracker.internalIsNodeVisible(node), true, 'internalIsNodeVisible, ' + message);
}
function assertInternalNodeNotVisible(node, message)
{
scrollToTop(); // make sure content nodes are actually in view port
if (!message) {
message = '';
}
strictEqual(tracker.internalIsNodeVisible(node), false, 'internalNodeIsVisible, ' + message);
}
function assertNodeNotInViewport(node, message)
{
scrollToTop(); // make sure content nodes are actually in view port
if (!message) {
message = '';
}
strictEqual(content.isOrWasNodeInViewport(node), false, 'internalNodeNotVisible, ' + message);
}
function assertNodeIsInViewport(node, message)
{
scrollToTop(); // make sure content nodes are actually in view port
if (!message) {
message = '';
}
strictEqual(content.isOrWasNodeInViewport(node), true, 'internalIsNodeVisible, ' + message);
window.scroll(0,200); // if we scroll done it was visible
strictEqual(content.isOrWasNodeInViewport(node), true, 'internalIsNodeVisible, ' + message);
}
setupContentTrackingFixture('visibleNodes', document.body); // #contenttest is placed by default in #other but #other is not visible so all tests would return false.
ok('test internalIsNodeVisible()');
assertInternalNodeNotVisible(undefined, 'no node set, cannot be visible');
assertInternalNodeNotVisible(_e('click1'), 'parent other is hidden');
assertInternalNodeNotVisible(document.createElement('div'), 'element is not in DOM');
assertInternalNodeVisible(_ex(1), 'node exists and should be visible');
assertInternalNodeNotVisible(_ex(2), 'hidden via opacity');
assertInternalNodeNotVisible(_ex(3), 'hidden via visibility');
assertInternalNodeNotVisible(_ex(4), 'hidden via display');
assertInternalNodeVisible(_ex(5), 'width is 0 but overflow can make it visible again?!?');
assertInternalNodeVisible(_ex(6), 'height is 0 but overflow can make it visible again?!?');
assertInternalNodeNotVisible(_ex(7), 'hidden via width:0, overflow is hidden');
assertInternalNodeNotVisible(_ex(8), 'hidden via height:0, overflow is hidden');
assertInternalNodeNotVisible(_ex(13), 'parent is hidden via opacity');
assertInternalNodeNotVisible(_ex(14), 'parent is hidden via visibility');
assertInternalNodeNotVisible(_ex(15), 'parent is hidden via display');
assertInternalNodeNotVisible(_ex(16), 'parent is hidden via width:0, overflow is hidden');
assertInternalNodeNotVisible(_ex(17), 'parent is hidden via height:0, overflow is hidden');
assertNodeNotInViewport(_ex(18), 'element is not visible, ends directly at left:0px');
assertInternalNodeVisible(_ex(19), 'element is visible by one px');
assertNodeIsInViewport(_ex(19), 'element is visible by one px');
assertNodeIsInViewport(_ex(20), 'element is position absolute and partially visible top');
assertNodeIsInViewport(_ex(21), 'element is position absolute and partially visible left');
assertNodeIsInViewport(_ex(22), 'element is position absolute and partially visible right');
assertNodeIsInViewport(_ex(23), 'element is position absolute and partially visible bottom');
assertNodeNotInViewport(_ex(24), 'element is position absolute and position too far top');
assertNodeNotInViewport(_ex(25), 'element is position absolute and position too far left');
assertNodeNotInViewport(_ex(26), 'element is position absolute and position too far right');
assertNodeNotInViewport(_ex(27), 'element is position absolute and position too far bottom');
assertNodeIsInViewport(_ex(28), 'element is position fixed and partially visible top');
assertNodeIsInViewport(_ex(29), 'element is position fixed and partially visible left');
assertNodeIsInViewport(_ex(30), 'element is position fixed and partially visible right');
assertNodeIsInViewport(_ex(31), 'element is position fixed and partially visible bottom');
assertNodeNotInViewport(_ex(32), 'element is position fixed and position too far top');
assertNodeNotInViewport(_ex(33), 'element is position fixed and position too far left');
assertNodeNotInViewport(_ex(34), 'element is position fixed and position too far right');
assertNodeNotInViewport(_ex(35), 'element is position fixed and position too far bottom');
assertInternalNodeVisible(_ex(37), 'element is within overflow scroll and it is visible');
assertInternalNodeNotVisible(_ex(38), 'element is within overflow scroll but not visible');
_ex(36).scrollTop = 35;_ex(36).scrolltop = 35; // scroll within div
assertInternalNodeVisible(_ex(38), 'element is within overflow scroll but not visible');
var nodesThatShouldBeInViewPort = [1,2,3,5,6,7,8,13,14,16,17];
var index;
for (index = 1; index < nodesThatShouldBeInViewPort.length; index++) {
if (4 === index) {
continue; // display:none will not be in view port
}
var exampleId = nodesThatShouldBeInViewPort[index];
assertNodeIsInViewport(_ex(exampleId), 'example ' + exampleId + ' the nodes have to be in view port otherwise we might test something else than expected');
}
assertNodeNotInViewport(_ex(9), 'margin left position is so far left it cannot be visible');
assertNodeNotInViewport(_ex(10), 'margin left position is so far right it cannot be visible');
assertContentNodeNotVisible(undefined, 'no node set');
assertContentNodeNotVisible(_ex(3), 'element is not visible but in viewport');
assertContentNodeNotVisible(_ex(18), 'element is visible but not viewport');
assertContentNodeNotVisible(_ex(4), 'element is neither visible nor in viewport');
assertContentNodeVisible(_ex(19), 'element is visible and in viewport');
});
test("contentFindContentValues", function() {
function _st(id) {
return id && (''+id) === id ? _s('#' + id) : id;
}
function assertFoundContent(id, expectedName, expectedPiece, expectedTarget, message) {
var node = _st(id)
if (!message) {
message = 'Id: ' + id;
}
strictEqual(content.findContentTarget(node), expectedTarget, 'findContentTarget, ' + message + ', expected ' + expectedTarget);
strictEqual(content.findContentPiece(node), expectedPiece, 'findContentPiece, ' + message + ', expected ' + expectedPiece);
strictEqual(content.findContentName(node), expectedName, 'findContentName, ' + message + ', expected ' + expectedName);
}
function buildContentStruct(name, piece, target) {
return {
name: name,
piece: piece,
target: target
};
}
function assertBuiltContent(id, expectedName, expectedPiece, expectedTarget, message) {
var node = _st(id);
if (!message) {
message = 'Id: ' + id;
}
var expected = buildContentStruct(expectedName, expectedPiece, expectedTarget);
propEqual(content.buildContentBlock(node), expected, 'buildContentBlock, ' + message);
}
function assertCollectedContent(ids, expected, message) {
var nodes = [];
var index;
for (index = 0; index < ids.length; index++) {
nodes.push(_st(ids[index]));
}
if (!message) {
message = 'Id: ' + id;
}
propEqual(content.collectContent(nodes), expected, 'collectContent , ' + message);
}
var tracker = Piwik.getTracker();
var content = tracker.getContent();
content.setLocation();
var actual;
setupContentTrackingFixture('manyExamples');
var origin = getOrigin();
var host = location.host;
var path = origin + location.pathname;
assertFoundContent(undefined, undefined, undefined, undefined, 'No node set');
assertFoundContent('ex1', toAbsolutePath('img-en.jpg'), toAbsoluteUrl('img-en.jpg'), undefined);
assertFoundContent('ex2', toAbsolutePath('img-en.jpg'), toAbsoluteUrl('img-en.jpg'), undefined);
assertFoundContent('ex3', 'img.jpg', 'img.jpg', 'http://www.example.com');
assertFoundContent('ex4', toAbsolutePath('img-en.jpg'), toAbsoluteUrl('img-en.jpg'), 'http://www.example.com');
assertFoundContent('ex5', toAbsolutePath('img-en.jpg'), toAbsoluteUrl('img-en.jpg'), 'http://www.example.com');
assertFoundContent('ex6', undefined, undefined, 'http://www.example.com');
assertFoundContent('ex7', undefined, undefined, 'http://www.example.com');
assertFoundContent('ex8', 'My content', 'My content', 'http://www.example.com');
assertFoundContent('ex9', 'Image1', toAbsoluteUrl('img-en.jpg'), undefined);
assertFoundContent('ex10', 'http://www.example.com/path/img-en.jpg', 'http://www.example.com/path/img-en.jpg', undefined);
assertFoundContent('ex11', undefined, undefined, 'http://www.example.com');
assertFoundContent('ex12', 'Block Title', undefined, 'http://www.example.com');
assertFoundContent('ex13', undefined, undefined, 'http://manual.example.com');
assertFoundContent('ex14', undefined, undefined, undefined);
assertFoundContent('ex15', undefined, undefined, 'http://attr.example.com');
assertFoundContent('ex16', undefined, undefined, 'http://www.example.com');
assertFoundContent('ex17', undefined, undefined, 'http://www.example.com');
assertFoundContent('ex18', 'My Ad', 'http://www.example.com/path/xyz.jpg', origin + '/anylink');
assertFoundContent('ex19', 'http://www.example.com/path/xyz.jpg', 'http://www.example.com/path/xyz.jpg', 'http://ad.example.com');
// test removal of domain if url === current domain
var newUrl = origin + '/path/xyz.jpg';
$(_s('#ex19 img')).attr('src', newUrl);
assertFoundContent('ex19', '/path/xyz.jpg', newUrl, 'http://ad.example.com', 'Should remove domain if the same as current');
newUrl = 'http://' + host + '/path/xyz.jpg';
$(_s('#ex19 img')).attr('src', newUrl);
assertFoundContent('ex19', '/path/xyz.jpg', newUrl, 'http://ad.example.com', 'Should remove domain if the same as current');
newUrl = 'https://' + host + '/path/xyz.jpg';
$(_s('#ex19 img')).attr('src', newUrl);
assertFoundContent('ex19', '/path/xyz.jpg', newUrl, 'http://ad.example.com', 'Should remove domain if the same as current');
assertFoundContent('ex20', 'My Ad', undefined, 'http://ad.example.com');
assertFoundContent('ex21', 'Block Title', undefined, 'http://www.example.com');
assertFoundContent('ex22', 'Piece Title', undefined, 'http://www.example.com');
assertFoundContent('ex23', 'Target Title', undefined, 'http://www.example.com');
assertFoundContent('ex24', 'Piece Title', undefined, 'http://target.example.com');
assertFoundContent('ex25', 'My Ad', 'http://www.example.com/path/xyz.jpg', origin + '/anylink');
assertFoundContent('ex26', 'My Ad', undefined, 'http://fallback.example.com');
assertFoundContent('ex27', 'My Ad', undefined, origin + '/test');
assertFoundContent('ex28', 'My Ad', undefined, toAbsoluteUrl('test'));
assertFoundContent('ex29', 'My Video', toAbsoluteUrl('movie.mp4'), 'videoplayer');
assertFoundContent('ex30', toAbsolutePath('audio.ogg'), toAbsoluteUrl('audio.ogg'), 'audioplayer');
assertFoundContent('ex31', ' name ', ' pie ce ', ' targ et ', 'Should not trim');
ok('test buildContentBlock(node)');
strictEqual(content.buildContentBlock(), undefined, 'no node set');
assertBuiltContent('ex31', 'name', 'pie ce', 'targ et', 'Should trim values');
assertBuiltContent('ex30', toAbsolutePath('audio.ogg'), toAbsoluteUrl('audio.ogg'), 'audioplayer', 'All values set');
assertBuiltContent(_e('div1'), 'Unknown', 'Unknown', '', 'It is not a content block, so should use defaults');
assertBuiltContent('ex1', toAbsolutePath('img-en.jpg'), toAbsoluteUrl('img-en.jpg'), '', 'Should use default for target');
assertBuiltContent('ex12', 'Block Title', 'Unknown', 'http://www.example.com', 'Should use default for piece');
assertBuiltContent('ex15', 'Unknown', 'Unknown', 'http://attr.example.com', 'Should use default for name and piece');
ok('test collectContent(node)');
propEqual(content.collectContent(), [], 'no node set should still return array');
var expected = [
buildContentStruct('name', 'pie ce', 'targ et'),
buildContentStruct(toAbsolutePath('audio.ogg'), toAbsoluteUrl('audio.ogg'), 'audioplayer'),
buildContentStruct('Unknown', 'Unknown', ''),
buildContentStruct(toAbsolutePath('img-en.jpg'), toAbsoluteUrl('img-en.jpg'), ''),
buildContentStruct('Block Title', 'Unknown', 'http://www.example.com'),
buildContentStruct('Unknown', 'Unknown', 'http://attr.example.com'),
];
var ids = ['ex31', 'ex30', _e('div1'), 'ex1', 'ex12', 'ex15'];
assertCollectedContent(ids, expected, 'should collect all content, make sure it trims values and it uses default values');
});
test("ContentTrackerInternals", function() {
var tracker = Piwik.getTracker();
var actual, expected, trackerUrl;
var impression = {name: 'name', piece: '5', target: 'target'};
var origin = getOrigin();
var originEncoded = window.encodeURIComponent(origin);
function assertTrackingRequest(actual, expectedStartsWith, message)
{
if (!message) {
message = '';
} else {
message += ', ';
}
strictEqual(actual.indexOf(expectedStartsWith), 0, message + actual + ' should start with ' + expectedStartsWith);
strictEqual(actual.indexOf('&idsite=&rec=1'), expectedStartsWith.length);
// make sure it contains all those other tracking stuff directly afterwards so we can assume it did append
// the other request stuff and we also make sure to compare the whole custom string as we check from
// expectedStartsWith.length
}
ok('test buildContentImpressionRequest()');
actual = tracker.buildContentImpressionRequest();
assertTrackingRequest(actual, 'c_n=undefined&c_p=undefined', 'nothing set');
actual = tracker.buildContentImpressionRequest('name', 'piece');
assertTrackingRequest(actual, 'c_n=name&c_p=piece', 'only name and piece');
actual = tracker.buildContentImpressionRequest('name', 'piece', 'target');
assertTrackingRequest(actual, 'c_n=name&c_p=piece&c_t=target');
actual = tracker.buildContentImpressionRequest('name://', 'x=5', '?x=5');
assertTrackingRequest(actual, 'c_n=name%3A%2F%2F&c_p=x%3D5&c_t=%3Fx%3D5', 'should encode values');
ok('test buildContentInteractionRequest()');
actual = tracker.buildContentInteractionRequest();
strictEqual(actual, undefined, 'nothing set should not build request');
actual = tracker.buildContentInteractionRequest('interaction');
assertTrackingRequest(actual, 'c_i=interaction');
actual = tracker.buildContentInteractionRequest('interaction', 'name', 'piece');
assertTrackingRequest(actual, 'c_i=interaction&c_n=name&c_p=piece');
actual = tracker.buildContentInteractionRequest('interaction', 'name', 'piece', 'target');
assertTrackingRequest(actual, 'c_i=interaction&c_n=name&c_p=piece&c_t=target', 'all params');
actual = tracker.buildContentInteractionRequest('interaction://', 'name://', 'p?=iece', 'tar=get');
assertTrackingRequest(actual, 'c_i=interaction%3A%2F%2F&c_n=name%3A%2F%2F&c_p=p%3F%3Diece&c_t=tar%3Dget', 'should encode');
setupContentTrackingFixture('manyExamples');
ok('test buildContentInteractionRequestNode()');
actual = tracker.buildContentInteractionRequestNode();
strictEqual(actual, undefined, 'nothing set should not build request');
actual = tracker.buildContentInteractionRequestNode(_e('div1'));
strictEqual(actual, undefined, 'does not contain a content block, should not build anything');
actual = tracker.buildContentInteractionRequestNode(_e('ex18'));
expected = 'c_i=Unknown&c_n=My%20Ad&c_p=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_t=' + originEncoded + '%2Fanylink';
assertTrackingRequest(actual, expected, 'no interaction set should default to unknown and recognize all other values');
actual = tracker.buildContentInteractionRequestNode(_e('ex18'), 'CustomInteraction://');
expected = 'c_i=CustomInteraction%3A%2F%2F&c_n=My%20Ad&c_p=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_t=' + originEncoded + '%2Fanylink';
assertTrackingRequest(actual, expected, 'custom interaction');
actual = tracker.buildContentInteractionRequestNode($('#ex18 a')[0], 'CustomInteraction://');
expected = 'c_i=CustomInteraction%3A%2F%2F&c_n=My%20Ad&c_p=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_t=' + originEncoded + '%2Fanylink';
assertTrackingRequest(actual, expected, 'should automatically find parent and search for content from there');
actual = tracker.buildContentInteractionTrackingRedirectUrl();
strictEqual(actual, undefined, 'nothing set');
actual = tracker.buildContentInteractionTrackingRedirectUrl('/path?a=b');
assertTrackingRequest(actual, '?redirecturl=' + encodeWrapper(origin + '/path?a=b') + '&c_t=%2Fpath%3Fa%3Db', 'should build redirect url including domain when absolute path. Target should also fallback to passed url if not set');
actual = tracker.buildContentInteractionTrackingRedirectUrl('path?a=b');
assertTrackingRequest(actual, '?redirecturl=' + toEncodedAbsoluteUrl('path?a=b') + '&c_t=path%3Fa%3Db', 'should build redirect url including domain when relative path. Target should also fallback to passed url if not set');
actual = tracker.buildContentInteractionTrackingRedirectUrl('#test', 'click', 'name', 'piece', 'target');
assertTrackingRequest(actual, '?redirecturl=' + toEncodedAbsoluteUrl('#test') + '&c_i=click&c_n=name&c_p=piece&c_t=target', 'all params set');
trackerUrl = tracker.getTrackerUrl();
tracker.setTrackerUrl('piwik.php?test=1');
actual = tracker.buildContentInteractionTrackingRedirectUrl('#test', 'click', 'name', 'piece', 'target');
assertTrackingRequest(actual, 'piwik.php?test=1&redirecturl=' + toEncodedAbsoluteUrl('#test') + '&c_i=click&c_n=name&c_p=piece&c_t=target', 'should use & if tracker url already contains question mark');
tracker.setTrackerUrl('piwik.php');
actual = tracker.buildContentInteractionTrackingRedirectUrl('piwik.php?redirecturl=http://www.example.com', 'click', 'name', 'piece', 'target');
strictEqual(actual, 'piwik.php?redirecturl=http://www.example.com', 'should return unmodified url if it is already a tracker url so users can set piwik.php link in href');
actual = tracker.buildContentInteractionTrackingRedirectUrl('http://www.example.com', 'click', 'name');
assertTrackingRequest(actual, 'piwik.php?redirecturl=' + encodeWrapper('http://www.example.com') + '&c_i=click&c_n=name&c_t=http%3A%2F%2Fwww.example.com', 'should not change url if absolute');
actual = tracker.buildContentInteractionTrackingRedirectUrl(origin, 'something', 'name', undefined, 'target');
assertTrackingRequest(actual, 'piwik.php?redirecturl=' + originEncoded + '&c_i=something&c_n=name&c_t=target', 'should not change url if same domain');
tracker.setTrackerUrl(trackerUrl);
ok('test wasContentImpressionAlreadyTracked()');
actual = tracker.wasContentImpressionAlreadyTracked(impression);
strictEqual(actual, false, 'wasContentImpressionAlreadyTracked, content impression was not tracked before');
tracker.buildContentImpressionsRequests([impression], []);
actual = tracker.wasContentImpressionAlreadyTracked(impression);
strictEqual(actual, true, 'wasContentImpressionAlreadyTracked, should be marked as already tracked now');
actual = tracker.wasContentImpressionAlreadyTracked({name: 'name', piece: 5, target: 'target'});
strictEqual(actual, false, 'wasContentImpressionAlreadyTracked, should compare with === equal parameter');
tracker.trackPageView();
actual = tracker.wasContentImpressionAlreadyTracked(impression);
strictEqual(actual, false, 'wasContentImpressionAlreadyTracked, trackPageView should reset tracked impressions');
setupContentTrackingFixture('trackerInternals');
ok('test appendContentInteractionToRequestIfPossible()');
ok(_e('notClickedTargetNode') && _e('ignoreInteraction2') && _e('ignoreInteraction1') && _e('click1') && _s('#ex103') && _s('#ex104'),
'Make sure the nodes we are using for testing actually exist. Otherwise tests would be useless');
actual = tracker.appendContentInteractionToRequestIfPossible();
strictEqual(actual, undefined, 'appendContentInteractionToRequestIfPossible, nothing set');
actual = tracker.appendContentInteractionToRequestIfPossible(_e('click1'));
strictEqual(actual, undefined, 'appendContentInteractionToRequestIfPossible, no content block');
actual = tracker.appendContentInteractionToRequestIfPossible(_e('ignoreInteraction1'));
strictEqual(actual, undefined, 'appendContentInteractionToRequestIfPossible, contains block but should be ignored in target node');
actual = tracker.appendContentInteractionToRequestIfPossible(_e('ignoreInteraction2'));
strictEqual(actual, undefined, 'appendContentInteractionToRequestIfPossible, contains block but should be ignored in block node as no target node');
actual = tracker.appendContentInteractionToRequestIfPossible(_e('notClickedTargetNode'));
strictEqual(actual, undefined, 'appendContentInteractionToRequestIfPossible, not a node within target node was clicked');
actual = tracker.appendContentInteractionToRequestIfPossible(_s('#ex103'));
strictEqual(actual, undefined, 'appendContentInteractionToRequestIfPossible, the content block node was clicked but it is not the target');
actual = tracker.appendContentInteractionToRequestIfPossible(_s('#ex104'));
strictEqual(actual, 'c_n=' + toEncodedAbsolutePath('img.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img.jpg'), 'appendContentInteractionToRequestIfPossible, the actual target node was clicked');
actual = tracker.appendContentInteractionToRequestIfPossible(_s('#ex104'), 'clicki');
strictEqual(actual, 'c_i=clicki&c_n=' + toEncodedAbsolutePath('img.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img.jpg'), 'appendContentInteractionToRequestIfPossible, with interaction');
actual = tracker.appendContentInteractionToRequestIfPossible(_s('#ex104_inner'));
strictEqual(actual, 'c_n=' + toEncodedAbsolutePath('img.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img.jpg'), 'appendContentInteractionToRequestIfPossible, block node is target node and any node within it was clicked which is good, we build a request');
actual = tracker.appendContentInteractionToRequestIfPossible(_s('#ex104_inner'));
strictEqual(actual, 'c_n=' + toEncodedAbsolutePath('img.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img.jpg'), 'appendContentInteractionToRequestIfPossible, a node within a target node was clicked which is googd');
actual = tracker.appendContentInteractionToRequestIfPossible(_s('#ex105_target'));
strictEqual(actual, 'c_n=' + toEncodedAbsolutePath('img.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img.jpg') + '&c_t=http%3A%2F%2Fwww.example.com', 'appendContentInteractionToRequestIfPossible, target node was clicked which is good');
actual = tracker.appendContentInteractionToRequestIfPossible(_s('#ex105_withinTarget'));
strictEqual(actual, 'c_n=' + toEncodedAbsolutePath('img.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img.jpg') + '&c_t=http%3A%2F%2Fwww.example.com', 'appendContentInteractionToRequestIfPossible, a node within target node was clicked which is googd');
actual = tracker.appendContentInteractionToRequestIfPossible(_s('#ex104_inner'), 'click', 'fallbacktarget');
strictEqual(actual, 'c_i=click&c_n=' + toEncodedAbsolutePath('img.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img.jpg') + '&c_t=fallbacktarget', 'appendContentInteractionToRequestIfPossible, if no target found we can specify a default target');
ok('test setupInteractionsTracking()');
actual = tracker.setupInteractionsTracking();
strictEqual(actual, undefined, 'setupInteractionsTracking, no nodes set');
actual = tracker.setupInteractionsTracking([_s('#ex106'), _s('#ex107')]);
strictEqual(_s('#ex106_target').contentInteractionTrackingSetupDone, true, 'setupInteractionsTracking, should add event to target node');
strictEqual(_s('#ex107').contentInteractionTrackingSetupDone, true, 'setupInteractionsTracking, should add event to block node if no target node specified');
ok('test trackContentImpressionClickInteraction()');
trackerUrl = tracker.getTrackerUrl();
tracker.setTrackerUrl('piwik.php');
tracker.disableLinkTracking();
ok(_s('#ignoreInteraction1') && _s('#ex108') && _s('#ex109'), 'make sure node exists otherwise test is useless');
actual = (tracker.trackContentImpressionClickInteraction())();
strictEqual(actual, undefined, 'trackContentImpressionClickInteraction, no target node set');
actual = (tracker.trackContentImpressionClickInteraction(_s('#ignoreInteraction1')))({target: _s('#ignoreInteraction1')});
strictEqual(actual, undefined, 'trackContentImpressionClickInteraction, no target node set');
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex108')))({target: _s('#ex108')});
assertTrackingRequest(actual, 'c_i=click&c_n=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_p=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_t=http%3A%2F%2Fad.example.com', 'trackContentImpressionClickInteraction, is outlink but should use xhr as link tracking not enabled');
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex109')))({target: _s('#ex109')});
strictEqual(actual, 'href', 'trackContentImpressionClickInteraction, is internal download but should use href as link tracking not enabled');
assertTrackingRequest($(_s('#ex109')).attr('href'), 'piwik.php?redirecturl=' + toEncodedAbsoluteUrl('/file.pdf') + '&c_i=click&c_n=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_p=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_t=' + originEncoded + '%2Ffile.pdf', 'trackContentImpressionClickInteraction, the href download link should be replaced with a redirect link to tracker');
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex110')))({target: _s('#ex110')});
strictEqual(actual, 'href', 'trackContentImpressionClickInteraction, should be tracked using redirect');
assertTrackingRequest($(_s('#ex110')).attr('href'), 'piwik.php?redirecturl=' + toEncodedAbsoluteUrl('/example') + '&c_i=click&c_n=MyName&c_p=img.jpg&c_t=' + originEncoded + '%2Fexample', 'trackContentImpressionClickInteraction, the href link should be replaced with a redirect link to tracker');
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex111')))({target: _s('#ex111')});
strictEqual(actual, 'href', 'trackContentImpressionClickInteraction, should detect it is a link to same page');
strictEqual($(_s('#ex111')).attr('href'), 'piwik.php?xyz=makesnosense', 'trackContentImpressionClickInteraction, a tracking link should not be changed');
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex112')))({target: _s('#ex112')});
assertTrackingRequest(actual, 'c_i=click&c_n=img.jpg&c_p=img.jpg&c_t=' + originEncoded + '%2Ftests%2Fjavascript%2F%23example', 'trackContentImpressionClickInteraction, a link that is an anchor should be tracked as XHR and no redirect');
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex113_target')))({target: _s('#ex113_target')});
assertTrackingRequest(actual, 'c_i=click&c_n=img.jpg&c_p=img.jpg', 'trackContentImpressionClickInteraction, if element is not A or AREA it should always use xhr');
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex114')))({target: _s('#ex114')});
assertTrackingRequest(actual, 'c_i=click&c_n=imgnohref.jpg&c_p=imgnohref.jpg&c_t=%2Ftest', 'trackContentImpressionClickInteraction, if element is an A or AREA element but has no href attribute it should always use xhr');
tracker.enableLinkTracking();
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex108')))({target: _s('#ex108')});
strictEqual(actual, 'link', 'trackContentImpressionClickInteraction, should not track as is an outlink and link tracking enabled');
$(_s('#ex109')).attr('href', '/file.pdf'); // reset download link as was replaced with piwik.php
actual = (tracker.trackContentImpressionClickInteraction(_s('#ex109')))({target: _s('#ex109')});
strictEqual(actual, 'download', 'trackContentImpressionClickInteraction, should not track as is a download and link tracking enabled');
tracker.disableLinkTracking();
tracker.setTrackerUrl(trackerUrl);
ok('test buildContentImpressionsRequests()');
ok(impression, 'we should have an impression');
tracker.clearTrackedContentImpressions();
actual = tracker.buildContentImpressionsRequests();
propEqual(actual, [], 'buildContentImpressionsRequests, nothing set');
strictEqual(tracker.getTrackedContentImpressions().length, 0, 'buildContentImpressionsRequests, tracked impressions should be empty');
actual = tracker.buildContentImpressionsRequests([impression]);
propEqual(tracker.getTrackedContentImpressions(), [impression], 'buildContentImpressionsRequests, should have marked content as tracked');
actual = tracker.buildContentImpressionsRequests([impression]);
propEqual(actual, [], 'buildContentImpressionsRequests, nothing tracked as supposed to be ignored');
propEqual(tracker.getTrackedContentImpressions(), [impression], 'buildContentImpressionsRequests, impression should be ignored as it was already tracked before');
tracker.clearTrackedContentImpressions();
_s('#ignoreInteraction1').contentInteractionTrackingSetupDone = false;
tracker.buildContentImpressionsRequests([impression], [_s('#ex101')]);
strictEqual(_s('#ignoreInteraction1').contentInteractionTrackingSetupDone, true, 'buildContentImpressionsRequests, should trigger setup of interaction tracking');
tracker.clearTrackedContentImpressions();
actual = tracker.buildContentImpressionsRequests([impression], [_s('#ex101')]);
strictEqual(actual.length, 1, 'buildContentImpressionsRequests, should generate a request for one request');
assertTrackingRequest(actual[0], 'c_n=name&c_p=5&c_t=target');
tracker.clearTrackedContentImpressions();
var impression2 = {name: 'name2', piece: 'piece2', target: 'http://www.example.com'};
var impression3 = {name: 'name3', piece: 'piece3', target: 'Anything'};
actual = tracker.buildContentImpressionsRequests([impression, impression, impression2, impression, impression3], [_s('#ex101')]);
strictEqual(actual.length, 3, 'buildContentImpressionsRequests, should be only 3 requests as one impression was there twice and should be ignored once');
assertTrackingRequest(actual[0], 'c_n=name&c_p=5&c_t=target');
assertTrackingRequest(actual[1], 'c_n=name2&c_p=piece2&c_t=http%3A%2F%2Fwww.example.com');
assertTrackingRequest(actual[2], 'c_n=name3&c_p=piece3&c_t=Anything');
setupContentTrackingFixture('manyExamples');
ok('test getContentImpressionsRequestsFromNodes()');
actual = tracker.getContentImpressionsRequestsFromNodes();
propEqual(actual, [], 'getContentImpressionsRequestsFromNodes, no nodes set');
tracker.clearTrackedContentImpressions();
actual = tracker.getContentImpressionsRequestsFromNodes([undefined, null]);
propEqual(actual, [], 'getContentImpressionsRequestsFromNodes, no nodes set that are actually content nodes');
tracker.clearTrackedContentImpressions();
actual = tracker.getContentImpressionsRequestsFromNodes([_s('#ex1'), _s('#ex2')]);
strictEqual(actual.length, 1, 'getContentImpressionsRequestsFromNodes, should ignore a duplicated node that has same content');
assertTrackingRequest(actual[0], 'c_n=' + toEncodedAbsolutePath('img-en.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img-en.jpg'));
tracker.clearTrackedContentImpressions();
actual = tracker.getContentImpressionsRequestsFromNodes([_s('#ex1'), undefined, _s('#ex2'), _s('#ex8'), _s('#ex19')]);
strictEqual(actual.length, 3, 'getContentImpressionsRequestsFromNodes, should only build requests for nodes that are content nodes');
assertTrackingRequest(actual[0], 'c_n=' + toEncodedAbsolutePath('img-en.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img-en.jpg'));
assertTrackingRequest(actual[1], 'c_n=My%20content&c_p=My%20content&c_t=http%3A%2F%2Fwww.example.com');
assertTrackingRequest(actual[2], 'c_n=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_p=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_t=http%3A%2F%2Fad.example.com');
setupContentTrackingFixture('trackerInternals', document.body);
ok('test getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet()');
actual = tracker.getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet();
propEqual(actual, [], 'getVisibleImpressions, no nodes set');
_s('#ex115').scrollIntoView(true);
tracker.clearTrackedContentImpressions();
actual = tracker.getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet([_s('#ex116_hidden')]);
propEqual(actual, [], 'getVisibleImpressions, if all are hidden should not return anything');
_s('#ex115').scrollIntoView(true);
tracker.clearTrackedContentImpressions();
actual = tracker.getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet([_s('#ex115'),_s('#ex115'), _s('#ex116_hidden')]);
strictEqual(actual.length, 1, 'getVisibleImpressions, should not ignore the found requests but the visible ones, should not add the same one twice');
assertTrackingRequest(actual[0], 'c_n=' + toEncodedAbsolutePath('img115.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img115.jpg') + '&c_t=http%3A%2F%2Fwww.example.com');
_s('#ex115').scrollIntoView(true);
tracker.clearTrackedContentImpressions();
actual = tracker.getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet([_s('#ex116_hidden'), _s('#ex116_hidden'), _s('#ex115'),_s('#ex115')]);
strictEqual(actual.length, 1, 'getVisibleImpressions, two hidden ones before a visible ones to make sure removing hidden content block from array works and does not ignore one');
assertTrackingRequest(actual[0], 'c_n=' + toEncodedAbsolutePath('img115.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img115.jpg') + '&c_t=http%3A%2F%2Fwww.example.com');
ok('test replaceHrefIfInternalLink()')
var trackerUrl = tracker.getTrackerUrl();
tracker.setTrackerUrl('piwik.php');
strictEqual(tracker.replaceHrefIfInternalLink(), false, 'no content node set');
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex117')), false, 'should be ignored');
$(_s('#ignoreInternalLink')).removeClass('piwikContentIgnoreInteraction'); // now it should be no longer ignored and as it is an intenral link replaced
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex117')), true, 'should be replaced as is internal link');
assertTrackingRequest($(_s('#ignoreInternalLink')).attr('href'), 'piwik.php?redirecturl=' + toEncodedAbsoluteUrl('/internallink') + '&c_i=click&c_n=Unknown&c_p=Unknown&c_t=' + originEncoded + '%2Finternallink', 'internal link should be replaced');
strictEqual($(_s('#ignoreInternalLink')).attr('data-content-target'), origin + '/internallink', 'we need to set data-content-target when link is set otherwise a replace would not be found');
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex122')), true, 'should be replaced');
strictEqual($(_s('#replacedLinkWithTarget')).attr('data-content-target'), '/test', 'should replace href but not a data-content-target if already exists');
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex118')), true, 'should not replace already replaced link');
strictEqual($(_s('#ex118')).attr('href'), 'piwik.php?test=5', 'link should not be replaced');
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex119')), false, 'anchor link should not be replaced');
strictEqual($(_s('#ex119')).attr('href'), '#test', 'link should not replace anchor link');
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex120')), false, 'external link should not be replaced');
strictEqual($(_s('#ex120')).attr('href'), 'http://www.example.com', 'should not replace external link');
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex121')), true, 'should replace download link if link tracking not enabled');
assertTrackingRequest($(_s('#ex121')).attr('href'), 'piwik.php?redirecturl=' + toEncodedAbsoluteUrl('/download.pdf') + '&c_i=click&c_n=Unknown&c_p=Unknown&c_t=' + originEncoded + '%2Fdownload.pdf', 'should replace download link as link tracking disabled');
$(_s('#ex121')).attr('href', '/download.pdf'); // reset link
tracker.enableLinkTracking();
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex121')), false, 'should not replace download link');
strictEqual($(_s('#ex121')).attr('href'), '/download.pdf', 'should not replace download link');
strictEqual(tracker.replaceHrefIfInternalLink(_s('#ex123')), false, 'should not replace a link that has no href');
strictEqual($(_s('#ex123')).attr('href'), undefined, 'should still not have a href attribute');
tracker.setTrackerUrl(trackerUrl);
removeContentTrackingFixture();
});
test("Basic requirements", function() {
expect(3);
equal( typeof encodeURIComponent, 'function', 'encodeURIComponent' );
ok( RegExp, "RegExp" );
ok( Piwik, "Piwik" );
});
test("Test API - addPlugin(), getTracker(), getHook(), and hook", function() {
expect(6);
ok( Piwik.addPlugin, "Piwik.addPlugin" );
var tracker = Piwik.getTracker();
equal( typeof tracker, 'object', "Piwik.getTracker()" );
equal( typeof tracker.getHook, 'function', "test Tracker getHook" );
equal( typeof tracker.hook, 'object', "test Tracker hook" );
equal( typeof tracker.getHook('test'), 'object', "test Tracker getHook('test')" );
equal( typeof tracker.hook.test, 'object', "test Tracker hook.test" );
});
test("API methods", function() {
expect(64);
equal( typeof Piwik.addPlugin, 'function', 'addPlugin' );
equal( typeof Piwik.getTracker, 'function', 'getTracker' );
equal( typeof Piwik.getAsyncTracker, 'function', 'getAsyncTracker' );
var tracker;
tracker = Piwik.getAsyncTracker();
ok(tracker instanceof Object, 'getAsyncTracker');
tracker = Piwik.getTracker();
ok(tracker instanceof Object, 'getTracker');
equal( typeof tracker.getVisitorId, 'function', 'getVisitorId' );
equal( typeof tracker.getVisitorInfo, 'function', 'getVisitorInfo' );
equal( typeof tracker.getAttributionInfo, 'function', 'getAttributionInfo' );
equal( typeof tracker.getAttributionReferrerTimestamp, 'function', 'getAttributionReferrerTimestamp' );
equal( typeof tracker.getAttributionReferrerUrl, 'function', 'getAttributionReferrerUrl' );
equal( typeof tracker.getAttributionCampaignName, 'function', 'getAttributionCampaignName' );
equal( typeof tracker.getAttributionCampaignKeyword, 'function', 'getAttributionCampaignKeyword' );
equal( typeof tracker.setTrackerUrl, 'function', 'setTrackerUrl' );
equal( typeof tracker.getRequest, 'function', 'getRequest' );
equal( typeof tracker.addPlugin, 'function', 'addPlugin' );
equal( typeof tracker.setUserId, 'function', 'setUserId' );
equal( typeof tracker.setSiteId, 'function', 'setSiteId' );
equal( typeof tracker.setCustomData, 'function', 'setCustomData' );
equal( typeof tracker.getCustomData, 'function', 'getCustomData' );
equal( typeof tracker.setCustomRequestProcessing, 'function', 'setCustomRequestProcessing' );
equal( typeof tracker.setCustomVariable, 'function', 'setCustomVariable' );
equal( typeof tracker.getCustomVariable, 'function', 'getCustomVariable' );
equal( typeof tracker.deleteCustomVariable, 'function', 'deleteCustomVariable' );
equal( typeof tracker.setLinkTrackingTimer, 'function', 'setLinkTrackingTimer' );
equal( typeof tracker.setDownloadExtensions, 'function', 'setDownloadExtensions' );
equal( typeof tracker.addDownloadExtensions, 'function', 'addDownloadExtensions' );
equal( typeof tracker.setDomains, 'function', 'setDomains' );
equal( typeof tracker.setIgnoreClasses, 'function', 'setIgnoreClasses' );
equal( typeof tracker.setRequestMethod, 'function', 'setRequestMethod' );
equal( typeof tracker.setRequestContentType, 'function', 'setRequestContentType' );
equal( typeof tracker.setReferrerUrl, 'function', 'setReferrerUrl' );
equal( typeof tracker.setCustomUrl, 'function', 'setCustomUrl' );
equal( typeof tracker.setDocumentTitle, 'function', 'setDocumentTitle' );
equal( typeof tracker.setDownloadClasses, 'function', 'setDownloadClasses' );
equal( typeof tracker.setLinkClasses, 'function', 'setLinkClasses' );
equal( typeof tracker.setCampaignNameKey, 'function', 'setCampaignNameKey' );
equal( typeof tracker.setCampaignKeywordKey, 'function', 'setCampaignKeywordKey' );
equal( typeof tracker.discardHashTag, 'function', 'discardHashTag' );
equal( typeof tracker.setCookieNamePrefix, 'function', 'setCookieNamePrefix' );
equal( typeof tracker.setCookieDomain, 'function', 'setCookieDomain' );
equal( typeof tracker.setCookiePath, 'function', 'setCookiePath' );
equal( typeof tracker.setVisitorCookieTimeout, 'function', 'setVisitorCookieTimeout' );
equal( typeof tracker.setSessionCookieTimeout, 'function', 'setSessionCookieTimeout' );
equal( typeof tracker.setReferralCookieTimeout, 'function', 'setReferralCookieTimeout' );
equal( typeof tracker.setConversionAttributionFirstReferrer, 'function', 'setConversionAttributionFirstReferrer' );
equal( typeof tracker.addListener, 'function', 'addListener' );
equal( typeof tracker.enableLinkTracking, 'function', 'enableLinkTracking' );
equal( typeof tracker.setHeartBeatTimer, 'function', 'setHeartBeatTimer' );
equal( typeof tracker.killFrame, 'function', 'killFrame' );
equal( typeof tracker.redirectFile, 'function', 'redirectFile' );
equal( typeof tracker.setCountPreRendered, 'function', 'setCountPreRendered' );
equal( typeof tracker.trackGoal, 'function', 'trackGoal' );
equal( typeof tracker.trackLink, 'function', 'trackLink' );
equal( typeof tracker.trackPageView, 'function', 'trackPageView' );
// content
equal( typeof tracker.trackAllContentImpressions, 'function', 'trackAllContentImpressions' );
equal( typeof tracker.trackVisibleContentImpressions, 'function', 'trackVisibleContentImpressions' );
equal( typeof tracker.trackContentImpression, 'function', 'trackContentImpression' );
equal( typeof tracker.trackContentImpressionsWithinNode, 'function', 'trackContentImpressionsWithinNode' );
equal( typeof tracker.trackContentInteraction, 'function', 'trackContentInteraction' );
equal( typeof tracker.trackContentInteractionNode, 'function', 'trackContentInteractionNode' );
// ecommerce
equal( typeof tracker.setEcommerceView, 'function', 'setEcommerceView' );
equal( typeof tracker.addEcommerceItem, 'function', 'addEcommerceItem' );
equal( typeof tracker.trackEcommerceOrder, 'function', 'trackEcommerceOrder' );
equal( typeof tracker.trackEcommerceCartUpdate, 'function', 'trackEcommerceCartUpdate' );
});
module("API and internals");
test("Tracker is_a functions", function() {
expect(22);
var tracker = Piwik.getTracker();
equal( typeof tracker.hook.test._isDefined, 'function', 'isDefined' );
ok( tracker.hook.test._isDefined(tracker), 'isDefined true' );
ok( tracker.hook.test._isDefined(tracker.hook), 'isDefined(obj.exists) true' );
ok( !tracker.hook.test._isDefined(tracker.non_existant_property), 'isDefined(obj.missing) false' );
equal( typeof tracker.hook.test._isFunction, 'function', 'isFunction' );
ok( tracker.hook.test._isFunction(tracker.hook.test._isFunction), 'isFunction(isFunction)' );
ok( tracker.hook.test._isFunction(function () { }), 'isFunction(function)' );
equal( typeof tracker.hook.test._isObject, 'function', 'isObject' );
ok( tracker.hook.test._isObject(null), 'isObject(null)' ); // null is an object!
ok( tracker.hook.test._isObject(new Object), 'isObject(Object)' );
ok( tracker.hook.test._isObject(window), 'isObject(window)' );
ok( !tracker.hook.test._isObject('string'), 'isObject("string")' );
ok( tracker.hook.test._isObject(new String), 'isObject(String)' ); // String is an object!
equal( typeof tracker.hook.test._isString, 'function', 'isString' );
ok( tracker.hook.test._isString(''), 'isString(emptyString)' );
ok( tracker.hook.test._isString('abc'), 'isString("abc")' );
ok( tracker.hook.test._isString('123'), 'isString("123")' );
ok( !tracker.hook.test._isString(123), 'isString(123)' );
ok( !tracker.hook.test._isString(null), 'isString(null)' );
ok( !tracker.hook.test._isString(window), 'isString(window)' );
ok( !tracker.hook.test._isString(function () { }), 'isString(function)' );
ok( tracker.hook.test._isString(new String), 'isString(String)' ); // String is a string
});
test("Default visitorId should be equal across Trackers", function() {
expect(4);
deleteCookies();
var asyncTracker = Piwik.getAsyncTracker();
var asyncVistorId = asyncTracker.getVisitorId();
equal(Piwik.getAsyncTracker().getVisitorId(), asyncVistorId, 'asyncVistorId');
wait(2000);
var delayedTracker = Piwik.getTracker();
var delayedVisitorId = delayedTracker.getVisitorId();
equal(Piwik.getAsyncTracker().getVisitorId(), delayedVisitorId, 'delayedVisitorId');
var prefixTracker = Piwik.getTracker();
prefixTracker.setCookieNamePrefix('_test_cookie_prefix');
var prefixVisitorId = prefixTracker.getVisitorId();
equal(Piwik.getAsyncTracker().getVisitorId(), prefixVisitorId, 'prefixVisitorId');
var customTracker = Piwik.getTracker('customTrackerUrl', '71');
var customVisitorId = customTracker.getVisitorId();
equal(Piwik.getAsyncTracker().getVisitorId(), customVisitorId, 'customVisitorId');
});
test("AnalyticsTracker alias", function() {
expect(1);
var tracker = AnalyticsTracker.getTracker();
equal( typeof tracker.hook.test._encode, 'function', 'encodeWrapper' );
});
test("Tracker encode, decode, urldecode wrappers", function() {
expect(6);
var tracker = Piwik.getTracker();
equal( typeof tracker.hook.test._encode, 'function', 'encodeWrapper' );
equal( typeof tracker.hook.test._decode, 'function', 'decodeWrapper' );
equal( typeof tracker.hook.test._urldecode, 'function', 'urldecodeWrapper' );
equal( tracker.hook.test._encode("&=?;/#"), '%26%3D%3F%3B%2F%23', 'encodeWrapper()' );
equal( tracker.hook.test._decode("%26%3D%3F%3B%2F%23"), '&=?;/#', 'decodeWrapper()' );
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()' );
});
test("Tracker getHostName(), getParameter(), urlFixup(), domainFixup(), titleFixup() and purify()", function() {
expect(57);
var tracker = Piwik.getTracker();
equal( typeof tracker.hook.test._getHostName, 'function', 'getHostName' );
equal( typeof tracker.hook.test._getParameter, 'function', 'getParameter' );
equal( tracker.hook.test._getHostName('http://example.com'), 'example.com', 'http://example.com');
equal( tracker.hook.test._getHostName('http://example.com/'), 'example.com', 'http://example.com/');
equal( tracker.hook.test._getHostName('http://example.com/index'), 'example.com', 'http://example.com/index');
equal( tracker.hook.test._getHostName('http://example.com/index?q=xyz'), 'example.com', 'http://example.com/index?q=xyz');
equal( tracker.hook.test._getHostName('http://example.com/?q=xyz'), 'example.com', 'http://example.com/?q=xyz');
equal( tracker.hook.test._getHostName('http://example.com/?q=xyz#hash'), 'example.com', 'http://example.com/?q=xyz#hash');
equal( tracker.hook.test._getHostName('http://example.com#hash'), 'example.com', 'http://example.com#hash');
equal( tracker.hook.test._getHostName('http://example.com/#hash'), 'example.com', 'http://example.com/#hash');
equal( tracker.hook.test._getHostName('http://example.com:80'), 'example.com', 'http://example.com:80');
equal( tracker.hook.test._getHostName('http://example.com:80/'), 'example.com', 'http://example.com:80/');
equal( tracker.hook.test._getHostName('https://example.com/'), 'example.com', 'https://example.com/');
equal( tracker.hook.test._getHostName('http://user@example.com/'), 'example.com', 'http://user@example.com/');
equal( tracker.hook.test._getHostName('http://user:password@example.com/'), 'example.com', 'http://user:password@example.com/');
equal( tracker.hook.test._getParameter('http://piwik.org/', 'q'), '', 'no query');
equal( tracker.hook.test._getParameter('http://piwik.org/?q=test', 'q'), 'test', '?q');
equal( tracker.hook.test._getParameter('http://piwik.org/?q=test#aq=not', 'q'), 'test', '?q');
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2', 'q'), 'test2', '&q');
// getParameter in hash tag
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#aq=not', 'q'), 'test2', '&q');
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#aq=not', 'aq'), 'not', '#aq');
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'bq'), 'yes', '#bq');
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#pk_campaign=campaign', 'pk_campaign'), 'campaign', '#pk_campaign');
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'q'), 'test2', '#q');
// URL decoded
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');
equal( tracker.hook.test._getParameter('http://piwik.org/?q=http%3a%2f%2flocalhost%2f%3fr%3d1%26q%3dfalse¬q=not', 'q'), 'http://localhost/?r=1&q=false', 'url');
// non existing parameters
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'bqq'), "", '#q');
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'bq='), "", '#q');
equal( tracker.hook.test._getParameter('http://piwik.org/?p=test1&q=test2#bq=yes&aq=not', 'sp='), "", '#q');
equal( typeof tracker.hook.test._urlFixup, 'function', 'urlFixup' );
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', '' ),
['piwik.org', 'http://piwik.org/qa', ''], 'webcache.googleusercontent.com' );
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', '' ),
['piwik.org', 'http://piwik.org/qa', ''], 'cc.bingj.com' );
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--', '' ),
['piwik.org', 'http://piwik.org/qa', ''], 'yahoo cache (1)' );
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--', '' ),
['piwik.org', 'http://piwik.org/qa', ''], 'yahoo cache (2)' );
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', '' ),
['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' );
equal( typeof tracker.hook.test._domainFixup, 'function', 'domainFixup' );
equal( tracker.hook.test._domainFixup( 'localhost' ), 'localhost', 'domainFixup: localhost' );
equal( tracker.hook.test._domainFixup( 'localhost.' ), 'localhost', 'domainFixup: localhost.' );
equal( tracker.hook.test._domainFixup( 'localhost.localdomain' ), 'localhost.localdomain', 'domainFixup: localhost.localdomain' );
equal( tracker.hook.test._domainFixup( 'localhost.localdomain.' ), 'localhost.localdomain', 'domainFixup: localhost.localdomain.' );
equal( tracker.hook.test._domainFixup( '127.0.0.1' ), '127.0.0.1', 'domainFixup: 127.0.0.1' );
equal( tracker.hook.test._domainFixup( 'www.example.com' ), 'www.example.com', 'domainFixup: www.example.com' );
equal( tracker.hook.test._domainFixup( 'www.example.com.' ), 'www.example.com', 'domainFixup: www.example.com.' );
equal( tracker.hook.test._domainFixup( '.example.com' ), '.example.com', 'domainFixup: .example.com' );
equal( tracker.hook.test._domainFixup( '.example.com.' ), '.example.com', 'domainFixup: .example.com.' );
equal( tracker.hook.test._domainFixup( '*.example.com' ), '.example.com', 'domainFixup: *.example.com' );
equal( tracker.hook.test._domainFixup( '*.example.com.' ), '.example.com', 'domainFixup: *.example.com.' );
equal( typeof tracker.hook.test._titleFixup, 'function', 'titleFixup' );
equal( tracker.hook.test._titleFixup( 'hello' ), 'hello', 'hello string' );
equal( tracker.hook.test._titleFixup( document.title ), 'piwik.js: Unit Tests', 'hello string' );
equal( typeof tracker.hook.test._purify, 'function', 'purify' );
equal( tracker.hook.test._purify('http://example.com'), 'http://example.com', 'http://example.com');
equal( tracker.hook.test._purify('http://example.com#hash'), 'http://example.com#hash', 'http://example.com#hash');
equal( tracker.hook.test._purify('http://example.com/?q=xyz#hash'), 'http://example.com/?q=xyz#hash', 'http://example.com/?q=xyz#hash');
tracker.discardHashTag(true);
equal( tracker.hook.test._purify('http://example.com'), 'http://example.com', 'http://example.com');
equal( tracker.hook.test._purify('http://example.com#hash'), 'http://example.com', 'http://example.com#hash');
equal( tracker.hook.test._purify('http://example.com/?q=xyz#hash'), 'http://example.com/?q=xyz', 'http://example.com/?q=xyz#hash');
});
// support for setCustomUrl( relativeURI )
test("getProtocolScheme and resolveRelativeReference", function() {
expect(27);
var tracker = Piwik.getTracker();
equal( typeof tracker.hook.test._getProtocolScheme, 'function', "getProtocolScheme" );
ok( tracker.hook.test._getProtocolScheme('http://example.com') === 'http', 'http://' );
ok( tracker.hook.test._getProtocolScheme('https://example.com') === 'https', 'https://' );
ok( tracker.hook.test._getProtocolScheme('file://somefile.txt') === 'file', 'file://' );
ok( tracker.hook.test._getProtocolScheme('mailto:somebody@example.com') === 'mailto', 'mailto:' );
ok( tracker.hook.test._getProtocolScheme('javascript:alert(document.cookie)') === 'javascript', 'javascript:' );
ok( tracker.hook.test._getProtocolScheme('') === null, 'empty string' );
ok( tracker.hook.test._getProtocolScheme(':') === null, 'unspecified scheme' );
ok( tracker.hook.test._getProtocolScheme('scheme') === null, 'missing colon' );
equal( typeof tracker.hook.test._resolveRelativeReference, 'function', 'resolveRelativeReference' );
var i, j, data = [
// unsupported
// ['http://example.com/index.php/pathinfo?query', 'test.php', 'http://example.com/test.php'],
// ['http://example.com/subdir/index.php', '../test.php', 'http://example.com/test.php'],
// already absolute
['http://example.com/', 'http://example.com', 'http://example.com'],
['http://example.com/', 'https://example.com/', 'https://example.com/'],
['http://example.com/', 'http://example.com/index', 'http://example.com/index'],
// relative to root
['http://example.com/', '', 'http://example.com/'],
['http://example.com/', '/', 'http://example.com/'],
['http://example.com/', '/test.php', 'http://example.com/test.php'],
['http://example.com/index', '/test.php', 'http://example.com/test.php'],
['http://example.com/index?query=x', '/test.php', 'http://example.com/test.php'],
['http://example.com/index?query=x#hash', '/test.php', 'http://example.com/test.php'],
['http://example.com/?query', '/test.php', 'http://example.com/test.php'],
['http://example.com/#hash', '/test.php', 'http://example.com/test.php'],
// relative to current document
['http://example.com/subdir/', 'test.php', 'http://example.com/subdir/test.php'],
['http://example.com/subdir/index', 'test.php', 'http://example.com/subdir/test.php'],
['http://example.com/subdir/index?query=x', 'test.php', 'http://example.com/subdir/test.php'],
['http://example.com/subdir/index?query=x#hash', 'test.php', 'http://example.com/subdir/test.php'],
['http://example.com/subdir/?query', 'test.php', 'http://example.com/subdir/test.php'],
['http://example.com/subdir/#hash', 'test.php', 'http://example.com/subdir/test.php']
];
for (i = 0; i < data.length; i++) {
j = data[i];
equal( tracker.hook.test._resolveRelativeReference(j[0], j[1]), j[2], j[2] );
}
});
test("Tracker setDomains() and isSiteHostName()", function() {
expect(13);
var tracker = Piwik.getTracker();
equal( typeof tracker.hook.test._isSiteHostName, 'function', "isSiteHostName" );
// test wildcards
tracker.setDomains( ['*.Example.com'] );
// skip test if testing on localhost
ok( window.location.hostname != 'localhost' ? !tracker.hook.test._isSiteHostName('localhost') : true, '!isSiteHostName("localhost")' );
ok( !tracker.hook.test._isSiteHostName('google.com'), '!isSiteHostName("google.com")' );
ok( tracker.hook.test._isSiteHostName('example.com'), 'isSiteHostName("example.com")' );
ok( tracker.hook.test._isSiteHostName('www.example.com'), 'isSiteHostName("www.example.com")' );
ok( tracker.hook.test._isSiteHostName('www.sub.example.com'), 'isSiteHostName("www.sub.example.com")' );
tracker.setDomains( 'dev.piwik.org' );
ok( !tracker.hook.test._isSiteHostName('piwik.org'), '!isSiteHostName("piwik.org")' );
ok( tracker.hook.test._isSiteHostName('dev.piwik.org'), 'isSiteHostName("dev.piwik.org")' );
ok( !tracker.hook.test._isSiteHostName('piwik.example.org'), '!isSiteHostName("piwik.example.org")');
ok( !tracker.hook.test._isSiteHostName('dev.piwik.org.com'), '!isSiteHostName("dev.piwik.org.com")');
tracker.setDomains( '.piwik.org' );
ok( tracker.hook.test._isSiteHostName('piwik.org'), 'isSiteHostName("piwik.org")' );
ok( tracker.hook.test._isSiteHostName('dev.piwik.org'), 'isSiteHostName("dev.piwik.org")' );
ok( !tracker.hook.test._isSiteHostName('piwik.org.com'), '!isSiteHostName("piwik.org.com")');
});
test("Tracker getClassesRegExp()", function() {
expect(3);
var tracker = Piwik.getTracker();
equal( typeof tracker.hook.test._getClassesRegExp, 'function', "getClassesRegExp" );
var download = tracker.hook.test._getClassesRegExp([], 'download');
ok( download.test('piwik_download'), 'piwik_download (default)' );
var outlink = tracker.hook.test._getClassesRegExp([], 'link');
ok( outlink.test('piwik_link'), 'piwik_link (default)' );
});
test("Tracker setIgnoreClasses() and getClassesRegExp(ignore)", function() {
expect(14);
var tracker = Piwik.getTracker();
var ignore = tracker.hook.test._getClassesRegExp([], 'ignore');
ok( ignore.test('piwik_ignore'), '[1] piwik_ignore' );
ok( !ignore.test('pk_ignore'), '[1] !pk_ignore' );
ok( !ignore.test('apiwik_ignore'), '!apiwik_ignore' );
ok( !ignore.test('piwik_ignorez'), '!piwik_ignorez' );
ok( ignore.test('abc piwik_ignore xyz'), 'abc piwik_ignore xyz' );
tracker.setIgnoreClasses( 'my_download' );
ignore = tracker.hook.test._getClassesRegExp(['my_download'], 'ignore');
ok( ignore.test('piwik_ignore'), '[2] piwik_ignore' );
ok( !ignore.test('pk_ignore'), '[2] !pk_ignore' );
ok( ignore.test('my_download'), 'my_download' );
ok( ignore.test('abc piwik_ignore xyz'), 'abc piwik_ignore xyz' );
ok( ignore.test('abc my_download xyz'), 'abc my_download xyz' );
tracker.setIgnoreClasses( ['my_download', 'my_outlink'] );
ignore = tracker.hook.test._getClassesRegExp(['my_download','my_outlink'], 'ignore');
ok( ignore.test('piwik_ignore'), '[3] piwik_ignore' );
ok( !ignore.test('pk_ignore'), '[3] !pk_ignore' );
ok( ignore.test('my_download'), 'my_download' );
ok( ignore.test('my_outlink'), 'my_outlink' );
});
test("Tracker hasCookies(), getCookie(), setCookie()", function() {
expect(2);
var tracker = Piwik.getTracker();
ok( tracker.hook.test._hasCookies() == '1', 'hasCookies()' );
var cookieName = '_pk_test_harness' + Math.random(),
expectedValue = String(Math.random());
tracker.hook.test._setCookie( cookieName, expectedValue );
equal( tracker.hook.test._getCookie( cookieName ), expectedValue, 'getCookie(), setCookie()' );
});
test("Tracker setDownloadExtensions(), addDownloadExtensions(), setDownloadClasses(), setLinkClasses(), and getLinkType()", function() {
expect(54);
var tracker = Piwik.getTracker();
function runTests(messagePrefix) {
equal( typeof tracker.hook.test._getLinkType, 'function', 'getLinkType' );
equal( tracker.hook.test._getLinkType('something', 'goofy.html', false), 'link', messagePrefix + 'implicit link' );
equal( tracker.hook.test._getLinkType('something', 'goofy.pdf', false), 'download', messagePrefix + 'external PDF files are downloads' );
equal( tracker.hook.test._getLinkType('something', 'goofy.pdf', true), 'download', messagePrefix + 'local PDF are downloads' );
equal( tracker.hook.test._getLinkType('something', 'goofy-with-dash.pdf', true), 'download', messagePrefix + 'local PDF are downloads' );
equal( tracker.hook.test._getLinkType('piwik_download', 'piwiktest.ext', true), 'download', messagePrefix + 'piwik_download' );
equal( tracker.hook.test._getLinkType('abc piwik_download xyz', 'piwiktest.ext', true), 'download', messagePrefix + 'abc piwik_download xyz' );
equal( tracker.hook.test._getLinkType('piwik_link', 'piwiktest.asp', true), 'link', messagePrefix+ 'piwik_link' );
equal( tracker.hook.test._getLinkType('abc piwik_link xyz', 'piwiktest.asp', true), 'link', messagePrefix + 'abc piwik_link xyz' );
equal( tracker.hook.test._getLinkType('something', 'piwiktest.txt', true), 'download', messagePrefix + 'download extension' );
equal( tracker.hook.test._getLinkType('something', 'piwiktest.ext', true), 0, messagePrefix + '[1] link (default)' );
equal( tracker.hook.test._getLinkType('something', 'file.zip', true), 'download', messagePrefix + 'download file.zip' );
equal( tracker.hook.test._getLinkType('something', 'index.php?name=file.zip#anchor', true), 'download', messagePrefix + 'download file.zip (anchor)' );
equal( tracker.hook.test._getLinkType('something', 'index.php?name=file.zip&redirect=yes', true), 'download', messagePrefix + 'download file.zip (is param)' );
equal( tracker.hook.test._getLinkType('something', 'file.zip?mirror=true', true), 'download', messagePrefix + 'download file.zip (with param)' );
tracker.setDownloadExtensions('pk');
equal( tracker.hook.test._getLinkType('something', 'piwiktest.pk', true), 'download', messagePrefix + '[1] .pk == download extension' );
equal( tracker.hook.test._getLinkType('something', 'piwiktest.txt', true), 0, messagePrefix + '.txt =! download extension' );
tracker.addDownloadExtensions('xyz');
equal( tracker.hook.test._getLinkType('something', 'piwiktest.pk', true), 'download', messagePrefix + '[2] .pk == download extension' );
equal( tracker.hook.test._getLinkType('something', 'piwiktest.xyz', true), 'download', messagePrefix + '.xyz == download extension' );
tracker.setDownloadClasses(['a', 'b']);
equal( tracker.hook.test._getLinkType('abc piwik_download', 'piwiktest.ext', true), 'download', messagePrefix + 'download (default)' );
equal( tracker.hook.test._getLinkType('abc a', 'piwiktest.ext', true), 'download', messagePrefix + 'download (a)' );
equal( tracker.hook.test._getLinkType('b abc', 'piwiktest.ext', true), 'download', messagePrefix + 'download (b)' );
tracker.setLinkClasses(['c', 'd']);
equal( tracker.hook.test._getLinkType('abc piwik_link', 'piwiktest.ext', true), 'link', messagePrefix + 'link (default)' );
equal( tracker.hook.test._getLinkType('abc c', 'piwiktest.ext', true), 'link', messagePrefix + 'link (c)' );
equal( tracker.hook.test._getLinkType('d abc', 'piwiktest.ext', true), 'link', messagePrefix + 'link (d)' );
}
var trackerUrl = tracker.getTrackerUrl();
var downloadExtensions = tracker.getConfigDownloadExtensions();
tracker.setTrackerUrl('');
tracker.setDownloadClasses([]);
tracker.setLinkClasses([]);
equal( tracker.hook.test._getLinkType('something', 'piwik.php', false), 'link', 'an empty tracker url should not match configtrackerurl' );
runTests('without tracker url, ');
tracker.setTrackerUrl('piwik.php');
tracker.setDownloadClasses([]);
tracker.setLinkClasses([]);
tracker.setDownloadExtensions(downloadExtensions);
runTests('with tracker url, ');
equal( tracker.hook.test._getLinkType('something', 'piwik.php', true), 0, 'matches tracker url and should never return any tracker Url' );
equal( tracker.hook.test._getLinkType('something', 'piwik.php?redirecturl=http://example.com/test.pdf', true), 0, 'should not match download as is config tracker url' );
equal( tracker.hook.test._getLinkType('something', 'piwik.php?redirecturl=http://example.com/', true), 0, 'should not match link as is config tracker url' );
tracker.setTrackerUrl(trackerUrl);
});
test("utf8_encode(), sha1()", function() {
expect(6);
var tracker = Piwik.getTracker();
equal( typeof tracker.hook.test._utf8_encode, 'function', 'utf8_encode' );
equal( tracker.hook.test._utf8_encode('hello world'), '<?php echo utf8_encode("hello world"); ?>', 'utf8_encode("hello world")' );
equal( tracker.hook.test._utf8_encode('Gesamtgröße'), '<?php echo utf8_encode("Gesamtgröße"); ?>', 'utf8_encode("Gesamtgröße")' );
equal( tracker.hook.test._utf8_encode('您好'), '<?php echo utf8_encode("您好"); ?>', 'utf8_encode("您好")' );
equal( typeof tracker.hook.test._sha1, 'function', 'sha1' );
equal( tracker.hook.test._sha1('hello world'), '<?php echo sha1("hello world"); ?>', 'sha1("hello world")' );
});
test("getRequest()", function() {
expect(1);
var tracker = Piwik.getTracker();
tracker.setCustomData("key is X", "value is Y");
equal( tracker.getRequest('hello=world').indexOf('hello=world&idsite=&rec=1&r='), 0);
});
// support for setCustomRequestProcessing( customRequestContentProcessingLogic )
test("Tracker setCustomRequestProcessing() and getRequest()", function() {
expect(4);
var tracker = Piwik.getTracker("trackerUrl", "42");
tracker.setCustomRequestProcessing(function(request){
var pairs = request.split('&');
var result = {};
pairs.forEach(function(pair) {
pair = pair.split('=');
result[pair[0]] = decodeURIComponent(pair[1] || '');
});
return JSON.stringify(result);
});
var json = JSON.parse(tracker.getRequest('hello=world'));
equal( json.hello, 'world');
equal( json.idsite, '42' );
equal( json.rec, 1);
ok( json.r.length > 0 );
});
// support for addPlugin( pluginName, pluginObj )
test("Tracker addPlugin() and getRequest()", function() {
expect(12);
var tracker = Piwik.getTracker();
var litp = (function() {
var lastInteractionType = "";
function ecommerce() { lastInteractionType = "ecommerce"; }
function event() { lastInteractionType = "event"; }
function goal() { lastInteractionType = "goal"; }
function link() { lastInteractionType = "link"; }
function load() { lastInteractionType = "load"; }
function log() { lastInteractionType = "log"; }
function ping() { lastInteractionType = "ping"; }
function sitesearch() { lastInteractionType = "sitesearch"; }
function unload() { lastInteractionType = "unload"; }
function getLastInteractionType() { return lastInteractionType; }
return {
ecommerce: ecommerce,
event : event,
goal : goal,
link : link,
load : load,
log : log,
ping: ping,
sitesearch : sitesearch,
unload : unload,
getLastInteractionType: getLastInteractionType
};
})();
tracker.addPlugin("interactionTypePlugin", litp);
ok(litp.getLastInteractionType() !== 'ecommerce');
tracker.trackEcommerceOrder("ORDER ID YES", 666.66);
ok(litp.getLastInteractionType() === 'ecommerce');
ok(litp.getLastInteractionType() !== 'event');
tracker.trackEvent("Event Category", "Event Action");
ok(litp.getLastInteractionType() === 'event');
ok(litp.getLastInteractionType() !== 'goal');
tracker.trackGoal(42);
ok(litp.getLastInteractionType() === 'goal');
ok(litp.getLastInteractionType() !== 'link');
tracker.trackLink("http://example.ca", "link");
ok(litp.getLastInteractionType() === 'link');
ok(litp.getLastInteractionType() !== 'log');
tracker.trackPageView();
ok(litp.getLastInteractionType() === 'log');
ok(litp.getLastInteractionType() !== 'sitesearch');
tracker.trackSiteSearch("search Keyword");
ok(litp.getLastInteractionType() === 'sitesearch');
});
test("prefixPropertyName()", function() {
expect(3);
var tracker = Piwik.getTracker();
equal( typeof tracker.hook.test._prefixPropertyName, 'function', 'prefixPropertyName' );
equal( tracker.hook.test._prefixPropertyName('', 'hidden'), 'hidden', 'no prefix' );
equal( tracker.hook.test._prefixPropertyName('webkit', 'hidden'), 'webkitHidden', 'webkit prefix' );
});
test("Internal timers and setLinkTrackingTimer()", function() {
expect(5);
var tracker = Piwik.getTracker();
ok( ! ( _paq instanceof Array ), "async tracker proxy not an array" );
equal( typeof tracker, typeof _paq, "async tracker proxy" );
var startTime, stopTime;
wait(1000); // in case there is a previous expireDateTime set
equal( typeof tracker.hook.test._beforeUnloadHandler, 'function', 'beforeUnloadHandler' );
startTime = new Date();
tracker.hook.test._beforeUnloadHandler();
stopTime = new Date();
var msSinceStarted = (stopTime.getTime() - startTime.getTime());
ok( msSinceStarted < 510, 'beforeUnloadHandler(): ' + msSinceStarted + ' was greater than 510 ' );
tracker.setLinkTrackingTimer(2000);
startTime = new Date();
tracker.trackPageView();
tracker.hook.test._beforeUnloadHandler();
stopTime = new Date();
var diffTime = (stopTime.getTime() - startTime.getTime());
ok( diffTime >= 2000, 'setLinkTrackingTimer()' );
});
test("Overlay URL Normalizer", function() {
expect(11);
var test = function(testCases) {
for (var i = 0; i < testCases.length; i++) {
var observed = Piwik_Overlay_UrlNormalizer.normalize(testCases[i][0]);
var expected = testCases[i][1];
equal(observed, expected, testCases[i][0]);
}
};
Piwik_Overlay_UrlNormalizer.initialize();
Piwik_Overlay_UrlNormalizer.setExcludedParameters(['excluded1', 'excluded2', 'excluded3']);
Piwik_Overlay_UrlNormalizer.setBaseHref(false);
Piwik_Overlay_UrlNormalizer.setCurrentDomain('example.com');
Piwik_Overlay_UrlNormalizer.setCurrentUrl('https://www.example.com/current/test.html?asdfasdf');
test([
[
'relative/path/',
'example.com/current/relative/path/'
], [
'http://www.example2.com/path/foo.html',
'example2.com/path/foo.html'
]
]);
Piwik_Overlay_UrlNormalizer.setCurrentDomain('www.example3.com');
Piwik_Overlay_UrlNormalizer.setCurrentUrl('http://example3.com/current/folder/');
test([[
'relative.html',
'example3.com/current/folder/relative.html'
]]);
Piwik_Overlay_UrlNormalizer.setBaseHref('http://example.com/base/');
test([
[
'http://www.example2.com/my/test/path.html?id=2&excluded2=foo#MyAnchor',
'example2.com/my/test/path.html?id=2#MyAnchor'
], [
'/my/test/foo/../path.html?excluded1=foo&excluded2=foo&excluded3=foo',
'example3.com/my/test/path.html'
], [
'path/./test//test///foo.bar?excluded2=foo&id=3',
'example.com/base/path/test/test/foo.bar?id=3'
], [
'path/./test//test///foo.bar?excluded2=foo#Anchor',
'example.com/base/path/test/test/foo.bar#Anchor'
], [
'https://example2.com//test.html?id=3&excluded1=foo&bar=baz#asdf',
'example2.com/test.html?id=3&bar=baz#asdf'
], [
'#',
''
], [
'#Anchor',
''
], [
'/',
'example3.com/'
]
]);
});
<?php
if ($sqlite) {
?>
module("request", {
setup: function () {
ok(true, "request.setup");
deleteCookies();
wait(500);
ok(document.cookie === "", "deleteCookies");
},
teardown: function () {
ok(true, "request.teardown");
}
});
test("tracking", function() {
expect(102);
/*
* Prevent Opera and HtmlUnit from performing the default action (i.e., load the href URL)
*/
var stopEvent = function (evt) {
evt = evt || window.event;
// evt.cancelBubble = true;
evt.returnValue = false;
if (evt.preventDefault)
evt.preventDefault();
// if (evt.stopPropagation)
// evt.stopPropagation();
// return false;
};
var tracker = Piwik.getTracker();
tracker.setTrackerUrl("piwik.php");
tracker.setSiteId(1);
var thirteenMonths = 1000 * 60 * 60 * 24 * 393;
strictEqual(thirteenMonths, tracker.getConfigVisitorCookieTimeout(), 'default visitor timeout should be 13 months');
var actualTimeout = tracker.getRemainingVisitorCookieTimeout();
var isAbout13Months = (thirteenMonths + 1000) > actualTimeout && ((thirteenMonths - 6000) < actualTimeout);
ok(isAbout13Months, 'remaining cookieTimeout should be about the deault tiemout of 13 months (' + thirteenMonths + ') but is ' + actualTimeout);
var visitorIdStart = tracker.getVisitorId();
// need to wait at least 1 second so that the cookie would be different, if it wasnt persisted
wait(2000);
var visitorIdStart2 = tracker.getVisitorId();
ok( visitorIdStart == visitorIdStart2, "getVisitorId() same when called twice with more than 1 second delay");
var customUrl = "http://localhost.localdomain/?utm_campaign=YEAH&utm_term=RIGHT!";
tracker.setCustomUrl(customUrl);
tracker.setCustomData({ "token" : getToken() });
var data = tracker.getCustomData();
ok( getToken() != "" && data.token == data["token"] && data.token == getToken(), "setCustomData() , getCustomData()" );
// Custom variables with integer/float values
tracker.setCustomVariable(1, 1, 2, "visit");
deepEqual( tracker.getCustomVariable(1, "visit"), ["1", "2"], "setCustomVariable() with integer name/value" );
tracker.setCustomVariable(1, 1, 0, "visit");
deepEqual( tracker.getCustomVariable(1, "visit"), ["1", "0"], "setCustomVariable() with integer name/value" );
tracker.setCustomVariable(2, 1.05, 2.11, "visit");
deepEqual( tracker.getCustomVariable(2, "visit"), ["1.05", "2.11"], "setCustomVariable() with integer name/value" );
// custom variables with undefined names or values
tracker.setCustomVariable(5);// setting a custom variable with no name and no value should not error
deepEqual( tracker.getCustomVariable(5), false, "getting a custom variable with no name nor value" );
deepEqual( tracker.getCustomVariable(55), false, "getting a custom variable with no name nor value" );
tracker.setCustomVariable(5, "new name");
deepEqual( tracker.getCustomVariable(5), ["new name", ""], "getting a custom variable with no value" );
tracker.deleteCustomVariable(5);
tracker.setDocumentTitle("PiwikTest");
var referrerUrl = "http://referrer.example.com/page/sub?query=test&test2=test3";
tracker.setReferrerUrl(referrerUrl);
referrerTimestamp = Math.round(new Date().getTime() / 1000);
tracker.trackPageView();
tracker.trackPageView("CustomTitleTest");
var customUrlShouldNotChangeCampaign = "http://localhost.localdomain/?utm_campaign=NONONONONONONO&utm_term=PLEASE NO!";
tracker.setCustomUrl(customUrl);
tracker.trackPageView();
var trackLinkCallbackFired = false;
var trackLinkCallback = function () {
trackLinkCallbackFired = true;
};
tracker.trackLink("http://example.ca", "link", { "token" : getToken() }, trackLinkCallback);
// async tracker proxy
_paq.push(["trackLink", "http://example.fr/async.zip", "download", { "token" : getToken() }]);
// push function
_paq.push([ function(t) {
tracker.trackLink("http://example.de", "link", { "token" : t });
}, getToken() ]);
tracker.setRequestMethod("POST");
tracker.trackGoal(42, 69, { "token" : getToken(), "boy" : "Michael", "girl" : "Mandy"});
piwik_log("CompatibilityLayer", 1, "piwik.php", { "token" : getToken() });
tracker.hook.test._addEventListener(_e("click8"), "click", stopEvent);
triggerEvent(_e("click8"), 'click');
tracker.enableLinkTracking();
tracker.setRequestMethod("GET");
var buttons = new Array("click1", "click2", "click3", "click4", "click5", "click6", "click7");
for (var i=0; i < buttons.length; i++) {
tracker.hook.test._addEventListener(_e(buttons[i]), "click", stopEvent);
triggerEvent(_e(buttons[i]), 'click');
}
var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() :
window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") :
null;
var clickDiv = _e("clickDiv"),
anchor = document.createElement("a");
anchor.id = "click9";
anchor.href = "http://example.us";
clickDiv.innerHTML = "";
clickDiv.appendChild(anchor);
tracker.addListener(anchor);
tracker.hook.test._addEventListener(anchor, "click", stopEvent);
triggerEvent(_e('click9'), 'click');
var visitorId1, visitorId2;
_paq.push([ function() {
visitorId1 = Piwik.getAsyncTracker().getVisitorId();
}]);
visitorId2 = tracker.getVisitorId();
ok( visitorId1 && visitorId1 != "" && visitorId2 && visitorId2 != "" && (visitorId1 == visitorId2), "getVisitorId()" );
var visitorInfo1, visitorInfo2;
// Visitor INFO + Attribution INFO tests
tracker.setReferrerUrl(referrerUrl);
_paq.push([ function() {
visitorInfo1 = Piwik.getAsyncTracker().getVisitorInfo();
attributionInfo1 = Piwik.getAsyncTracker().getAttributionInfo();
referrer1 = Piwik.getAsyncTracker().getAttributionReferrerUrl();
}]);
visitorInfo2 = tracker.getVisitorInfo();
ok( visitorInfo1 && visitorInfo2 && visitorInfo1.length == visitorInfo2.length, "getVisitorInfo()" );
for (var i = 0; i < 6; i++) {
ok( visitorInfo1[i] == visitorInfo2[i], "(loadVisitorId())["+i+"]" );
}
attributionInfo2 = tracker.getAttributionInfo();
ok( attributionInfo1 && attributionInfo2 && attributionInfo1.length == attributionInfo2.length, "getAttributionInfo()" );
referrer2 = tracker.getAttributionReferrerUrl();
ok( referrer2 == referrerUrl, "getAttributionReferrerUrl()" );
ok( referrer1 == referrerUrl, "async getAttributionReferrerUrl()" );
referrerTimestamp2 = tracker.getAttributionReferrerTimestamp();
ok( referrerTimestamp2 == referrerTimestamp, "tracker.getAttributionReferrerTimestamp()" );
campaignName2 = tracker.getAttributionCampaignName();
campaignKeyword2 = tracker.getAttributionCampaignKeyword();
ok( campaignName2 == "YEAH", "getAttributionCampaignName()");
ok( campaignKeyword2 == "RIGHT!", "getAttributionCampaignKeyword()");
// Test visitor ID at the start is the same at the end
var visitorIdEnd = tracker.getVisitorId();
ok( visitorIdStart == visitorIdEnd, "tracker.getVisitorId() same at the start and end of process");
// Custom variables
tracker.storeCustomVariablesInCookie();
tracker.setCookieNamePrefix("PREFIX");
tracker.setCustomVariable(1, "cookiename", "cookievalue");
deepEqual( tracker.getCustomVariable(1), ["cookiename", "cookievalue"], "setCustomVariable(cvarExists), getCustomVariable()" );
tracker.setCustomVariable(2, "cookiename2", "cookievalue2", "visit");
deepEqual( tracker.getCustomVariable(2), ["cookiename2", "cookievalue2"], "setCustomVariable(cvarExists), getCustomVariable()" );
deepEqual( tracker.getCustomVariable(2, "visit"), ["cookiename2", "cookievalue2"], "setCustomVariable(cvarExists), getCustomVariable()" );
deepEqual( tracker.getCustomVariable(2, 2), ["cookiename2", "cookievalue2"], "GA compability - setCustomVariable(cvarExists), getCustomVariable()" );
tracker.setCustomVariable(2, "cookiename2PAGE", "cookievalue2PAGE", "page");
deepEqual( tracker.getCustomVariable(2, "page"), ["cookiename2PAGE", "cookievalue2PAGE"], "setCustomVariable(cvarExists), getCustomVariable()" );
deepEqual( tracker.getCustomVariable(2, 3), ["cookiename2PAGE", "cookievalue2PAGE"], "GA compability - setCustomVariable(cvarExists), getCustomVariable()" );
tracker.setCustomVariable(2, "cookiename2EVENT", "cookievalue2EVENT", "event");
deepEqual( tracker.getCustomVariable(2, "event"), ["cookiename2EVENT", "cookievalue2EVENT"], "CustomVariable and event scope" );
tracker.trackPageView("SaveCustomVariableCookie");
// test Site Search
tracker.trackSiteSearch("No result keyword éà", "Search cat", 0);
tracker.trackSiteSearch("Keyword with 10 results", false, 10);
tracker.trackSiteSearch("search Keyword");
// Testing Custom events
tracker.setCustomVariable(1, "cvarEventName", "cvarEventValue", "event");
tracker.trackEvent("Event Category", "Event Action");
tracker.trackEvent("Event Category2", "Event Action2", "Event Name2");
tracker.trackEvent("Event Category3", "Event Action3", "Event Name3", 3.333);
//Ecommerce views
tracker.setEcommerceView( "", false, ["CATEGORY1","CATEGORY2"] );
deepEqual( tracker.getCustomVariable(3, "page"), false, "Ecommerce view SKU");
tracker.setEcommerceView( "SKUMultiple", false, ["CATEGORY1","CATEGORY2"] );
deepEqual( tracker.getCustomVariable(4, "page"), ["_pkn",""], "Ecommerce view Name");
deepEqual( tracker.getCustomVariable(5, "page"), ["_pkc","[\"CATEGORY1\",\"CATEGORY2\"]"], "Ecommerce view Category");
tracker.trackPageView("MultipleCategories");
var tracker2 = Piwik.getTracker();
tracker2.setTrackerUrl("piwik.php");
tracker2.setSiteId(1);
tracker2.storeCustomVariablesInCookie();
tracker2.setCustomData({ "token" : getToken() });
tracker2.setCookieNamePrefix("PREFIX");
deepEqual( tracker2.getCustomVariable(1), ["cookiename", "cookievalue"], "getCustomVariable(cvarExists) from cookie" );
ok( /PREFIX/.test( document.cookie ), "setCookieNamePrefix()" );
tracker2.deleteCustomVariable(1);
//console.log(tracker2.getCustomVariable(1));
ok( tracker2.getCustomVariable(1) === false, "VISIT deleteCustomVariable(), getCustomVariable() === false" );
tracker2.deleteCustomVariable(2, "page");
//console.log(tracker2.getCustomVariable(2, "page"));
ok( tracker2.getCustomVariable(2, "page") === false, "PAGE deleteCustomVariable(), getCustomVariable() === false" );
tracker2.trackPageView("DeleteCustomVariableCookie");
var tracker3 = Piwik.getTracker();
tracker3.setTrackerUrl("piwik.php");
tracker3.setSiteId(1);
tracker3.setCustomData({ "token" : getToken() });
tracker3.setCookieNamePrefix("PREFIX");
ok( tracker3.getCustomVariable(1) === false, "getCustomVariable(cvarDeleted) from cookie === false" );
// Ecommerce Views
tracker3.setEcommerceView( "SKU", "NAME HERE", "CATEGORY HERE" );
deepEqual( tracker3.getCustomVariable(3, "page"), ["_pks","SKU"], "Ecommerce view SKU");
deepEqual( tracker3.getCustomVariable(4, "page"), ["_pkn","NAME HERE"], "Ecommerce view Name");
deepEqual( tracker3.getCustomVariable(5, "page"), ["_pkc","CATEGORY HERE"], "Ecommerce view Category");
tracker3.trackPageView("EcommerceView");
//Ecommerce tests
tracker3.addEcommerceItem("SKU PRODUCT", "PRODUCT NAME", "PRODUCT CATEGORY", 11.1111, 2);
tracker3.addEcommerceItem("SKU PRODUCT", "random", "random PRODUCT CATEGORY", 11.1111, 2);
tracker3.addEcommerceItem("SKU ONLY SKU", "", "", "", "");
tracker3.addEcommerceItem("SKU ONLY NAME", "PRODUCT NAME 2", "", "");
tracker3.addEcommerceItem("SKU NO PRICE NO QUANTITY", "PRODUCT NAME 3", "CATEGORY", "", "" );
tracker3.addEcommerceItem("SKU ONLY" );
tracker3.trackEcommerceCartUpdate( 555.55 );
tracker3.trackEcommerceOrder( "ORDER ID YES", 666.66, 333, 222, 111, 1 );
// do not track
tracker3.setDoNotTrack(false);
// User ID
var userIdString = 'userid@mydomain.org';
tracker3.setUserId(userIdString);
equal(userIdString, tracker3.getUserId());
// Append tracking url parameter
tracker3.appendToTrackingUrl("appended=1&appended2=value");
// Track pageview
tracker3.trackPageView("DoTrack");
// Firefox 9: navigator.doNotTrack is read-only
navigator.doNotTrack = "yes";
if (navigator.doNotTrack === "yes")
{
tracker3.setDoNotTrack(true);
tracker3.trackPageView("DoNotTrack");
}
// Testing JavaScriptErrorTracking START
var oldOnError = window.onerror;
var customOnErrorInvoked = false;
window.onerror = function (message, url, line, column, error) {
customOnErrorInvoked = true;
equal(message, 'Uncaught Error: The message', 'message forwarded to custom onerror handler');
equal(url, 'http://piwik.org/path/to/file.js?cb=34343', 'url forwarded to custom onerror handler');
equal(line, 44, 'line forwarded to custom onerror handler');
equal(column, 12, 'column forwarded to custom onerror handler');
ok(error instanceof Error, 'error forwarded to custom onerror handler');
};
tracker.enableJSErrorTracking();
window.onerror('Uncaught Error: The message', 'http://piwik.org/path/to/file.js?cb=34343', 44, 12, new Error('The message'));
ok(customOnErrorInvoked, "Custom onerror handler was called as expected");
// delete existing onerror handler and setup tracking again
window.onerror = customOnErrorInvoked = false;
tracker2.enableJSErrorTracking();
window.onerror('Second Error: With less data', 'http://piwik.org/path/to/file.js?cb=3kfkf', 45);
ok(!customOnErrorInvoked, "Custom onerror handler was ignored as expected");
window.onerror = oldOnError;
// Testing JavaScriptErrorTracking END
stop();
setTimeout(function() {
xhr.open("GET", "piwik.php?requests=" + getToken(), false);
xhr.send(null);
results = xhr.responseText;
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "30", "count tracking events" );
// firing callback
ok( trackLinkCallbackFired, "trackLink() callback fired" );
// tracking requests
ok( /PiwikTest/.test( results ), "trackPageView(), setDocumentTitle()" );
ok( results.indexOf("tests/javascript/piwik.php?action_name=Asynchronous%20Tracker%20ONE&idsite=1&rec=1") >= 0 , "async trackPageView() called before setTrackerUrl() should work" );
ok( /Asynchronous%20tracking%20TWO/.test( results ), "async trackPageView() called after another trackPageView()" );
ok( /CustomTitleTest/.test( results ), "trackPageView(customTitle)" );
ok( ! /click.example.com/.test( results ), "click: ignore href=javascript" );
ok( /example.ca/.test( results ), "trackLink()" );
ok( /example.fr/.test( results ), "async trackLink()" );
ok( /example.de/.test( results ), "push function" );
ok( /example.us/.test( results ), "addListener()" );
ok( /example.net/.test( results ), "setRequestMethod(GET), click: implicit outlink (by outbound URL)" );
ok( /example.html/.test( results ), "click: explicit outlink" );
ok( /example.pdf/.test( results ), "click: implicit download (by file extension)" );
ok( /example.word/.test( results ), "click: explicit download" );
ok( ! /example.exe/.test( results ), "enableLinkTracking()" );
ok( ! /example.php/.test( results ), "click: ignored example.php" );
ok( ! /example.org/.test( results ), "click: ignored example.org" );
ok( /idgoal=42.*?revenue=69.*?Michael.*?Mandy/.test( results ), "setRequestMethod(POST), trackGoal()" );
ok( /CompatibilityLayer/.test( results ), "piwik_log(): compatibility layer" );
ok( /localhost.localdomain/.test( results ), "setCustomUrl()" );
ok( /referrer.example.com/.test( results ), "setReferrerUrl()" );
ok( /cookiename/.test( results ) && /cookievalue/.test( results ), "tracking request contains custom variable" );
ok( /DeleteCustomVariableCookie/.test( results ), "tracking request deleting custom variable" );
ok( /DoTrack/.test( results ), "setDoNotTrack(false)" );
ok( ! /DoNotTrack/.test( results ), "setDoNotTrack(true)" );
// Test Custom variables
ok( /SaveCustomVariableCookie.*&cvar=%7B%222%22%3A%5B%22cookiename2PAGE%22%2C%22cookievalue2PAGE%22%5D%7D.*&_cvar=%7B%221%22%3A%5B%22cookiename%22%2C%22cookievalue%22%5D%2C%222%22%3A%5B%22cookiename2%22%2C%22cookievalue2%22%5D%7D/.test(results), "test custom vars are set");
// Test campaign parameters set
ok( /&_rcn=YEAH&_rck=RIGHT!/.test( results), "Test campaign parameters found");
ok( /&_ref=http%3A%2F%2Freferrer.example.com%2Fpage%2Fsub%3Fquery%3Dtest%26test2%3Dtest3/.test( results), "Test cookie Ref URL found ");
// Test site search
ok( /search=No%20result%20keyword%20%C3%A9%C3%A0&search_cat=Search%20cat&search_count=0&idsite=1/.test(results), "site search, cat, 0 result ");
ok( /search=Keyword%20with%2010%20results&search_count=10&idsite=1/.test(results), "site search, no cat, 10 results ");
ok( /search=search%20Keyword&idsite=1/.test(results), "site search, no cat, no results count ");
// Test events
ok( /(e_c=Event%20Category&e_a=Event%20Action&idsite=1).*(&e_cvar=%7B%221%22%3A%5B%22cvarEventName%22%2C%22cvarEventValue%22%5D%2C%222%22%3A%5B%22cookiename2EVENT%22%2C%22cookievalue2EVENT%22%5D%7D)/.test(results), "event Category + Action + Custom Variable");
ok( /e_c=Event%20Category2&e_a=Event%20Action2&e_n=Event%20Name2&idsite=1/.test(results), "event Category + Action + Name");
ok( /e_c=Event%20Category3&e_a=Event%20Action3&e_n=Event%20Name3&e_v=3.333&idsite=1/.test(results), "event Category + Action + Name + Value");
// ecommerce view
ok( /(EcommerceView).*(&cvar=%7B%225%22%3A%5B%22_pkc%22%2C%22CATEGORY%20HERE%22%5D%2C%223%22%3A%5B%22_pks%22%2C%22SKU%22%5D%2C%224%22%3A%5B%22_pkn%22%2C%22NAME%20HERE%22%5D%7D)/.test(results)
|| /(EcommerceView).*(&cvar=%7B%223%22%3A%5B%22_pks%22%2C%22SKU%22%5D%2C%224%22%3A%5B%22_pkn%22%2C%22NAME%20HERE%22%5D%2C%225%22%3A%5B%22_pkc%22%2C%22CATEGORY%20HERE%22%5D%7D)/.test(results), "ecommerce view");
// ecommerce view multiple categories
ok( /(MultipleCategories).*(&cvar=%7B%222%22%3A%5B%22cookiename2PAGE%22%2C%22cookievalue2PAGE%22%5D%2C%225%22%3A%5B%22_pkc%22%2C%22%5B%5C%22CATEGORY1%5C%22%2C%5C%22CATEGORY2%5C%22%5D%22%5D%2C%223%22%3A%5B%22_pks%22%2C%22SKUMultiple%22%5D%2C%224%22%3A%5B%22_pkn%22%2C%22%22%5D%7D)/.test(results)
|| /(MultipleCategories).*(&cvar=%7B%222%22%3A%5B%22cookiename2PAGE%22%2C%22cookievalue2PAGE%22%5D%2C%223%22%3A%5B%22_pks%22%2C%22SKUMultiple%22%5D%2C%224%22%3A%5B%22_pkn%22%2C%22%22%5D%2C%225%22%3A%5B%22_pkc%22%2C%22%5B%5C%22CATEGORY1%5C%22%2C%5C%22CATEGORY2%5C%22%5D%22%5D%7D)/.test(results), "ecommerce view multiple categories");
// Ecommerce order
ok( /idgoal=0&ec_id=ORDER%20ID%20YES&revenue=666.66&ec_st=333&ec_tx=222&ec_sh=111&ec_dt=1&ec_items=%5B%5B%22SKU%20PRODUCT%22%2C%22random%22%2C%22random%20PRODUCT%20CATEGORY%22%2C11.1111%2C2%5D%2C%5B%22SKU%20ONLY%20SKU%22%2C%22%22%2C%22%22%2C0%2C1%5D%2C%5B%22SKU%20ONLY%20NAME%22%2C%22PRODUCT%20NAME%202%22%2C%22%22%2C0%2C1%5D%2C%5B%22SKU%20NO%20PRICE%20NO%20QUANTITY%22%2C%22PRODUCT%20NAME%203%22%2C%22CATEGORY%22%2C0%2C1%5D%2C%5B%22SKU%20ONLY%22%2C%22%22%2C%22%22%2C0%2C1%5D%5D/.test( results ), "logEcommerceOrder() with items" );
// Not set for the first ecommerce order
ok( ! /idgoal=0&ec_id=ORDER%20ID.*_ects=1/.test(results), "Ecommerce last timestamp set");
// Ecommerce last timestamp set properly for subsequent page view
ok( /DoTrack.*_ects=1/.test(results), "Ecommerce last timestamp set");
// Cart update
ok( /idgoal=0&revenue=555.55&ec_items=%5B%5B%22SKU%20PRODUCT%22%2C%22random%22%2C%22random%20PRODUCT%20CATEGORY%22%2C11.1111%2C2%5D%2C%5B%22SKU%20ONLY%20SKU%22%2C%22%22%2C%22%22%2C0%2C1%5D%2C%5B%22SKU%20ONLY%20NAME%22%2C%22PRODUCT%20NAME%202%22%2C%22%22%2C0%2C1%5D%2C%5B%22SKU%20NO%20PRICE%20NO%20QUANTITY%22%2C%22PRODUCT%20NAME%203%22%2C%22CATEGORY%22%2C0%2C1%5D%2C%5B%22SKU%20ONLY%22%2C%22%22%2C%22%22%2C0%2C1%5D%5D/.test( results ), "logEcommerceCartUpdate() with items" );
// parameters inserted by plugin hooks
ok( /testlog/.test( results ), "plugin hook log" );
ok( /testlink/.test( results ), "plugin hook link" );
ok( /testgoal/.test( results ), "plugin hook goal" );
// Testing the Tracking URL append
ok( /&appended=1&appended2=value/.test( results ), "appendToTrackingUrl(query) function");
// Testing the User ID setter
ok( /&uid=userid%40mydomain.org/.test( results ), "setUserId(userId) function");
// Testing the JavaScript Error Tracking
ok( /e_c=JavaScript%20Errors&e_a=http%3A%2F%2Fpiwik.org%2Fpath%2Fto%2Ffile.js%3Fcb%3D34343%3A44%3A12&e_n=Uncaught%20Error%3A%20The%20message&idsite=1/.test( results ), "enableJSErrorTracking() function with predefined onerror event");
ok( /e_c=JavaScript%20Errors&e_a=http%3A%2F%2Fpiwik.org%2Fpath%2Fto%2Ffile.js%3Fcb%3D3kfkf%3A45&e_n=Second%20Error%3A%20With%20less%20data&idsite=1/.test( results ), "enableJSErrorTracking() function without predefined onerror event and less parameters");
start();
}, 5000);
});
test("trackingContent", function() {
expect(81);
function assertTrackingRequest(actual, expectedStartsWith, message)
{
if (!message) {
message = '';
} else {
message += ', ';
}
expectedStartsWith = '<span>' + toAbsolutePath('piwik.php') + '?' + expectedStartsWith;
strictEqual(actual.indexOf(expectedStartsWith), 0, message + actual + ' should start with ' + expectedStartsWith);
strictEqual(actual.indexOf('&idsite=1&rec=1'), expectedStartsWith.length);
}
function resetTracker(track, token, replace)
{
tracker.clearTrackedContentImpressions();
tracker.clearEnableTrackOnlyVisibleContent();
tracker.setCustomData('token', token);
scrollToTop();
}
var token = getContentToken();
var tracker = Piwik.getTracker();
tracker.setTrackerUrl("piwik.php");
tracker.setSiteId(1);
resetTracker(tracker, token);
var visitorIdStart = tracker.getVisitorId();
// need to wait at least 1 second so that the cookie would be different, if it wasnt persisted
wait(2000);
var origin = getOrigin();
var originEncoded = window.encodeURIComponent(origin);
var actual, expected, trackerUrl;
var contentBlocks = [
null,
{
"name": toAbsolutePath("img1-en.jpg"),
"piece": toAbsoluteUrl("img1-en.jpg"),
"target": ""
},
{
"name": "img.jpg",
"piece": "img.jpg",
"target": "http://img2.example.com"
},
{
"name": toAbsolutePath("img3-en.jpg"),
"piece": toAbsoluteUrl("img3-en.jpg"),
"target": "http://img3.example.com"
},
{
"name": "My content 4",
"piece": "My content 4",
"target": "http://img4.example.com"
},
{
"name": "My Ad 5",
"piece": "http://img5.example.com/path/xyz.jpg",
"target": origin + "/anylink5"
},
{
"name": "http://www.example.com/path/xyz.jpg",
"piece": "http://www.example.com/path/xyz.jpg",
"target": "http://img6.example.com"
},
{
"name": "My Ad 7",
"piece": "Unknown",
"target": "http://img7.example.com"
}
];
tracker.trackAllContentImpressions();
strictEqual(tracker.getTrackedContentImpressions().length, 0, 'getTrackedContentImpressions, there is no content block to track');
tracker.trackContentImpressionsWithinNode(_e('other'));
strictEqual(tracker.getTrackedContentImpressions().length, 0, 'getTrackedContentImpressionsWithinNode, there is no content block to track');
tracker.trackContentInteractionNode();
strictEqual(tracker.getTrackedContentImpressions().length, 0, 'trackContentInteractionNode, no node given should not track anything');
setupContentTrackingFixture('trackingContent', document.body);
tracker.trackAllContentImpressions();
strictEqual(tracker.getTrackedContentImpressions().length, 7, 'should mark 7 content blocks as tracked');
wait(300);
var token2 = '2' + token;
resetTracker(tracker, token2);
tracker.trackContentImpressionsWithinNode(_s('#block1'));
expected = [contentBlocks[4], contentBlocks[3], contentBlocks[2]];
propEqual(tracker.getTrackedContentImpressions(), expected, 'should mark 3 content blocks as tracked');
tracker.clearTrackedContentImpressions();
tracker.trackContentImpressionsWithinNode(_e('click1'));
strictEqual(tracker.getTrackedContentImpressions().length, 0, 'should not track anything as does not contain content block');
wait(300);
var token3 = '3' + token;
resetTracker(tracker, token3);
tracker.trackContentImpression(); // should not track anything as name is required
tracker.trackContentImpression('MyName'); // piece should default to Unknown
wait(300);
tracker.trackContentImpression('Any://Name', 'AnyPiece?', 'http://www.example.com');
strictEqual(tracker.getTrackedContentImpressions().length, 0, 'manual impression call should not be marked as already tracked');
wait(300);
var token4 = '4' + token;
resetTracker(tracker, token4);
tracker.trackContentInteraction(); // should not track anything as interaction and name is required
tracker.trackContentInteraction('Clicki'); // should not track anything as interaction and name is required
tracker.trackContentInteraction('Clicke', 'IntName'); // should use default for piece and ignore target as it is not set
wait(500);
tracker.trackContentInteraction('Clicki', 'IntN:/ame', 'IntPiece?', 'http://int.example.com');
wait(300);
setupContentTrackingFixture('trackingContent', document.body);
var token5 = '5' + token;
resetTracker(tracker, token5);
tracker.trackContentInteractionNode(_s('#ex5'), 'Clicki?iii');
wait(300);
var token6 = '6' + token;
resetTracker(tracker, token6);
tracker.enableTrackOnlyVisibleContent(false, 0);
tracker.trackAllContentImpressions();
expected = [contentBlocks[7], contentBlocks[6], contentBlocks[5], contentBlocks[1], contentBlocks[4], contentBlocks[3], contentBlocks[2]];
propEqual(tracker.getTrackedContentImpressions().length, 7, 'should still track all impressions even if visible enabled');
var token7 = '7' + token;
resetTracker(tracker, token7);
tracker.enableTrackOnlyVisibleContent(false, 0);
tracker.trackContentImpressionsWithinNode();
strictEqual(tracker.getTrackedContentImpressions().length, 0, 'should not track anything, no node provided');
tracker.trackContentImpressionsWithinNode(_s('#block1'));
strictEqual(tracker.getTrackedContentImpressions().length, 0, 'should not track any block since all not visible');
tracker.trackContentImpressionsWithinNode(_s('#block2'));
expected = [contentBlocks[6], contentBlocks[5]];
propEqual(tracker.getTrackedContentImpressions(), expected, 'should track the two visible ones');
wait(300);
var token8 = '8' + token;
resetTracker(tracker, token8);
tracker.trackVisibleContentImpressions(false, 0, tracker);
expected = [contentBlocks[6], contentBlocks[5], contentBlocks[1]];
propEqual(tracker.getTrackedContentImpressions(), expected, 'should only track all visible impressions');
wait(300);
// test detection of content via interval
var token9 = '9' + token;
var token10 = '10' + token;
resetTracker(tracker, token9);
tracker.trackVisibleContentImpressions(false, 500);
expected = [contentBlocks[6], contentBlocks[5], contentBlocks[1]];
propEqual(tracker.getTrackedContentImpressions(), expected, 'should only track all visible impressions, timeInterval');
_s('#block1').style.display = 'block';
scrollToTop();
stop();
setTimeout(function () {
expected = [contentBlocks[6], contentBlocks[5], contentBlocks[1], contentBlocks[4], contentBlocks[3], contentBlocks[2]];
propEqual(tracker.getTrackedContentImpressions(), expected, 'should now have tracked 6 impressions via time interval');
tracker.clearEnableTrackOnlyVisibleContent(); // stop visible content time interval check
// test detection of content via scroll
setTimeout(function () {
_s('#block1').style.display = 'none';
resetTracker(tracker, token10);
tracker.trackVisibleContentImpressions(true, 0);
expected = [contentBlocks[6], contentBlocks[5], contentBlocks[1]];
propEqual(tracker.getTrackedContentImpressions(), expected, 'should track 3 initial visible impressions, scroll');
_s('#block1').style.display = 'block';
window.scrollTo(0, 10); // should trigger scroll event
setTimeout(function () {
strictEqual(tracker.getTrackedContentImpressions().length, 6, 'should detect 3 more afer scroll');
tracker.clearEnableTrackOnlyVisibleContent(); // stop visible content scroll interval check
start();
}, 700);
}, 400); // wait for time interval to stop.
}, 1500);
var trackingRequests = [
null,
'c_n=' + toEncodedAbsolutePath('img1-en.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img1-en.jpg'),
'c_n=img.jpg&c_p=img.jpg&c_t=http%3A%2F%2Fimg2.example.com',
'c_n=' + toEncodedAbsolutePath('img3-en.jpg') + '&c_p=' + toEncodedAbsoluteUrl('img3-en.jpg') + '&c_t=http%3A%2F%2Fimg3.example.com',
'c_n=My%20content%204&c_p=My%20content%204&c_t=http%3A%2F%2Fimg4.example.com',
'c_n=My%20Ad%205&c_p=http%3A%2F%2Fimg5.example.com%2Fpath%2Fxyz.jpg&c_t=' + originEncoded + '%2Fanylink5',
'c_n=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_p=http%3A%2F%2Fwww.example.com%2Fpath%2Fxyz.jpg&c_t=http%3A%2F%2Fimg6.example.com',
'c_n=My%20Ad%207&c_p=Unknown&c_t=http%3A%2F%2Fimg7.example.com'
];
stop();
setTimeout(function() {
removeContentTrackingFixture();
// trackAllContentImpressions()
var results = fetchTrackedRequests(token);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "7", "count trackAllContentImpressions requests. all content blocks should be tracked" );
var requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], trackingRequests[7]);
assertTrackingRequest(requests[1], trackingRequests[6]);
assertTrackingRequest(requests[2], trackingRequests[5]);
assertTrackingRequest(requests[3], trackingRequests[4]);
assertTrackingRequest(requests[4], trackingRequests[3]);
assertTrackingRequest(requests[5], trackingRequests[2]);
assertTrackingRequest(requests[6], trackingRequests[1]);
// trackContentImpressionsWithinNode()
results = fetchTrackedRequests(token2);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "3", "count trackContentImpressionsWithinNode requests. should track only content blocks within node" );
requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], trackingRequests[4]);
assertTrackingRequest(requests[1], trackingRequests[3]);
assertTrackingRequest(requests[2], trackingRequests[2]);
// trackContentImpression()
results = fetchTrackedRequests(token3);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "2", "count trackContentImpression requests. " );
requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
var firstRequest = 0;
var secondRequest = 1;
if (-1 === requests[0].indexOf('MyName')) {
firstRequest = 1;
secondRequest = 0;
}
assertTrackingRequest(requests[firstRequest], 'c_n=MyName&c_p=Unknown');
assertTrackingRequest(requests[secondRequest], 'c_n=Any%3A%2F%2FName&c_p=AnyPiece%3F&c_t=http%3A%2F%2Fwww.example.com');
// trackContentInteraction()
results = fetchTrackedRequests(token4);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "2", "count trackContentInteraction requests." );
requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
firstRequest = 0;
secondRequest = 1;
if (-1 === requests[0].indexOf('IntName')) {
firstRequest = 1;
secondRequest = 0;
}
assertTrackingRequest(requests[firstRequest], 'c_i=Clicke&c_n=IntName&c_p=Unknown');
assertTrackingRequest(requests[secondRequest], 'c_i=Clicki&c_n=IntN%3A%2Fame&c_p=IntPiece%3F&c_t=http%3A%2F%2Fint.example.com');
// trackContentInteractionNode()
results = fetchTrackedRequests(token5);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "1", "count trackContentInteractionNode requests." );
requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], 'c_i=Clicki%3Fiii&c_n=My%20Ad%205&c_p=http%3A%2F%2Fimg5.example.com%2Fpath%2Fxyz.jpg&c_t=' + originEncoded + '%2Fanylink5');
// enableTrackOnlyVisibleContent() && trackAllContentImpressions()
results = fetchTrackedRequests(token6);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "7", "count enabledVisibleContentImpressions requests." );
// enableTrackOnlyVisibleContent() && trackContentImpressionsWithinNode()
results = fetchTrackedRequests(token7);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "2", "count enabledVisibleContentImpressionsWithinNode requests." );
requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], trackingRequests[6]);
assertTrackingRequest(requests[1], trackingRequests[5]);
// trackVisibleContentImpressions()
results = fetchTrackedRequests(token8);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "3", "count enabledVisibleContentImpressions requests." );
requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], trackingRequests[6]);
assertTrackingRequest(requests[1], trackingRequests[5]);
assertTrackingRequest(requests[2], trackingRequests[1]);
// enableTrackOnlyVisibleContent(false, 500)
results = fetchTrackedRequests(token9);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "6", "count automatically tracked requests via time interval. " );
var requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], trackingRequests[6]);
assertTrackingRequest(requests[1], trackingRequests[5]);
assertTrackingRequest(requests[2], trackingRequests[1]);
assertTrackingRequest(requests[3], trackingRequests[4]);
assertTrackingRequest(requests[4], trackingRequests[3]);
assertTrackingRequest(requests[5], trackingRequests[2]);
// enableTrackOnlyVisibleContent(true, 0)
results = fetchTrackedRequests(token10);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "6", "count automatically tracked requests, via scroll. " );
start();
}, 7000);
});
test("trackingContentInteractionInteractive", function() {
expect(18);
function assertTrackingRequest(actual, expectedStartsWith, message)
{
if (!message) {
message = '';
} else {
message += ', ';
}
expectedStartsWith = '<span>' + toAbsolutePath('piwik.php') + '?' + expectedStartsWith;
strictEqual(actual.indexOf(expectedStartsWith), 0, message + actual + ' should start with ' + expectedStartsWith);
strictEqual(actual.indexOf('&idsite=1&rec=1'), expectedStartsWith.length);
}
function resetTracker(track, token)
{
tracker.clearTrackedContentImpressions();
tracker.clearEnableTrackOnlyVisibleContent();
tracker.setCustomData('token', token);
scrollToTop();
}
function preventClickDefault(selector)
{
$(_s(selector)).on('click', function (event) { event.preventDefault(); })
}
var token = getContentToken() + 'i'; // interactive namespace
var origin = getOrigin();
var originEncoded = window.encodeURIComponent(origin);
var actual, expected, trackerUrl;
var tracker = Piwik.getTracker();
tracker.setTrackerUrl("piwik.php");
tracker.setSiteId(1);
resetTracker(tracker, token);
var visitorIdStart = tracker.getVisitorId();
// need to wait at least 1 second so that the cookie would be different, if it wasnt persisted
wait(2000);
setupContentTrackingFixture('trackingContent', document.body);
tracker.trackAllContentImpressions();
strictEqual(tracker.getTrackedContentImpressions().length, 7, 'should mark 7 content blocks as tracked');
var token1 = '1' + token;
resetTracker(tracker, token1);
preventClickDefault('#isWithinOutlink');
triggerEvent(_s('#isWithinOutlink'), 'click'); // should only track interaction and no outlink as link tracking not enabled
tracker.enableLinkTracking();
wait(300);
var token2 = '2' + token;
resetTracker(tracker, token2);
preventClickDefault('#isWithinOutlink');
triggerEvent(_s('#isWithinOutlink'), 'click'); // click on an element within a link
wait(300);
var token3 = '3' + token;
resetTracker(tracker, token3);
preventClickDefault('#isOutlink');
triggerEvent(_s('#isOutlink'), 'click'); // click on the link element itself
wait(300);
var token4 = '4' + token;
resetTracker(tracker, token4);
preventClickDefault('#notWithinTarget');
triggerEvent(_s('#notWithinTarget'), 'click'); // this element is in a content block, there is a content target, but this element is not child of content target
var token5 = '5' + token;
resetTracker(tracker, token5);
preventClickDefault('#internalLink');
var expectedLink = toAbsoluteUrl('piwik.php') + '?redirecturl=' + toEncodedAbsoluteUrl('/anylink5') + '&c_i=click&c_n=My%20Ad%205&c_p=http%3A%2F%2Fimg5.example.com%2Fpath%2Fxyz.jpg&c_t=' + originEncoded + '%2Fanylink5&idsite=1&rec=1';
var newHref = _s('#internalLink').href;
strictEqual(0, newHref.indexOf(expectedLink), 'replaced href is replaced: ' + newHref); // make sure was already replace by trackContentImpressions()
strictEqual(_s('#internalLink').wasContentTargetAttrReplaced, true, 'has to be marked as replaced so we know we have to update content target again in case the url changes meanwhile');
// now we are going to change the link to see whether it will be replaced again
tracker.getContent().setHrefAttribute(_s('#internalLink'), '/newlink');
wait(300);
triggerEvent(_s('#internalLink'), 'click'); // should replace href php
newHref = _s('#internalLink').href;
expectedLink = toAbsoluteUrl('piwik.php') + '?redirecturl=' + toEncodedAbsoluteUrl('/newlink') + '&c_i=click&c_n=My%20Ad%205&c_p=http%3A%2F%2Fimg5.example.com%2Fpath%2Fxyz.jpg&c_t=' + originEncoded + '%2Fnewlink&idsite=1&rec=1';
strictEqual(0, newHref.indexOf(expectedLink), 'replaced href2 is replaced again: ' + newHref); // make sure was already replace by trackContentImpressions()
wait(300);
stop();
setTimeout(function() {
removeContentTrackingFixture();
var results = fetchTrackedRequests(token1);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "1", "count #isWithinOutlink requests as interaction. " );
var requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], 'c_i=click&c_n=img.jpg&c_p=img.jpg&c_t=http%3A%2F%2Fimg2.example.com');
results = fetchTrackedRequests(token2);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "1", "count #isWithinOutlink requests as outlink + interaction. " );
requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], 'link=http%3A%2F%2Fimg2.example.com%2F&c_i=click&c_n=img.jpg&c_p=img.jpg&c_t=http%3A%2F%2Fimg2.example.com');
results = fetchTrackedRequests(token3);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "1", "count #isOutlink requests as outlink + interaction. " );
requests = results.match(/<span\>(.*?)\<\/span\>/g);
requests.shift();
assertTrackingRequest(requests[0], 'link=http%3A%2F%2Fimg2.example.com%2F&c_i=click&c_n=img.jpg&c_p=img.jpg&c_t=http%3A%2F%2Fimg2.example.com');
results = fetchTrackedRequests(token4);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "0", "count #notWithinTarget requests." );
results = fetchTrackedRequests(token5);
equal( (/<span\>([0-9]+)\<\/span\>/.exec(results))[1], "0", "count #internalLink requests. (would be tracked via redirect which we do not want to perform in test and it is tested above)" );
start();
}, 4000);
});
<?php
}
?>
}
function addEventListener(element, eventType, eventHandler, useCapture) {
if (element.addEventListener) {
element.addEventListener(eventType, eventHandler, useCapture);
return true;
}
if (element.attachEvent) {
return element.attachEvent('on' + eventType, eventHandler);
}
element['on' + eventType] = eventHandler;
}
(function (f) {
if (document.addEventListener) {
addEventListener(document, 'DOMContentLoaded', function ready() {
document.removeEventListener('DOMContentLoaded', ready, false);
f();
});
} else if (document.attachEvent) {
document.attachEvent('onreadystatechange', function ready() {
if (document.readyState === 'complete') {
document.detachEvent('onreadystatechange', ready);
f();
}
});
if (document.documentElement.doScroll && window === top) {
(function ready() {
if (!hasLoaded) {
try {
document.documentElement.doScroll('left');
} catch (error) {
setTimeout(ready, 0);
return;
}
f();
}
}());
}
}
addEventListener(window, 'load', f, false);
})(PiwikTest);
</script>
<div id="jashDiv">
<a href="#" onclick="javascript:loadJash();" title="Open JavaScript Shell"><img id="title" src="gnome-terminal.png" border="0" width="24" height="24" /></a>
</div>
</body>
</html>
|