diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewCategory__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewCategory__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..3de4537c1f435d87b8604c9958db35508ae96e70
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewCategory__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,8 @@
+
+
+ Category1
+ Category2
+ Category3
+ Category4
+ Category7
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewCategory__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewCategory__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..795e37d874c8f6ee5c69cef703936aad4bf6d2db
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewCategory__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 6
+ 6
+ 6
+ 6
+ 5
+ 1
+ 100%
+ 1
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewName__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewName__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..30d4eb9a25af19c14a394eeb1b7f230ac3cdefb4
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewName__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ MyName
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewName__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewName__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..795e37d874c8f6ee5c69cef703936aad4bf6d2db
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewName__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 6
+ 6
+ 6
+ 6
+ 5
+ 1
+ 100%
+ 1
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewPrice__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewPrice__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..2673898acdd2899cffcac91b1cd934086fbf7e76
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewPrice__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ 17.4
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewPrice__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewPrice__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..795e37d874c8f6ee5c69cef703936aad4bf6d2db
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewPrice__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 6
+ 6
+ 6
+ 6
+ 5
+ 1
+ 100%
+ 1
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewSku__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewSku__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e31ca4dd4f3d3d8ae11de29233e9ffecb2aa9a8d
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewSku__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ Custom SKU
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewSku__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewSku__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..795e37d874c8f6ee5c69cef703936aad4bf6d2db
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_productViewSku__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 6
+ 6
+ 6
+ 6
+ 5
+ 1
+ 100%
+ 1
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_profilable__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_profilable__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..727df89075bc503fcf5af62e4014e402415cf003
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_profilable__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,5 @@
+
+
+ 0
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_profilable__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_profilable__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..d8bcdace18e8112b2726ba46257b048d489879f9
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_profilable__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 0
+ 0
+ 0
+ 0
+ 0
+ 0
+ 0%
+ 0
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_provider__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_provider__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6cf1af346e992b077af21e6bc1a092c8617d224b
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_provider__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,5 @@
+
+
+ comcast.net
+ awesomeisp.com
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_provider__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_provider__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..c51a1bc13ddcf73b5147d5085963724dfcceada2
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_provider__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 2
+ 4
+ 2
+ 1
+ 1261
+ 3
+ 50%
+ 2
+ 631
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerKeyword__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerKeyword__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..2959b13a9cc9cc1a443b5499ffaa1413ce319fca
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerKeyword__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ wikileaks ftw
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerKeyword__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerKeyword__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dfa3a2062361e1f2127a84e9e33202e73a513ee2
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerKeyword__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 1
+ 1
+ 1
+ 1
+ 0
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerName__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerName__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6ca20195970c309a4323b78b8d51fc60674ba6bf
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerName__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ Google
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerName__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerName__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dfa3a2062361e1f2127a84e9e33202e73a513ee2
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerName__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 1
+ 1
+ 1
+ 1
+ 0
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerType__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerType__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..1e0cbc467f857e3479293cca985ba4e3998e6924
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerType__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,9 @@
+
+
+ direct
+ website
+ search
+ social
+ ai
+ campaign
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerType__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerType__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..a2c18c80f9584b7e7776a3f643e09761cd8ed621
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerType__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 34
+ 94
+ 34
+ 17
+ 27579
+ 5
+ 50%
+ 2.8
+ 811
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerUrl__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerUrl__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f7cd8deb3b45d5a0d160c10c4218d88eacd7a576
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerUrl__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ http://google.com/?q=Wikileaks FTW
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerUrl__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerUrl__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dfa3a2062361e1f2127a84e9e33202e73a513ee2
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_referrerUrl__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 1
+ 1
+ 1
+ 1
+ 0
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_regionCode__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_regionCode__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..9a69fa129e2a264cfa0dc8710016f2089ef40374
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_regionCode__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,12 @@
+
+
+ BC
+ WAR
+ SPE
+ 18
+ BFC
+ KEN
+ LND
+ XZ
+ CA
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_regionCode__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_regionCode__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..58db26f696acf3739fdc6b0a47e5dff3cfde0b41
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_regionCode__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 6
+ 16
+ 6
+ 3
+ 4867
+ 5
+ 50%
+ 2.7
+ 811
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_resolution__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_resolution__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..5a29930810865357556ccf30a0d06ced404986e9
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_resolution__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ 1024x768
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_resolution__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_resolution__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_resolution__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_revenueAbandonedCart__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_revenueAbandonedCart__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..c234bed59e963e268d7a9bc05348d941758c4aa9
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_revenueAbandonedCart__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,2 @@
+
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_revenueOrder__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_revenueOrder__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..c234bed59e963e268d7a9bc05348d941758c4aa9
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_revenueOrder__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,2 @@
+
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_searches__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_searches__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..70bdb9e417c3c53850b93db3d86b1e0c107e039a
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_searches__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_searches__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_searches__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..4be0b7b205564cbba38e64815598618fa6d1f2a0
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_searches__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 9
+ 45
+ 9
+ 0
+ 14599
+ 5
+ 0%
+ 5
+ 1622
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceFirstVisit__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceFirstVisit__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..33a755040669434405ecdd3462c1abffa7f1fc95
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceFirstVisit__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,6 @@
+
+
+ 3600
+ 86400
+ 90000
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceFirstVisit__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceFirstVisit__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..4be0b7b205564cbba38e64815598618fa6d1f2a0
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceFirstVisit__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 9
+ 45
+ 9
+ 0
+ 14599
+ 5
+ 0%
+ 5
+ 1622
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastEcommerceOrder__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastEcommerceOrder__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..17be108e1d777baf07903afc8d2b4b2604e6ea7c
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastEcommerceOrder__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,5 @@
+
+
+ 82800
+ 86400
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastEcommerceOrder__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastEcommerceOrder__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..1df89ff2220e37044bb840d3041209454c7f78e1
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastEcommerceOrder__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 5
+ 5
+ 5
+ 5
+ 5
+ 1
+ 100%
+ 1
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastVisit__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastVisit__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..8a1a76d013244f3aa9640ab7a74b1a3f4440bc96
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastVisit__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,5 @@
+
+
+ 3600
+ 82800
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastVisit__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastVisit__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..b5c4efe72acca168ccd4982f185c0c2c1475c358
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_secondsSinceLastVisit__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 17
+ 77
+ 17
+ 0
+ 27571
+ 5
+ 0%
+ 4.5
+ 1622
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCategory__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCategory__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f7624776eb073bec0b7df7e31ba5a3eb130a9f1b
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCategory__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ CAT
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCategory__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCategory__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..4be0b7b205564cbba38e64815598618fa6d1f2a0
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCategory__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 9
+ 45
+ 9
+ 0
+ 14599
+ 5
+ 0%
+ 5
+ 1622
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCount__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCount__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..aad5e66529d4a17283f0ec4632257960335764e6
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCount__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,7 @@
+
+
+ 12
+ 24
+ 36
+ 48
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCount__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCount__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..4fcc0a92d694d404086851037dab9f5f45887100
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchCount__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 2
+ 10
+ 2
+ 0
+ 3242
+ 5
+ 0%
+ 5
+ 1621
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchKeyword__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchKeyword__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..0690d54c62d47a1983a4e8a69ad2e55b69137958
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchKeyword__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ Bring on the party
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchKeyword__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchKeyword__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..4be0b7b205564cbba38e64815598618fa6d1f2a0
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_siteSearchKeyword__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 9
+ 45
+ 9
+ 0
+ 14599
+ 5
+ 0%
+ 5
+ 1622
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_userId__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_userId__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..381e1be3afb5f0e4bd9e9fae2a0b0d6f727d30b5
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_userId__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ userid.email@example.org
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_userId__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_userId__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dfa3a2062361e1f2127a84e9e33202e73a513ee2
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_userId__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 1
+ 1
+ 1
+ 1
+ 0
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalId__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalId__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..109907075606b2156778b36916539a781c74d929
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalId__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,5 @@
+
+
+ 1
+ 2
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalId__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalId__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalId__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalName__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalName__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..ac0a78bbed4fa710512649b5851ee709c81f4446
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalName__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,5 @@
+
+
+ all
+ two
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalName__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalName__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConvertedGoalName__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConverted__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConverted__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..70bdb9e417c3c53850b93db3d86b1e0c107e039a
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConverted__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConverted__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConverted__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitConverted__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitCount__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitCount__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..a549f79155cb1045d960bc103c73f63f80f385ac
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitCount__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,7 @@
+
+
+ 1
+ 2
+ 3
+ 4
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitCount__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitCount__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..724075c272c53a20b3bbe2566f59d007a51e37c2
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitCount__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 10
+ 10
+ 10
+ 10
+ 0
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitDuration__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitDuration__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..603ab11347fafce1f5e4d9de0012ea3bd4e131b8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitDuration__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,6 @@
+
+
+ 1621
+ 1
+ 1623
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitDuration__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitDuration__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f6406a6a05c257d354414bbfdacb3c1a2a7c86f8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitDuration__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 10
+ 44
+ 10
+ 0
+ 16210
+ 5
+ 0%
+ 4.4
+ 1621
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEcommerceStatus__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEcommerceStatus__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..5acd8f333f4a723df408e388a6ee1abb31721a02
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEcommerceStatus__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,7 @@
+
+
+ none
+ ordered
+ abandonedCart
+ orderedThenAbandonedCart
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEcommerceStatus__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEcommerceStatus__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..22e494d0c3230a196e643647d16691c420550bcf
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEcommerceStatus__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 28
+ 62
+ 28
+ 18
+ 16218
+ 5
+ 64%
+ 2.2
+ 579
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDate__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDate__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..69a9077a56336568575606c3f2d4ae6a82a13709
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDate__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,34 @@
+
+
+ 2018-02-02
+ 2018-02-01
+ 2018-01-31
+ 2018-01-30
+ 2018-01-29
+ 2018-01-28
+ 2018-01-27
+ 2018-01-26
+ 2018-01-25
+ 2018-01-24
+ 2018-01-23
+ 2018-01-22
+ 2018-01-21
+ 2018-01-20
+ 2018-01-19
+ 2018-01-18
+ 2018-01-17
+ 2018-01-16
+ 2018-01-15
+ 2018-01-14
+ 2018-01-13
+ 2018-01-12
+ 2018-01-11
+ 2018-01-10
+ 2018-01-09
+ 2018-01-08
+ 2018-01-07
+ 2018-01-06
+ 2018-01-05
+ 2018-01-04
+ 2018-01-03
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDate__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDate__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dee7cc9e508d4d14ee333a063d4f9d1e99eb1704
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDate__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 4
+ 12
+ 4
+ 2
+ 3242
+ 5
+ 50%
+ 3
+ 811
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfMonth__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfMonth__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6e7cfc1a1d592c0cfb6d276b183c3bff8da6832e
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfMonth__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,34 @@
+
+
+ 0
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfMonth__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfMonth__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dee7cc9e508d4d14ee333a063d4f9d1e99eb1704
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfMonth__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 4
+ 12
+ 4
+ 2
+ 3242
+ 5
+ 50%
+ 3
+ 811
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfWeek__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfWeek__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..02f69dbb12cb8f9586cfaaa4a76d0ff56f902c2a
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfWeek__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,10 @@
+
+
+ 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfWeek__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfWeek__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..08ff0fac5508bfc31f6d8068021443b60a819e59
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfWeek__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 3
+ 7
+ 3
+ 2
+ 1623
+ 5
+ 67%
+ 2.3
+ 541
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfYear__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfYear__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..35bc2d8319f26f041892005197bea4fec8b95507
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfYear__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,33 @@
+
+
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfYear__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfYear__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..26b7cb42daa88d9fdabe03ffc236678712e4cad6
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerDayOfYear__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 8
+ 24
+ 8
+ 4
+ 6492
+ 5
+ 50%
+ 3
+ 812
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMinute__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMinute__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6e7cfc1a1d592c0cfb6d276b183c3bff8da6832e
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMinute__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,34 @@
+
+
+ 0
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMinute__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMinute__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..9857cf3bdd4b2a5d262c48784844a88c0c3f91b4
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMinute__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 18
+ 18
+ 18
+ 18
+ 8
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMonth__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMonth__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..823ea43efb22fdb0a35c5136a087ff758b3677a4
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMonth__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,15 @@
+
+
+ 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+ 10
+ 11
+ 12
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMonth__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMonth__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerMonth__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerQuarter__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerQuarter__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..a549f79155cb1045d960bc103c73f63f80f385ac
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerQuarter__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,7 @@
+
+
+ 1
+ 2
+ 3
+ 4
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerQuarter__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerQuarter__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerQuarter__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerSecond__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerSecond__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6e7cfc1a1d592c0cfb6d276b183c3bff8da6832e
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerSecond__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,34 @@
+
+
+ 0
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerSecond__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerSecond__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..dfa3a2062361e1f2127a84e9e33202e73a513ee2
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerSecond__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 1
+ 1
+ 1
+ 1
+ 0
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerWeekOfYear__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerWeekOfYear__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..35bc2d8319f26f041892005197bea4fec8b95507
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerWeekOfYear__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,33 @@
+
+
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerWeekOfYear__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerWeekOfYear__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..549d12e95589389da05687ec9affe2de6b326fe2
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerWeekOfYear__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 30
+ 83
+ 30
+ 15
+ 24336
+ 5
+ 50%
+ 2.8
+ 811
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerYear__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerYear__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..d829abc6d69cea6511edef9a62e5842a1be9c45b
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerYear__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,34 @@
+
+
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerYear__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerYear__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitEndServerYear__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitId__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitId__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..c234bed59e963e268d7a9bc05348d941758c4aa9
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitId__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,2 @@
+
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitIp__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitIp__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..aeab59dbdd27e46104bd0b755e44527bd70d0dfd
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitIp__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,20 @@
+
+
+ 194.57.91.215
+ 1.2.4.0
+ 1.2.4.1
+ 1.2.4.2
+ 1.2.4.3
+ 1.2.4.4
+ 1.2.4.5
+ 1.2.4.6
+ 1.2.4.7
+ 1.2.4.8
+ 103.29.196.229
+ 113.62.1.1
+ 137.82.0.0
+ 137.82.130.0
+ 151.100.101.92
+ 2003:f6:93bf:26f:9ec7:a6ff:fe29:27df
+ ::ffff:137.82.130.49
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitIp__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitIp__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..08ff0fac5508bfc31f6d8068021443b60a819e59
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitIp__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 3
+ 7
+ 3
+ 2
+ 1623
+ 5
+ 67%
+ 2.3
+ 541
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalHour__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalHour__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e8a749dda2b6085ef8578623c04847e5e4a61dfc
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalHour__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ 12
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalHour__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalHour__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalHour__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalMinute__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalMinute__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6e7cfc1a1d592c0cfb6d276b183c3bff8da6832e
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalMinute__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,34 @@
+
+
+ 0
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalMinute__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalMinute__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitLocalMinute__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerHour__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerHour__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..70bdb9e417c3c53850b93db3d86b1e0c107e039a
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerHour__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,4 @@
+
+
+ 1
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerHour__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerHour__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..b5c4efe72acca168ccd4982f185c0c2c1475c358
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerHour__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 17
+ 77
+ 17
+ 0
+ 27571
+ 5
+ 0%
+ 4.5
+ 1622
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerMinute__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerMinute__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6e7cfc1a1d592c0cfb6d276b183c3bff8da6832e
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerMinute__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,34 @@
+
+
+ 0
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerMinute__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerMinute__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..7ace3fcbe7421cce6dce7bbfe3716507389dcb5f
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitServerMinute__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 18
+ 18
+ 18
+ 18
+ 0
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerHour__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerHour__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..98314b9ea4e80dfda128bf92053acb3951a0a6d5
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerHour__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,27 @@
+
+
+ 0
+ 1
+ 2
+ 3
+ 4
+ 5
+ 6
+ 7
+ 8
+ 9
+ 10
+ 11
+ 12
+ 13
+ 14
+ 15
+ 16
+ 17
+ 18
+ 19
+ 20
+ 21
+ 22
+ 23
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerHour__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerHour__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..9857cf3bdd4b2a5d262c48784844a88c0c3f91b4
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerHour__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 18
+ 18
+ 18
+ 18
+ 8
+ 1
+ 100%
+ 1
+ 0
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerMinute__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerMinute__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6e7cfc1a1d592c0cfb6d276b183c3bff8da6832e
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerMinute__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,34 @@
+
+
+ 0
+ 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
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerMinute__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerMinute__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e0d7aff01a418c6c06b62f0b4d2017e49b8c91a8
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitStartServerMinute__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 35
+ 95
+ 35
+ 18
+ 27579
+ 5
+ 51%
+ 2.7
+ 788
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorId__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorId__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..6d1659382f9fc9b29ad5e43c5d884ea8ae63b507
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorId__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,13 @@
+
+
+ 08f90c1a41715536
+ 1bd69c7df3112fb9
+ 908c9a564a864265
+ a9b7ba70783b617e
+ aa68c75c4a77c87f
+ b8c37e33defde51c
+ e93028bdc1aacdfb
+ fba9d88164f3e2d9
+ fed33392d3a48aa1
+ e64bc481700c5d69
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorId__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorId__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..d7fe9062dfffe178aa393802237c94bf5654bb0f
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorId__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 4
+ 11
+ 4
+ 2
+ 3245
+ 5
+ 50%
+ 2.8
+ 811
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorType__API.getSuggestedValuesForSegment.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorType__API.getSuggestedValuesForSegment.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e598eaeee89323e9ce80d632c35f52f68ab0d67c
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorType__API.getSuggestedValuesForSegment.xml
@@ -0,0 +1,6 @@
+
+
+ returningCustomer
+ returning
+ new
+
\ No newline at end of file
diff --git a/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorType__VisitsSummary.get_range.xml b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorType__VisitsSummary.get_range.xml
new file mode 100644
index 0000000000000000000000000000000000000000..eb5668a39b6d99a674b999d7b3a06f99797c3a77
--- /dev/null
+++ b/plugins/API/tests/System/expected/test_AutoSuggestAPITest_visitorType__VisitsSummary.get_range.xml
@@ -0,0 +1,12 @@
+
+
+ 5
+ 20
+ 5
+ 0
+ 8105
+ 4
+ 0%
+ 4
+ 1621
+
\ No newline at end of file
diff --git a/plugins/API/tests/Unit/ConsoleRendererTest.php b/plugins/API/tests/Unit/ConsoleRendererTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..78eea77727f08f6d3c1fceb01c08e58bb7ded617
--- /dev/null
+++ b/plugins/API/tests/Unit/ConsoleRendererTest.php
@@ -0,0 +1,139 @@
+builder = $this->makeBuilder(array());
+ DataTable\Manager::getInstance()->deleteAll();
+ }
+
+ public function testRenderSuccessShouldAlwaysReturnTrueAndIgnoreMessage()
+ {
+ $response = $this->builder->renderSuccess('ok');
+
+ $this->assertEquals('Success:ok', $response);
+ }
+
+ public function testRenderExceptionShouldThrowTheException()
+ {
+ $response = $this->builder->renderException('This message should be used', new \BadMethodCallException('The other message'));
+
+ $this->assertEquals('Error: This message should be used', $response);
+ }
+
+ public function testRenderScalarShouldReturnTheSameValue()
+ {
+ $response = $this->builder->renderScalar(true);
+ $this->assertSame("- 1 ['0' => 1] [] [idsubtable = ]
+", $response);
+
+ $response = $this->builder->renderScalar(5);
+ $this->assertSame("- 1 ['0' => 5] [] [idsubtable = ]
+", $response);
+
+ $response = $this->builder->renderScalar('string');
+ $this->assertSame("- 1 ['0' => 'string'] [] [idsubtable = ]
+", $response);
+ }
+
+ public function testRenderObjectShouldReturAnError()
+ {
+ $response = $this->builder->renderObject(new \stdClass());
+
+ $this->assertEquals('Error: The API cannot handle this data structure.', $response);
+ }
+
+ public function testRenderResourceShouldReturAnError()
+ {
+ $response = $this->builder->renderResource(new \stdClass());
+
+ $this->assertEquals('Error: The API cannot handle this data structure.', $response);
+ }
+
+ public function testRenderDataTableShouldReturnResult()
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertSame("- 1 ['nb_visits' => 5, 'nb_random' => 10] [] [idsubtable = ]
+", $response);
+ }
+
+ public function testRenderDataTableWithObjectsShouldReturnResult()
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+ $dataTable->setMetadata('processedRows', [
+ new AverageTimeOnSite(),
+ new \stdClass(),
+ Date::factory('2016-01-01 00:00:00'),
+ ]);
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertSame("- 1 ['nb_visits' => 5, 'nb_random' => 10] [] [idsubtable = ]
+
Metadata processedRows 0 => Object [Piwik\Plugins\CoreHome\Columns\Metrics\AverageTimeOnSite]1 => Object [stdClass]2 => 2016-01-01", $response);
+ }
+
+ public function testRenderArrayShouldReturnConsoleResult()
+ {
+ $input = array(1, 2, 5, 'string', 10);
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertSame("- 1 ['0' => 1] [] [idsubtable = ]
+- 2 ['0' => 2] [] [idsubtable = ]
+- 3 ['0' => 5] [] [idsubtable = ]
+- 4 ['0' => 'string'] [] [idsubtable = ]
+- 5 ['0' => 10] [] [idsubtable = ]
+", $response);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalAssociativeArrayToJson()
+ {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage('Data structure returned is not convertible in the requested format');
+
+ $input = array(
+ "firstElement" => "isFirst",
+ "secondElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ "thirdElement" => "isThird");
+
+ $actual = $this->builder->renderArray($input);
+ $this->assertSame($input, $actual);
+ }
+
+ private function makeBuilder($request)
+ {
+ return new Console($request);
+ }
+}
diff --git a/plugins/API/tests/Unit/CsvRendererTest.php b/plugins/API/tests/Unit/CsvRendererTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..c7b5f6be0179df7f0085228577de07424572f2fe
--- /dev/null
+++ b/plugins/API/tests/Unit/CsvRendererTest.php
@@ -0,0 +1,354 @@
+builder = $this->makeBuilder(array('method' => 'MultiSites_getAll', 'convertToUnicode' => 0));
+ }
+
+ public function testRenderSuccessShouldIncludeMessage()
+ {
+ $response = $this->builder->renderSuccess('ok');
+
+ $this->assertEquals("message
+ok", $response);
+ }
+
+ public function testRenderExceptionShouldIncludeTheMessageAndNotExceptionMessage()
+ {
+ $response = $this->builder->renderException("The error message", new \Exception('The other message'));
+
+ $this->assertEquals('Error: The error message', $response);
+ }
+
+ public function testRenderExceptionShouldRespectNewlines()
+ {
+ $response = $this->builder->renderException("The\nerror\nmessage", new \Exception('The other message'));
+
+ $this->assertEquals('Error: The
+error
+message', $response);
+ }
+
+ public function testRenderObjectShouldReturAnError()
+ {
+ $response = $this->builder->renderObject(new \stdClass());
+
+ $this->assertEquals('Error: The API cannot handle this data structure.', $response);
+ }
+
+ public function testRenderResourceShouldReturAnError()
+ {
+ $response = $this->builder->renderResource(new \stdClass());
+
+ $this->assertEquals('Error: The API cannot handle this data structure.', $response);
+ }
+
+ public function testRenderScalarShouldConvertToUnicodeByDefault()
+ {
+ $builder = $this->makeBuilder(array('method' => 'MultiSites_getAll'));
+ $response = $builder->renderScalar(true);
+
+ $this->assertStringStartsWith(chr(255) . chr(254), $response);
+ }
+
+ public function testRenderScalarShouldReturnABooleanAsIntegerWrappedInTable()
+ {
+ $response = $this->builder->renderScalar(true);
+
+ $this->assertEquals('value
+1', $response);
+ }
+
+ public function testRenderScalarShouldReturnAnIntegerWrappedInTable()
+ {
+ $response = $this->builder->renderScalar(5);
+
+ $this->assertEquals('value
+5', $response);
+ }
+
+ public function testRenderScalarShouldReturnAStringWrappedInValue()
+ {
+ $response = $this->builder->renderScalar('The Output');
+
+ $this->assertEquals('value
+The Output', $response);
+ }
+
+ public function testRenderScalarShouldNotRemoveLineBreaks()
+ {
+ $response = $this->builder->renderScalar('The\nOutput');
+
+ $this->assertEquals('value
+The\nOutput', $response);
+ }
+
+ /**
+ * @dataProvider getCellValuesToPrefixOrNot
+ */
+ public function testRenderScalarWhenCellValueIsFormulaShouldPrefixWithQuote($value, $expectedCsvValue)
+ {
+ $response = $this->builder->renderScalar($value);
+
+ $this->assertEquals("value\n$expectedCsvValue", $response);
+ }
+
+ public function getCellValuesToPrefixOrNot()
+ {
+ // input, expected csv output
+ return array(
+ // we prefix with quotes
+ array('=test()', '\'=test()'),
+ array('=test()%%', '\'=test()%%'),
+ array('=1+1', '\'=1+1'),
+ array('@1+1', '\'@1+1'),
+ array('+1+1', '\'+1+1'),
+ array('+1+test()', '\'+1+test()'),
+ array('-1+1', '\'-1+1'),
+ array('@-1+1', '\'@-1+1'),
+ array('-test()', '\'-test()'),
+ array('-te,st()', '"\'-te,st()"'),
+ array('-te"st()', '"\'-te""st()"'),
+ array("value\nbreak", "\"value\nbreak\""),
+
+ // we do not need to prefix with quote
+ array('1', '1'),
+ array('2', '2'),
+ array('2@', '2@'),
+ array('20000000', '20000000'),
+ array('10%', '10%'),
+ array('%%', '%%'),
+ array('10.5%', '10.5%'),
+ array('-10.5%', '-10.5%'),
+ array('+10,5%', '"\'+10,5%"'),
+ array('10,5', '"10,5"'),
+ array('1+test()', '1+test()'),
+ array('1+test@', '1+test@'),
+ array('%10%5', '%10%5'),
+ array('', ''),
+ array(0, '0'),
+ array(2.2, '2.2'),
+ array(-2.2, '-2.2'),
+ array(false, '0'),
+ array(null, ''),
+ );
+ }
+
+ /**
+ * @dataProvider getCellValuesToPrefixOrNot
+ */
+ public function testRenderDataTableShouldRenderFormulas($value, $expectedValue)
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => $value));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals("nb_visits,nb_random\n5,$expectedValue", $response);
+ }
+
+ public function testRenderDataTableShouldRenderABasicDataTable()
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('nb_visits,nb_random
+5,10', $response);
+ }
+
+ public function testRenderDataTableShouldNotRenderSubtablesAsItIsNotSupportedYet()
+ {
+ $subtable = new DataTable();
+ $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6));
+
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+ $dataTable->getFirstRow()->setSubtable($subtable);
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('nb_visits,nb_random
+5,10', $response);
+ }
+
+ public function testRenderDataTableShouldRenderDataTableMaps()
+ {
+ $map = new DataTable\Map();
+
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $dataTable2 = new DataTable();
+ $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6));
+
+ $map->addTable($dataTable, 'table1');
+ $map->addTable($dataTable2, 'table2');
+
+ $response = $this->builder->renderDataTable($map);
+
+ $this->assertEquals('defaultKeyName,nb_visits,nb_random
+table1,5,10
+table2,3,6', $response);
+ }
+
+ public function testRenderDataTableShouldRenderSimpleDataTable()
+ {
+ $dataTable = new DataTable\Simple();
+ $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('nb_visits,nb_random
+3,6', $response);
+ }
+
+ public function testRenderArrayShouldConvertSimpleArrayToJson()
+ {
+ $input = array(1, 2, 5, 'string', 10);
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('1
+2
+5
+string
+10', $response);
+ }
+
+ public function testRenderArrayShouldRenderAnEmptyArray()
+ {
+ $response = $this->builder->renderArray(array());
+
+ $this->assertEquals('No data available', $response);
+ }
+
+ public function testRenderArrayShouldConvertAssociativeArrayToJson()
+ {
+ $input = array('nb_visits' => 6, 'nb_random' => 8);
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('nb_visits,nb_random
+6,8', $response);
+ }
+
+ public function testRenderArrayShouldConvertsIndexedAssociativeArrayToJson()
+ {
+ $input = array(
+ array('nb_visits' => 6, 'nb_random' => 8),
+ array('nb_visits' => 3, 'nb_random' => 4),
+ );
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('nb_visits,nb_random
+6,8
+3,4', $response);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalStandardArrayToJson()
+ {
+ $input = array("firstElement",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement");
+
+ $actual = $this->builder->renderArray($input);
+ $this->assertEquals('0,1,2
+firstElement,,
+firstElement,secondElement,
+,,thirdElement', $actual);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalAssociativeArrayToJson()
+ {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage("Data structure returned is not convertible in the requested format: Only integer keys supported for array columns on base level. Unsupported string 'secondElement' found for row 'array (
+ 'firstElement' => 'isFirst',
+ 'secondElement' => 'isSecond',
+)'.");
+
+ $input = array(
+ "firstElement" => "isFirst",
+ "secondElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ "thirdElement" => "isThird");
+
+ $this->builder->renderArray($input);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalIndexArrayToJson()
+ {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage("Data structure returned is not convertible in the requested format: Multidimensional column values not supported. Found unexpected array value for column '1' in row '0': 'array (
+ 0 => 'firstElement',
+ 1 => 'secondElement',
+)'.");
+
+ $input = array(array("firstElement",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement"));
+
+ $this->builder->renderArray($input);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalMixedArrayToJson()
+ {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage("Data structure returned is not convertible in the requested format: Only integer keys supported for array columns on base level. Unsupported string 'thirdElement' found for row 'array (
+ 'firstElement' => 'isFirst',
+ 'secondElement' => 'isSecond',
+)'.");
+
+ $input = array(
+ "firstElement" => "isFirst",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ );
+
+ $this->builder->renderArray($input);
+ }
+
+ private function makeBuilder($request)
+ {
+ return new Csv($request);
+ }
+}
diff --git a/plugins/API/tests/Unit/DataTable/MergeDataTablesTest.php b/plugins/API/tests/Unit/DataTable/MergeDataTablesTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..a7616261d932e90d5e603562f3c84e8cdf010d0d
--- /dev/null
+++ b/plugins/API/tests/Unit/DataTable/MergeDataTablesTest.php
@@ -0,0 +1,387 @@
+instance = new MergeDataTables();
+ }
+
+ public function testMergeDataTablesReturnsCorrectDataWhenTwoTablesAreMerged()
+ {
+ $table1 = new DataTable();
+ $table1->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 2, 'nb_other' => 3],
+ ]),
+ ]);
+ $table1->setAllTableMetadata([
+ 'a' => 'b',
+ ]);
+
+ $table2 = new DataTable();
+ $table2->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 1, 'nb_other' => 1],
+ ]),
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 2', 'nb_visits' => 5, 'nb_other' => 5],
+ ]),
+ ]);
+ $table2->setAllTableMetadata([
+ 'c' => '3',
+ ]);
+
+ $this->instance->mergeDataTables($table1, $table2);
+
+ $xml = $this->getTableAsXml($table1);
+
+ $expectedXml = <<
+
+
+ label 1
+ 1
+ 1
+
+
+END;
+
+ $this->assertEquals($expectedXml, $xml);
+ }
+
+ public function testMergeDataTablesReturnsCorrectDataWhenTwoMapsAreMergedAndBothHaveTheSameAmountOfData()
+ {
+ $table1 = new DataTable\Map();
+ $table1->setKeyName('period');
+
+ $childTable1 = new DataTable();
+ $childTable1->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 1, 'nb_other' => 1],
+ ]),
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 2', 'nb_visits' => 5, 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable1->setAllTableMetadata(['a' => 'b']);
+ $table1->addTable($childTable1, 'p1');
+
+ $childTable2 = new DataTable();
+ $childTable2->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 5', 'nb_visits' => 1],
+ ]),
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 6', 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable2->setAllTableMetadata(['c' => 'd']);
+ $table1->addTable($childTable1, 'p2');
+
+ $table2 = new DataTable\Map();
+ $table2->setKeyName('period');
+
+ $childTable1 = new DataTable();
+ $childTable1->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 4, 'nb_other' => 4],
+ ]),
+ ]);
+ $childTable1->setAllTableMetadata(['a' => 'b']);
+ $table2->addTable($childTable1, 'p1');
+
+ $childTable2 = new DataTable();
+ $childTable2->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 6', 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable2->setAllTableMetadata(['c' => 'd']);
+ $table2->addTable($childTable1, 'p2');
+
+ $this->instance->mergeDataTables($table1, $table2);
+
+ $xml = $this->getTableAsXml($table1);
+
+ $expectedXml = <<
+
+
+
+ label 1
+ 4
+ 4
+
+
+ label 2
+ 5
+ 5
+
+
+
+
+ label 1
+ 4
+ 4
+
+
+ label 2
+ 5
+ 5
+
+
+
+END;
+
+ $this->assertEquals($expectedXml, $xml);
+ }
+
+ public function testMergeDataTablesReturnsCorrectDataWhenTwoMapsAreMergedAndFirstHasLessThanSecond()
+ {
+ $table1 = new DataTable\Map();
+ $table1->setKeyName('period');
+
+ $childTable2 = new DataTable();
+ $childTable2->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 5', 'nb_visits' => 1],
+ ]),
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 6', 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable2->setAllTableMetadata(['c' => 'd']);
+ $table1->addTable($childTable2, 'p2');
+
+ $table2 = new DataTable\Map();
+ $table2->setKeyName('period');
+
+ $childTable1 = new DataTable();
+ $childTable1->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 4, 'nb_other' => 4],
+ ]),
+ ]);
+ $childTable1->setAllTableMetadata(['a' => 'b']);
+ $table2->addTable($childTable1, 'p1');
+
+ $childTable2 = new DataTable();
+ $childTable2->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 6', 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable1->setAllTableMetadata(['c' => 'd']);
+ $table2->addTable($childTable1, 'p2');
+
+ $this->instance->mergeDataTables($table1, $table2);
+
+ $xml = $this->getTableAsXml($table1);
+
+ $expectedXml = <<
+
+
+
+ label 1
+ 4
+ 4
+
+
+ label 6
+ 5
+
+
+
+
+ label 1
+ 4
+ 4
+
+
+
+END;
+
+ $this->assertEquals($expectedXml, $xml);
+ }
+
+ public function testMergeDataTablesReturnsCorrectDataWhenTwoMapsAreMergedAndSecondHasLessThanFirst()
+ {
+ $table1 = new DataTable\Map();
+ $table1->setKeyName('period');
+
+ $childTable1 = new DataTable();
+ $childTable1->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 1, 'nb_other' => 1],
+ ]),
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 2', 'nb_visits' => 5, 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable1->setAllTableMetadata(['a' => 'b']);
+ $table1->addTable($childTable1, 'p1');
+
+ $childTable2 = new DataTable();
+ $childTable2->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 5', 'nb_visits' => 1],
+ ]),
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 6', 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable2->setAllTableMetadata(['c' => 'd']);
+ $table1->addTable($childTable1, 'p2');
+
+ $table2 = new DataTable\Map();
+ $table2->setKeyName('period');
+
+ $childTable1 = new DataTable();
+ $childTable1->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 4, 'nb_other' => 4],
+ ]),
+ ]);
+ $childTable1->setAllTableMetadata(['a' => 'b']);
+ $table2->addTable($childTable1, 'p1');
+
+ $this->instance->mergeDataTables($table1, $table2);
+
+ $xml = $this->getTableAsXml($table1);
+
+ $expectedXml = <<
+
+
+
+ label 1
+ 4
+ 4
+
+
+ label 2
+ 5
+ 5
+
+
+
+
+ label 1
+ 4
+ 4
+
+
+ label 2
+ 5
+ 5
+
+
+
+END;
+
+ $this->assertEquals($expectedXml, $xml);
+ }
+
+ public function testMergeDataTablesReturnsCorrectDataWhenMapsAreNested()
+ {
+ $table1 = new DataTable\Map();
+ $table1->setKeyName('site');
+
+ $childTableMap1 = new DataTable\Map();
+ $childTableMap1->setKeyName('period');
+ $table1->addTable($childTableMap1, 's1');
+
+ $childTable1 = new DataTable();
+ $childTable1->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 1, 'nb_other' => 1],
+ ]),
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 2', 'nb_visits' => 5, 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable1->setAllTableMetadata(['a' => 'b']);
+ $childTableMap1->addTable($childTable1, 'p1');
+
+ $table2 = new DataTable\Map();
+ $table2->setKeyName('site');
+
+ $childTableMap2 = new DataTable\Map();
+ $childTableMap2->setKeyName('period');
+ $table2->addTable($childTableMap2, 's2');
+
+ $childTable2 = new DataTable();
+ $childTable2->addRowsFromArray([
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 1', 'nb_visits' => 1, 'nb_other' => 1],
+ ]),
+ new DataTable\Row([
+ DataTable\Row::COLUMNS => ['label' => 'label 2', 'nb_visits' => 5, 'nb_other' => 5],
+ ]),
+ ]);
+ $childTable2->setAllTableMetadata(['c' => 'd']);
+ $childTableMap2->addTable($childTable2, 'p1');
+
+ $this->instance->mergeDataTables($table1, $table2);
+
+ $xml = $this->getTableAsXml($table1);
+
+ $expectedXml = <<
+
+
+
+
+ label 1
+ 1
+ 1
+
+
+ label 2
+ 5
+ 5
+
+
+
+
+
+
+ label 1
+ 1
+ 1
+
+
+
+
+END;
+
+ $this->assertEquals($expectedXml, $xml);
+ }
+// TODO: test for metadata
+ private function getTableAsXml(DataTable\DataTableInterface $table1)
+ {
+ $renderer = new DataTable\Renderer\Xml();
+ $renderer->setTable($table1);
+ return $renderer->render();
+ }
+}
diff --git a/plugins/API/tests/Unit/HtmlRendererTest.php b/plugins/API/tests/Unit/HtmlRendererTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..f8e4cacf7537d6c5f89390e19a8ea0220e556080
--- /dev/null
+++ b/plugins/API/tests/Unit/HtmlRendererTest.php
@@ -0,0 +1,519 @@
+builder = $this->makeBuilder(array('method' => 'MultiSites_getAll'));
+ DataTable\Manager::getInstance()->deleteAll();
+ }
+
+ public function testRenderSuccessShouldIncludeMessage()
+ {
+ $response = $this->builder->renderSuccess('ok');
+
+ $this->assertEquals('', $response);
+ }
+
+ public function testRenderExceptionShouldIncludeTheMessageAndNotExceptionMessage()
+ {
+ $response = $this->builder->renderException("The error message", new \Exception('The other message'));
+
+ $this->assertEquals('The error message', $response);
+ }
+
+ public function testRenderExceptionShouldConvertNewLinesToBr()
+ {
+ $response = $this->builder->renderException("The\nerror\nmessage", new \Exception('The other message'));
+
+ $this->assertEquals('The
+error
+message', $response);
+ }
+
+ public function testRenderObjectShouldReturAnError()
+ {
+ $response = $this->builder->renderObject(new \stdClass());
+
+ $this->assertEquals('The API cannot handle this data structure.', $response);
+ }
+
+ public function testRenderResourceShouldReturAnError()
+ {
+ $response = $this->builder->renderResource(new \stdClass());
+
+ $this->assertEquals('The API cannot handle this data structure.', $response);
+ }
+
+ public function testRenderScalarShouldReturnABooleanAsIntegerWrappedInTable()
+ {
+ $response = $this->builder->renderScalar(true);
+
+ $this->assertEquals('
+
+
+ value
+
+
+
+
+ 1
+
+
+
+', $response);
+ }
+
+ public function testRenderScalarShouldReturnAnIntegerWrappedInTable()
+ {
+ $response = $this->builder->renderScalar(5);
+
+ $this->assertEquals('
+
+
+ value
+
+
+
+
+ 5
+
+
+
+', $response);
+ }
+
+ public function testRenderScalarShouldReturnAStringWrappedInValue()
+ {
+ $response = $this->builder->renderScalar('The Output');
+
+ $this->assertEquals('
+
+
+ value
+
+
+
+
+ The Output
+
+
+
+', $response);
+ }
+
+ public function testRenderScalarShouldNotRemoveLineBreaks()
+ {
+ $response = $this->builder->renderScalar('The\nOutput');
+
+ $this->assertEquals('
+
+
+ value
+
+
+
+
+ The\nOutput
+
+
+
+', $response);
+ }
+
+ public function testRenderDataTableShouldRenderABasicDataTable()
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('
+
+
+ nb_visits
+ nb_random
+
+
+
+
+ 5
+ 10
+
+
+
+', $response);
+ }
+
+ public function testRenderDataTableShouldRenderSubtables()
+ {
+ $subtable = new DataTable();
+ $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6));
+
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+ $dataTable->getFirstRow()->setSubtable($subtable);
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('
+
+
+ nb_visits
+ nb_random
+ _idSubtable
+
+
+
+
+ 5
+ 10
+ 1
+
+
+
+', $response);
+ }
+
+ public function testRenderDataTableShouldRenderDataTableMaps()
+ {
+ $map = new DataTable\Map();
+
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $dataTable2 = new DataTable();
+ $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6));
+
+ $map->addTable($dataTable, 'table1');
+ $map->addTable($dataTable2, 'table2');
+
+ $response = $this->builder->renderDataTable($map);
+
+ $this->assertEquals('
+
+
+ _defaultKeyName
+ nb_visits
+ nb_random
+
+
+
+
+ table1
+ 5
+ 10
+
+
+ table2
+ 3
+ 6
+
+
+
+', $response);
+ }
+
+ public function testRenderDataTableShouldRenderSimpleDataTable()
+ {
+ $dataTable = new DataTable\Simple();
+ $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('
+
+
+ nb_visits
+ nb_random
+
+
+
+
+ 3
+ 6
+
+
+
+', $response);
+ }
+
+ public function testRenderDataTableShouldRenderDataTableWithComplexMetadata()
+ {
+ $dataTable = new DataTable\Simple();
+ $row = new DataTable\Row();
+ $row->setColumn('nb_visits', 3);
+ $row->setColumn('nb_random', 6);
+ $row->setMetadata('processedRows', [
+ new AverageTimeOnSite(),
+ new \stdClass(),
+ Date::factory('2016-01-01 00:00:00'),
+ ]);
+ $dataTable->addRow($row);
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $stdClass = version_compare(PHP_VERSION, 7.3, '>=') ?
+ "(object) array(\n )," :
+ "stdClass::__set_state(array(\n )),";
+
+ $isPHP82orNewer = version_compare(PHP_VERSION, 8.2, '>=');
+
+ $this->assertEquals('
+
+
+ nb_visits
+ nb_random
+ _metadata
+
+
+
+
+ 3
+ 6
+ \'processedRows\' => array (
+ 0 =>
+ ' . ($isPHP82orNewer ? '\\' : '') . 'Piwik\Plugins\CoreHome\Columns\Metrics\AverageTimeOnSite::__set_state(array(
+ )),
+ 1 =>
+ ' . $stdClass . '
+ 2 =>
+ ' . ($isPHP82orNewer ? '\\' : '') . 'Piwik\Date::__set_state(array(
+ \'timestamp\' => 1451606400,
+ \'timezone\' => \'UTC\',
+ )),
+)
+
+
+
+', $response);
+ }
+
+ public function testRenderArrayShouldConvertSimpleArrayToJson()
+ {
+ $input = array(1, 2, 5, 'string', 10);
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('
+
+
+ value
+
+
+
+
+ 1
+
+
+ 2
+
+
+ 5
+
+
+ string
+
+
+ 10
+
+
+
+', $response);
+ }
+
+ public function testRenderArrayShouldRenderAnEmptyArray()
+ {
+ $response = $this->builder->renderArray(array());
+
+ $this->assertEquals('
+', $response);
+ }
+
+ public function testRenderArrayShouldConvertAssociativeArrayToJson()
+ {
+ $input = array('nb_visits' => 6, 'nb_random' => 8);
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('
+
+
+ nb_visits
+ nb_random
+
+
+
+
+ 6
+ 8
+
+
+
+', $response);
+ }
+
+ public function testRenderArrayShouldConvertsIndexedAssociativeArrayToJson()
+ {
+ $input = array(
+ array('nb_visits' => 6, 'nb_random' => 8),
+ array('nb_visits' => 3, 'nb_random' => 4),
+ );
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('
+
+
+ nb_visits
+ nb_random
+
+
+
+
+ 6
+ 8
+
+
+ 3
+ 4
+
+
+
+', $response);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalStandardArrayToJson()
+ {
+ $input = array("firstElement",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement");
+
+ $actual = $this->builder->renderArray($input);
+ $this->assertEquals('
+
+
+ value
+ 1
+ 2
+
+
+
+
+ firstElement
+ -
+ -
+
+
+ firstElement
+ secondElement
+ -
+
+
+ -
+ -
+ thirdElement
+
+
+
+', $actual);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalAssociativeArrayToJson()
+ {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage("Data structure returned is not convertible in the requested format: Only integer keys supported for array columns on base level. Unsupported string 'secondElement' found for row 'array (
+ 'firstElement' => 'isFirst',
+ 'secondElement' => 'isSecond',
+)'.");
+
+ $input = array(
+ "firstElement" => "isFirst",
+ "secondElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ "thirdElement" => "isThird");
+
+ $this->builder->renderArray($input);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalIndexArrayToJson()
+ {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage("Data structure returned is not convertible in the requested format: Multidimensional column values not supported. Found unexpected array value for column '1' in row '0': 'array (
+ 0 => 'firstElement',
+ 1 => 'secondElement',
+)'.");
+
+ $input = array(array("firstElement",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement"));
+
+ $this->builder->renderArray($input);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalMixedArrayToJson()
+ {
+ $this->expectException(\Exception::class);
+ $this->expectExceptionMessage("Data structure returned is not convertible in the requested format: Only integer keys supported for array columns on base level. Unsupported string 'thirdElement' found for row 'array (
+ 'firstElement' => 'isFirst',
+ 'secondElement' => 'isSecond',
+)'.");
+
+ $input = array(
+ "firstElement" => "isFirst",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ );
+
+ $this->builder->renderArray($input);
+ }
+
+ private function makeBuilder($request)
+ {
+ return new Html($request);
+ }
+}
diff --git a/plugins/API/tests/Unit/JsonRendererTest.php b/plugins/API/tests/Unit/JsonRendererTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..24277d6199f4d0157d6f39a2769ba11913df262b
--- /dev/null
+++ b/plugins/API/tests/Unit/JsonRendererTest.php
@@ -0,0 +1,411 @@
+jsonBuilder = $this->makeBuilder(array());
+ DataTable\Manager::getInstance()->deleteAll();
+ }
+
+ public function testRenderSuccessShouldIncludeMessage()
+ {
+ $response = $this->jsonBuilder->renderSuccess('ok');
+
+ $this->assertEquals('{"result":"success","message":"ok"}', $response);
+ $this->assertEquals((array) array('result' => 'success', 'message' => 'ok'), json_decode($response, true));
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderSuccessShouldWrapIfEnabledAndCallbackShouldBePreferred()
+ {
+ $builder = $this->makeBuilder(array('callback' => 'myName', 'jsoncallback' => 'myOther'));
+ $response = $builder->renderSuccess('ok');
+
+ $this->assertEquals('myName({"result":"success","message":"ok"})', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderSuccessShouldWrapIfEnabledAndFallbackToJsonCallbackIfCallbackNotSet()
+ {
+ $builder = $this->makeBuilder(array('jsoncallback' => 'myOther'));
+ $response = $builder->renderSuccess('ok');
+
+ $this->assertEquals('myOther({"result":"success","message":"ok"})', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderSuccessShouldNotWrapIfCallbackContainsInvalidCharacters()
+ {
+ $builder = $this->makeBuilder(array('callback' => 'myOther#?._kek'));
+ $response = $builder->renderSuccess('ok');
+
+ $this->assertEquals('{"result":"success","message":"ok"}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderExceptionShouldIncludeTheMessageAndNotExceptionMessage()
+ {
+ $response = $this->jsonBuilder->renderException("The error message", new \Exception('The other message'));
+
+ $this->assertEquals('{"result":"error","message":"The error message"}', $response);
+ $this->assertEquals((array) array('result' => 'error', 'message' => 'The error message'), json_decode($response, true));
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderExceptionShouldRemoveNewlines()
+ {
+ $response = $this->jsonBuilder->renderException("The\nerror\r\nmessage", new \Exception());
+
+ $this->assertEquals('{"result":"error","message":"The error message"}', $response);
+ $this->assertEquals((array) array('result' => 'error', 'message' => 'The error message'), json_decode($response, true));
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderExceptionShouldWrapIfEnabled()
+ {
+ $builder = $this->makeBuilder(array('callback' => 'myName'));
+ $response = $builder->renderException('error', new \Exception());
+
+ $this->assertEquals('myName({"result":"error","message":"error"})', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderObjectShouldReturAnError()
+ {
+ $response = $this->jsonBuilder->renderObject(new \stdClass());
+
+ $this->assertEquals('{"result":"error","message":"The API cannot handle this data structure."}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderResourceShouldReturAnError()
+ {
+ $response = $this->jsonBuilder->renderResource(new \stdClass());
+
+ $this->assertEquals('{"result":"error","message":"The API cannot handle this data structure."}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderScalarShouldReturnABooleanWrappedInValue()
+ {
+ $response = $this->jsonBuilder->renderScalar(true);
+
+ $this->assertEquals('{"value":true}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderScalarShouldReturnAnIntegerWrappedInValue()
+ {
+ $response = $this->jsonBuilder->renderScalar(5);
+
+ $this->assertEquals('{"value":5}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderScalarShouldReturnAStringWrappedInValue()
+ {
+ $response = $this->jsonBuilder->renderScalar('The Output');
+
+ $this->assertEquals('{"value":"The Output"}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderScalarShouldNotRemoveLineBreaks()
+ {
+ $response = $this->jsonBuilder->renderScalar('The\nOutput');
+
+ $this->assertEquals('{"value":"The\\\\nOutput"}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderScalarShouldWrapJsonIfNeeded()
+ {
+ $builder = $this->makeBuilder(array('callback' => 'myName'));
+ $response = $builder->renderScalar(true);
+
+ $this->assertEquals('myName({"value":true})', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderDataTableShouldRenderABasicDataTable()
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $response = $this->jsonBuilder->renderDataTable($dataTable);
+
+ $this->assertEquals('[{"nb_visits":5,"nb_random":10}]', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderDataTableShouldRenderSubtables()
+ {
+ $subtable = new DataTable();
+ $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6));
+
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+ $dataTable->getFirstRow()->setSubtable($subtable);
+
+ $response = $this->jsonBuilder->renderDataTable($dataTable);
+
+ $this->assertEquals('[{"nb_visits":5,"nb_random":10,"idsubdatatable":1}]', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderDataTableShouldRenderDataTableMaps()
+ {
+ $map = new DataTable\Map();
+
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $dataTable2 = new DataTable();
+ $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6));
+
+ $map->addTable($dataTable, 'table1');
+ $map->addTable($dataTable2, 'table2');
+
+ $response = $this->jsonBuilder->renderDataTable($map);
+
+ $this->assertEquals('{"table1":[{"nb_visits":5,"nb_random":10}],"table2":[{"nb_visits":3,"nb_random":6}]}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderDataTableShouldRenderSimpleDataTable()
+ {
+ $dataTable = new DataTable\Simple();
+ $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6));
+
+ $response = $this->jsonBuilder->renderDataTable($dataTable);
+
+ $this->assertEquals('{"nb_visits":3,"nb_random":6}', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderDataTableShouldWrapADataTable()
+ {
+ $builder = $this->makeBuilder(array('callback' => 'myName'));
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $response = $builder->renderDataTable($dataTable);
+
+ $this->assertEquals('myName([{"nb_visits":5,"nb_random":10}])', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderArrayShouldConvertSimpleArrayToJson()
+ {
+ $input = array(1, 2, 5, 'string', 10);
+
+ $response = $this->jsonBuilder->renderArray($input);
+
+ $this->assertEquals('[1,2,5,"string",10]', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderArrayShouldWrapJsonIfRequested()
+ {
+ $input = array(1, 2, 5, 'string', 10);
+
+ $builder = $this->makeBuilder(array('jsoncallback' => 'myName'));
+ $response = $builder->renderArray($input);
+
+ $this->assertEquals('myName([1,2,5,"string",10])', $response);
+ }
+
+ public function testRenderArrayWithAssociativeArrayJsonpCorrectlyFormatted()
+ {
+ $input = array('key' => 'value');
+ $renderer = $this->makeBuilder(array('callback' => '__myfunc', 'jsoncallback' => '__myfunc'));
+ $result = $renderer->renderArray($input);
+
+ $this->assertEquals('__myfunc({"key":"value"})', $result);
+ $this->assertNoJsonError($result);
+ }
+
+ public function testRenderArrayWithMultidimensionalArrayJsonpCorrectlyFormatted()
+ {
+ $input = array('key' => 'value', 'deepKey' => array('deeper' => 'deepValue'));
+ $renderer = $this->makeBuilder(array('callback' => '__myfunc', 'jsoncallback' => '__myfunc'));
+ $result = $renderer->renderArray($input);
+
+ $this->assertEquals('__myfunc({"key":"value","deepKey":{"deeper":"deepValue"}})', $result);
+ $this->assertNoJsonError($result);
+ }
+
+ public function testRenderArrayShouldRenderAnEmptyArray()
+ {
+ $response = $this->jsonBuilder->renderArray(array());
+
+ $this->assertEquals('[]', $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderArrayShouldConvertAssociativeArrayToJson()
+ {
+ $input = array('nb_visits' => 6, 'nb_random' => 8);
+
+ $response = $this->jsonBuilder->renderArray($input);
+ $expected = json_encode($input);
+
+ $this->assertEquals($expected, $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderArrayShouldConvertsIndexedAssociativeArrayToJson()
+ {
+ $input = array(
+ array('nb_visits' => 6, 'nb_random' => 8),
+ array('nb_visits' => 3, 'nb_random' => 4),
+ );
+
+ $response = $this->jsonBuilder->renderArray($input);
+ $expected = json_encode($input);
+
+ $this->assertEquals($expected, $response);
+ $this->assertNoJsonError($response);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalStandardArrayToJson()
+ {
+ $input = array("firstElement",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement");
+
+ $expected = json_encode($input);
+
+ $actual = $this->jsonBuilder->renderArray($input);
+ $this->assertEquals($expected, $actual);
+ $this->assertNoJsonError($actual);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalAssociativeArrayToJson()
+ {
+ $input = array(
+ "firstElement" => "isFirst",
+ "secondElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ "thirdElement" => "isThird");
+
+ $expected = json_encode($input);
+
+ $actual = $this->jsonBuilder->renderArray($input);
+ $this->assertEquals($expected, $actual);
+ $this->assertNoJsonError($actual);
+ }
+
+ public function testRenderArrayShouldConvertSingleDimensionalAssociativeArrayToJson()
+ {
+ $input = array(
+ "fistElement" => "isFirst",
+ "secondElement" => "isSecond",
+ );
+
+ $expected = json_encode($input);
+
+ $actual = $this->jsonBuilder->renderArray($input);
+ $this->assertEquals($expected, $actual);
+ $this->assertNoJsonError($actual);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalIndexArrayToJson()
+ {
+ $input = array(array("firstElement",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement"));
+
+ $expected = json_encode($input);
+
+ $actual = $this->jsonBuilder->renderArray($input);
+ $this->assertEquals($expected, $actual);
+ $this->assertNoJsonError($actual);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalMixedArrayToJson()
+ {
+ $input = array(
+ "firstElement" => "isFirst",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ );
+
+ $expected = json_encode($input);
+
+ $actual = $this->jsonBuilder->renderArray($input);
+ $this->assertEquals($expected, $actual);
+ $this->assertNoJsonError($actual);
+ }
+
+ public function testJsonRenderArrayShouldConvertSingleDimensionalAssociativeArray()
+ {
+ $input = array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ );
+
+ $expected = '{"firstElement":"isFirst","secondElement":"isSecond"}';
+
+ $oldJsonBuilder = new Json($input);
+ $actual = $oldJsonBuilder->renderArray($input);
+ $this->assertEquals($expected, $actual);
+ $this->assertNoJsonError($actual);
+ }
+
+ public function testRenderWithNestedEmptyArrayWorks()
+ {
+ $input = [[]];
+ $render = new Json($input);
+ $result = $render->renderArray($input);
+ $this->assertEquals('[[]]', $result);
+ }
+
+ private function makeBuilder($request)
+ {
+ return new Json($request);
+ }
+
+ private function assertNoJsonError($response)
+ {
+ return null !== json_decode($response);
+ }
+}
diff --git a/plugins/API/tests/Unit/OriginalRendererTest.php b/plugins/API/tests/Unit/OriginalRendererTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..94abfdb45d612e87bde5ab74d284c608e8393b20
--- /dev/null
+++ b/plugins/API/tests/Unit/OriginalRendererTest.php
@@ -0,0 +1,137 @@
+builder = $this->makeBuilder(array());
+ }
+
+ public function testRenderSuccessShouldAlwaysReturnTrueAndIgnoreMessage()
+ {
+ $response = $this->builder->renderSuccess('ok');
+
+ $this->assertTrue($response);
+ }
+
+ public function testRenderExceptionShouldThrowTheException()
+ {
+ $this->expectException(\BadMethodCallException::class);
+ $this->expectExceptionMessage('The other message');
+
+ $this->builder->renderException('This message should be ignored', new \BadMethodCallException('The other message'));
+ }
+
+ public function testRenderScalarShouldReturnTheSameValue()
+ {
+ $response = $this->builder->renderScalar(true);
+ $this->assertSame(true, $response);
+
+ $response = $this->builder->renderScalar(5);
+ $this->assertSame(5, $response);
+
+ $response = $this->builder->renderScalar('string');
+ $this->assertSame('string', $response);
+ }
+
+ public function testRenderObjectShouldReturnTheSameValue()
+ {
+ $response = $this->builder->renderObject($this);
+ $this->assertSame($this, $response);
+
+ $stdObject = (object) array('test' => 5);
+ $response = $this->builder->renderObject($stdObject);
+ $this->assertSame($stdObject, $response);
+ }
+
+ public function testRenderResourceShouldReturnTheSameValue()
+ {
+ $resource = curl_init();
+ $response = $this->builder->renderResource($resource);
+ $this->assertSame($resource, $response);
+ }
+
+ public function testRenderDataTableShouldReturnSameInstanceAndNotSerializeByDefault()
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertSame($dataTable, $response);
+ }
+
+ public function testRenderDataTableShouldSerializeIfEnabled()
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $builder = $this->makeBuilder(array('serialize' => 1));
+ $response = $builder->renderDataTable($dataTable);
+
+ $builder = $this->makeBuilder(array('serialize' => 0));
+ $original = $builder->renderDataTable($dataTable);
+
+ $expected = serialize($original);
+ $this->assertEquals($expected, $response);
+ }
+
+ public function testRenderArrayShouldReturnSameArrayAndNotSerializeByDefault()
+ {
+ $input = array(1, 2, 5, 'string', 10);
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertSame($input, $response);
+ }
+
+ public function testRenderArrayShouldSerializeIfEnabled()
+ {
+ $builder = $this->makeBuilder(array('serialize' => 1));
+ $input = array(1, 2, 5, 'string', 10);
+
+ $response = $builder->renderArray($input);
+
+ $this->assertSame('a:5:{i:0;i:1;i:1;i:2;i:2;i:5;i:3;s:6:"string";i:4;i:10;}', $response);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalAssociativeArrayToJson()
+ {
+ $input = array(
+ "firstElement" => "isFirst",
+ "secondElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ "thirdElement" => "isThird");
+
+ $actual = $this->builder->renderArray($input);
+ $this->assertSame($input, $actual);
+ }
+
+ private function makeBuilder($request)
+ {
+ return new Original($request);
+ }
+}
diff --git a/plugins/API/tests/Unit/WidgetMetadataTest.php b/plugins/API/tests/Unit/WidgetMetadataTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..7ddebe20d42c55a80534e74a3539812098d2420d
--- /dev/null
+++ b/plugins/API/tests/Unit/WidgetMetadataTest.php
@@ -0,0 +1,361 @@
+metadata = new WidgetMetadata();
+ }
+
+ public function testBuildWidgetMetadataShouldGenerateMetadata()
+ {
+ $config = $this->createWidgetConfig('Test', 'CategoryId', 'SubcategoryId');
+ $list = $this->createCategoryList(array('CategoryId' => array('SubcategoryId')));
+ $metadata = $this->metadata->buildWidgetMetadata($config, $list);
+
+ $this->assertEquals(array(
+ 'name' => 'Test',
+ 'category' => array(
+ 'id' => 'CategoryId',
+ 'name' => 'CategoryId',
+ 'order' => 99,
+ 'icon' => '',
+ 'help' => '',
+ 'widget' => null,
+ 'groups' => array(''),
+ ),
+ 'subcategory' => array(
+ 'id' => 'SubcategoryId',
+ 'name' => 'SubcategoryIdName',
+ 'order' => 99,
+ 'help' => '',
+ ),
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ 'order' => 99,
+ 'parameters' => array (
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ ),
+ 'uniqueId' => 'widgetCoreHomerender',
+ 'isWide' => false,
+ ), $metadata);
+ }
+
+ public function testBuildWidgetMetadataShouldSetCategoryAndSubcategoryToNullIfBothGivenButNotExistInList()
+ {
+ $config = $this->createWidgetConfig('Test', 'CategoryId', 'SubcategoryId');
+ $list = $this->createCategoryList();
+ $metadata = $this->metadata->buildWidgetMetadata($config, $list);
+
+ $this->assertNull($metadata['category']);
+ $this->assertNull($metadata['subcategory']);
+ }
+
+ public function testBuildWidgetMetadataShouldSetSubcategoryToNullIfCategoryGivenInListButSubcategoryNot()
+ {
+ $config = $this->createWidgetConfig('Test', 'CategoryId', 'SubcategoryId');
+ $list = $this->createCategoryList(array('CategoryId' => array()));
+ $metadata = $this->metadata->buildWidgetMetadata($config, $list);
+
+ $this->assertSame(array(
+ 'id' => 'CategoryId',
+ 'name' => 'CategoryId',
+ 'order' => 99,
+ 'icon' => '',
+ 'help' => '',
+ 'widget' => null,
+ 'groups' => array(''),
+ ), $metadata['category']);
+ $this->assertNull($metadata['subcategory']);
+ }
+
+ public function testBuildWidgetMetadataShouldNotAddCategoryAndSubcategoryToNullIfNoCategoryListGiven()
+ {
+ $config = $this->createWidgetConfig('Test', 'CategoryId', 'SubcategoryId');
+ $metadata = $this->metadata->buildWidgetMetadata($config);
+
+ $this->assertArrayNotHasKey('category', $metadata);
+ $this->assertArrayNotHasKey('subcategory', $metadata);
+ }
+
+ public function testBuildWidgetMetadataShouldAddOptionalMiddlewareParameters()
+ {
+ $config = $this->createWidgetConfig('Test', 'CategoryId', 'SubcategoryId');
+ $config->setMiddlewareParameters(array('module' => 'Goals', 'action' => 'hasAnyConversions'));
+ $metadata = $this->metadata->buildWidgetMetadata($config);
+
+ $this->assertSame(array('module' => 'Goals', 'action' => 'hasAnyConversions'), $metadata['middlewareParameters']);
+ }
+
+ public function testBuildWidgetMetadataShouldAddOptionalClientComponent()
+ {
+ $config = $this->createWidgetConfig('Test', 'CategoryId', 'SubcategoryId');
+ $config->setClientSideComponent('Transitions', 'TransitionsPage');
+ $config->setClientSideProps(array('foo' => 'bar'));
+ $metadata = $this->metadata->buildWidgetMetadata($config);
+
+ $this->assertSame(array(
+ 'plugin' => 'Transitions',
+ 'name' => 'TransitionsPage',
+ 'props' => array('foo' => 'bar'),
+ ), $metadata['clientComponent']);
+ }
+
+ public function testBuildWidgetMetadataShouldAddReportInformtionIfReportWidgetConfigGiven()
+ {
+ $config = new ReportWidgetConfig();
+ $config->setDefaultViewDataTable('graph');
+ $metadata = $this->metadata->buildWidgetMetadata($config);
+
+ $this->assertSame('graph', $metadata['viewDataTable']);
+ $this->assertTrue($metadata['isReport']);
+ }
+
+ public function testBuildWidgetMetadataShouldAddContainerInformtionIfWidgetContainerConfigGiven()
+ {
+ $config = new WidgetContainerConfig();
+ $config->setLayout('ByDimension');
+ $config->addWidgetConfig($this->createWidgetConfig('NestedName1', 'NestedCategory1', 'NestedSubcategory1'));
+ $config->addWidgetConfig($this->createWidgetConfig('NestedName2', 'NestedCategory2', 'NestedSubcategory2'));
+ $metadata = $this->metadata->buildWidgetMetadata($config);
+
+ $this->assertSame('ByDimension', $metadata['layout']);
+ $this->assertTrue($metadata['isContainer']);
+ $this->assertCount(2, $metadata['widgets']);
+
+ $widget1 = $metadata['widgets'][0];
+ $widget2 = $metadata['widgets'][1];
+ $this->assertSame(array(
+ 'name' => 'NestedName1',
+ 'category' => array (
+ 'id' => 'NestedCategory1',
+ 'name' => 'NestedCategory1',
+ 'order' => 99,
+ 'icon' => '',
+ 'help' => '',
+ 'widget' => null,
+ 'groups' => array(''),
+ ),
+ 'subcategory' => array (
+ 'id' => 'NestedSubcategory1',
+ 'name' => 'NestedSubcategory1',
+ 'order' => 99,
+ 'help' => '',
+ ),
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ 'order' => 99,
+ 'parameters' => array (
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ ),
+ 'uniqueId' => 'widgetCoreHomerender',
+ 'isWide' => false,
+ ), $widget1);
+ $this->assertSame(array(
+ 'name' => 'NestedName2',
+ 'category' => array (
+ 'id' => 'NestedCategory2',
+ 'name' => 'NestedCategory2',
+ 'order' => 99,
+ 'icon' => '',
+ 'help' => '',
+ 'widget' => null,
+ 'groups' => array(''),
+ ),
+ 'subcategory' => array (
+ 'id' => 'NestedSubcategory2',
+ 'name' => 'NestedSubcategory2',
+ 'order' => 99,
+ 'help' => '',
+ ),
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ 'order' => 99,
+ 'parameters' => array (
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ ),
+ 'uniqueId' => 'widgetCoreHomerender',
+ 'isWide' => false,
+ ), $widget2);
+ }
+
+ public function testBuildWidgetMetadataShouldUseOverrideValuesIfSupplied()
+ {
+ $categoryList = $this->createCategoryList([
+ 'Category' => ['Subcategory'],
+ 'Category2' => ['Subcategory2'],
+ ]);
+
+ $config = $this->createWidgetConfig('name', 'Category', 'Subcategory');
+ $metadata = $this->metadata->buildWidgetMetadata($config, $categoryList, [
+ 'name' => 'changed name',
+ 'category' => 'Category2',
+ 'subcategory' => 'Subcategory2',
+ ]);
+
+ $this->assertEquals([
+ 'name' => 'changed name',
+ 'category' => [
+ 'id' => 'Category2',
+ 'name' => 'Category2',
+ 'order' => 99,
+ 'icon' => '',
+ 'help' => '',
+ 'widget' => null,
+ 'groups' => [''],
+ ],
+ 'subcategory' => [
+ 'id' => 'Subcategory2',
+ 'name' => 'Subcategory2Name',
+ 'order' => 99,
+ 'help' => '',
+ ],
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ 'order' => 99,
+ 'parameters' => [
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ ],
+ 'uniqueId' => 'widgetCoreHomerender',
+ 'isWide' => false,
+ ], $metadata);
+ }
+
+ public function testBuildPageMetadataShouldAddContainerInformtionIfWidgetContainerConfigGiven()
+ {
+ $config = new WidgetContainerConfig();
+ $config->setLayout('ByDimension');
+
+ $widgets = array(
+ $this->createWidgetConfig('NestedName1', 'NestedCategory1', 'NestedSubcategory1'),
+ $this->createWidgetConfig('NestedName2', 'NestedCategory2', 'NestedSubcategory1'),
+ );
+
+ $category = $this->createCategory('NestedCategory1');
+ $subcategory = $this->createSubcategory('NestedCategory1', 'NestedSubcategory1');
+
+ $metadata = $this->metadata->buildPageMetadata($category, $subcategory, $widgets);
+
+ $this->assertSame(array(
+ 'uniqueId' => 'NestedCategory1.NestedSubcategory1',
+ 'category' => array (
+ 'id' => 'NestedCategory1',
+ 'name' => 'NestedCategory1',
+ 'order' => 99,
+ 'icon' => '',
+ 'help' => '',
+ 'widget' => null,
+ 'groups' => array(''),
+ ),
+ 'subcategory' => array (
+ 'id' => 'NestedSubcategory1',
+ 'name' => 'NestedSubcategory1Name',
+ 'order' => 99,
+ 'help' => '',
+ ),
+ 'widgets' => array (
+ 0 => array ( // widgets should not have category / subcategory again, it's already present above
+ 'name' => 'NestedName1',
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ 'order' => 99,
+ 'parameters' => array (
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ ),
+ 'uniqueId' => 'widgetCoreHomerender',
+ 'isWide' => false,
+ ), array (
+ 'name' => 'NestedName2',
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ 'order' => 99,
+ 'parameters' => array (
+ 'module' => 'CoreHome',
+ 'action' => 'render',
+ ),
+ 'uniqueId' => 'widgetCoreHomerender',
+ 'isWide' => false,
+ ),
+ ),
+ ), $metadata);
+ }
+
+ private function createWidgetConfig($name, $categoryId, $subcategoryId = '')
+ {
+ $widgetConfig = new WidgetConfig();
+ $widgetConfig->setName($name);
+ $widgetConfig->setCategoryId($categoryId);
+ $widgetConfig->setSubcategoryId($subcategoryId);
+ $widgetConfig->setModule('CoreHome');
+ $widgetConfig->setAction('render');
+
+ return $widgetConfig;
+ }
+
+ private function createCategoryList($categories = array())
+ {
+ $list = new CategoryList();
+
+ foreach ($categories as $categoryId => $subcategoryIds) {
+ $category = $this->createCategory($categoryId);
+ $list->addCategory($category);
+
+ foreach ($subcategoryIds as $subcategoryId) {
+ $subcategory = $this->createSubcategory($categoryId, $subcategoryId);
+ $category->addSubcategory($subcategory);
+ }
+ }
+
+ return $list;
+ }
+
+ private function createSubcategory($categoryId, $subcategoryId)
+ {
+ $subcategory = new Subcategory();
+ $subcategory->setCategoryId($categoryId);
+ $subcategory->setId($subcategoryId);
+ $subcategory->setName($subcategoryId . 'Name');
+
+ return $subcategory;
+ }
+
+ private function createCategory($categoryId)
+ {
+ $category = new Category();
+ $category->setId($categoryId);
+ return $category;
+ }
+}
diff --git a/plugins/API/tests/Unit/XmlRendererTest.php b/plugins/API/tests/Unit/XmlRendererTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..5832919021282255f3f37d0c63770ac64f9e8801
--- /dev/null
+++ b/plugins/API/tests/Unit/XmlRendererTest.php
@@ -0,0 +1,352 @@
+builder = $this->makeBuilder(array());
+ DataTable\Manager::getInstance()->deleteAll();
+ }
+
+ public function tearDown(): void
+ {
+ DataTable\Manager::getInstance()->deleteAll();
+ }
+
+ public function testRenderSuccessShouldIncludeMessage()
+ {
+ $response = $this->builder->renderSuccess('ok');
+
+ $this->assertEquals('
+
+
+ ', $response);
+ }
+
+ public function testRenderExceptionShouldIncludeTheMessageAndNotExceptionMessage()
+ {
+ $response = $this->builder->renderException("The error message", new \Exception('The other message'));
+
+ $this->assertEquals('
+
+
+ ', $response);
+ }
+
+ public function testRenderObjectShouldReturAnError()
+ {
+ $response = $this->builder->renderObject(new \stdClass());
+
+ $this->assertEquals('
+
+
+ ', $response);
+ }
+
+ public function testRenderResourceShouldReturAnError()
+ {
+ $response = $this->builder->renderResource(new \stdClass());
+
+ $this->assertEquals('
+
+
+ ', $response);
+ }
+
+ public function testRenderScalarShouldReturnABooleanAsIntegerWrappedInResult()
+ {
+ $response = $this->builder->renderScalar(true);
+
+ $this->assertEquals('
+1 ', $response);
+ }
+
+ public function testRenderScalarShouldReturnAnIntegerWrappedInResult()
+ {
+ $response = $this->builder->renderScalar(5);
+
+ $this->assertEquals('
+5 ', $response);
+ }
+
+ public function testRenderScalarShouldReturnAStringWrappedInValue()
+ {
+ $response = $this->builder->renderScalar('The Output');
+
+ $this->assertEquals('
+The Output ', $response);
+ }
+
+ public function testRenderScalarShouldNotRemoveLineBreaks()
+ {
+ $response = $this->builder->renderScalar('The\nOutput');
+
+ $this->assertEquals('
+The\nOutput ', $response);
+ }
+
+ public function testRenderDataTableShouldRenderABasicDataTable()
+ {
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('
+
+
+ 5
+ 10
+
+ ', $response);
+ }
+
+ public function testRenderDataTableShouldRenderSubtables()
+ {
+ $subtable = new DataTable();
+ $subtable->addRowFromSimpleArray(array('nb_visits' => 2, 'nb_random' => 6));
+
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+ $dataTable->getFirstRow()->setSubtable($subtable);
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('
+
+
+ 5
+ 10
+ 1
+
+ ', $response);
+ }
+
+ public function testRenderDataTableShouldRenderDataTableMaps()
+ {
+ $map = new DataTable\Map();
+
+ $dataTable = new DataTable();
+ $dataTable->addRowFromSimpleArray(array('nb_visits' => 5, 'nb_random' => 10));
+
+ $dataTable2 = new DataTable();
+ $dataTable2->addRowFromSimpleArray(array('nb_visits' => 3, 'nb_random' => 6));
+
+ $map->addTable($dataTable, 'table1');
+ $map->addTable($dataTable2, 'table2');
+
+ $response = $this->builder->renderDataTable($map);
+
+ $this->assertEquals('
+
+
+
+ 5
+ 10
+
+
+
+
+ 3
+ 6
+
+
+ ', $response);
+ }
+
+ public function testRenderDataTableShouldRenderSimpleDataTable()
+ {
+ $dataTable = new DataTable\Simple();
+ $dataTable->addRowsFromArray(array('nb_visits' => 3, 'nb_random' => 6));
+
+ $response = $this->builder->renderDataTable($dataTable);
+
+ $this->assertEquals('
+
+ 3
+ 6
+ ', $response);
+ }
+
+ public function testRenderArrayShouldConvertSimpleArrayToJson()
+ {
+ $input = array(1, 2, 5, 'string', 10);
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('
+
+ 1
+ 2
+ 5
+ string
+ 10
+ ', $response);
+ }
+
+ public function testRenderArrayShouldRenderAnEmptyArray()
+ {
+ $response = $this->builder->renderArray(array());
+
+ $this->assertEquals('
+ ', $response);
+ }
+
+ public function testRenderArrayShouldConvertAssociativeArrayToJson()
+ {
+ $input = array('nb_visits' => 6, 'nb_random' => 8);
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('
+
+
+ 6
+ 8
+
+ ', $response);
+ }
+
+ public function testRenderArrayShouldConvertsIndexedAssociativeArrayToJson()
+ {
+ $input = array(
+ array('nb_visits' => 6, 'nb_random' => 8),
+ array('nb_visits' => 3, 'nb_random' => 4),
+ );
+
+ $response = $this->builder->renderArray($input);
+
+ $this->assertEquals('
+
+
+ 6
+ 8
+
+
+ 3
+ 4
+
+ ', $response);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalStandardArrayToJson()
+ {
+ $input = array("firstElement",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement");
+
+ $actual = $this->builder->renderArray($input);
+ $this->assertEquals('
+
+ firstElement
+
+ firstElement
+ secondElement
+
+ thirdElement
+ ', $actual);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalAssociativeArrayToJson()
+ {
+ $input = array(
+ "firstElement" => "isFirst",
+ "secondElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ "thirdElement" => "isThird");
+
+ $actual = $this->builder->renderArray($input);
+ $this->assertEquals('
+
+ isFirst
+
+ isFirst
+ isSecond
+
+ isThird
+ ', $actual);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalIndexArrayToJson()
+ {
+ $input = array(array("firstElement",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement"));
+
+ $actual = $this->builder->renderArray($input);
+ $this->assertEquals('
+
+
+ firstElement
+
+ firstElement
+ secondElement
+
+ thirdElement
+
+ ', $actual);
+ }
+
+ public function testRenderArrayShouldConvertMultiDimensionalMixedArrayToJson()
+ {
+ $input = array(
+ "firstElement" => "isFirst",
+ array(
+ "firstElement",
+ "secondElement",
+ ),
+ "thirdElement" => array(
+ "firstElement" => "isFirst",
+ "secondElement" => "isSecond",
+ ),
+ );
+
+ $actual = $this->builder->renderArray($input);
+ $this->assertEquals('
+
+ isFirst
+
+ firstElement
+ secondElement
+
+
+ isFirst
+ isSecond
+
+ ', $actual);
+ }
+
+ private function makeBuilder($request)
+ {
+ return new Xml($request);
+ }
+}
diff --git a/plugins/API/vue/dist/API.umd.js b/plugins/API/vue/dist/API.umd.js
new file mode 100644
index 0000000000000000000000000000000000000000..1ed371b88b3a657297b2dcf0826b4788acd998e5
--- /dev/null
+++ b/plugins/API/vue/dist/API.umd.js
@@ -0,0 +1,329 @@
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory(require("CoreHome"), require("vue"));
+ else if(typeof define === 'function' && define.amd)
+ define(["CoreHome", ], factory);
+ else if(typeof exports === 'object')
+ exports["API"] = factory(require("CoreHome"), require("vue"));
+ else
+ root["API"] = factory(root["CoreHome"], root["Vue"]);
+})((typeof self !== 'undefined' ? self : this), function(__WEBPACK_EXTERNAL_MODULE__19dc__, __WEBPACK_EXTERNAL_MODULE__8bbf__) {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "plugins/API/vue/dist/";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = "fae3");
+/******/ })
+/************************************************************************/
+/******/ ({
+
+/***/ "19dc":
+/***/ (function(module, exports) {
+
+module.exports = __WEBPACK_EXTERNAL_MODULE__19dc__;
+
+/***/ }),
+
+/***/ "8bbf":
+/***/ (function(module, exports) {
+
+module.exports = __WEBPACK_EXTERNAL_MODULE__8bbf__;
+
+/***/ }),
+
+/***/ "fae3":
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+// ESM COMPAT FLAG
+__webpack_require__.r(__webpack_exports__);
+
+// EXPORTS
+__webpack_require__.d(__webpack_exports__, "Glossary", function() { return /* reexport */ Glossary; });
+
+// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/setPublicPath.js
+// This file is imported into lib/wc client bundles.
+
+if (typeof window !== 'undefined') {
+ var currentScript = window.document.currentScript
+ if (false) { var getCurrentScript; }
+
+ var src = currentScript && currentScript.src.match(/(.+\/)[^/]+\.js(\?.*)?$/)
+ if (src) {
+ __webpack_require__.p = src[1] // eslint-disable-line
+ }
+}
+
+// Indicate to webpack that this file can be concatenated
+/* harmony default export */ var setPublicPath = (null);
+
+// EXTERNAL MODULE: external {"commonjs":"vue","commonjs2":"vue","root":"Vue"}
+var external_commonjs_vue_commonjs2_vue_root_Vue_ = __webpack_require__("8bbf");
+
+// CONCATENATED MODULE: ./node_modules/@vue/cli-plugin-babel/node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/@vue/cli-plugin-babel/node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/@vue/cli-service/node_modules/vue-loader-v16/dist/templateLoader.js??ref--6!./node_modules/@vue/cli-service/node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/@vue/cli-service/node_modules/vue-loader-v16/dist??ref--1-1!./plugins/API/vue/src/Glossary/Glossary.vue?vue&type=template&id=18b6840f
+
+const _hoisted_1 = {
+ ref: "root",
+ class: "glossaryPage"
+};
+const _hoisted_2 = {
+ class: "row"
+};
+const _hoisted_3 = {
+ class: "col s12"
+};
+const _hoisted_4 = {
+ class: "row glossary"
+};
+const _hoisted_5 = {
+ class: "col s12"
+};
+const _hoisted_6 = {
+ class: "tabs"
+};
+const _hoisted_7 = ["href"];
+const _hoisted_8 = ["id"];
+const _hoisted_9 = {
+ class: "card"
+};
+const _hoisted_10 = {
+ class: "card-content"
+};
+const _hoisted_11 = {
+ style: {
+ "background": "#fff",
+ "width": "100%"
+ },
+ class: "pushpin"
+};
+const _hoisted_12 = {
+ class: "card-title"
+};
+const _hoisted_13 = {
+ class: "pagination"
+};
+const _hoisted_14 = ["href"];
+const _hoisted_15 = ["id"];
+const _hoisted_16 = {
+ style: {
+ "color": "#4183C4",
+ "font-weight": "bold"
+ }
+};
+const _hoisted_17 = {
+ key: 0,
+ style: {
+ "color": "#999",
+ "text-transform": "uppercase",
+ "font-weight": "normal",
+ "margin-top": "-16px"
+ }
+};
+const _hoisted_18 = ["innerHTML"];
+const _hoisted_19 = {
+ key: 0
+};
+const _hoisted_20 = {
+ key: 1,
+ style: {
+ "color": "#bbb"
+ }
+};
+function render(_ctx, _cache, $props, $setup, $data, $options) {
+ const _directive_content_intro = Object(external_commonjs_vue_commonjs2_vue_root_Vue_["resolveDirective"])("content-intro");
+ return Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("div", _hoisted_1, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("div", _hoisted_2, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("div", _hoisted_3, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["withDirectives"])((Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("div", null, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("h2", null, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(_ctx.translate('API_Glossary')), 1), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("p", null, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(_ctx.translate('API_LearnAboutCommonlyUsedTerms2')), 1)])), [[_directive_content_intro]])])]), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("div", _hoisted_4, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("div", _hoisted_5, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("ul", _hoisted_6, [(Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(true), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])(external_commonjs_vue_commonjs2_vue_root_Vue_["Fragment"], null, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["renderList"])(_ctx.glossaryItems, (item, keyword, index) => {
+ return Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("li", {
+ key: keyword,
+ class: "tab col s3"
+ }, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("a", {
+ class: Object(external_commonjs_vue_commonjs2_vue_root_Vue_["normalizeClass"])(index === 0 ? 'active' : ''),
+ href: `#${keyword}`
+ }, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(item.title), 11, _hoisted_7)]);
+ }), 128))])]), (Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(true), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])(external_commonjs_vue_commonjs2_vue_root_Vue_["Fragment"], null, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["renderList"])(_ctx.glossaryItems, (item, keyword) => {
+ return Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("div", {
+ key: keyword,
+ id: keyword,
+ class: "col s12"
+ }, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("div", _hoisted_9, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("div", _hoisted_10, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("div", _hoisted_11, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("h2", _hoisted_12, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(item.title), 1), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("ul", _hoisted_13, [(Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(true), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])(external_commonjs_vue_commonjs2_vue_root_Vue_["Fragment"], null, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["renderList"])(item.letters, (letter, index) => {
+ return Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("li", {
+ key: index,
+ class: "waves-effect",
+ style: {
+ "margin-right": "3.5px"
+ }
+ }, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("a", {
+ href: `#${keyword}${letter}`
+ }, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(letter), 9, _hoisted_14)]);
+ }), 128))])]), (Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(true), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])(external_commonjs_vue_commonjs2_vue_root_Vue_["Fragment"], null, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["renderList"])(_ctx.entriesByLetter(item.entries), ([letter, entries]) => {
+ return Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("div", {
+ key: letter,
+ class: "scrollspy",
+ id: `${keyword}${letter}`
+ }, [(Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(true), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])(external_commonjs_vue_commonjs2_vue_root_Vue_["Fragment"], null, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["renderList"])(entries, (entry, index) => {
+ return Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("div", {
+ key: index
+ }, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("h3", _hoisted_16, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(entry.name), 1), entry.subtitle ? (Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("p", _hoisted_17, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(_ctx.translate(entry.subtitle)), 1)) : Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createCommentVNode"])("", true), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("p", null, [Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementVNode"])("span", {
+ innerHTML: _ctx.$sanitize(entry.documentation)
+ }, null, 8, _hoisted_18), entry.id ? (Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("br", _hoisted_19)) : Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createCommentVNode"])("", true), entry.id ? (Object(external_commonjs_vue_commonjs2_vue_root_Vue_["openBlock"])(), Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createElementBlock"])("span", _hoisted_20, Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(entry.id) + Object(external_commonjs_vue_commonjs2_vue_root_Vue_["toDisplayString"])(keyword === 'metrics' || entry.is_metric ? ' (API)' : ''), 1)) : Object(external_commonjs_vue_commonjs2_vue_root_Vue_["createCommentVNode"])("", true)])]);
+ }), 128))], 8, _hoisted_15);
+ }), 128))])])], 8, _hoisted_8);
+ }), 128))])], 512);
+}
+// CONCATENATED MODULE: ./plugins/API/vue/src/Glossary/Glossary.vue?vue&type=template&id=18b6840f
+
+// EXTERNAL MODULE: external "CoreHome"
+var external_CoreHome_ = __webpack_require__("19dc");
+
+// CONCATENATED MODULE: ./node_modules/@vue/cli-plugin-typescript/node_modules/cache-loader/dist/cjs.js??ref--15-0!./node_modules/babel-loader/lib!./node_modules/@vue/cli-plugin-typescript/node_modules/ts-loader??ref--15-2!./node_modules/@vue/cli-service/node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/@vue/cli-service/node_modules/vue-loader-v16/dist??ref--1-1!./plugins/API/vue/src/Glossary/Glossary.vue?vue&type=script&lang=ts
+
+
+const {
+ $
+} = window;
+/* harmony default export */ var Glossaryvue_type_script_lang_ts = (Object(external_commonjs_vue_commonjs2_vue_root_Vue_["defineComponent"])({
+ props: {
+ glossaryItems: {
+ type: Object,
+ required: true
+ }
+ },
+ directives: {
+ ContentIntro: external_CoreHome_["ContentIntro"]
+ },
+ mounted() {
+ const root = this.$refs.root;
+ setTimeout(() => {
+ $('.scrollspy', root).scrollSpy();
+ $('.pushpin', root).pushpin({
+ top: $('.pushpin', root).offset().top
+ });
+ $('.tabs', root).tabs();
+ });
+ },
+ methods: {
+ entriesByLetter(entries) {
+ const byLetter = {};
+ entries.forEach(entry => {
+ byLetter[entry.letter] = byLetter[entry.letter] || [];
+ byLetter[entry.letter].push(entry);
+ });
+ const byLetterArray = Object.entries(byLetter);
+ byLetterArray.sort(([lhsLetter], [rhsLetter]) => {
+ if (lhsLetter < rhsLetter) {
+ return -1;
+ }
+ if (lhsLetter > rhsLetter) {
+ return 1;
+ }
+ return 0;
+ });
+ return byLetterArray;
+ }
+ }
+}));
+// CONCATENATED MODULE: ./plugins/API/vue/src/Glossary/Glossary.vue?vue&type=script&lang=ts
+
+// CONCATENATED MODULE: ./plugins/API/vue/src/Glossary/Glossary.vue
+
+
+
+Glossaryvue_type_script_lang_ts.render = render
+
+/* harmony default export */ var Glossary = (Glossaryvue_type_script_lang_ts);
+// CONCATENATED MODULE: ./plugins/API/vue/src/index.ts
+/*!
+ * Matomo - free/libre analytics platform
+ *
+ * @link https://matomo.org
+ * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
+*/
+
+// CONCATENATED MODULE: ./node_modules/@vue/cli-service/lib/commands/build/entry-lib-no-default.js
+
+
+
+
+/***/ })
+
+/******/ });
+});
+//# sourceMappingURL=API.umd.js.map
\ No newline at end of file
diff --git a/plugins/API/vue/dist/API.umd.min.js b/plugins/API/vue/dist/API.umd.min.js
new file mode 100644
index 0000000000000000000000000000000000000000..c69d403f821ae0e4f3eb3dc99c71b9a418c0d61f
--- /dev/null
+++ b/plugins/API/vue/dist/API.umd.min.js
@@ -0,0 +1,8 @@
+(function(e,t){"object"===typeof exports&&"object"===typeof module?module.exports=t(require("CoreHome"),require("vue")):"function"===typeof define&&define.amd?define(["CoreHome"],t):"object"===typeof exports?exports["API"]=t(require("CoreHome"),require("vue")):e["API"]=t(e["CoreHome"],e["Vue"])})("undefined"!==typeof self?self:this,(function(e,t){return function(e){var t={};function c(o){if(t[o])return t[o].exports;var r=t[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,c),r.l=!0,r.exports}return c.m=e,c.c=t,c.d=function(e,t,o){c.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},c.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.t=function(e,t){if(1&t&&(e=c(e)),8&t)return e;if(4&t&&"object"===typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(c.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)c.d(o,r,function(t){return e[t]}.bind(null,r));return o},c.n=function(e){var t=e&&e.__esModule?function(){return e["default"]}:function(){return e};return c.d(t,"a",t),t},c.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},c.p="plugins/API/vue/dist/",c(c.s="fae3")}({"19dc":function(t,c){t.exports=e},"8bbf":function(e,c){e.exports=t},fae3:function(e,t,c){"use strict";if(c.r(t),c.d(t,"Glossary",(function(){return C})),"undefined"!==typeof window){var o=window.document.currentScript,r=o&&o.src.match(/(.+\/)[^/]+\.js(\?.*)?$/);r&&(c.p=r[1])}var n=c("8bbf");const l={ref:"root",class:"glossaryPage"},s={class:"row"},i={class:"col s12"},a={class:"row glossary"},b={class:"col s12"},d={class:"tabs"},u=["href"],p=["id"],j={class:"card"},m={class:"card-content"},O={style:{background:"#fff",width:"100%"},class:"pushpin"},f={class:"card-title"},y={class:"pagination"},k=["href"],g=["id"],v={style:{color:"#4183C4","font-weight":"bold"}},E={key:0,style:{color:"#999","text-transform":"uppercase","font-weight":"normal","margin-top":"-16px"}},B=["innerHTML"],h={key:0},V={key:1,style:{color:"#bbb"}};function N(e,t,c,o,r,N){const S=Object(n["resolveDirective"])("content-intro");return Object(n["openBlock"])(),Object(n["createElementBlock"])("div",l,[Object(n["createElementVNode"])("div",s,[Object(n["createElementVNode"])("div",i,[Object(n["withDirectives"])((Object(n["openBlock"])(),Object(n["createElementBlock"])("div",null,[Object(n["createElementVNode"])("h2",null,Object(n["toDisplayString"])(e.translate("API_Glossary")),1),Object(n["createElementVNode"])("p",null,Object(n["toDisplayString"])(e.translate("API_LearnAboutCommonlyUsedTerms2")),1)])),[[S]])])]),Object(n["createElementVNode"])("div",a,[Object(n["createElementVNode"])("div",b,[Object(n["createElementVNode"])("ul",d,[(Object(n["openBlock"])(!0),Object(n["createElementBlock"])(n["Fragment"],null,Object(n["renderList"])(e.glossaryItems,(e,t,c)=>(Object(n["openBlock"])(),Object(n["createElementBlock"])("li",{key:t,class:"tab col s3"},[Object(n["createElementVNode"])("a",{class:Object(n["normalizeClass"])(0===c?"active":""),href:"#"+t},Object(n["toDisplayString"])(e.title),11,u)]))),128))])]),(Object(n["openBlock"])(!0),Object(n["createElementBlock"])(n["Fragment"],null,Object(n["renderList"])(e.glossaryItems,(t,c)=>(Object(n["openBlock"])(),Object(n["createElementBlock"])("div",{key:c,id:c,class:"col s12"},[Object(n["createElementVNode"])("div",j,[Object(n["createElementVNode"])("div",m,[Object(n["createElementVNode"])("div",O,[Object(n["createElementVNode"])("h2",f,Object(n["toDisplayString"])(t.title),1),Object(n["createElementVNode"])("ul",y,[(Object(n["openBlock"])(!0),Object(n["createElementBlock"])(n["Fragment"],null,Object(n["renderList"])(t.letters,(e,t)=>(Object(n["openBlock"])(),Object(n["createElementBlock"])("li",{key:t,class:"waves-effect",style:{"margin-right":"3.5px"}},[Object(n["createElementVNode"])("a",{href:`#${c}${e}`},Object(n["toDisplayString"])(e),9,k)]))),128))])]),(Object(n["openBlock"])(!0),Object(n["createElementBlock"])(n["Fragment"],null,Object(n["renderList"])(e.entriesByLetter(t.entries),([t,o])=>(Object(n["openBlock"])(),Object(n["createElementBlock"])("div",{key:t,class:"scrollspy",id:`${c}${t}`},[(Object(n["openBlock"])(!0),Object(n["createElementBlock"])(n["Fragment"],null,Object(n["renderList"])(o,(t,o)=>(Object(n["openBlock"])(),Object(n["createElementBlock"])("div",{key:o},[Object(n["createElementVNode"])("h3",v,Object(n["toDisplayString"])(t.name),1),t.subtitle?(Object(n["openBlock"])(),Object(n["createElementBlock"])("p",E,Object(n["toDisplayString"])(e.translate(t.subtitle)),1)):Object(n["createCommentVNode"])("",!0),Object(n["createElementVNode"])("p",null,[Object(n["createElementVNode"])("span",{innerHTML:e.$sanitize(t.documentation)},null,8,B),t.id?(Object(n["openBlock"])(),Object(n["createElementBlock"])("br",h)):Object(n["createCommentVNode"])("",!0),t.id?(Object(n["openBlock"])(),Object(n["createElementBlock"])("span",V,Object(n["toDisplayString"])(t.id)+Object(n["toDisplayString"])("metrics"===c||t.is_metric?" (API)":""),1)):Object(n["createCommentVNode"])("",!0)])]))),128))],8,g))),128))])])],8,p))),128))])],512)}var S=c("19dc");const{$:w}=window;var x=Object(n["defineComponent"])({props:{glossaryItems:{type:Object,required:!0}},directives:{ContentIntro:S["ContentIntro"]},mounted(){const e=this.$refs.root;setTimeout(()=>{w(".scrollspy",e).scrollSpy(),w(".pushpin",e).pushpin({top:w(".pushpin",e).offset().top}),w(".tabs",e).tabs()})},methods:{entriesByLetter(e){const t={};e.forEach(e=>{t[e.letter]=t[e.letter]||[],t[e.letter].push(e)});const c=Object.entries(t);return c.sort(([e],[t])=>et?1:0),c}}});x.render=N;var C=x;
+/*!
+ * Matomo - free/libre analytics platform
+ *
+ * @link https://matomo.org
+ * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
+*/}})}));
+//# sourceMappingURL=API.umd.min.js.map
\ No newline at end of file
diff --git a/plugins/API/vue/dist/umd.metadata.json b/plugins/API/vue/dist/umd.metadata.json
new file mode 100644
index 0000000000000000000000000000000000000000..9ecfcc0456204cf8e8e80416ebc95ef42d4fbd28
--- /dev/null
+++ b/plugins/API/vue/dist/umd.metadata.json
@@ -0,0 +1,5 @@
+{
+ "dependsOn": [
+ "CoreHome"
+ ]
+}
\ No newline at end of file
diff --git a/plugins/API/vue/src/Glossary/Glossary.vue b/plugins/API/vue/src/Glossary/Glossary.vue
new file mode 100644
index 0000000000000000000000000000000000000000..3d64f5bf99ff85e4ff17745fab112ab222bc4a22
--- /dev/null
+++ b/plugins/API/vue/src/Glossary/Glossary.vue
@@ -0,0 +1,141 @@
+
+
+
+
+
+
+
+
{{ translate('API_Glossary') }}
+
+ {{ translate('API_LearnAboutCommonlyUsedTerms2') }}
+
+
+
+
+
+
+
+
+
+
+
+
{{ item.title }}
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/plugins/API/vue/src/index.ts b/plugins/API/vue/src/index.ts
new file mode 100644
index 0000000000000000000000000000000000000000..618caf9a86b2e18c07dedae0765cff2c14a64d46
--- /dev/null
+++ b/plugins/API/vue/src/index.ts
@@ -0,0 +1,8 @@
+/*!
+ * Matomo - free/libre analytics platform
+ *
+ * @link https://matomo.org
+ * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
+*/
+
+export { default as Glossary } from './Glossary/Glossary.vue';
diff --git a/plugins/Actions/API.php b/plugins/Actions/API.php
new file mode 100644
index 0000000000000000000000000000000000000000..b36425b07f441d4e12720882cbe2f07bafef8d90
--- /dev/null
+++ b/plugins/Actions/API.php
@@ -0,0 +1,874 @@
+Actions metrics for each row.
+ *
+ * It is also possible to request data for a specific Page Title with "getPageTitle"
+ * and setting the parameter pageName to the page title you wish to request.
+ * Similarly, you can request metrics for a given Page URL via "getPageUrl", a Download file via "getDownload"
+ * and an outlink via "getOutlink".
+ *
+ * Note: pageName, pageUrl, outlinkUrl, downloadUrl parameters must be URL encoded before you call the API.
+ * @method static \Piwik\Plugins\Actions\API getInstance()
+ */
+class API extends \Piwik\Plugin\API
+{
+ /**
+ * Returns aggregated action metrics for the requested site and period.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param list|string|false $columns Metrics to include in the response.
+ * Accepts a comma-separated list or array of metric names.
+ * @return DataTable|DataTable\Map Action metrics for the selected site, period, and segment.
+ */
+ public function get($idSite, string $period, string $date, $segment = false, $columns = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ /** @var Reports\Get $report */
+ $report = ReportsProvider::factory("Actions", "get");
+ $archive = Archive::build($idSite, $period, $date, $segment);
+
+ $requestedColumns = Piwik::getArrayFromApiParameter($columns);
+ $columns = $report->getMetricsRequiredForReport($allColumns = null, $requestedColumns);
+
+ $inDbColumnNames = array_map(function ($value) {
+ return 'Actions_' . $value;
+ }, $columns);
+ $dataTable = $archive->getDataTableFromNumeric($inDbColumnNames);
+
+ $dataTable->deleteColumns(array_diff($requestedColumns, $columns));
+
+ $newNameMapping = array_combine($inDbColumnNames, $columns);
+ $dataTable->filter('ReplaceColumnNames', [$newNameMapping]);
+
+ $columnsToShow = $requestedColumns ?: $report->getAllMetrics();
+ $dataTable->queueFilter('ColumnDelete', [$columnsToRemove = [], $columnsToShow]);
+
+ return $dataTable;
+ }
+
+ /**
+ * Returns page URL metrics for the requested site and period.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @param int|null|false $depth Maximum depth of subtables to include when expanding results.
+ * @param bool $flat Whether to flatten the hierarchical URL report into a single table.
+ * @return DataTable|DataTable\Map Page URL metrics for the requested action rows.
+ */
+ public function getPageUrls(
+ $idSite,
+ string $period,
+ string $date,
+ $segment = false,
+ bool $expanded = false,
+ $idSubtable = false,
+ $depth = false,
+ bool $flat = false
+ ) {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = Archive::createDataTableFromArchive('Actions_actions_url', $idSite, $period, $date, $segment, $expanded, $flat, $idSubtable, $depth);
+
+ $this->filterActionsDataTable($dataTable, Action::TYPE_PAGE_URL);
+
+ if ($flat) {
+ $dataTable->filter(function (DataTable $dataTable) {
+ $notDefinedUrl = ArchivingHelper::getUnknownActionName(Action::TYPE_PAGE_URL);
+ foreach ($dataTable->getRows() as $row) {
+ $label = (string)$row->getColumn('label');
+ if (substr($label, 0, 1) !== '/' && $label !== $notDefinedUrl) {
+ $row->setColumn('label', '/' . $label);
+ }
+ }
+ });
+ }
+
+ return $dataTable;
+ }
+
+ /**
+ * Returns page URL metrics for pages viewed immediately after an internal site search.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @return DataTable|DataTable\Map Page URLs that followed an internal search.
+ */
+ public function getPageUrlsFollowingSiteSearch($idSite, string $period, string $date, $segment = false, bool $expanded = false, $idSubtable = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = $this->getPageUrls($idSite, $period, $date, $segment, $expanded, $idSubtable);
+ $this->keepPagesFollowingSearch($dataTable);
+ return $dataTable;
+ }
+
+ /**
+ * Returns page title metrics for pages viewed immediately after an internal site search.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @return DataTable|DataTable\Map Page titles that followed an internal search.
+ */
+ public function getPageTitlesFollowingSiteSearch($idSite, string $period, string $date, $segment = false, bool $expanded = false, $idSubtable = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = $this->getPageTitles($idSite, $period, $date, $segment, $expanded, $idSubtable);
+ $this->keepPagesFollowingSearch($dataTable);
+ return $dataTable;
+ }
+
+ /**
+ * @param DataTable|DataTable\Map $dataTable
+ */
+ protected function keepPagesFollowingSearch($dataTable): void
+ {
+ // Keep only pages which are following site search
+ $dataTable->filter('ColumnCallbackDeleteRow', [
+ PiwikMetrics::INDEX_PAGE_IS_FOLLOWING_SITE_SEARCH_NB_HITS,
+ function ($value) {
+ return $value <= 0;
+ },
+ ]);
+ }
+
+ /**
+ * Returns a DataTable with analytics information for every unique entry page URL, for
+ * the specified site, period & segment.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @param bool $flat Whether to flatten the hierarchical URL report into a single table.
+ * @return DataTable|DataTable\Map Entry page URL metrics for the requested site.
+ */
+ public function getEntryPageUrls(
+ $idSite,
+ string $period,
+ string $date,
+ $segment = false,
+ bool $expanded = false,
+ $idSubtable = false,
+ bool $flat = false
+ ) {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = $this->getPageUrls($idSite, $period, $date, $segment, $expanded, $idSubtable, false, $flat);
+ $this->filterNonEntryActions($dataTable);
+ return $dataTable;
+ }
+
+ /**
+ * Returns a DataTable with analytics information for every unique exit page URL, for
+ * the specified site, period & segment.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @param bool $flat Whether to flatten the hierarchical URL report into a single table.
+ * @return DataTable|DataTable\Map Exit page URL metrics for the requested site.
+ */
+ public function getExitPageUrls(
+ $idSite,
+ string $period,
+ string $date,
+ $segment = false,
+ bool $expanded = false,
+ $idSubtable = false,
+ bool $flat = false
+ ) {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = $this->getPageUrls($idSite, $period, $date, $segment, $expanded, $idSubtable, false, $flat);
+ $this->filterNonExitActions($dataTable);
+ return $dataTable;
+ }
+
+ /**
+ * Returns metrics for a specific page URL.
+ *
+ * @param string $pageUrl The URL-encoded page URL to look up.
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @return DataTable|DataTable\Map Metrics for the requested page URL, or an empty table if it is not found.
+ */
+ public function getPageUrl($pageUrl, $idSite, string $period, string $date, $segment = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $callBackParameters = ['Actions_actions_url', $idSite, $period, $date, $segment, $expanded = false, $flat = false, $idSubtable = null];
+ $dataTable = $this->getFilterPageDatatableSearch($callBackParameters, $pageUrl, Action::TYPE_PAGE_URL);
+ $this->addPageProcessedMetrics($dataTable);
+ $this->filterActionsDataTable($dataTable, Action::TYPE_PAGE_URL);
+ return $dataTable;
+ }
+
+ /**
+ * Returns page title metrics for the requested site and period.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @param bool $flat Whether to flatten the hierarchical title report into a single table.
+ * @return DataTable|DataTable\Map Page title metrics for the requested action rows.
+ */
+ public function getPageTitles($idSite, string $period, string $date, $segment = false, bool $expanded = false, $idSubtable = false, bool $flat = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = Archive::createDataTableFromArchive('Actions_actions', $idSite, $period, $date, $segment, $expanded, $flat, $idSubtable);
+
+ $this->filterActionsDataTable($dataTable, Action::TYPE_PAGE_TITLE);
+
+ return $dataTable;
+ }
+
+ /**
+ * Returns a DataTable with analytics information for every unique entry page title
+ * for the given site, time period & segment.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @param bool $flat Whether to flatten the hierarchical title report into a single table.
+ * @return DataTable|DataTable\Map Entry page title metrics for the requested site.
+ */
+ public function getEntryPageTitles(
+ $idSite,
+ string $period,
+ string $date,
+ $segment = false,
+ bool $expanded = false,
+ $idSubtable = false,
+ bool $flat = false
+ ) {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = $this->getPageTitles($idSite, $period, $date, $segment, $expanded, $idSubtable, $flat);
+ $this->filterNonEntryActions($dataTable);
+ return $dataTable;
+ }
+
+ /**
+ * Returns a DataTable with analytics information for every unique exit page title
+ * for the given site, time period & segment.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @param bool $flat Whether to flatten the hierarchical title report into a single table.
+ * @return DataTable|DataTable\Map Exit page title metrics for the requested site.
+ */
+ public function getExitPageTitles(
+ $idSite,
+ string $period,
+ string $date,
+ $segment = false,
+ bool $expanded = false,
+ $idSubtable = false,
+ bool $flat = false
+ ) {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = $this->getPageTitles($idSite, $period, $date, $segment, $expanded, $idSubtable, $flat);
+ $this->filterNonExitActions($dataTable);
+ return $dataTable;
+ }
+
+ /**
+ * Returns metrics for a specific page title.
+ *
+ * @param string $pageName The URL-encoded page title to look up.
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @return DataTable|DataTable\Map Metrics for the requested page title, or an empty table if it is not found.
+ */
+ public function getPageTitle($pageName, $idSite, string $period, string $date, $segment = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $callBackParameters = ['Actions_actions', $idSite, $period, $date, $segment, $expanded = false, $flat = false, $idSubtable = null];
+ $dataTable = $this->getFilterPageDatatableSearch($callBackParameters, $pageName, Action::TYPE_PAGE_TITLE);
+ $this->addPageProcessedMetrics($dataTable);
+ $this->filterActionsDataTable($dataTable, Action::TYPE_PAGE_TITLE);
+ return $dataTable;
+ }
+
+ /**
+ * Returns download metrics for the requested site and period.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @param bool $flat Whether to flatten the hierarchical download report into a single table.
+ * @return DataTable|DataTable\Map Download metrics for the requested action rows.
+ */
+ public function getDownloads($idSite, string $period, string $date, $segment = false, bool $expanded = false, $idSubtable = false, bool $flat = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = Archive::createDataTableFromArchive('Actions_downloads', $idSite, $period, $date, $segment, $expanded, $flat, $idSubtable);
+ $this->filterActionsDataTable($dataTable, Action::TYPE_DOWNLOAD);
+ return $dataTable;
+ }
+
+ /**
+ * Returns metrics for a specific download URL.
+ *
+ * @param string $downloadUrl The URL-encoded download URL to look up.
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @return DataTable|DataTable\Map Metrics for the requested download URL, or an empty table if it is not found.
+ */
+ public function getDownload($downloadUrl, $idSite, string $period, string $date, $segment = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $callBackParameters = ['Actions_downloads', $idSite, $period, $date, $segment, $expanded = false, $flat = false, $idSubtable = null];
+ $dataTable = $this->getFilterPageDatatableSearch($callBackParameters, $downloadUrl, Action::TYPE_DOWNLOAD);
+ $this->filterActionsDataTable($dataTable, Action::TYPE_DOWNLOAD);
+ return $dataTable;
+ }
+
+ /**
+ * Returns outlink metrics for the requested site and period.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @param bool $expanded Whether to expand all rows and include their subtables.
+ * @param int|null|false $idSubtable Subtable ID to fetch instead of the top-level report.
+ * @param bool $flat Whether to flatten the hierarchical outlink report into a single table.
+ * @return DataTable|DataTable\Map Outlink metrics for the requested action rows.
+ */
+ public function getOutlinks($idSite, string $period, string $date, $segment = false, bool $expanded = false, $idSubtable = false, bool $flat = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = Archive::createDataTableFromArchive('Actions_outlink', $idSite, $period, $date, $segment, $expanded, $flat, $idSubtable);
+ $this->filterActionsDataTable($dataTable, Action::TYPE_OUTLINK);
+ return $dataTable;
+ }
+
+ /**
+ * Returns metrics for a specific outlink URL.
+ *
+ * @param string $outlinkUrl The URL-encoded outlink URL to look up.
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @return DataTable|DataTable\Map Metrics for the requested outlink URL, or an empty table if it is not found.
+ */
+ public function getOutlink($outlinkUrl, $idSite, string $period, string $date, $segment = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $callBackParameters = ['Actions_outlink', $idSite, $period, $date, $segment, $expanded = false, $flat = false, $idSubtable = null];
+ $dataTable = $this->getFilterPageDatatableSearch($callBackParameters, $outlinkUrl, Action::TYPE_OUTLINK);
+ $this->filterActionsDataTable($dataTable, Action::TYPE_OUTLINK);
+ return $dataTable;
+ }
+
+ /**
+ * Returns internal search keywords that produced search results.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @return DataTable|DataTable\Map Site search keywords that returned at least one result.
+ */
+ public function getSiteSearchKeywords($idSite, string $period, string $date, $segment = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = $this->getSiteSearchKeywordsRaw($idSite, $period, $date, $segment);
+ $dataTable->deleteColumn(PiwikMetrics::INDEX_SITE_SEARCH_HAS_NO_RESULT);
+ $this->filterActionsDataTable($dataTable, Action::TYPE_SITE_SEARCH);
+ $dataTable->filter('ReplaceColumnNames');
+ $dataTable->filter('AddSegmentByLabel', ['siteSearchKeyword']);
+ $this->addPagesPerSearchColumn($dataTable);
+ return $dataTable;
+ }
+
+ /**
+ * Visitors can search, and then click "next" to view more results. This is the average number of search results pages viewed for this keyword.
+ *
+ * @param DataTable|DataTable\Simple|DataTable\Map $dataTable
+ * @param string $columnToRead
+ */
+ protected function addPagesPerSearchColumn($dataTable, $columnToRead = 'nb_hits'): void
+ {
+ $dataTable->filter('ColumnCallbackAddColumnQuotient', ['nb_pages_per_search', $columnToRead, 'nb_visits', $precision = 1]);
+ }
+
+ /**
+ * Returns the raw internal site search keyword report before post-processing.
+ *
+ * @param int|string|int[] $idSite
+ * @param string|null|false $segment
+ * @return DataTable|DataTable\Map
+ */
+ protected function getSiteSearchKeywordsRaw($idSite, string $period, string $date, $segment)
+ {
+ return Archive::createDataTableFromArchive('Actions_sitesearch', $idSite, $period, $date, $segment, $expanded = false);
+ }
+
+ /**
+ * Returns internal search keywords that produced no results.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @return DataTable|DataTable\Map Site search keywords that returned no results.
+ */
+ public function getSiteSearchNoResultKeywords($idSite, string $period, string $date, $segment = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = $this->getSiteSearchKeywordsRaw($idSite, $period, $date, $segment);
+ // Delete all rows that have some results
+ $dataTable->filter(
+ 'ColumnCallbackDeleteRow',
+ [
+ PiwikMetrics::INDEX_SITE_SEARCH_HAS_NO_RESULT,
+ function ($value) {
+ return $value < 1;
+ },
+ ]
+ );
+ $dataTable->deleteRow(DataTable::ID_SUMMARY_ROW);
+ $dataTable->deleteColumn(PiwikMetrics::INDEX_SITE_SEARCH_HAS_NO_RESULT);
+ $this->filterActionsDataTable($dataTable, $isPageTitleType = false);
+ $dataTable->filter('AddSegmentByLabel', ['siteSearchKeyword']);
+ $dataTable->filter('ReplaceColumnNames');
+ $this->addPagesPerSearchColumn($dataTable);
+ return $dataTable;
+ }
+
+ /**
+ * Returns internal search categories used by visitors on the site.
+ *
+ * @param int|string|int[] $idSite Website ID(s) to query.
+ * - Single site ID (e.g. 1)
+ * - Multiple site IDs (e.g. [1, 4, 5])
+ * - Comma-separated list ("1,4,5") or "all"
+ * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
+ * containing the specified date.
+ * @param string $date The date or date range to process.
+ * 'YYYY-MM-DD', magic keywords (today, yesterday, lastWeek, lastMonth, lastYear),
+ * or date range (ie, 'YYYY-MM-DD,YYYY-MM-DD', lastX, previousX).
+ * @param string|null|false $segment Custom segment to filter the report.
+ * Example: "referrerName==example.com"
+ * Supports AND (;) and OR (,) operators.
+ * @return DataTable|DataTable\Map Site search categories and their metrics.
+ */
+ public function getSiteSearchCategories($idSite, string $period, string $date, $segment = false)
+ {
+ Piwik::checkUserHasViewAccess($idSite);
+
+ $dataTable = Archive::createDataTableFromArchive('Actions_SiteSearchCategories', $idSite, $period, $date, $segment);
+
+ $dataTable->queueFilter('ColumnDelete', ['nb_uniq_visitors']);
+ $this->filterActionsDataTable($dataTable, $isPageTitleType = false);
+ $dataTable->filter('ReplaceColumnNames');
+ $dataTable->filter('AddSegmentValue');
+ $this->addPagesPerSearchColumn($dataTable, $columnToRead = 'nb_actions');
+
+ return $dataTable;
+ }
+
+ /**
+ * Searches an actions report for the first row whose label matches the requested value.
+ *
+ * @param list $callBackParameters
+ * @param string $search
+ * @param int $actionType
+ * @return DataTable|DataTable\Map
+ */
+ protected function getFilterPageDatatableSearch($callBackParameters, $search, $actionType)
+ {
+ // build the query parts that are searched inside the tree
+ if ($actionType == Action::TYPE_PAGE_TITLE) {
+ $searchedString = Common::unsanitizeInputValue($search);
+ } else {
+ $idSite = $callBackParameters[1];
+ try {
+ $searchedString = PageUrl::excludeQueryParametersFromUrl($search, $idSite);
+ } catch (Exception $e) {
+ $searchedString = $search;
+ }
+ }
+ ArchivingHelper::reloadConfig();
+ $searchTree = ArchivingHelper::getActionExplodedNames($searchedString, $actionType);
+
+ /** @var DataTable|DataTable\Map $table */
+ $table = call_user_func_array('\Piwik\Archive::createDataTableFromArchive', $callBackParameters);
+
+ if ($table instanceof DataTable\Map) {
+ // search an array of tables, e.g. when using date=last30
+ // note that if the root is an array, we filter all children
+ // if an array occurs inside the nested table, we only look for the first match (see below)
+ $dataTableMap = $table->getEmptyClone();
+
+ foreach ($table->getDataTables() as $label => $subTable) {
+ $newSubTable = $this->doFilterPageDatatableSearch($callBackParameters, $subTable, $searchTree);
+
+ $dataTableMap->addTable($newSubTable, $label);
+ }
+
+ return $dataTableMap;
+ }
+
+ return $this->doFilterPageDatatableSearch($callBackParameters, $table, $searchTree);
+ }
+
+ /**
+ * Traverses an actions report tree and returns the first matching row as a table.
+ *
+ * @FIXME This looks very similar to LabelFilter.php should it be refactored somehow?
+ *
+ * @param list $callBackParameters
+ * @param DataTable|DataTable\Map $table
+ * @param list $searchTree
+ * @return DataTable
+ */
+ protected function doFilterPageDatatableSearch($callBackParameters, $table, $searchTree)
+ {
+ // filter a data table array
+ if ($table instanceof DataTable\Map) {
+ foreach ($table->getDataTables() as $subTable) {
+ $filteredSubTable = $this->doFilterPageDatatableSearch($callBackParameters, $subTable, $searchTree);
+
+ if ($filteredSubTable->getRowsCount() > 0) {
+ // match found in a sub table, return and stop searching the others
+ return $filteredSubTable;
+ }
+ }
+
+ // nothing found in all sub tables
+ $result = new DataTable();
+ $subTables = $table->getDataTables();
+ if (count($subTables) > 0) {
+ // use the first subtable's metadata to ensure basic metadata like `period` is available in response
+ $subTable = reset($subTables);
+ $result->setAllTableMetadata($subTable->getAllTableMetadata());
+ }
+ return $result;
+ }
+
+ // filter regular data table
+ if ($table instanceof DataTable) {
+ // search for the first part of the tree search
+ $search = array_shift($searchTree);
+ $row = $table->getRowFromLabel($search);
+ if ($row === false) {
+ // not found
+ $result = new DataTable();
+ $result->setAllTableMetadata($table->getAllTableMetadata());
+ return $result;
+ }
+
+ // end of tree search reached
+ if (count($searchTree) == 0) {
+ $result = $table->getEmptyClone();
+ $result->addRow($row);
+ $result->setAllTableMetadata($table->getAllTableMetadata());
+ return $result;
+ }
+
+ // match found on this level and more levels remaining: go deeper
+ $idSubTable = $row->getIdSubDataTable();
+ $callBackParameters[7] = $idSubTable;
+
+ /**
+ * @var \Piwik\Period|false $period
+ */
+ $period = $table->getMetadata('period');
+ if (!empty($period)) {
+ $callBackParameters[3] = $period->getDateStart() . ',' . $period->getDateEnd();
+ }
+
+ $table = call_user_func_array('\Piwik\Archive::createDataTableFromArchive', $callBackParameters);
+ return $this->doFilterPageDatatableSearch($callBackParameters, $table, $searchTree);
+ }
+ }
+
+ /**
+ * Applies the shared post-processing filters used by Actions API reports.
+ *
+ * @template T of DataTable|DataTable\Map
+ *
+ * @param T $dataTable
+ * @param int|false $actionType Action type constant used to normalize labels and metadata.
+ * @return T
+ */
+ private function filterActionsDataTable($dataTable, $actionType)
+ {
+ $dataTable->filter(function ($dataTable) {
+ $dataTable->setMetadata(DataTable::COLUMN_AGGREGATION_OPS_METADATA_NAME, Metrics::getColumnsAggregationOperation());
+ });
+ // Must be applied before Sort in this case, since the DataTable can contain both int and strings indexes
+ // (in the transition period between pre 1.2 and post 1.2 datatable structure)
+ $dataTable->filter('Piwik\Plugins\Actions\DataTable\Filter\Actions', [$actionType]);
+ $dataTable->filter('Piwik\Plugins\Goals\DataTable\Filter\CalculateConversionPageRate');
+ return $dataTable;
+ }
+
+ /**
+ * Removes DataTable rows referencing actions that were never the first action of a visit.
+ *
+ * @param DataTable|DataTable\Map $dataTable
+ */
+ private function filterNonEntryActions($dataTable): void
+ {
+ $dataTable->filter(
+ 'ColumnCallbackDeleteRow',
+ [
+ PiwikMetrics::INDEX_PAGE_ENTRY_NB_VISITS,
+ function ($visits) {
+ return !strlen($visits);
+ },
+ ]
+ );
+ }
+
+ /**
+ * Removes DataTable rows referencing actions that were never the last action of a visit.
+ *
+ * @param DataTable|DataTable\Map $dataTable
+ */
+ private function filterNonExitActions($dataTable): void
+ {
+ $dataTable->filter(
+ 'ColumnCallbackDeleteRow',
+ [
+ PiwikMetrics::INDEX_PAGE_EXIT_NB_VISITS,
+ function ($visits) {
+ return !strlen($visits);
+ },
+ ]
+ );
+ }
+
+ private function addPageProcessedMetrics(DataTable\DataTableInterface $dataTable): void
+ {
+ $dataTable->filter(function (DataTable $table) {
+ /** @var ProcessedMetric[] $extraProcessedMetrics */
+ $extraProcessedMetrics = $table->getMetadata(DataTable::EXTRA_PROCESSED_METRICS_METADATA_NAME) ?: [];
+ $extraProcessedMetrics[] = new AverageTimeOnPage();
+ $extraProcessedMetrics[] = new BounceRate();
+ $extraProcessedMetrics[] = new ExitRate();
+ $extraProcessedMetrics[] = new AveragePageGenerationTime();
+
+ $table->setMetadata(DataTable::EXTRA_PROCESSED_METRICS_METADATA_NAME, $extraProcessedMetrics);
+ });
+ }
+}
diff --git a/plugins/Actions/Actions.php b/plugins/Actions/Actions.php
new file mode 100644
index 0000000000000000000000000000000000000000..12e145a1a446b767fbfde572b5f5d5c446884db5
--- /dev/null
+++ b/plugins/Actions/Actions.php
@@ -0,0 +1,198 @@
+ 'configureViewDataTable',
+ 'AssetManager.getJavaScriptFiles' => 'getJsFiles',
+ 'Insights.addReportToOverview' => 'addReportToInsightsOverview',
+ 'Metrics.getDefaultMetricTranslations' => 'addMetricTranslations',
+ 'Metrics.getDefaultMetricSemanticTypes' => 'addMetricSemanticTypes',
+ 'Metrics.getDefaultMetricDocumentationTranslations' => 'addMetricDocumentationTranslations',
+ 'Actions.addActionTypes' => 'addActionTypes',
+ );
+ }
+
+ public function addMetricSemanticTypes(array &$types): void
+ {
+ $metrics = array(
+ 'nb_pageviews' => Dimension::TYPE_NUMBER,
+ 'nb_uniq_pageviews' => Dimension::TYPE_NUMBER,
+ 'nb_downloads' => Dimension::TYPE_NUMBER,
+ 'nb_uniq_downloads' => Dimension::TYPE_NUMBER,
+ 'nb_outlinks' => Dimension::TYPE_NUMBER,
+ 'nb_uniq_outlinks' => Dimension::TYPE_NUMBER,
+ 'nb_searches' => Dimension::TYPE_NUMBER,
+ 'nb_keywords' => Dimension::TYPE_NUMBER,
+ 'entry_nb_visits' => Dimension::TYPE_NUMBER,
+ 'entry_bounce_count' => Dimension::TYPE_NUMBER,
+ 'exit_nb_visits' => Dimension::TYPE_NUMBER,
+ 'nb_pages_per_search' => Dimension::TYPE_NUMBER,
+ 'nb_hits_following_search' => Dimension::TYPE_NUMBER,
+ );
+
+ $types = array_merge($types, $metrics);
+ }
+
+ public function addMetricTranslations(&$translations)
+ {
+ $metrics = array(
+ 'nb_pageviews' => 'General_ColumnPageviews',
+ 'nb_uniq_pageviews' => 'General_ColumnUniquePageviews',
+ 'nb_downloads' => 'General_Downloads',
+ 'nb_uniq_downloads' => 'Actions_ColumnUniqueDownloads',
+ 'nb_outlinks' => 'General_Outlinks',
+ 'nb_uniq_outlinks' => 'Actions_ColumnUniqueOutlinks',
+ 'nb_searches' => 'Actions_ColumnSearches',
+ 'nb_keywords' => 'Actions_ColumnSiteSearchKeywords',
+ 'avg_time_generation' => 'General_ColumnAverageGenerationTime',
+ 'exit_rate' => 'General_ColumnExitRate',
+ 'entry_nb_visits' => 'General_ColumnEntrances',
+ 'entry_bounce_count' => 'General_ColumnBounces',
+ 'exit_nb_visits' => 'General_ColumnExits',
+ 'nb_pages_per_search' => 'Actions_ColumnPagesPerSearch',
+ 'nb_hits_following_search' => 'General_ColumnViewedAfterSearch',
+ );
+
+ $translations = array_merge($translations, $metrics);
+ }
+
+ public function addMetricDocumentationTranslations(&$translations)
+ {
+ $metrics = array(
+ 'nb_pageviews' => 'General_ColumnPageviewsDocumentation',
+ 'nb_uniq_pageviews' => 'General_ColumnUniquePageviewsDocumentation',
+ 'nb_downloads' => 'Actions_ColumnClicksDocumentation',
+ 'nb_uniq_downloads' => 'Actions_ColumnUniqueClicksDocumentation',
+ 'nb_outlinks' => 'Actions_ColumnClicksDocumentation',
+ 'nb_uniq_outlinks' => 'Actions_ColumnUniqueClicksDocumentation',
+ 'nb_searches' => 'Actions_ColumnSearchesDocumentation',
+ 'avg_time_generation' => 'General_ColumnAverageGenerationTimeDocumentation',
+ 'entry_nb_visits' => 'General_ColumnEntrancesDocumentation',
+ 'entry_bounce_count' => 'General_ColumnBouncesDocumentation',
+ 'exit_nb_visits' => 'General_ColumnExitsDocumentation',
+ 'exit_rate' => 'General_ColumnExitRateDocumentation',
+ );
+
+ $translations = array_merge($translations, $metrics);
+ }
+
+ public function addReportToInsightsOverview(&$reports)
+ {
+ $reports['Actions_getPageUrls'] = array();
+ $reports['Actions_getPageTitles'] = array();
+ $reports['Actions_getDownloads'] = array('flat' => 1);
+ }
+
+ public function getJsFiles(&$jsFiles)
+ {
+ $jsFiles[] = "plugins/Actions/javascripts/actionsDataTable.js";
+ $jsFiles[] = "plugins/Actions/javascripts/rowactions.js";
+ }
+
+ public function addActionTypes(&$types)
+ {
+ $types[] = [
+ 'id' => Action::TYPE_PAGE_URL,
+ 'name' => 'pageviews',
+ ];
+ $types[] = [
+ 'id' => Action::TYPE_CONTENT,
+ 'name' => 'contents',
+ ];
+ $types[] = [
+ 'id' => Action::TYPE_SITE_SEARCH,
+ 'name' => 'sitesearches',
+ ];
+ $types[] = [
+ 'id' => Action::TYPE_EVENT,
+ 'name' => 'events',
+ ];
+ $types[] = [
+ 'id' => Action::TYPE_OUTLINK,
+ 'name' => 'outlinks',
+ ];
+ $types[] = [
+ 'id' => Action::TYPE_DOWNLOAD,
+ 'name' => 'downloads',
+ ];
+ }
+
+ public function isSiteSearchEnabled($idSites, $idSite)
+ {
+ $idSites = Site::getIdSitesFromIdSitesString($idSites, true);
+
+ if (!empty($idSite)) {
+ $idSites[] = $idSite;
+ }
+
+ if (empty($idSites)) {
+ return false;
+ }
+
+ foreach ($idSites as $idSite) {
+ if (!Site::isSiteSearchEnabledFor($idSite)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+
+ public function configureViewDataTable(ViewDataTable $view)
+ {
+ if ($this->pluginName == $view->requestConfig->getApiModuleToRequest()) {
+ if ($view->isRequestingSingleDataTable()) {
+ // make sure custom visualizations are shown on actions reports
+ $view->config->show_all_views_icons = true;
+ $view->config->show_bar_chart = false;
+ $view->config->show_pie_chart = false;
+ $view->config->show_tag_cloud = false;
+ }
+ }
+ }
+
+ /**
+ * @param \Piwik\DataTable $dataTable
+ * @param int $level
+ */
+ public static function setDataTableRowLevels($dataTable, $level = 0)
+ {
+ foreach ($dataTable->getRows() as $row) {
+ $row->setMetadata('css_class', 'level' . $level);
+
+ $subtable = $row->getSubtable();
+ if ($subtable) {
+ self::setDataTableRowLevels($subtable, $level + 1);
+ }
+ }
+ }
+}
diff --git a/plugins/Actions/Actions/ActionClickUrl.php b/plugins/Actions/Actions/ActionClickUrl.php
new file mode 100644
index 0000000000000000000000000000000000000000..e1087112f561dd9381b2cd72e0fd85523da9149b
--- /dev/null
+++ b/plugins/Actions/Actions/ActionClickUrl.php
@@ -0,0 +1,70 @@
+setActionUrlWithoutExcludingParameters($request->getParam('link'));
+ }
+
+ public static function shouldHandle(Request $request)
+ {
+ $outlinkUrl = $request->getParam('link');
+
+ return !empty($outlinkUrl);
+ }
+
+ protected function getActionsToLookup()
+ {
+ return array(
+ // Note: we do not normalize outlink URL
+ 'idaction_url' => array($this->getActionUrl(), $this->getActionType()),
+ );
+ }
+
+ public function writeDebugInfo()
+ {
+ parent::writeDebugInfo();
+
+ if ($this->detectActionIsOutlinkOnAliasHost($this, $this->request->getIdSite())) {
+ Common::printDebug("INFO: The outlink URL host is one of the known host for this website. ");
+ }
+ }
+
+ /**
+ * Detect whether action is an outlink given host aliases
+ *
+ * @return bool true if the outlink the visitor clicked on points to one of the known hosts for this website
+ */
+ protected function detectActionIsOutlinkOnAliasHost(Action $action, $idSite)
+ {
+ $decodedActionUrl = $action->getActionUrl();
+ $actionUrlParsed = @parse_url($decodedActionUrl);
+
+ if (!isset($actionUrlParsed['host'])) {
+ return false;
+ }
+
+ return Visit::isHostKnownAliasHost($actionUrlParsed['host'], $idSite);
+ }
+}
diff --git a/plugins/Actions/Actions/ActionDownloadUrl.php b/plugins/Actions/Actions/ActionDownloadUrl.php
new file mode 100644
index 0000000000000000000000000000000000000000..f9fd6233b239e4db8e3630f464762001e256fc8b
--- /dev/null
+++ b/plugins/Actions/Actions/ActionDownloadUrl.php
@@ -0,0 +1,41 @@
+setActionUrlWithoutExcludingParameters($request->getParam('download'));
+ }
+
+ public static function shouldHandle(Request $request)
+ {
+ $downloadUrl = $request->getParam('download');
+
+ return !empty($downloadUrl);
+ }
+
+ protected function getActionsToLookup()
+ {
+ return array(
+ // Note: we do not normalize download URL
+ 'idaction_url' => array($this->getActionUrl(), $this->getActionType()),
+ );
+ }
+}
diff --git a/plugins/Actions/Actions/ActionSiteSearch.php b/plugins/Actions/Actions/ActionSiteSearch.php
new file mode 100644
index 0000000000000000000000000000000000000000..441434f64be2594cd24e4cb7e7038b2ff92eb102
--- /dev/null
+++ b/plugins/Actions/Actions/ActionSiteSearch.php
@@ -0,0 +1,285 @@
+originalUrl = $request->getParam('url');
+
+ if ($detect) {
+ $this->isSearchDetected();
+ }
+ }
+
+ public static function shouldHandle(Request $request)
+ {
+ $search = new self($request, false);
+
+ return $search->detectSiteSearch($request->getParam('url'));
+ }
+
+ protected function getActionsToLookup()
+ {
+ return array(
+ 'idaction_name' => array($this->getActionName(), Action::TYPE_SITE_SEARCH),
+ );
+ }
+
+ public function getIdActionUrl()
+ {
+ // Site Search, by default, will not track URL. We do not want URL to appear as "Page URL not defined"
+ // so we specifically set it to NULL in the table (the archiving query does IS NOT NULL)
+ return null;
+ }
+
+ public function getIdActionUrlForEntryAndExitIds()
+ {
+ return $this->getIdActionUrl();
+ }
+
+ public function getIdActionNameForEntryAndExitIds()
+ {
+ return $this->getIdActionName();
+ }
+
+ protected function isSearchDetected()
+ {
+ $siteSearch = $this->detectSiteSearch($this->originalUrl);
+
+ if (empty($siteSearch)) {
+ return false;
+ }
+
+ list($actionName, $url, $category, $count) = $siteSearch;
+
+ if (!empty($category)) {
+ $this->searchCategory = trim($category);
+ }
+ if ($count !== false) {
+ $this->searchCount = $count;
+ }
+ $this->setActionName($actionName);
+ $this->setActionUrl($url);
+
+ return true;
+ }
+
+ public function getSearchCategory()
+ {
+ $searchCategory = trim($this->searchCategory);
+ if (!empty($searchCategory)) {
+ // Max length of DB field = 200
+ $searchCategory = substr($this->searchCategory, 0, 200);
+ }
+ return $searchCategory;
+ }
+
+ public function getSearchCount()
+ {
+ if ($this->searchCount !== false) {
+ $this->searchCount = (int)$this->searchCount;
+ }
+ return $this->searchCount;
+ }
+
+ public static function detectSiteSearchFromUrl($website, $parsedUrl, $pageEncoding = null)
+ {
+ $doRemoveSearchParametersFromUrl = true;
+ $separator = '&';
+ $count = $actionName = $categoryName = false;
+
+ $keywordParameters = isset($website['sitesearch_keyword_parameters'])
+ ? $website['sitesearch_keyword_parameters']
+ : array();
+ $queryString = !empty($parsedUrl['query']) ? $parsedUrl['query'] : '';
+ $fragment = !empty($parsedUrl['fragment']) ? $parsedUrl['fragment'] : '';
+
+ $parsedFragment = parse_url($fragment);
+
+ // check if fragment contains a separate query (beginning with ?) otherwise assume complete fragment as query
+ if ($fragment && strpos($fragment, '?') !== false && !empty($parsedFragment['query'])) {
+ $fragmentBeforeQuery = !empty($parsedFragment['path']) ? $parsedFragment['path'] : '';
+ $fragmentQuery = $parsedFragment['query'];
+ } else {
+ $fragmentQuery = $fragment;
+ $fragmentBeforeQuery = '';
+ }
+
+ $parametersRaw = UrlHelper::getArrayFromQueryString($queryString . $separator . $fragmentQuery);
+
+ // strtolower the parameter names for smooth site search detection
+ $parameters = array();
+ foreach ($parametersRaw as $k => $v) {
+ $parameters[mb_strtolower($k)] = $v;
+ }
+ // decode values if they were sent from a client using another charset
+ PageUrl::reencodeParameters($parameters, $pageEncoding);
+
+ // Detect Site Search keyword
+ foreach ($keywordParameters as $keywordParameterRaw) {
+ $keywordParameter = mb_strtolower($keywordParameterRaw);
+ if (!empty($parameters[$keywordParameter])) {
+ $actionName = $parameters[$keywordParameter];
+ break;
+ }
+ }
+
+ if (empty($actionName)) {
+ return false;
+ }
+
+ $categoryParameters = isset($website['sitesearch_category_parameters'])
+ ? $website['sitesearch_category_parameters']
+ : array();
+
+ foreach ($categoryParameters as $categoryParameterRaw) {
+ $categoryParameter = mb_strtolower($categoryParameterRaw);
+ if (!empty($parameters[$categoryParameter])) {
+ $categoryName = $parameters[$categoryParameter];
+ break;
+ }
+ }
+
+ if (
+ isset($parameters['search_count'])
+ && self::isValidSearchCount($parameters['search_count'])
+ ) {
+ $count = $parameters['search_count'];
+ }
+ // Remove search kwd from URL
+ if ($doRemoveSearchParametersFromUrl) {
+ // @see excludeQueryParametersFromUrl()
+ // Excluded the detected parameters from the URL
+ $parametersToExclude = array($categoryParameterRaw, $keywordParameterRaw);
+ if (isset($parsedUrl['query'])) {
+ $parsedUrl['query'] = UrlHelper::getQueryStringWithExcludedParameters(UrlHelper::getArrayFromQueryString($parsedUrl['query']), $parametersToExclude);
+ }
+ if (isset($parsedUrl['fragment'])) {
+ $parsedUrl['fragment'] = UrlHelper::getQueryStringWithExcludedParameters(UrlHelper::getArrayFromQueryString($fragmentQuery), $parametersToExclude);
+ if ($fragmentBeforeQuery) {
+ if ($parsedUrl['fragment']) {
+ $parsedUrl['fragment'] = $fragmentBeforeQuery . '?' . $parsedUrl['fragment'];
+ } else {
+ $parsedUrl['fragment'] = $fragmentBeforeQuery;
+ }
+ }
+ }
+ }
+ $url = UrlHelper::getParseUrlReverse($parsedUrl);
+ if (is_array($actionName)) {
+ $actionName = reset($actionName);
+ }
+
+ $actionName = PageUrl::urldecodeValidUtf8($actionName);
+ $actionName = trim($actionName);
+ if (empty($actionName)) {
+ return false;
+ }
+
+ if (is_array($categoryName)) {
+ $categoryName = reset($categoryName);
+ }
+ $categoryName = PageUrl::urldecodeValidUtf8($categoryName);
+ $categoryName = trim($categoryName);
+
+ return array($url, $actionName, $categoryName, $count);
+ }
+
+ protected static function isValidSearchCount($count)
+ {
+ return is_numeric($count) && $count >= 0;
+ }
+
+ public function detectSiteSearch($originalUrl)
+ {
+ $website = Cache::getCacheWebsiteAttributes($this->request->getIdSite());
+ if (empty($website['sitesearch'])) {
+ Common::printDebug("Internal 'Site Search' tracking is not enabled for this site. ");
+ return false;
+ }
+
+ $actionName = $url = $categoryName = $count = false;
+
+ $originalUrl = PageUrl::cleanupUrl($originalUrl);
+
+ // Detect Site search from Tracking API parameters rather than URL
+ $searchKwd = $this->request->getParam('search');
+ if (!empty($searchKwd)) {
+ $actionName = $searchKwd;
+ $isCategoryName = $this->request->getParam('search_cat');
+ if (!empty($isCategoryName)) {
+ $categoryName = $isCategoryName;
+ }
+ $isCount = $this->request->getParam('search_count');
+ if ($this->isValidSearchCount($isCount)) {
+ $count = $isCount;
+ }
+ }
+
+ if (empty($actionName)) {
+ $parsedUrl = @parse_url($originalUrl);
+
+ // Detect Site Search from URL query parameters
+ if (!empty($parsedUrl['query']) || !empty($parsedUrl['fragment'])) {
+ // array($url, $actionName, $categoryName, $count);
+ $searchInfo = $this->detectSiteSearchFromUrl($website, $parsedUrl, $this->request->getParam('cs'));
+ if (!empty($searchInfo)) {
+ list ($url, $actionName, $categoryName, $count) = $searchInfo;
+ }
+ }
+ }
+
+ $actionName = trim($actionName);
+ $categoryName = trim($categoryName);
+
+ if (empty($actionName)) {
+ Common::printDebug("(this is not a Site Search request)");
+ return false;
+ }
+
+ Common::printDebug("Detected Site Search keyword '$actionName'. ");
+ if (!empty($categoryName)) {
+ Common::printDebug("- Detected Site Search Category '$categoryName'. ");
+ }
+ if ($count !== false) {
+ Common::printDebug("- Search Results Count was '$count'. ");
+ }
+ if ($url != $originalUrl) {
+ Common::printDebug("NOTE: The Page URL was changed / removed, during the Site Search detection, was '$originalUrl', now is '$url'");
+ }
+
+ return array(
+ $actionName,
+ $url,
+ $categoryName,
+ $count,
+ );
+ }
+}
diff --git a/plugins/Actions/Archiver.php b/plugins/Actions/Archiver.php
new file mode 100644
index 0000000000000000000000000000000000000000..f4ee67548bac8387ba7eb43c52234d3c66a1f286
--- /dev/null
+++ b/plugins/Actions/Archiver.php
@@ -0,0 +1,38 @@
+fetch()) {
+ if (empty($row['idaction'])) {
+ $row['type'] = ($fieldQueried == 'idaction_url' ? Action::TYPE_PAGE_URL : Action::TYPE_PAGE_TITLE);
+ // This will be replaced with 'X not defined' later
+ $row['name'] = '';
+ // Yes, this is kind of a hack, so we don't mix 'page url not defined' with 'page title not defined' etc.
+ $row['idaction'] = -$row['type'];
+ }
+
+ if ($row['type'] != Action::TYPE_SITE_SEARCH) {
+ unset($row[PiwikMetrics::INDEX_SITE_SEARCH_HAS_NO_RESULT]);
+ }
+
+ if (in_array($row['type'], array(Action::TYPE_CONTENT, Action::TYPE_EVENT, Action::TYPE_EVENT_NAME, Action::TYPE_CONTENT_PIECE, Action::TYPE_CONTENT_TARGET))) {
+ continue;
+ }
+
+ $hasRowName = !empty($row['name']) && $row['name'] != RankingQuery::LABEL_SUMMARY_ROW;
+
+ // This will appear as in the API, which is actually very important to keep
+ // eg. When there's at least one row in a report that does not have a URL, not having this would break HTML/PDF reports.
+ $url = '';
+ $pageTitlePath = null;
+ if (
+ $row['type'] == Action::TYPE_SITE_SEARCH
+ || $row['type'] == Action::TYPE_PAGE_TITLE
+ ) {
+ $url = null;
+ if ($hasRowName) {
+ $pageTitlePath = $row['name'];
+ }
+ } elseif ($hasRowName) {
+ $url = PageUrl::reconstructNormalizedUrl((string)$row['name'], $row['url_prefix']);
+ }
+
+ if (
+ isset($row['name'])
+ && isset($row['type'])
+ ) {
+ $actionName = $row['name'];
+ $actionType = $row['type'];
+ $urlPrefix = $row['url_prefix'];
+ $idaction = $row['idaction'];
+
+ // in some unknown case, the type field is NULL, as reported in #1082 - we ignore this page view
+ if (empty($actionType)) {
+ if ($idaction != DataTable::LABEL_SUMMARY_ROW) {
+ self::setCachedActionRow($idaction, $actionType, false);
+ }
+ continue;
+ }
+
+ $tableMode = $tableModesByType[$actionType] ?? self::ACTION_TABLE_MODE_HIERARCHICAL;
+ $actionRow = self::getActionRow($actionName, $actionType, $urlPrefix, $actionsTablesByType, $tableMode);
+
+ self::setCachedActionRow($idaction, $actionType, $actionRow);
+ } else {
+ $actionRow = self::getCachedActionRow($row['idaction'], $row['type']);
+
+ // Action processed as "to skip" for some reasons
+ if ($actionRow === false) {
+ continue;
+ }
+ }
+
+ if (is_null($actionRow)) {
+ continue;
+ }
+
+ // Here we do ensure that, the Metadata URL set for a given row, is the one from the Pageview with the most hits.
+ // This is to ensure that when, different URLs are loaded with the same page name.
+ // For example https://piwik.org and https://id.piwik.org are reported in Piwik > Actions > Pages with /index
+ // But, we must make sure https://piwik.org is used to link & for transitions
+ // Note: this code is partly duplicated from Row->sumRowMetadata()
+ if (
+ !is_null($url)
+ && !$actionRow->isSummaryRow()
+ ) {
+ if (($existingUrl = $actionRow->getMetadata('url')) !== false) {
+ if (
+ !empty($row[PiwikMetrics::INDEX_PAGE_NB_HITS])
+ && $row[PiwikMetrics::INDEX_PAGE_NB_HITS] > $actionRow->maxVisitsSummed
+ ) {
+ $actionRow->setMetadata('url', $url);
+ $actionRow->maxVisitsSummed = $row[PiwikMetrics::INDEX_PAGE_NB_HITS];
+ }
+ } else {
+ $actionRow->setMetadata('url', $url);
+ $actionRow->maxVisitsSummed = !empty($row[PiwikMetrics::INDEX_PAGE_NB_HITS]) ? $row[PiwikMetrics::INDEX_PAGE_NB_HITS] : 0;
+ }
+ }
+
+ if (
+ $pageTitlePath !== null
+ && !$actionRow->isSummaryRow()
+ ) {
+ $actionRow->setMetadata('page_title_path', $pageTitlePath);
+ }
+
+ if (
+ $row['type'] != Action::TYPE_PAGE_URL
+ && $row['type'] != Action::TYPE_PAGE_TITLE
+ ) {
+ // only keep performance metrics when they're used (i.e. for URLs and page titles)
+ if (array_key_exists(PiwikMetrics::INDEX_PAGE_SUM_TIME_GENERATION, $row)) {
+ unset($row[PiwikMetrics::INDEX_PAGE_SUM_TIME_GENERATION]);
+ }
+ if (array_key_exists(PiwikMetrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION, $row)) {
+ unset($row[PiwikMetrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION]);
+ }
+ if (array_key_exists(PiwikMetrics::INDEX_PAGE_MIN_TIME_GENERATION, $row)) {
+ unset($row[PiwikMetrics::INDEX_PAGE_MIN_TIME_GENERATION]);
+ }
+ if (array_key_exists(PiwikMetrics::INDEX_PAGE_MAX_TIME_GENERATION, $row)) {
+ unset($row[PiwikMetrics::INDEX_PAGE_MAX_TIME_GENERATION]);
+ }
+ }
+
+ unset($row['name']);
+ unset($row['type']);
+ unset($row['idaction']);
+ unset($row['url_prefix']);
+
+ foreach ($row as $name => $value) {
+ // in some edge cases, we have twice the same action name with 2 different idaction
+ // - this happens when 2 visitors visit the same new page at the same time, and 2 actions get recorded for the same name
+ // - this could also happen when 2 URLs end up having the same label (eg. 2 subdomains get aggregated to the "/index" page name)
+ if (($alreadyValue = $actionRow->getColumn($name)) !== false) {
+ $newValue = self::getColumnValuesMerged($name, $alreadyValue, $value, $metricsConfig);
+ $actionRow->setColumn($name, $newValue);
+ } else {
+ $actionRow->addColumn($name, $value);
+ }
+ }
+
+ // if the exit_action was not recorded properly in the log_link_visit_action
+ // there would be an error message when getting the nb_hits column
+ // we must fake the record and add the columns
+ if ($actionRow->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS) === false) {
+ // to test this code: delete the entries in log_link_action_visit for
+ // a given exit_idaction_url
+ foreach (self::getDefaultRow()->getColumns() as $name => $value) {
+ $actionRow->addColumn($name, $value);
+ }
+ }
+ $rowsProcessed++;
+ }
+
+ // just to make sure php copies the last $actionRow in the $parentTable array
+ $actionRow =& $actionsTablesByType;
+ return $rowsProcessed;
+ }
+
+ /**
+ * Update the existing action datatable with goal columns
+ *
+ * @param Zend_Db_Statement|PDOStatement $resultSet Result set from the goals data query
+ * @param bool $isPages True if page view goals metrics should be used, else entry goal metrics
+ *
+ * @return int Number of rows processed
+ * @throws \Exception
+ */
+ public static function updateActionsTableWithGoals($resultSet, bool $isPages): int
+ {
+ $rowsProcessed = 0;
+
+ while ($row = $resultSet->fetch()) {
+ if (self::updateActionsTableRowWithGoals($row, $isPages)) {
+ $rowsProcessed++;
+ }
+ }
+ return $rowsProcessed;
+ }
+
+ /**
+ * Add goals metrics to a single row of the actions table
+ *
+ * @param array $row The array of goals metric data to add to the action table row
+ * @param bool $isPages True if page view goals metrics should be used, else entry goal metrics
+ * @return bool True if the row was updated, false otherwise
+ */
+ private static function updateActionsTableRowWithGoals(array $row, bool $isPages): bool
+ {
+
+ if (!isset($row['idaction']) || !isset($row['type'])) {
+ return false;
+ }
+
+ // Match the existing action row in the datatable
+ $actionRow = self::getCachedActionRow($row['idaction'], $row['type']);
+ if ($actionRow === false || is_null($actionRow)) {
+ return false;
+ }
+
+ // Define the possible goal metrics available in the goals data resultset
+ if ($isPages) {
+ // Page view metrics
+ $possibleMetrics = [
+ PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS => 'nb_conversions', // 1
+ PiwikMetrics::INDEX_GOAL_REVENUE => 'revenue', // 2
+ PiwikMetrics::INDEX_GOAL_NB_PAGES_UNIQ_BEFORE => 'nb_conv_pages_before', // 9
+ PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ATTRIB => 'nb_conversions_attrib', // 10
+ PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_PAGE_RATE => 'nb_conversions_page_rate', // 11
+ PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_PAGE_UNIQ => 'nb_conversions_page_uniq', // 12
+ PiwikMetrics::INDEX_GOAL_REVENUE_ATTRIB => 'revenue_attrib', // 15
+ ];
+ } else {
+ // Entry page metrics
+ $possibleMetrics = [
+ PiwikMetrics::INDEX_GOAL_REVENUE_ENTRY => 'revenue_entry', // 17
+ PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ENTRY_RATE => 'nb_conversions_entry_rate', // 12
+ PiwikMetrics::INDEX_GOAL_REVENUE_PER_ENTRY => 'revenue_per_entry', // 13
+ PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ENTRY => 'nb_conversions_entry', // 16
+ ];
+ }
+
+ unset($row['type']);
+ unset($row['idaction']);
+
+ if (!isset($row['idgoal'])) {
+ return false;
+ }
+
+ if (
+ $isPages &&
+ isset($row[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ATTRIB]) &&
+ isset($row[PiwikMetrics::INDEX_GOAL_NB_PAGES_UNIQ_BEFORE])
+ ) {
+ /**
+ * Ensures this metric is available. It will be calculated later using a filter.
+ * @see \Piwik\Plugins\Goals\DataTable\Filter\CalculateConversionPageRate
+ */
+ $row[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_PAGE_RATE] = 0;
+ }
+
+ if (isset($row[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ATTRIB])) {
+ $row[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ATTRIB] = (float) $row[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ATTRIB];
+ }
+
+ if (isset($row[PiwikMetrics::INDEX_GOAL_REVENUE_ATTRIB])) {
+ $row[PiwikMetrics::INDEX_GOAL_REVENUE_ATTRIB] = (float) $row[PiwikMetrics::INDEX_GOAL_REVENUE_ATTRIB];
+ }
+
+ if (!$isPages) {
+ self::normalizeEntryGoalMetricsForEntrances(
+ $row,
+ $actionRow->getColumn(PiwikMetrics::INDEX_PAGE_ENTRY_NB_VISITS)
+ );
+ }
+
+ // Get goals column
+ $goalsColumn = $actionRow->getColumn(PiwikMetrics::INDEX_GOALS);
+ if ($goalsColumn === false) {
+ $goalsColumn = [];
+ }
+
+ // Create goal subarray if not exists
+ if (!isset($goalsColumn[$row['idgoal']])) {
+ $goalsColumn[$row['idgoal']] = [];
+ }
+
+ // Find metric columns in the goal query row and add them to the actions data table row
+ foreach ($possibleMetrics as $metricKey => $columnName) {
+ if (isset($row[$metricKey])) {
+ // Add metric
+ self::mergeGoalMetric($goalsColumn[$row['idgoal']], $metricKey, $row[$metricKey]);
+
+ // Write goals column back to datatable
+ $actionRow->setColumn(PiwikMetrics::INDEX_GOALS, $goalsColumn);
+ }
+ }
+ return true;
+ }
+
+ public static function normalizeFlatGoalsMetricsForHierarchy(array $flatPageTablesByType): void
+ {
+ foreach ($flatPageTablesByType as $dataTable) {
+ if (!$dataTable instanceof DataTable) {
+ continue;
+ }
+
+ $rowsByLabel = [];
+ foreach ($dataTable->getRowsWithoutSummaryRow() as $row) {
+ $label = $row->getColumn('label');
+ if (!is_string($label) || $label === '') {
+ continue;
+ }
+
+ $rowsByLabel[$label][] = $row;
+ }
+
+ foreach ($rowsByLabel as $rows) {
+ self::normalizeFlatGoalsMetricsForHierarchyPathRows($rows);
+ }
+ }
+ }
+
+ private static function normalizeFlatGoalsMetricsForHierarchyPathRows(array $rows): void
+ {
+ $entryVisitsTotal = 0.0;
+ $maxPagesBeforeByGoal = [];
+
+ foreach ($rows as $row) {
+ $entryVisits = $row->getColumn(PiwikMetrics::INDEX_PAGE_ENTRY_NB_VISITS);
+ if (is_numeric($entryVisits)) {
+ $entryVisitsTotal += (float) $entryVisits;
+ }
+
+ $goals = $row->getColumn(PiwikMetrics::INDEX_GOALS);
+ if (!is_array($goals)) {
+ continue;
+ }
+
+ foreach ($goals as $goalId => $goalMetrics) {
+ if (!is_array($goalMetrics)) {
+ continue;
+ }
+
+ $pagesBefore = $goalMetrics[PiwikMetrics::INDEX_GOAL_NB_PAGES_UNIQ_BEFORE] ?? null;
+ if (!is_numeric($pagesBefore)) {
+ continue;
+ }
+
+ if (
+ !isset($maxPagesBeforeByGoal[$goalId])
+ || $maxPagesBeforeByGoal[$goalId]['value'] < (float) $pagesBefore
+ ) {
+ $maxPagesBeforeByGoal[$goalId] = [
+ 'row' => $row,
+ 'value' => (float) $pagesBefore,
+ ];
+ }
+ }
+ }
+
+ foreach ($rows as $row) {
+ $goals = $row->getColumn(PiwikMetrics::INDEX_GOALS);
+ if (!is_array($goals)) {
+ continue;
+ }
+
+ foreach ($goals as &$goalMetrics) {
+ if (!is_array($goalMetrics)) {
+ continue;
+ }
+
+ if (isset($goalMetrics[PiwikMetrics::INDEX_GOAL_NB_PAGES_UNIQ_BEFORE])) {
+ $goalMetrics[PiwikMetrics::INDEX_GOAL_NB_PAGES_UNIQ_BEFORE] = 0;
+ }
+
+ self::normalizeEntryGoalMetricsForEntrances($goalMetrics, $entryVisitsTotal);
+ }
+ unset($goalMetrics);
+
+ $row[PiwikMetrics::INDEX_GOALS] = $goals;
+ }
+
+ foreach ($maxPagesBeforeByGoal as $goalId => $maxValue) {
+ /** @var Row $maxRow */
+ $maxRow = $maxValue['row'];
+ $goals = $maxRow->getColumn(PiwikMetrics::INDEX_GOALS);
+ if (!is_array($goals) || !isset($goals[$goalId]) || !is_array($goals[$goalId])) {
+ continue;
+ }
+
+ $goals[$goalId][PiwikMetrics::INDEX_GOAL_NB_PAGES_UNIQ_BEFORE] = $maxValue['value'];
+ $maxRow[PiwikMetrics::INDEX_GOALS] = $goals;
+ }
+ }
+
+ private static function normalizeEntryGoalMetricsForEntrances(array &$goalMetrics, $nbEntrances): void
+ {
+ if (!is_numeric($nbEntrances) || $nbEntrances <= 0) {
+ return;
+ }
+
+ if (isset($goalMetrics[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ENTRY])) {
+ $goalMetrics[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ENTRY_RATE] = Piwik::getQuotientSafe(
+ $goalMetrics[PiwikMetrics::INDEX_GOAL_NB_CONVERSIONS_ENTRY],
+ $nbEntrances,
+ GoalManager::REVENUE_PRECISION + 1
+ );
+ }
+
+ if (isset($goalMetrics[PiwikMetrics::INDEX_GOAL_REVENUE_ENTRY])) {
+ $goalMetrics[PiwikMetrics::INDEX_GOAL_REVENUE_PER_ENTRY] = (float) Piwik::getQuotientSafe(
+ $goalMetrics[PiwikMetrics::INDEX_GOAL_REVENUE_ENTRY],
+ $nbEntrances,
+ GoalManager::REVENUE_PRECISION + 1
+ );
+
+ $goalMetrics[PiwikMetrics::INDEX_GOAL_REVENUE_ENTRY] = (float) $goalMetrics[PiwikMetrics::INDEX_GOAL_REVENUE_ENTRY];
+ }
+ }
+
+ private static function mergeGoalMetric(array &$goalMetrics, int $metricKey, $value): void
+ {
+ if (!isset($goalMetrics[$metricKey])) {
+ $goalMetrics[$metricKey] = $value;
+ return;
+ }
+
+ if ($metricKey == PiwikMetrics::INDEX_GOAL_NB_PAGES_UNIQ_BEFORE) {
+ if ($goalMetrics[$metricKey] < $value) {
+ $goalMetrics[$metricKey] = $value;
+ }
+ return;
+ }
+
+ $goalMetrics[$metricKey] += $value;
+ }
+
+ public static function removeEmptyColumns($dataTable)
+ {
+ // Delete all columns that have a value of zero
+ $dataTable->filter('ColumnDelete', array(
+ $columnsToRemove = array(PiwikMetrics::INDEX_PAGE_IS_FOLLOWING_SITE_SEARCH_NB_HITS),
+ $columnsToKeep = array(),
+ $deleteIfZeroOnly = true,
+ ));
+ }
+
+ /**
+ * For rows which have subtables (eg. directories with sub pages),
+ * deletes columns which don't make sense when all values of sub pages are summed.
+ *
+ * @param $dataTable DataTable
+ */
+ public static function deleteInvalidSummedColumnsFromDataTable($dataTable)
+ {
+ foreach ($dataTable->getRows() as $id => $row) {
+ if (
+ ($idSubtable = $row->getIdSubDataTable()) !== null
+ || $id === DataTable::ID_SUMMARY_ROW
+ ) {
+ $subTable = $row->getSubtable();
+ if ($subTable) {
+ self::deleteInvalidSummedColumnsFromDataTable($subTable);
+ }
+
+ if ($row instanceof DataTableSummaryRow) {
+ $row->recalculate();
+ }
+
+ foreach (Metrics::$columnsToDeleteAfterAggregation as $name) {
+ $row->deleteColumn($name);
+ }
+
+ if ($idSubtable !== null) {
+ foreach (array_values(Metrics::$columnsToRenameAfterAggregation) as $name) {
+ $row->deleteColumn($name);
+ }
+ }
+ }
+ }
+
+ // And this as well
+ ArchivingHelper::removeEmptyColumns($dataTable);
+ }
+
+ /**
+ * Returns the limit to use with RankingQuery for this plugin.
+ *
+ * @return int
+ */
+ public static function getRankingQueryLimit()
+ {
+ $configGeneral = Config::getInstance()->General;
+ $configLimit = $configGeneral['archiving_ranking_query_row_limit'];
+ $limit = $configLimit == 0 ? 0 : max(
+ $configLimit,
+ $configGeneral['datatable_archiving_maximum_rows_actions'],
+ $configGeneral['datatable_archiving_maximum_rows_subtable_actions']
+ );
+
+ // FIXME: This is a quick fix for #3482. The actual cause of the bug is that
+ // the site search & performance metrics additions to
+ // ArchivingHelper::updateActionsTableWithRowQuery expect every
+ // row to have 'type' data, but not all of the SQL queries that are run w/o
+ // ranking query join on the log_action table and thus do not select the
+ // log_action.type column.
+ //
+ // NOTES: Archiving logic can be generalized as follows:
+ // 0) Do SQL query over log_link_visit_action & join on log_action to select
+ // some metrics (like visits, hits, etc.)
+ // 1) For each row, cache the action row & metrics. (This is done by
+ // updateActionsTableWithRowQuery for result set rows that have
+ // name & type columns.)
+ // 2) Do other SQL queries for metrics we can't put in the first query (like
+ // entry visits, exit vists, etc.) w/o joining log_action.
+ // 3) For each row, find the cached row by idaction & add the new metrics to
+ // it. (This is done by updateActionsTableWithRowQuery for result set rows
+ // that DO NOT have name & type columns.)
+ //
+ // The site search & performance metrics additions expect a 'type' all the time
+ // which breaks the original pre-rankingquery logic. Ranking query requires a
+ // join, so the bug is only seen when ranking query is disabled.
+ if ($limit === 0) {
+ $limit = 100000;
+ }
+ return $limit;
+ }
+
+ /**
+ * @param $columnName
+ * @param $alreadyValue
+ * @param $value
+ * @return mixed
+ */
+ private static function getColumnValuesMerged($columnName, $alreadyValue, $value, $metricsConfig)
+ {
+ if (array_key_exists($columnName, $metricsConfig)) {
+ $config = $metricsConfig[$columnName];
+
+ if (!empty($config['aggregation'])) {
+ if ($config['aggregation'] == 'min') {
+ if (empty($alreadyValue)) {
+ $newValue = $value;
+ } elseif (empty($value)) {
+ $newValue = $alreadyValue;
+ } else {
+ $newValue = min($alreadyValue, $value);
+ }
+ return $newValue;
+ }
+ if ($config['aggregation'] == 'max') {
+ $newValue = max($alreadyValue, $value);
+ return $newValue;
+ }
+ }
+ }
+
+ $newValue = $alreadyValue + $value;
+ return $newValue;
+ }
+
+ public static $maximumRowsInDataTableLevelZero;
+ public static $maximumRowsInSubDataTable;
+ public static $maximumRowsInDataTableSiteSearch;
+ public static $maximumRowsInDataTableFlat;
+ public static $columnToSortByBeforeTruncation;
+
+ protected static $actionUrlCategoryDelimiter = null;
+ protected static $actionTitleCategoryDelimiter = null;
+ protected static $defaultActionName = null;
+ protected static $defaultActionNameWhenNotDefined = null;
+ protected static $defaultActionUrlWhenNotDefined = null;
+
+ public static function reloadConfig()
+ {
+ // for BC, we read the old style delimiter first (see #1067)
+ $actionDelimiter = @Config::getInstance()->General['action_category_delimiter'];
+ if (empty($actionDelimiter)) {
+ self::$actionUrlCategoryDelimiter = Config::getInstance()->General['action_url_category_delimiter'];
+ self::$actionTitleCategoryDelimiter = Config::getInstance()->General['action_title_category_delimiter'];
+ } else {
+ self::$actionUrlCategoryDelimiter = self::$actionTitleCategoryDelimiter = $actionDelimiter;
+ }
+
+ self::$defaultActionName = Config::getInstance()->General['action_default_name'];
+ self::$columnToSortByBeforeTruncation = PiwikMetrics::INDEX_NB_VISITS;
+ self::$maximumRowsInDataTableLevelZero = Config::getInstance()->General['datatable_archiving_maximum_rows_actions'];
+ self::$maximumRowsInSubDataTable = Config::getInstance()->General['datatable_archiving_maximum_rows_subtable_actions'];
+ self::$maximumRowsInDataTableSiteSearch = Config::getInstance()->General['datatable_archiving_maximum_rows_site_search'];
+ self::$maximumRowsInDataTableFlat = Config::getInstance()->General['datatable_archiving_maximum_rows_actions_flat'] ?? 0;
+ self::$defaultActionNameWhenNotDefined = null;
+ self::$defaultActionUrlWhenNotDefined = null;
+
+ DataTable::setMaximumDepthLevelAllowedAtLeast(self::getSubCategoryLevelLimit() + 1);
+ }
+
+ /**
+ * The default row is used when archiving, if data is inconsistent in the DB,
+ * there could be pages that have exit/entry hits, but don't yet
+ * have a record in the table (or the record was truncated).
+ *
+ * @return Row
+ */
+ private static function getDefaultRow()
+ {
+ static $row = false;
+ if ($row === false) {
+ // This row is used in the case where an action is know as an exit_action
+ // but this action was not properly recorded when it was hit in the first place
+ // so we add this fake row information to make sure there is a nb_hits, etc. column for every action
+ $row = new Row(array(
+ Row::COLUMNS => array(
+ PiwikMetrics::INDEX_NB_VISITS => 1,
+ PiwikMetrics::INDEX_NB_UNIQ_VISITORS => 1,
+ PiwikMetrics::INDEX_PAGE_NB_HITS => 1,
+ )));
+ }
+ return $row;
+ }
+
+ /**
+ * Given a page name and type, returns the matching action row, building a recursive
+ * category-tree datatable (split by delimiter) in hierarchical mode, or a flat row
+ * keyed by the full label in flat mode.
+ *
+ * @param string $actionName
+ * @param int $actionType
+ * @param int $urlPrefix
+ * @param array $actionsTablesByType
+ * @param string $tableMode One of self::ACTION_TABLE_MODE_HIERARCHICAL or self::ACTION_TABLE_MODE_FLAT
+ * @return DataTable\Row
+ */
+ public static function getActionRow(
+ $actionName,
+ $actionType,
+ $urlPrefix,
+ $actionsTablesByType,
+ string $tableMode = self::ACTION_TABLE_MODE_HIERARCHICAL
+ ) {
+ // we work on the root table of the given TYPE (either ACTION_URL or DOWNLOAD or OUTLINK etc.)
+ /* @var DataTable $currentTable */
+ $currentTable = $actionsTablesByType[$actionType];
+
+ if (is_null($currentTable)) {
+ throw new \Exception("Action table for type '$actionType' was not found during Actions archiving.");
+ }
+
+ // check for ranking query cut-off
+ if ($actionName == RankingQuery::LABEL_SUMMARY_ROW) {
+ $summaryRow = $currentTable->getRowFromId(DataTable::ID_SUMMARY_ROW);
+ if ($summaryRow === false) {
+ $summaryRow = $currentTable->addSummaryRow(self::createSummaryRow());
+ }
+ return $summaryRow;
+ }
+
+ if ($tableMode === self::ACTION_TABLE_MODE_FLAT) {
+ return self::getFlatActionRow($actionName, $actionType, $urlPrefix, $currentTable);
+ }
+
+ // go to the level of the subcategory
+ $actionExplodedNames = self::getActionExplodedNames($actionName, $actionType, $urlPrefix);
+ list($row, $level) = $currentTable->walkPath(
+ $actionExplodedNames,
+ self::getDefaultRowColumns(),
+ self::$maximumRowsInSubDataTable
+ );
+
+ return $row;
+ }
+
+ public static function mergeHierarchicalActionsTableIntoFlatTable(DataTable $hierarchicalTable, DataTable $flatTable): void
+ {
+ self::appendHierarchicalRowsToFlatTable(
+ $hierarchicalTable,
+ [],
+ $flatTable,
+ [self::class, 'buildFlatRowLabel']
+ );
+ }
+
+ public static function mergeHierarchicalActionsTableIntoBestEffortFlatTable(
+ DataTable $hierarchicalTable,
+ DataTable $flatTable,
+ int $actionType
+ ): void {
+ self::appendHierarchicalRowsToFlatTable(
+ $hierarchicalTable,
+ [],
+ $flatTable,
+ function (array $path) use ($actionType): string {
+ return self::buildBestEffortActionLabelFromPath($path, $actionType);
+ },
+ false
+ );
+ }
+
+ private static function getFlatActionRow($actionName, $actionType, $urlPrefix, DataTable $table): Row
+ {
+ $flatLabel = self::buildFlatActionLabelFromActionName($actionName, $actionType, $urlPrefix);
+
+ $row = $table->getRowFromLabel($flatLabel);
+ if ($row !== false) {
+ return $row;
+ }
+
+ $row = new Row(array(
+ Row::COLUMNS => array('label' => $flatLabel) + self::getDefaultFlatRowColumns(),
+ ));
+
+ // when the table is full, addRow() aggregates the row into the summary row and
+ // returns the summary row instead, so metrics of truncated actions accumulate there
+ return $table->addRow($row);
+ }
+
+ public static function buildBestEffortActionLabelFromPath(array $actionPath, int $actionType): string
+ {
+ if (empty($actionPath)) {
+ return '';
+ }
+
+ $segments = array_values($actionPath);
+ $lastIndex = count($segments) - 1;
+ $lastSegment = (string) $segments[$lastIndex];
+
+ if ($actionType === Action::TYPE_PAGE_URL) {
+ if (strpos($lastSegment, self::URL_ACTION_LEAF_MARKER) === 0) {
+ $lastSegment = substr($lastSegment, strlen(self::URL_ACTION_LEAF_MARKER));
+ }
+ $segments[$lastIndex] = $lastSegment;
+ $delimiter = self::$actionUrlCategoryDelimiter;
+ } else {
+ if (strpos($lastSegment, self::TITLE_ACTION_LEAF_MARKER) === 0) {
+ $lastSegment = substr($lastSegment, strlen(self::TITLE_ACTION_LEAF_MARKER));
+ }
+ $segments[$lastIndex] = $lastSegment;
+ $delimiter = self::$actionTitleCategoryDelimiter;
+ }
+
+ if ($delimiter === '') {
+ $label = implode('', $segments);
+ } else {
+ $label = implode($delimiter, $segments);
+ }
+
+ if (
+ $actionType === Action::TYPE_PAGE_URL
+ && $label !== self::getUnknownActionName(Action::TYPE_PAGE_URL)
+ && substr($label, 0, 1) !== '/'
+ ) {
+ return '/' . $label;
+ }
+
+ return $label;
+ }
+
+ public static function removePageUrlLeafMarkerFromFlatLabel(string $label): string
+ {
+ return ltrim($label, self::URL_ACTION_LEAF_MARKER);
+ }
+
+ private static function appendHierarchicalRowsToFlatTable(
+ DataTable $sourceTable,
+ array $path,
+ DataTable $flatTable,
+ callable $flatLabelBuilder,
+ bool $useDefaultFlatRowColumns = true
+ ): void {
+ foreach ($sourceTable->getRowsWithoutSummaryRow() as $row) {
+ $label = $row->getColumn('label');
+ if (!is_string($label) || $label === '') {
+ continue;
+ }
+
+ $currentPath = $path;
+ $currentPath[] = $label;
+
+ $subtable = $row->getSubtable();
+ if ($subtable) {
+ self::appendHierarchicalRowsToFlatTable(
+ $subtable,
+ $currentPath,
+ $flatTable,
+ $flatLabelBuilder,
+ $useDefaultFlatRowColumns
+ );
+ continue;
+ }
+
+ $flatLabel = call_user_func($flatLabelBuilder, $currentPath);
+ $flatRow = $flatTable->getRowFromLabel($flatLabel);
+ if ($flatRow === false) {
+ $columns = array('label' => $flatLabel);
+ if ($useDefaultFlatRowColumns) {
+ $columns += self::getDefaultFlatRowColumns();
+ }
+
+ $flatRow = new Row(array(
+ Row::COLUMNS => $columns,
+ ));
+ $flatTable->addRow($flatRow);
+ }
+ self::mergeRowIntoDestination($row, $flatRow);
+ }
+
+ $summaryRow = $sourceTable->getRowFromId(DataTable::ID_SUMMARY_ROW);
+ if ($summaryRow !== false) {
+ if (self::isRowEmptyOfMetrics($summaryRow)) {
+ return;
+ }
+
+ $globalSummary = $flatTable->getRowFromId(DataTable::ID_SUMMARY_ROW);
+ if ($globalSummary === false) {
+ $globalSummary = self::createSummaryRow();
+ $flatTable->addSummaryRow($globalSummary);
+ }
+ self::mergeRowIntoDestination($summaryRow, $globalSummary);
+ }
+ }
+
+ private static function buildFlatRowLabel(array $actionPath): string
+ {
+ $encodedPath = json_encode($actionPath);
+ if ($encodedPath === false) {
+ return implode("\n", $actionPath);
+ }
+
+ return $encodedPath;
+ }
+
+ private static function buildFlatActionLabelFromActionName($actionName, $actionType, $urlPrefix): string
+ {
+ if (!is_string($actionName)) {
+ return (string) $actionName;
+ }
+
+ $actionType = (int) $actionType;
+
+ if (
+ ($actionType === Action::TYPE_PAGE_URL || $actionType === Action::TYPE_PAGE_TITLE)
+ && $actionName !== RankingQuery::LABEL_SUMMARY_ROW
+ ) {
+ $actionPath = self::getActionExplodedNames($actionName, $actionType, $urlPrefix);
+ return self::buildBestEffortActionLabelFromPath($actionPath, $actionType);
+ }
+
+ return $actionName;
+ }
+
+ private static function mergeRowIntoDestination(Row $source, Row $destination): void
+ {
+ $sourceCopy = clone $source;
+ $sourceCopy->deleteMetadata(self::ACTION_FLAT_PATH_METADATA_NAME);
+
+ $aggregationOps = Metrics::getColumnsAggregationOperation();
+ $destination->sumRow($sourceCopy, $enableCopyMetadata = true, $aggregationOps);
+
+ $metadataValue = $sourceCopy->getMetadata('url');
+ if ($metadataValue !== false) {
+ $destination->setMetadata('url', $metadataValue);
+ }
+ }
+
+ private static function isRowEmptyOfMetrics(Row $row): bool
+ {
+ foreach ($row->getColumns() as $name => $value) {
+ if ($name === 'label') {
+ continue;
+ }
+
+ if (!empty($value)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Returns the configured sub-category level limit.
+ *
+ * @return int
+ */
+ public static function getSubCategoryLevelLimit()
+ {
+ return Config::getInstance()->General['action_category_level_limit'];
+ }
+
+ /**
+ * Returns default label for the action type
+ *
+ * @param $type
+ * @return string
+ */
+ public static function getUnknownActionName($type)
+ {
+ if (empty(self::$defaultActionNameWhenNotDefined)) {
+ self::$defaultActionNameWhenNotDefined = Piwik::translate('General_NotDefined', Piwik::translate('Actions_ColumnPageName'));
+ self::$defaultActionUrlWhenNotDefined = Piwik::translate('General_NotDefined', Piwik::translate('Actions_ColumnPageURL'));
+ }
+ if ($type == Action::TYPE_PAGE_TITLE) {
+ return self::$defaultActionNameWhenNotDefined;
+ }
+ return self::$defaultActionUrlWhenNotDefined;
+ }
+
+ /**
+ * Explodes action name into an array of elements.
+ *
+ * NOTE: before calling this function make sure ArchivingHelper::reloadConfig(); is called
+ *
+ * for downloads:
+ * we explode link https://piwik.org/some/path/piwik.zip into an array( 'piwik.org', '/some/path/piwik.zip' );
+ *
+ * for outlinks:
+ * we explode link https://dev.piwik.org/some/path into an array( 'dev.piwik.org', '/some/path' );
+ *
+ * for action urls:
+ * we explode link https://piwik.org/some/path into an array( 'some', 'path' );
+ *
+ * for action names:
+ * we explode name 'Piwik / Category 1 / Category 2' into an array('Matomo', 'Category 1', 'Category 2');
+ *
+ * @param string $name action name
+ * @param int $type action type
+ * @param int|null $urlPrefix url prefix (only used for TYPE_PAGE_URL)
+ * @return array of exploded elements from $name
+ */
+ public static function getActionExplodedNames($name, $type, $urlPrefix = null)
+ {
+ // Site Search does not split Search keywords
+ if ($type == Action::TYPE_SITE_SEARCH) {
+ return array($name);
+ }
+
+ $name = str_replace("\n", "", $name);
+
+ if ($type == Action::TYPE_PAGE_TITLE && self::$actionTitleCategoryDelimiter === '') {
+ if ($name === '' || $name === false || $name === null || trim($name) === '') {
+ $name = self::getUnknownActionName($type);
+ }
+ return array(self::TITLE_ACTION_LEAF_MARKER . trim($name));
+ }
+
+ $name = self::parseNameFromPageUrl($name, $type, $urlPrefix);
+
+ // outlinks and downloads
+ if (is_array($name)) {
+ return $name;
+ }
+
+ $split = self::splitNameByDelimiter($name, $type);
+
+ if (empty($split)) {
+ $defaultName = self::getUnknownActionName($type);
+ return array(trim($defaultName));
+ }
+
+ $lastPageName = end($split);
+ // we are careful to prefix the page URL / name with some value
+ // so that if a page has the same name as a category
+ // we don't merge both entries
+ if ($type != Action::TYPE_PAGE_TITLE) {
+ $lastPageName = self::URL_ACTION_LEAF_MARKER . $lastPageName;
+ } else {
+ $lastPageName = self::TITLE_ACTION_LEAF_MARKER . $lastPageName;
+ }
+ $split[count($split) - 1] = $lastPageName;
+ return array_values($split);
+ }
+
+ /**
+ * Gets the key for the cache of action rows from an action ID and type.
+ *
+ * @param int $idAction
+ * @param int $actionType
+ * @return string|int
+ */
+ private static function getCachedActionRowKey($idAction, $actionType)
+ {
+ return $idAction == RankingQuery::LABEL_SUMMARY_ROW
+ ? $actionType . '_others'
+ : $idAction;
+ }
+
+ /**
+ * Static cache to store Rows during processing
+ */
+ protected static $cacheParsedAction = array();
+
+ public static function clearActionsCache()
+ {
+ self::$cacheParsedAction = array();
+ }
+
+ /**
+ * Get cached action row by id & type. If $idAction is set to RankingQuery::LABEL_SUMMARY_ROW, the 'Others' row
+ * for the specific action type will be returned.
+ *
+ * @param int $idAction
+ * @param int $actionType
+ * @return Row|false
+ */
+ private static function getCachedActionRow($idAction, $actionType)
+ {
+ $cacheLabel = self::getCachedActionRowKey($idAction, $actionType);
+
+ if (!isset(self::$cacheParsedAction[$cacheLabel])) {
+ // This can happen when
+ // - We select an entry page ID that was only seen yesterday, so wasn't selected in the first query
+ // - We count time spent on a page, when this page was only seen yesterday
+ return false;
+ }
+
+ return self::$cacheParsedAction[$cacheLabel];
+ }
+
+ /**
+ * Set cached action row for an id & type.
+ *
+ * @param int $idAction
+ * @param int $actionType
+ * @param \Piwik\DataTable\Row|false|null $actionRow
+ */
+ private static function setCachedActionRow($idAction, $actionType, $actionRow)
+ {
+ $cacheLabel = self::getCachedActionRowKey($idAction, $actionType);
+ self::$cacheParsedAction[$cacheLabel] = $actionRow;
+ }
+
+ /**
+ * Returns the default columns for a row in an Actions DataTable.
+ *
+ * @return array
+ */
+ private static function getDefaultRowColumns()
+ {
+ return array(PiwikMetrics::INDEX_NB_VISITS => 0,
+ PiwikMetrics::INDEX_NB_UNIQ_VISITORS => 0,
+ PiwikMetrics::INDEX_PAGE_NB_HITS => 0,
+ PiwikMetrics::INDEX_PAGE_SUM_TIME_SPENT => 0);
+ }
+
+ private static function getDefaultFlatRowColumns()
+ {
+ return array(PiwikMetrics::INDEX_NB_VISITS => 0,
+ PiwikMetrics::INDEX_PAGE_NB_HITS => 0,
+ PiwikMetrics::INDEX_PAGE_SUM_TIME_SPENT => 0);
+ }
+
+ /**
+ * Creates a summary row for an Actions DataTable.
+ *
+ * @return Row
+ */
+ private static function createSummaryRow()
+ {
+ $summaryRow = new Row(array(
+ Row::COLUMNS =>
+ array('label' => DataTable::LABEL_SUMMARY_ROW) + self::getDefaultRowColumns(),
+ ));
+ $summaryRow->setIsSummaryRow(); // this should be set in DataTable::addSummaryRow(), but we set it here as well to be safe
+ return $summaryRow;
+ }
+
+ private static function splitNameByDelimiter($name, $type)
+ {
+ if (is_array($name)) {
+ return $name;
+ }
+ if ($type == Action::TYPE_PAGE_TITLE) {
+ $categoryDelimiter = self::$actionTitleCategoryDelimiter;
+ } else {
+ $categoryDelimiter = self::$actionUrlCategoryDelimiter;
+ }
+
+ if (empty($categoryDelimiter)) {
+ return array(trim($name));
+ }
+
+ $split = explode($categoryDelimiter, $name, self::getSubCategoryLevelLimit());
+
+ // trim every category and remove empty categories
+ $split = array_map('trim', $split);
+ $split = array_filter($split, 'strlen');
+
+ // forces array key to start at 0
+ $split = array_values($split);
+
+ return $split;
+ }
+
+ private static function parseNameFromPageUrl($name, $type, $urlPrefix)
+ {
+ $urlRegexAfterDomain = '([^/]+)[/]?([^#]*)[#]?(.*)';
+ if ($urlPrefix === null) {
+ // match url with protocol (used for outlinks / downloads)
+ $urlRegex = '@^http[s]?://' . $urlRegexAfterDomain . '$@i';
+ } else {
+ // the name is a url that does not contain protocol and www anymore
+ // we know that normalization has been done on db level because $urlPrefix is set
+ $urlRegex = '@^' . $urlRegexAfterDomain . '$@i';
+ }
+
+ $matches = array();
+ preg_match($urlRegex, $name, $matches);
+ if (!count($matches)) {
+ return $name;
+ }
+ $urlHost = $matches[1];
+ $urlPath = $matches[2];
+ $urlFragment = $matches[3];
+
+ if (in_array($type, array(Action::TYPE_DOWNLOAD, Action::TYPE_OUTLINK))) {
+ $path = '/' . trim($urlPath);
+ if (!empty($urlFragment)) {
+ $path .= '#' . $urlFragment;
+ }
+
+ return array(trim($urlHost), $path);
+ }
+
+ $name = $urlPath;
+ if ($name === '' || substr($name, -1) == '/') {
+ $name .= self::$defaultActionName;
+ }
+
+ $urlFragment = PageUrl::processUrlFragment($urlFragment);
+ if (!empty($urlFragment)) {
+ $name .= '#' . $urlFragment;
+ }
+
+ return $name;
+ }
+
+ public static function setFolderPathMetadata(DataTable $dataTable, $isUrl, $prefix = '')
+ {
+ $configGeneral = Config::getInstance()->General;
+ $separator = $isUrl ? $configGeneral['action_url_category_delimiter'] : $configGeneral['action_title_category_delimiter'];
+ $metadataName = $isUrl ? 'folder_url_start' : 'page_title_path';
+
+ foreach ($dataTable->getRows() as $row) {
+ $subtable = $row->getSubtable();
+ if (!$subtable) {
+ continue;
+ }
+
+ $metadataValue = $prefix . $row->getColumn('label');
+ $row->setMetadata($metadataName, $metadataValue);
+
+ self::setFolderPathMetadata($subtable, $isUrl, $metadataValue . $separator);
+ }
+ }
+}
diff --git a/plugins/Actions/Categories/DownloadsSubcategory.php b/plugins/Actions/Categories/DownloadsSubcategory.php
new file mode 100644
index 0000000000000000000000000000000000000000..2afb128a16d15d789df11f638ee1240f957d80c0
--- /dev/null
+++ b/plugins/Actions/Categories/DownloadsSubcategory.php
@@ -0,0 +1,26 @@
+' . Piwik::translate('Actions_DownloadsSubcategoryHelp1') . ''
+ . '' . Piwik::translate('Actions_DownloadsSubcategoryHelp2') . '
';
+ }
+}
diff --git a/plugins/Actions/Categories/EntryPagesSubcategory.php b/plugins/Actions/Categories/EntryPagesSubcategory.php
new file mode 100644
index 0000000000000000000000000000000000000000..c2b26a44500be4f217286a9637ca72889d0daff1
--- /dev/null
+++ b/plugins/Actions/Categories/EntryPagesSubcategory.php
@@ -0,0 +1,27 @@
+' . Piwik::translate('Actions_EntryPagesSubcategoryHelp1') . ''
+ . '' . Piwik::translate('Actions_EntryPagesSubcategoryHelp2') . '
'
+ . '' . Piwik::translate('Actions_PagesSubcategoryHelp3') . '
';
+ }
+}
diff --git a/plugins/Actions/Categories/ExitPagesSubcategory.php b/plugins/Actions/Categories/ExitPagesSubcategory.php
new file mode 100644
index 0000000000000000000000000000000000000000..da45e07da6f034e5b61b019dc85c3efa4e303da8
--- /dev/null
+++ b/plugins/Actions/Categories/ExitPagesSubcategory.php
@@ -0,0 +1,27 @@
+' . Piwik::translate('Actions_ExitPagesSubcategoryHelp1') . ''
+ . '' . Piwik::translate('Actions_ExitPagesSubcategoryHelp2') . '
'
+ . '' . Piwik::translate('Actions_PagesSubcategoryHelp3') . '
';
+ }
+}
diff --git a/plugins/Actions/Categories/OutlinksSubcategory.php b/plugins/Actions/Categories/OutlinksSubcategory.php
new file mode 100644
index 0000000000000000000000000000000000000000..4ea551d55a5b3215f99de79ff976a7f369069b07
--- /dev/null
+++ b/plugins/Actions/Categories/OutlinksSubcategory.php
@@ -0,0 +1,26 @@
+' . Piwik::translate('Actions_OutlinksSubcategoryHelp1') . ''
+ . '' . Piwik::translate('Actions_PagesSubcategoryHelp3') . '
';
+ }
+}
diff --git a/plugins/Actions/Categories/PageTitlesSubcategory.php b/plugins/Actions/Categories/PageTitlesSubcategory.php
new file mode 100644
index 0000000000000000000000000000000000000000..66beb21ceb72bee6b1adca5424dc00cc68f87d41
--- /dev/null
+++ b/plugins/Actions/Categories/PageTitlesSubcategory.php
@@ -0,0 +1,26 @@
+' . Piwik::translate('Actions_PageTitlesSubcategoryHelp1') . ''
+ . '' . Piwik::translate('Actions_PageTitlesSubcategoryHelp2') . '
';
+ }
+}
diff --git a/plugins/Actions/Categories/PagesSubcategory.php b/plugins/Actions/Categories/PagesSubcategory.php
new file mode 100644
index 0000000000000000000000000000000000000000..755058ec061162355103bdd8c65fd39dba420ff4
--- /dev/null
+++ b/plugins/Actions/Categories/PagesSubcategory.php
@@ -0,0 +1,27 @@
+' . Piwik::translate('Actions_PagesSubcategoryHelp1') . ''
+ . '' . Piwik::translate('Actions_PagesSubcategoryHelp2') . '
'
+ . '' . Piwik::translate('Actions_PagesSubcategoryHelp3') . '
';
+ }
+}
diff --git a/plugins/Actions/Categories/SiteSearchSubcategory.php b/plugins/Actions/Categories/SiteSearchSubcategory.php
new file mode 100644
index 0000000000000000000000000000000000000000..cdaee090e9c63670fd1e449a613430bcb8ad7c9e
--- /dev/null
+++ b/plugins/Actions/Categories/SiteSearchSubcategory.php
@@ -0,0 +1,29 @@
+' . Piwik::translate('Actions_SiteSearchSubcategoryHelp1') . ''
+ . '' . Piwik::translate('Actions_SiteSearchSubcategoryHelp2') . '
'
+ . '' . Url::getExternalLinkTag('https://matomo.org/docs/site-search/', null, null, 'App.Actions.getSiteSearchCategories')
+ . Piwik::translate('Actions_SiteSearchSubcategoryHelp3') . '
';
+ }
+}
diff --git a/plugins/Actions/Columns/ActionType.php b/plugins/Actions/Columns/ActionType.php
new file mode 100644
index 0000000000000000000000000000000000000000..2c636e2e51baf3110a876137037f301f4ba3cbe3
--- /dev/null
+++ b/plugins/Actions/Columns/ActionType.php
@@ -0,0 +1,81 @@
+ 76,
+ * 'name' => 'media_play'
+ * );
+ * }
+ *
+ * @param array $availableTypes
+ */
+ Piwik::postEvent('Actions.addActionTypes', [&$availableTypes]);
+
+ $types = [];
+
+ foreach ($availableTypes as $type) {
+ if (empty($type['id']) || empty($type['name'])) {
+ throw new Exception("Invalid action added with event `Actions.addActionTypes`: " . var_export($type, true));
+ }
+ if (Development::isEnabled() && array_key_exists($type['id'], $types)) {
+ throw new Exception(sprintf("Action '%s' with id %s couldn't be added, as '%s' was already added for this id", $type['name'], $type['id'], $types[$type['id']]));
+ }
+ $types[$type['id']] = $type['name'];
+ }
+
+ return $types;
+ }
+
+ public function configureMetrics(MetricsList $metricsList, DimensionMetricFactory $dimensionMetricFactory)
+ {
+ // do not generate any metric for this
+ }
+}
diff --git a/plugins/Actions/Columns/ActionUrl.php b/plugins/Actions/Columns/ActionUrl.php
new file mode 100644
index 0000000000000000000000000000000000000000..cf9d90bc01fbf8594d26c2ec113c30e259f267ea
--- /dev/null
+++ b/plugins/Actions/Columns/ActionUrl.php
@@ -0,0 +1,40 @@
+setSegment('actionUrl');
+ $segment->setName('Actions_ColumnActionURL');
+ $segment->setUnionOfSegments(array('pageUrl', 'downloadUrl', 'outlinkUrl', 'eventUrl'));
+
+ $segmentsList->addSegment($dimensionSegmentFactory->createSegment($segment));
+ }
+}
diff --git a/plugins/Actions/Columns/ClickedUrl.php b/plugins/Actions/Columns/ClickedUrl.php
new file mode 100644
index 0000000000000000000000000000000000000000..ac1e98ca4e8bb11d25a953eb1b2ffaa9b5739bde
--- /dev/null
+++ b/plugins/Actions/Columns/ClickedUrl.php
@@ -0,0 +1,38 @@
+getIdActionNameForEntryAndExitIds();
+ }
+
+ return (int) $idActionName;
+ }
+}
diff --git a/plugins/Actions/Columns/EntryPageUrl.php b/plugins/Actions/Columns/EntryPageUrl.php
new file mode 100644
index 0000000000000000000000000000000000000000..fa32139f7de1e79a6152eb3eeee5cf3c9eb7650d
--- /dev/null
+++ b/plugins/Actions/Columns/EntryPageUrl.php
@@ -0,0 +1,80 @@
+getIdActionUrlForEntryAndExitIds();
+ }
+
+ if ($idActionUrl === false) {
+ return false;
+ }
+
+ return (int) $idActionUrl;
+ }
+
+ /*
+ * @param Request $request
+ * @param Visitor $visitor
+ * @param Action|null $action
+ * @return mixed
+ */
+ public function onExistingVisit(Request $request, Visitor $visitor, $action)
+ {
+ $idAction = $visitor->getVisitorColumn('visit_entry_idaction_url');
+
+ if (is_null($idAction) && !empty($action)) {
+ $idAction = $action->getIdActionUrlForEntryAndExitIds();
+ if (!empty($idAction)) {
+ return $idAction;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/plugins/Actions/Columns/ExitPageTitle.php b/plugins/Actions/Columns/ExitPageTitle.php
new file mode 100644
index 0000000000000000000000000000000000000000..effb1fdd0fa925e907f56395aa19d3418bbf8144
--- /dev/null
+++ b/plugins/Actions/Columns/ExitPageTitle.php
@@ -0,0 +1,69 @@
+getIdActionNameForEntryAndExitIds();
+ }
+
+ return (int) $idActionName;
+ }
+
+ /**
+ * @param Action|null $action
+ * @return int|false|null
+ */
+ public function onExistingVisit(Request $request, Visitor $visitor, $action)
+ {
+ if (empty($action)) {
+ return false;
+ }
+
+ return $action->getIdActionNameForEntryAndExitIds();
+ }
+}
diff --git a/plugins/Actions/Columns/ExitPageUrl.php b/plugins/Actions/Columns/ExitPageUrl.php
new file mode 100644
index 0000000000000000000000000000000000000000..34428c51077f938b97392b61ee3ea0e31447c289
--- /dev/null
+++ b/plugins/Actions/Columns/ExitPageUrl.php
@@ -0,0 +1,82 @@
+getIdActionUrlForEntryAndExitIds();
+ }
+
+ return (int) $idActionUrl;
+ }
+
+ /**
+ * @param Action|null $action
+ * @return int|false
+ */
+ public function onExistingVisit(Request $request, Visitor $visitor, $action)
+ {
+ if (empty($action)) {
+ return false;
+ }
+
+ $id = $action->getIdActionUrlForEntryAndExitIds();
+
+ if (!empty($id)) {
+ $id = (int) $id;
+ }
+
+ return $id;
+ }
+}
diff --git a/plugins/Actions/Columns/IdPageview.php b/plugins/Actions/Columns/IdPageview.php
new file mode 100644
index 0000000000000000000000000000000000000000..d385449d819ddf9840817197f9ff570b49532de8
--- /dev/null
+++ b/plugins/Actions/Columns/IdPageview.php
@@ -0,0 +1,39 @@
+getParam('pv_id'), 0, 6);
+ }
+
+ public function configureMetrics(MetricsList $metricsList, DimensionMetricFactory $dimensionMetricFactory)
+ {
+ // metrics for idpageview do not really make any sense
+ }
+}
diff --git a/plugins/Actions/Columns/Keyword.php b/plugins/Actions/Columns/Keyword.php
new file mode 100644
index 0000000000000000000000000000000000000000..bfe88473b7e75916d4c03b84585157a11f25d89b
--- /dev/null
+++ b/plugins/Actions/Columns/Keyword.php
@@ -0,0 +1,18 @@
+getMetric($row, 'sum_time_generation');
+ $hitsWithTimeGeneration = $this->getMetric($row, 'nb_hits_with_time_generation');
+
+ return Piwik::getQuotientSafe($sumGenerationTime, $hitsWithTimeGeneration, $precision = 3);
+ }
+
+ public function format($value, Formatter $formatter)
+ {
+ if (
+ $formatter instanceof Formatter\Html
+ && !$value
+ ) {
+ return '-';
+ } else {
+ return $formatter->getPrettyTimeFromSeconds($value, $displayAsSentence = true);
+ }
+ }
+
+ public function beforeCompute($report, DataTable $table)
+ {
+ $hasTimeGeneration = array_sum($this->getMetricValues($table, 'sum_time_generation')) > 0;
+
+ if (
+ !$hasTimeGeneration
+ && $table->getRowsCount() != 0
+ && !$this->hasAverageTimeGeneration($table)
+ ) {
+ // No generation time: remove it from the API output and add it to empty_columns metadata, so that
+ // the columns can also be removed from the view
+ $table->filter('ColumnDelete', array(array(
+ Metrics::INDEX_PAGE_SUM_TIME_GENERATION,
+ Metrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION,
+ Metrics::INDEX_PAGE_MIN_TIME_GENERATION,
+ Metrics::INDEX_PAGE_MAX_TIME_GENERATION,
+ 'sum_time_generation',
+ 'nb_hits_with_time_generation',
+ 'min_time_generation',
+ 'max_time_generation',
+ )));
+
+ if ($table instanceof DataTable) {
+ $emptyColumns = $table->getMetadata(DataTable::EMPTY_COLUMNS_METADATA_NAME);
+ if (!is_array($emptyColumns)) {
+ $emptyColumns = array();
+ }
+ $emptyColumns[] = 'sum_time_generation';
+ $emptyColumns[] = 'avg_time_generation';
+ $emptyColumns[] = 'min_time_generation';
+ $emptyColumns[] = 'max_time_generation';
+ $table->setMetadata(DataTable::EMPTY_COLUMNS_METADATA_NAME, $emptyColumns);
+ }
+ }
+
+ return $hasTimeGeneration;
+ }
+
+ private function hasAverageTimeGeneration(DataTable $table)
+ {
+ return $table->getFirstRow()->getColumn('avg_time_generation') !== false;
+ }
+
+ public function getSemanticType(): ?string
+ {
+ return Dimension::TYPE_DURATION_S;
+ }
+}
diff --git a/plugins/Actions/Columns/Metrics/AverageTimeOnPage.php b/plugins/Actions/Columns/Metrics/AverageTimeOnPage.php
new file mode 100644
index 0000000000000000000000000000000000000000..d891ffe2d8736604fcce6ce5621210a6301e40c2
--- /dev/null
+++ b/plugins/Actions/Columns/Metrics/AverageTimeOnPage.php
@@ -0,0 +1,59 @@
+getMetric($row, 'sum_time_spent');
+ $visits = $this->getMetric($row, 'nb_hits');
+
+ return Piwik::getQuotientSafe($sumTimeSpent, $visits, $precision = 0);
+ }
+
+ public function format($value, Formatter $formatter)
+ {
+ return $formatter->getPrettyTimeFromSeconds($value, $timeAsSentence = false);
+ }
+
+ public function getDependentMetrics()
+ {
+ return array('sum_time_spent', 'nb_hits');
+ }
+
+ public function getSemanticType(): ?string
+ {
+ return Dimension::TYPE_DURATION_S;
+ }
+}
diff --git a/plugins/Actions/Columns/Metrics/BounceRate.php b/plugins/Actions/Columns/Metrics/BounceRate.php
new file mode 100644
index 0000000000000000000000000000000000000000..3966b85d7cac7a554dad34905069b2c916ddec6c
--- /dev/null
+++ b/plugins/Actions/Columns/Metrics/BounceRate.php
@@ -0,0 +1,59 @@
+getMetric($row, 'entry_bounce_count');
+ $entryVisits = $this->getMetric($row, 'entry_nb_visits');
+
+ return Piwik::getQuotientSafe($entryBounceCount, $entryVisits, $precision = 2);
+ }
+
+ public function format($value, Formatter $formatter)
+ {
+ return $formatter->getPrettyPercentFromQuotient($value);
+ }
+
+ public function getDependentMetrics()
+ {
+ return array('entry_bounce_count', 'entry_nb_visits');
+ }
+
+ public function getSemanticType(): ?string
+ {
+ return Dimension::TYPE_PERCENT;
+ }
+}
diff --git a/plugins/Actions/Columns/Metrics/ExitRate.php b/plugins/Actions/Columns/Metrics/ExitRate.php
new file mode 100644
index 0000000000000000000000000000000000000000..396be73bd706c613599a21cad3d5e302038648fd
--- /dev/null
+++ b/plugins/Actions/Columns/Metrics/ExitRate.php
@@ -0,0 +1,59 @@
+getMetric($row, 'exit_nb_visits');
+ $visits = $this->getMetric($row, 'nb_visits');
+
+ return Piwik::getQuotientSafe($exitVisits, $visits, $precision = 2);
+ }
+
+ public function format($value, Formatter $formatter)
+ {
+ return $formatter->getPrettyPercentFromQuotient($value);
+ }
+
+ public function getDependentMetrics()
+ {
+ return array('exit_nb_visits', 'nb_visits');
+ }
+
+ public function getSemanticType(): ?string
+ {
+ return Dimension::TYPE_PERCENT;
+ }
+}
diff --git a/plugins/Actions/Columns/PageGenerationTime.php b/plugins/Actions/Columns/PageGenerationTime.php
new file mode 100644
index 0000000000000000000000000000000000000000..f0dbf7424c9acd172cf6a805af3ddccb26a574bb
--- /dev/null
+++ b/plugins/Actions/Columns/PageGenerationTime.php
@@ -0,0 +1,57 @@
+createMetric(ArchivedMetric::AGGREGATION_SUM);
+ $metricsList->addMetric($metric1);
+
+ $metric2 = $dimensionMetricFactory->createMetric(ArchivedMetric::AGGREGATION_MAX);
+ $metricsList->addMetric($metric2);
+
+ $metric3 = $dimensionMetricFactory->createMetric(ArchivedMetric::AGGREGATION_COUNT_WITH_NUMERIC_VALUE);
+ $metric3->setName('pageviews_with_generation_time');
+ $metric3->setTranslatedName(Piwik::translate('General_ColumnViewsWithGenerationTime'));
+ $metricsList->addMetric($metric3);
+
+ $metric = $dimensionMetricFactory->createComputedMetric($metric1->getName(), $metric3->getName(), ComputedMetric::AGGREGATION_AVG);
+ $metric->setName('avg_page_generation_time');
+ $metric->setTranslatedName(Piwik::translate('General_ColumnAverageGenerationTime'));
+ $metricsList->addMetric($metric);
+ }
+}
diff --git a/plugins/Actions/Columns/PageTitle.php b/plugins/Actions/Columns/PageTitle.php
new file mode 100644
index 0000000000000000000000000000000000000000..08ed22ca510e607573bfb984da41da3e0e36fc3a
--- /dev/null
+++ b/plugins/Actions/Columns/PageTitle.php
@@ -0,0 +1,39 @@
+isNewVisit()) {
+ return 1;
+ } elseif ($shouldCount) {
+ return VisitTotalInteractions::getNextInteractionPosition($request);
+ }
+
+ // we re-use same interaction position as last page view eg for events etc.
+ $position = VisitTotalInteractions::getCurrentInteractionPosition($request);
+ if ($position >= 1) {
+ return $position;
+ }
+
+ return false;
+ }
+}
diff --git a/plugins/Actions/Columns/SearchCategory.php b/plugins/Actions/Columns/SearchCategory.php
new file mode 100644
index 0000000000000000000000000000000000000000..4475963e33ae6d0782012b40aeb527dd3ba9ed79
--- /dev/null
+++ b/plugins/Actions/Columns/SearchCategory.php
@@ -0,0 +1,45 @@
+getSearchCategory();
+ }
+
+ return parent::onNewAction($request, $visitor, $action);
+ }
+
+ public function configureSegments(SegmentsList $segmentsList, DimensionSegmentFactory $dimensionSegmentFactory)
+ {
+ $segment = new Segment();
+ $segment->setName('Actions_SiteSearchCategory');
+ $segmentsList->addSegment($dimensionSegmentFactory->createSegment($segment));
+ }
+}
diff --git a/plugins/Actions/Columns/SearchCount.php b/plugins/Actions/Columns/SearchCount.php
new file mode 100644
index 0000000000000000000000000000000000000000..87209891ae9e25b2e27b69f4a5b3e510b87bd8e6
--- /dev/null
+++ b/plugins/Actions/Columns/SearchCount.php
@@ -0,0 +1,35 @@
+getSearchCount();
+ }
+
+ return parent::onNewAction($request, $visitor, $action);
+ }
+}
diff --git a/plugins/Actions/Columns/SearchDestinationPage.php b/plugins/Actions/Columns/SearchDestinationPage.php
new file mode 100644
index 0000000000000000000000000000000000000000..09303467ef59c1cc0cef2c33f826ca3e90b2d174
--- /dev/null
+++ b/plugins/Actions/Columns/SearchDestinationPage.php
@@ -0,0 +1,18 @@
+getVisitorColumn('time_spent_ref_action');
+
+ if (empty($timeSpent)) {
+ return 0;
+ }
+
+ return $timeSpent;
+ }
+}
diff --git a/plugins/Actions/Columns/VisitTotalActions.php b/plugins/Actions/Columns/VisitTotalActions.php
new file mode 100644
index 0000000000000000000000000000000000000000..f9d175d34b6a8c0c4bba71d80d0b7ea30b54cd1c
--- /dev/null
+++ b/plugins/Actions/Columns/VisitTotalActions.php
@@ -0,0 +1,104 @@
+createCustomMetric('bounce_count', Piwik::translate('General_ColumnBounces'), 'sum(case %s when 1 then 1 when 0 then 1 else 0 end)');
+ $metric1->setDocumentation(Piwik::translate('General_ColumnBouncesDocumentation'));
+ $metricsList->addMetric($metric1);
+
+ $metric = $dimensionMetricFactory->createMetric(ArchivedMetric::AGGREGATION_SUM);
+ $metricsList->addMetric($metric);
+
+ $metric = $dimensionMetricFactory->createMetric(ArchivedMetric::AGGREGATION_MAX);
+ $metricsList->addMetric($metric);
+
+ $metric = $dimensionMetricFactory->createComputedMetric($metric1->getName(), 'nb_visits', ComputedMetric::AGGREGATION_RATE);
+ $metric->setTranslatedName(Piwik::translate('General_ColumnBounceRate'));
+ $metric->setName('bounce_rate');
+ $metric->setDocumentation(Piwik::translate('General_ColumnBounceRateDocumentation'));
+ $metricsList->addMetric($metric);
+ }
+
+ /**
+ * @param Action|null $action
+ * @return int
+ */
+ public function onNewVisit(Request $request, Visitor $visitor, $action)
+ {
+ $actionType = false;
+ if ($action) {
+ $actionType = $action->getActionType();
+ }
+
+ $actions = array(
+ Action::TYPE_PAGE_URL,
+ Action::TYPE_DOWNLOAD,
+ Action::TYPE_OUTLINK,
+ Action::TYPE_SITE_SEARCH,
+ Action::TYPE_EVENT,
+ );
+
+ // if visit starts with something else (e.g. ecommerce order), don't record as an action
+ if (in_array($actionType, $actions)) {
+ return 1;
+ }
+
+ return 0;
+ }
+
+ /**
+ * @param Action|null $action
+ * @return string|false
+ */
+ public function onExistingVisit(Request $request, Visitor $visitor, $action)
+ {
+ if (!$action) {
+ return false;
+ }
+
+ $increment = 'visit_total_actions + 1';
+
+ $idActionUrl = $action->getIdActionUrlForEntryAndExitIds();
+
+ if ($idActionUrl !== false) {
+ return $increment;
+ }
+
+ $actionType = $action->getActionType();
+ $types = array(Action::TYPE_SITE_SEARCH, Action::TYPE_EVENT, Action::TYPE_OUTLINK, Action::TYPE_DOWNLOAD);
+
+ if (in_array($actionType, $types)) {
+ return $increment;
+ }
+
+ return false;
+ }
+}
diff --git a/plugins/Actions/Columns/VisitTotalInteractions.php b/plugins/Actions/Columns/VisitTotalInteractions.php
new file mode 100644
index 0000000000000000000000000000000000000000..77993d78483d95f3a3444774ac8f8301b8e06db9
--- /dev/null
+++ b/plugins/Actions/Columns/VisitTotalInteractions.php
@@ -0,0 +1,110 @@
+suggestedValuesCallback = function ($idSite, $maxValuesToReturn) {
+ $positions = range(1, 50);
+
+ return array_slice($positions, 0, $maxValuesToReturn);
+ };
+ }
+
+ /**
+ * @param Action|null $action
+ * @return int
+ */
+ public function onNewVisit(Request $request, Visitor $visitor, $action)
+ {
+ if (self::shouldCountInteraction($action)) {
+ return 1;
+ }
+
+ return 0;
+ }
+
+ /**
+ * @param Action|null $action
+ * @return string|false
+ */
+ public function onExistingVisit(Request $request, Visitor $visitor, $action)
+ {
+ $request->setMetadata('Actions', $this->columnName, $visitor->getVisitorColumn($this->columnName));
+
+ if (self::shouldCountInteraction($action)) {
+ return $this->columnName . ' + 1';
+ }
+
+ return false;
+ }
+
+ /**
+ * @param Request $request
+ * @return int
+ */
+ public static function getCurrentInteractionPosition($request)
+ {
+ $position = $request->getMetadata('Actions', 'visit_total_interactions');
+
+ return (int) $position;
+ }
+
+ /**
+ * @param Request $request
+ * @return int
+ */
+ public static function getNextInteractionPosition($request)
+ {
+ $position = self::getCurrentInteractionPosition($request);
+
+ return $position + 1;
+ }
+
+ /**
+ * @param Action|null $action
+ * @return bool
+ */
+ public static function shouldCountInteraction($action)
+ {
+ if (empty($action)) {
+ return false;
+ }
+
+ $idActionUrl = $action->getIdActionUrlForEntryAndExitIds();
+
+ if ($idActionUrl !== false) {
+ return true;
+ }
+
+ $actionType = $action->getActionType();
+ $types = array(Action::TYPE_SITE_SEARCH);
+
+ if (in_array($actionType, $types)) {
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/plugins/Actions/Columns/VisitTotalSearches.php b/plugins/Actions/Columns/VisitTotalSearches.php
new file mode 100644
index 0000000000000000000000000000000000000000..6248481f25a9959768cb7b20fa1b58d7240ada2f
--- /dev/null
+++ b/plugins/Actions/Columns/VisitTotalSearches.php
@@ -0,0 +1,65 @@
+0');
+ }
+
+ /**
+ * @param Action|null $action
+ * @return int
+ */
+ public function onNewVisit(Request $request, Visitor $visitor, $action)
+ {
+ if ($this->isSiteSearchAction($action)) {
+ return 1;
+ }
+
+ return 0;
+ }
+
+ /**
+ * @param Action|null $action
+ * @return string|false
+ */
+ public function onExistingVisit(Request $request, Visitor $visitor, $action)
+ {
+ if ($this->isSiteSearchAction($action)) {
+ return 'visit_total_searches + 1';
+ }
+
+ return false;
+ }
+
+ /**
+ * @param Action|null $action
+ * @return bool
+ */
+ private function isSiteSearchAction($action)
+ {
+ return ($action && $action->getActionType() == Action::TYPE_SITE_SEARCH);
+ }
+}
diff --git a/plugins/Actions/DataTable/Filter/Actions.php b/plugins/Actions/DataTable/Filter/Actions.php
new file mode 100644
index 0000000000000000000000000000000000000000..061377153fcc5ebff534509e4f179d657104a177
--- /dev/null
+++ b/plugins/Actions/DataTable/Filter/Actions.php
@@ -0,0 +1,227 @@
+|null>
+ */
+ private $siteBaseUrlsCache = [];
+
+ /**
+ * @param DataTable $table The table to eventually filter.
+ * @param int $actionType The action type being processed.
+ */
+ public function __construct($table, $actionType)
+ {
+ parent::__construct($table);
+ $this->actionType = $actionType;
+ }
+
+ /**
+ * @param DataTable $table
+ */
+ public function filter($table)
+ {
+ $isFlattening = Common::getRequestVar('flat', 0);
+ $table->filter(function (DataTable $dataTable) use ($isFlattening) {
+ $site = $dataTable->getMetadata('site');
+ $urlPrefix = $site ? $site->getMainUrl() : null;
+
+ $defaultActionName = GeneralConfig::getConfigValue('action_default_name');
+
+ $isPageTitleType = $this->actionType == Action::TYPE_PAGE_TITLE;
+
+ // for BC, we read the old style delimiter first (see #1067)
+ $actionDelimiter = GeneralConfig::getConfigValue('action_category_delimiter');
+ if (empty($actionDelimiter)) {
+ if ($isPageTitleType) {
+ $actionDelimiter = GeneralConfig::getConfigValue('action_title_category_delimiter');
+ } else {
+ $actionDelimiter = GeneralConfig::getConfigValue('action_url_category_delimiter');
+ }
+ }
+
+ $notDefinedUrl = ArchivingHelper::getUnknownActionName(Action::TYPE_PAGE_URL);
+ $notDefinedTitle = ArchivingHelper::getUnknownActionName(Action::TYPE_PAGE_TITLE);
+
+ foreach ($dataTable->getRows() as $row) {
+ if (!$row->isSummaryRow()) {
+ $url = $row->getMetadata('url');
+ $pageTitlePath = $row->getMetadata('page_title_path');
+ $folderUrlStart = $row->getMetadata('folder_url_start');
+ $label = $row->getColumn('label');
+ if ($url) {
+ $row->setMetadata('segmentValue', urlencode($url));
+
+ if ($site && strpos($url, 'http://') === 0) {
+ $host = parse_url($url, PHP_URL_HOST);
+
+ if ($host && PageUrl::shouldUseHttpsHost($site->getId(), $host)) {
+ $row->setMetadata('url', 'https://' . mb_substr($url, 7 /* = strlen('http://') */));
+ }
+ }
+ } elseif ($folderUrlStart) {
+ $row->setMetadata('segment', $this->buildFolderUrlSegment($folderUrlStart, $site));
+ } elseif ($pageTitlePath) {
+ if ($row->getIdSubDataTable()) {
+ $row->setMetadata('segment', 'pageTitle=^' . urlencode(urlencode(trim($pageTitlePath))));
+ } else {
+ $row->setMetadata('segmentValue', urlencode(trim($pageTitlePath)));
+ }
+ } elseif ($isPageTitleType && !in_array($label, [DataTable::LABEL_SUMMARY_ROW])) {
+ // for older data w/o page_title_path metadata
+ if ($row->getIdSubDataTable()) {
+ $row->setMetadata('segment', 'pageTitle=^' . urlencode(urlencode(trim($label))));
+ } else {
+ if (trim($label) == $notDefinedTitle) {
+ // segmenting by an "empty" value is currently broken for actions, so we do not set a segment value to hide row actions like segmented visit log
+ $row->setMetadata('segment', null);
+ } else {
+ $row->setMetadata('segmentValue', urlencode(trim($label)));
+ }
+ }
+ } elseif ($this->actionType == Action::TYPE_PAGE_URL) { // folder for older data w/ no folder URL metadata
+ if ($label === $notDefinedUrl) {
+ // segmenting by an "empty" value is currently broken for actions, so we do not set a segment value to hide row actions like segmented visit log
+ $row->setMetadata('segment', null);
+ } elseif ($urlPrefix) {
+ $row->setMetadata(
+ 'segment',
+ $this->buildFolderUrlSegment($urlPrefix . '/' . $label, $site)
+ );
+ }
+ }
+ }
+
+ // remove the default action name 'index' in the end of flattened urls and prepend $actionDelimiter
+ if ($isFlattening) {
+ $label = $row->getColumn('label');
+ $stringToSearch = $actionDelimiter . $defaultActionName;
+ if (substr($label, -strlen($stringToSearch)) == $stringToSearch) {
+ $label = substr($label, 0, -strlen($defaultActionName));
+ $label = rtrim($label, $actionDelimiter) . $actionDelimiter;
+ $row->setColumn('label', $label);
+ }
+ $dataTable->setLabelsHaveChanged();
+ }
+
+ $row->deleteMetadata('folder_url_start');
+ $row->deleteMetadata('page_title_path');
+ }
+ });
+
+ foreach ($table->getRowsWithoutSummaryRow() as $row) {
+ $subtable = $row->getSubtable();
+ if ($subtable) {
+ $this->filter($subtable);
+ }
+ }
+ }
+
+ /**
+ * Builds the `pageUrl=^` segment for a folder row. If the site has additional URL
+ * aliases registered, the segment is an OR-joined list with one `pageUrl=^` clause
+ * per host so the visitor log query matches rows tracked under any of the site's
+ * known hosts, not only `main_url`.
+ */
+ private function buildFolderUrlSegment(string $folderUrlStart, $site): string
+ {
+ $original = 'pageUrl=^' . urlencode(urlencode($folderUrlStart));
+
+ if (!$site) {
+ return $original;
+ }
+
+ $mainUrl = $site->getMainUrl();
+ if (empty($mainUrl)) {
+ return $original;
+ }
+
+ // `folder_url_start` (and the legacy fallback) is always built as
+ // `/`. Strip the main URL to get the path-only portion
+ // that we can re-attach to each known host.
+ $mainUrlNormalized = rtrim($mainUrl, '/') . '/';
+ if (strpos($folderUrlStart, $mainUrlNormalized) !== 0) {
+ return $original;
+ }
+ $folderPath = substr($folderUrlStart, strlen($mainUrlNormalized));
+
+ $baseUrls = $this->getResolvedBaseUrls((int) $site->getId());
+ if ($baseUrls === null) {
+ return $original;
+ }
+
+ $clauses = [];
+ foreach ($baseUrls as $baseUrl) {
+ $clauses[] = 'pageUrl=^' . urlencode(urlencode($baseUrl . $folderPath));
+ }
+
+ if (empty($clauses)) {
+ return $original;
+ }
+
+ return implode(',', $clauses);
+ }
+
+ /**
+ * Returns the site's main URL and aliases as a list of normalized base URLs
+ * (each ending with `/`). Preserves any path component carried on `main_url`
+ * or on individual aliases so the rebuilt segment still matches the archived
+ * folder rows. Returns `null` if the API failed for this site (callers fall
+ * back to the single-clause original segment).
+ *
+ * @return list|null
+ */
+ private function getResolvedBaseUrls(int $idSite): ?array
+ {
+ if (array_key_exists($idSite, $this->siteBaseUrlsCache)) {
+ return $this->siteBaseUrlsCache[$idSite];
+ }
+
+ try {
+ $allUrls = SitesManagerAPI::getInstance()->getSiteUrlsFromId($idSite);
+ } catch (\Exception $e) {
+ return $this->siteBaseUrlsCache[$idSite] = null;
+ }
+
+ $seen = [];
+ $baseUrls = [];
+ foreach ($allUrls as $url) {
+ if (!parse_url($url, PHP_URL_HOST)) {
+ continue;
+ }
+ $normalized = rtrim($url, '/') . '/';
+ if (isset($seen[$normalized])) {
+ continue;
+ }
+ $seen[$normalized] = true;
+ $baseUrls[] = $normalized;
+ }
+
+ return $this->siteBaseUrlsCache[$idSite] = $baseUrls;
+ }
+}
diff --git a/plugins/Actions/Metrics.php b/plugins/Actions/Metrics.php
new file mode 100644
index 0000000000000000000000000000000000000000..0e8907b897a07fcc006265a0a68224ac2d7f3d40
--- /dev/null
+++ b/plugins/Actions/Metrics.php
@@ -0,0 +1,103 @@
+ PiwikMetrics::INDEX_SUM_DAILY_NB_UNIQ_VISITORS,
+ PiwikMetrics::INDEX_PAGE_ENTRY_NB_UNIQ_VISITORS => PiwikMetrics::INDEX_PAGE_ENTRY_SUM_DAILY_NB_UNIQ_VISITORS,
+ PiwikMetrics::INDEX_PAGE_EXIT_NB_UNIQ_VISITORS => PiwikMetrics::INDEX_PAGE_EXIT_SUM_DAILY_NB_UNIQ_VISITORS,
+ );
+
+ public static $columnsToDeleteAfterAggregation = array(
+ PiwikMetrics::INDEX_NB_UNIQ_VISITORS,
+ PiwikMetrics::INDEX_PAGE_ENTRY_NB_UNIQ_VISITORS,
+ PiwikMetrics::INDEX_PAGE_EXIT_NB_UNIQ_VISITORS,
+ );
+
+ public static function getColumnsAggregationOperation()
+ {
+ $operations = [];
+ $actionMetrics = self::getActionMetrics();
+
+ foreach ($actionMetrics as $actionMetric => $definition) {
+ if (!empty($definition['aggregation']) && $definition['aggregation'] !== 'sum') {
+ $operations[$actionMetric] = $definition['aggregation'];
+ }
+ }
+
+ return $operations;
+ }
+
+ public static function getActionMetrics()
+ {
+ $metricsConfig = array(
+ PiwikMetrics::INDEX_NB_VISITS => array(
+ 'aggregation' => 'sum',
+ 'query' => "count(distinct log_link_visit_action.idvisit)",
+ ),
+ PiwikMetrics::INDEX_NB_UNIQ_VISITORS => array(
+ 'aggregation' => false,
+ 'query' => "count(distinct log_link_visit_action.idvisitor)",
+ ),
+ PiwikMetrics::INDEX_PAGE_NB_HITS => array(
+ 'aggregation' => 'sum',
+ 'query' => "count(*)",
+ ),
+ PiwikMetrics::INDEX_PAGE_SUM_TIME_GENERATION => array(
+ 'aggregation' => 'sum',
+ 'query' => "sum(
+ case when " . Action::DB_COLUMN_CUSTOM_FLOAT . " is null
+ then 0
+ else " . Action::DB_COLUMN_CUSTOM_FLOAT . "
+ end
+ ) / 1000",
+ ),
+ PiwikMetrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION => array(
+ 'aggregation' => 'sum',
+ 'query' => "sum(
+ case when " . Action::DB_COLUMN_CUSTOM_FLOAT . " is null
+ then 0
+ else 1
+ end
+ )",
+ ),
+ PiwikMetrics::INDEX_PAGE_MIN_TIME_GENERATION => array(
+ 'aggregation' => 'min',
+ 'query' => "min(" . Action::DB_COLUMN_CUSTOM_FLOAT . ") / 1000",
+ ),
+ PiwikMetrics::INDEX_PAGE_MAX_TIME_GENERATION => array(
+ 'aggregation' => 'max',
+ 'query' => "max(" . Action::DB_COLUMN_CUSTOM_FLOAT . ") / 1000",
+ ),
+ );
+
+ Piwik::postEvent('Actions.Archiving.addActionMetrics', array(&$metricsConfig));
+
+ return $metricsConfig;
+ }
+}
diff --git a/plugins/Actions/RecordBuilders/ActionReports.php b/plugins/Actions/RecordBuilders/ActionReports.php
new file mode 100644
index 0000000000000000000000000000000000000000..4caeafeb6d414c83e9b5f0f3b5bd0ef31d8eb9db
--- /dev/null
+++ b/plugins/Actions/RecordBuilders/ActionReports.php
@@ -0,0 +1,982 @@
+setBlobColumnAggregationOps(Metrics::getColumnsAggregationOperation());
+ $pageTitlesRecord = Record::make(Record::TYPE_BLOB, Archiver::PAGE_TITLES_RECORD_NAME)
+ ->setBlobColumnAggregationOps(Metrics::getColumnsAggregationOperation());
+
+ if ($this->isFlatArchivingEnabled()) {
+ $this->setHierarchyBuiltFromFlatRecord(
+ $pageUrlsRecord,
+ Archiver::PAGE_URLS_FLAT_RECORD_NAME,
+ [$this, 'flatRowToUrlHierarchyPath'],
+ [$this, 'reduceLegacyUrlHierarchyIntoFlatTable']
+ );
+ $this->setHierarchyBuiltFromFlatRecord(
+ $pageTitlesRecord,
+ Archiver::PAGE_TITLES_FLAT_RECORD_NAME,
+ [$this, 'flatRowToTitleHierarchyPath'],
+ [$this, 'reduceLegacyTitleHierarchyIntoFlatTable']
+ );
+ }
+
+ $records = [
+ Record::make(Record::TYPE_BLOB, Archiver::SITE_SEARCH_RECORD_NAME)
+ ->setMaxRowsInTable(ArchivingHelper::$maximumRowsInDataTableSiteSearch),
+
+ $pageUrlsRecord,
+ $pageTitlesRecord,
+
+ Record::make(Record::TYPE_BLOB, Archiver::DOWNLOADS_RECORD_NAME),
+ Record::make(Record::TYPE_BLOB, Archiver::OUTLINKS_RECORD_NAME),
+
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_SEARCHES_RECORD_NAME),
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_KEYWORDS_RECORD_NAME)
+ ->setIsCountOfBlobRecordRows(Archiver::SITE_SEARCH_RECORD_NAME),
+
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_OUTLINKS_RECORD_NAME),
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_UNIQ_OUTLINKS_RECORD_NAME),
+
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_PAGEVIEWS_RECORD_NAME),
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_UNIQ_PAGEVIEWS_RECORD_NAME),
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_SUM_TIME_RECORD_NAME),
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_HITS_TIMED_RECORD_NAME),
+
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_DOWNLOADS_RECORD_NAME),
+ Record::make(Record::TYPE_NUMERIC, Archiver::METRIC_UNIQ_DOWNLOADS_RECORD_NAME),
+ ];
+
+ if ($this->isFlatArchivingEnabled()) {
+ $records[] = Record::make(Record::TYPE_BLOB, Archiver::PAGE_URLS_FLAT_RECORD_NAME)
+ ->setBlobColumnAggregationOps(Metrics::getColumnsAggregationOperation())
+ ->setMaxRowsInTable(ArchivingHelper::$maximumRowsInDataTableFlat);
+ $records[] = Record::make(Record::TYPE_BLOB, Archiver::PAGE_TITLES_FLAT_RECORD_NAME)
+ ->setBlobColumnAggregationOps(Metrics::getColumnsAggregationOperation())
+ ->setMaxRowsInTable(ArchivingHelper::$maximumRowsInDataTableFlat);
+ }
+
+ return $records;
+ }
+
+ public function flatRowToUrlHierarchyPath(Row $flatRow): ?array
+ {
+ return $this->flatRowToHierarchyPath($flatRow, Action::TYPE_PAGE_URL);
+ }
+
+ public function flatRowToTitleHierarchyPath(Row $flatRow): ?array
+ {
+ return $this->flatRowToHierarchyPath($flatRow, Action::TYPE_PAGE_TITLE);
+ }
+
+ public function reduceLegacyUrlHierarchyIntoFlatTable(DataTable $legacyHierarchy, DataTable $flatTable, ArchiveProcessor $archiveProcessor, Record $record): void
+ {
+ ArchivingHelper::mergeHierarchicalActionsTableIntoBestEffortFlatTable(
+ $legacyHierarchy,
+ $flatTable,
+ Action::TYPE_PAGE_URL
+ );
+ }
+
+ public function reduceLegacyTitleHierarchyIntoFlatTable(DataTable $legacyHierarchy, DataTable $flatTable, ArchiveProcessor $archiveProcessor, Record $record): void
+ {
+ ArchivingHelper::mergeHierarchicalActionsTableIntoBestEffortFlatTable(
+ $legacyHierarchy,
+ $flatTable,
+ Action::TYPE_PAGE_TITLE
+ );
+ }
+
+ protected function aggregate(ArchiveProcessor $archiveProcessor): array
+ {
+ if (!$this->isFlatArchivingEnabled()) {
+ return $this->aggregateLegacyHierarchical($archiveProcessor);
+ }
+
+ $rankingQueryLimit = ArchivingHelper::getRankingQueryLimit();
+ ArchivingHelper::reloadConfig();
+
+ $tablesByType = $this->makeReportTables();
+ $flatPageTablesByType = $this->makeFlatPageTables();
+ $tableModesByType = [
+ Action::TYPE_PAGE_URL => ArchivingHelper::ACTION_TABLE_MODE_FLAT,
+ Action::TYPE_PAGE_TITLE => ArchivingHelper::ACTION_TABLE_MODE_FLAT,
+ ];
+ $dayTablesByType = $tablesByType;
+ $dayTablesByType[Action::TYPE_PAGE_URL] = $flatPageTablesByType[Action::TYPE_PAGE_URL];
+ $dayTablesByType[Action::TYPE_PAGE_TITLE] = $flatPageTablesByType[Action::TYPE_PAGE_TITLE];
+
+ $this->archiveDayActions(
+ $archiveProcessor,
+ $rankingQueryLimit,
+ $dayTablesByType,
+ array_diff(array_keys($dayTablesByType), [Action::TYPE_SITE_SEARCH]),
+ true,
+ $tableModesByType
+ );
+
+ if ($archiveProcessor->getParams()->getSite()->isSiteSearchEnabled()) {
+ $rankingQueryLimitSiteSearch = max($rankingQueryLimit, ArchivingHelper::$maximumRowsInDataTableSiteSearch);
+ $this->archiveDayActions(
+ $archiveProcessor,
+ $rankingQueryLimitSiteSearch,
+ $dayTablesByType,
+ [Action::TYPE_SITE_SEARCH],
+ false,
+ $tableModesByType
+ );
+ }
+
+ $this->archiveDayEntryActions($archiveProcessor->getLogAggregator(), $dayTablesByType, $rankingQueryLimit, $tableModesByType);
+ $this->archiveDayExitActions($archiveProcessor->getLogAggregator(), $dayTablesByType, $rankingQueryLimit, $tableModesByType);
+ $this->archiveDayActionsTime($archiveProcessor->getLogAggregator(), $dayTablesByType, $rankingQueryLimit, $tableModesByType);
+ $this->archiveDayActionsGoals($archiveProcessor, $rankingQueryLimit);
+ ArchivingHelper::normalizeFlatGoalsMetricsForHierarchy($flatPageTablesByType);
+
+ ArchivingHelper::clearActionsCache();
+
+ $tablesByType[Action::TYPE_PAGE_URL] = $this->buildDayHierarchicalTableFromFlatTable(
+ $flatPageTablesByType[Action::TYPE_PAGE_URL],
+ [$this, 'flatRowToUrlHierarchyPath']
+ );
+ $tablesByType[Action::TYPE_PAGE_TITLE] = $this->buildDayHierarchicalTableFromFlatTable(
+ $flatPageTablesByType[Action::TYPE_PAGE_TITLE],
+ [$this, 'flatRowToTitleHierarchyPath']
+ );
+ $this->finalizeBuiltFromFlatHierarchyTable(
+ $archiveProcessor,
+ $tablesByType[Action::TYPE_PAGE_URL],
+ Archiver::PAGE_URLS_RECORD_NAME
+ );
+ $this->finalizeBuiltFromFlatHierarchyTable(
+ $archiveProcessor,
+ $tablesByType[Action::TYPE_PAGE_TITLE],
+ Archiver::PAGE_TITLES_RECORD_NAME
+ );
+
+ $dataTable = $tablesByType[Action::TYPE_SITE_SEARCH];
+ $this->deleteUnusedColumnsFromKeywordsDataTable($dataTable);
+
+ foreach ($tablesByType as $actionType => $dataTable) {
+ if (
+ $actionType === Action::TYPE_PAGE_URL
+ || $actionType === Action::TYPE_PAGE_TITLE
+ ) {
+ continue;
+ }
+
+ ArchivingHelper::deleteInvalidSummedColumnsFromDataTable($dataTable);
+ }
+ foreach ($flatPageTablesByType as $flatDataTable) {
+ // also removes unique visitor columns from the summary row, as those cannot
+ // be summed and would otherwise be aggregated into non-day periods
+ ArchivingHelper::deleteInvalidSummedColumnsFromDataTable($flatDataTable);
+ }
+
+ $nbSearches = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS));
+ $nbKeywords = $dataTable->getRowsCount();
+
+ $dataTable = $tablesByType[Action::TYPE_OUTLINK];
+ $nbOutlinks = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS));
+ $nbUniqOutlinks = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_NB_VISITS));
+
+ $dataTable = $flatPageTablesByType[Action::TYPE_PAGE_URL];
+ $nbPageviews = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS));
+ $nbUniqPageviews = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_NB_VISITS));
+ $nbSumTimeGeneration = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_SUM_TIME_GENERATION));
+ $nbHitsWithTimeGeneration = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION));
+
+ $dataTable = $tablesByType[Action::TYPE_DOWNLOAD];
+ $nbDownloads = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS));
+ $nbUniqDownloads = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_NB_VISITS));
+
+ return [
+ // blob records
+ Archiver::PAGE_URLS_FLAT_RECORD_NAME => $flatPageTablesByType[Action::TYPE_PAGE_URL],
+ Archiver::PAGE_TITLES_FLAT_RECORD_NAME => $flatPageTablesByType[Action::TYPE_PAGE_TITLE],
+ Archiver::PAGE_URLS_RECORD_NAME => $tablesByType[Action::TYPE_PAGE_URL],
+ Archiver::PAGE_TITLES_RECORD_NAME => $tablesByType[Action::TYPE_PAGE_TITLE],
+ Archiver::DOWNLOADS_RECORD_NAME => $tablesByType[Action::TYPE_DOWNLOAD],
+ Archiver::OUTLINKS_RECORD_NAME => $tablesByType[Action::TYPE_OUTLINK],
+ Archiver::SITE_SEARCH_RECORD_NAME => $tablesByType[Action::TYPE_SITE_SEARCH],
+
+ // numeric records
+ Archiver::METRIC_SEARCHES_RECORD_NAME => $nbSearches,
+ Archiver::METRIC_KEYWORDS_RECORD_NAME => $nbKeywords,
+
+ Archiver::METRIC_OUTLINKS_RECORD_NAME => $nbOutlinks,
+ Archiver::METRIC_UNIQ_OUTLINKS_RECORD_NAME => $nbUniqOutlinks,
+
+ Archiver::METRIC_PAGEVIEWS_RECORD_NAME => $nbPageviews,
+ Archiver::METRIC_UNIQ_PAGEVIEWS_RECORD_NAME => $nbUniqPageviews,
+ Archiver::METRIC_SUM_TIME_RECORD_NAME => $nbSumTimeGeneration,
+ Archiver::METRIC_HITS_TIMED_RECORD_NAME => $nbHitsWithTimeGeneration,
+
+ Archiver::METRIC_DOWNLOADS_RECORD_NAME => $nbDownloads,
+ Archiver::METRIC_UNIQ_DOWNLOADS_RECORD_NAME => $nbUniqDownloads,
+ ];
+ }
+
+ protected function beforeInsertBuiltFromFlatHierarchyRecord(
+ ArchiveProcessor $archiveProcessor,
+ Record $hierarchicalRecord,
+ DataTable $hierarchicalTable,
+ DataTable $flatTable
+ ): void {
+ $recordName = $hierarchicalRecord->getName();
+ if (
+ $recordName !== Archiver::PAGE_URLS_RECORD_NAME
+ && $recordName !== Archiver::PAGE_TITLES_RECORD_NAME
+ ) {
+ return;
+ }
+
+ $this->finalizeBuiltFromFlatHierarchyTable($archiveProcessor, $hierarchicalTable, $recordName);
+ }
+
+ private function flatRowToHierarchyPath(Row $flatRow, int $actionType): ?array
+ {
+ $label = $flatRow->getColumn('label');
+ if (!is_string($label) || $label === '') {
+ return null;
+ }
+
+ if ($actionType === Action::TYPE_PAGE_URL) {
+ if ($label === ArchivingHelper::getUnknownActionName(Action::TYPE_PAGE_URL)) {
+ return [$label];
+ }
+
+ return ArchivingHelper::getActionExplodedNames(
+ ArchivingHelper::removePageUrlLeafMarkerFromFlatLabel($label),
+ $actionType
+ );
+ }
+
+ return ArchivingHelper::getActionExplodedNames($label, $actionType);
+ }
+
+ private function removeFlatPathMetadataFromDataTable(DataTable $dataTable): void
+ {
+ $summaryRow = $dataTable->getRowFromId(DataTable::ID_SUMMARY_ROW);
+ if ($summaryRow instanceof Row) {
+ $summaryRow->deleteMetadata(ArchivingHelper::ACTION_FLAT_PATH_METADATA_NAME);
+ }
+
+ foreach ($dataTable->getRows() as $row) {
+ $row->deleteMetadata(ArchivingHelper::ACTION_FLAT_PATH_METADATA_NAME);
+
+ $subtable = $row->getSubtable();
+ if ($subtable instanceof DataTable) {
+ $this->removeFlatPathMetadataFromDataTable($subtable);
+ }
+ }
+ }
+
+ private function finalizeBuiltFromFlatHierarchyTable(
+ ArchiveProcessor $archiveProcessor,
+ DataTable $hierarchicalTable,
+ string $recordName
+ ): void {
+ $hierarchicalTable->setMetadata(DataTable::COLUMN_AGGREGATION_OPS_METADATA_NAME, Metrics::getColumnsAggregationOperation());
+
+ if ($recordName === Archiver::PAGE_URLS_RECORD_NAME) {
+ $prefix = $archiveProcessor->getParams()->getSite()->getMainUrl();
+ $prefix = rtrim($prefix, '/') . '/';
+ ArchivingHelper::setFolderPathMetadata($hierarchicalTable, $isUrl = true, $prefix);
+ } elseif ($recordName === Archiver::PAGE_TITLES_RECORD_NAME) {
+ ArchivingHelper::setFolderPathMetadata($hierarchicalTable, $isUrl = false);
+ }
+
+ $this->removeFlatPathMetadataFromDataTable($hierarchicalTable);
+ ArchivingHelper::deleteInvalidSummedColumnsFromDataTable($hierarchicalTable);
+ }
+
+ private function isFlatArchivingEnabled(): bool
+ {
+ ArchivingHelper::reloadConfig();
+ return ArchivingHelper::$maximumRowsInDataTableFlat > 0;
+ }
+
+ private function setHierarchyBuiltFromFlatRecord(
+ Record $record,
+ string $flatRecordName,
+ callable $flatToHierarchyPathCallback,
+ callable $legacyHierarchyToFlatReducer
+ ): void {
+ $record->setBuiltFromFlatRecord(
+ $flatRecordName,
+ $flatToHierarchyPathCallback,
+ $legacyHierarchyToFlatReducer
+ )->setMaxRowsInTable(0)->setMaxRowsInSubtable(0);
+ }
+
+ private function buildDayHierarchicalTableFromFlatTable(
+ DataTable $flatTable,
+ callable $flatToHierarchyPathCallback
+ ): DataTable {
+ return $this->buildHierarchicalTableFromFlatTable(
+ $flatTable,
+ Metrics::getColumnsAggregationOperation(),
+ $flatToHierarchyPathCallback,
+ $this->getDefaultHierarchyRowColumns()
+ );
+ }
+
+ private function getDefaultHierarchyRowColumns(): array
+ {
+ return [
+ PiwikMetrics::INDEX_NB_VISITS => 0,
+ PiwikMetrics::INDEX_NB_UNIQ_VISITORS => 0,
+ PiwikMetrics::INDEX_PAGE_NB_HITS => 0,
+ PiwikMetrics::INDEX_PAGE_SUM_TIME_SPENT => 0,
+ ];
+ }
+
+ private function aggregateLegacyHierarchical(ArchiveProcessor $archiveProcessor): array
+ {
+ $rankingQueryLimit = ArchivingHelper::getRankingQueryLimit();
+ ArchivingHelper::reloadConfig();
+
+ $tablesByType = $this->makeReportTables();
+
+ $this->archiveDayActions(
+ $archiveProcessor,
+ $rankingQueryLimit,
+ $tablesByType,
+ array_diff(array_keys($tablesByType), [Action::TYPE_SITE_SEARCH]),
+ true
+ );
+
+ if ($archiveProcessor->getParams()->getSite()->isSiteSearchEnabled()) {
+ $rankingQueryLimitSiteSearch = max($rankingQueryLimit, ArchivingHelper::$maximumRowsInDataTableSiteSearch);
+ $this->archiveDayActions($archiveProcessor, $rankingQueryLimitSiteSearch, $tablesByType, [Action::TYPE_SITE_SEARCH], false);
+ }
+
+ $this->archiveDayEntryActions($archiveProcessor->getLogAggregator(), $tablesByType, $rankingQueryLimit);
+ $this->archiveDayExitActions($archiveProcessor->getLogAggregator(), $tablesByType, $rankingQueryLimit);
+ $this->archiveDayActionsTime($archiveProcessor->getLogAggregator(), $tablesByType, $rankingQueryLimit);
+ $this->archiveDayActionsGoals($archiveProcessor, $rankingQueryLimit);
+
+ ArchivingHelper::clearActionsCache();
+
+ $prefix = $archiveProcessor->getParams()->getSite()->getMainUrl();
+ $prefix = rtrim($prefix, '/') . '/';
+ ArchivingHelper::setFolderPathMetadata($tablesByType[Action::TYPE_PAGE_URL], $isUrl = true, $prefix);
+ ArchivingHelper::setFolderPathMetadata($tablesByType[Action::TYPE_PAGE_TITLE], $isUrl = false);
+
+ $dataTable = $tablesByType[Action::TYPE_SITE_SEARCH];
+ $this->deleteUnusedColumnsFromKeywordsDataTable($dataTable);
+
+ foreach ($tablesByType as $dataTable) {
+ ArchivingHelper::deleteInvalidSummedColumnsFromDataTable($dataTable);
+ }
+
+ $nbSearches = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS));
+ $nbKeywords = $dataTable->getRowsCount();
+
+ $dataTable = $tablesByType[Action::TYPE_OUTLINK];
+ $nbOutlinks = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS));
+ $nbUniqOutlinks = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_NB_VISITS));
+
+ $dataTable = $tablesByType[Action::TYPE_PAGE_URL];
+ $nbPageviews = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS));
+ $nbUniqPageviews = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_NB_VISITS));
+ $nbSumTimeGeneration = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_SUM_TIME_GENERATION));
+ $nbHitsWithTimeGeneration = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS_WITH_TIME_GENERATION));
+
+ $dataTable = $tablesByType[Action::TYPE_DOWNLOAD];
+ $nbDownloads = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_PAGE_NB_HITS));
+ $nbUniqDownloads = array_sum($dataTable->getColumn(PiwikMetrics::INDEX_NB_VISITS));
+
+ return [
+ Archiver::PAGE_URLS_RECORD_NAME => $tablesByType[Action::TYPE_PAGE_URL],
+ Archiver::PAGE_TITLES_RECORD_NAME => $tablesByType[Action::TYPE_PAGE_TITLE],
+ Archiver::DOWNLOADS_RECORD_NAME => $tablesByType[Action::TYPE_DOWNLOAD],
+ Archiver::OUTLINKS_RECORD_NAME => $tablesByType[Action::TYPE_OUTLINK],
+ Archiver::SITE_SEARCH_RECORD_NAME => $tablesByType[Action::TYPE_SITE_SEARCH],
+
+ Archiver::METRIC_SEARCHES_RECORD_NAME => $nbSearches,
+ Archiver::METRIC_KEYWORDS_RECORD_NAME => $nbKeywords,
+ Archiver::METRIC_OUTLINKS_RECORD_NAME => $nbOutlinks,
+ Archiver::METRIC_UNIQ_OUTLINKS_RECORD_NAME => $nbUniqOutlinks,
+ Archiver::METRIC_PAGEVIEWS_RECORD_NAME => $nbPageviews,
+ Archiver::METRIC_UNIQ_PAGEVIEWS_RECORD_NAME => $nbUniqPageviews,
+ Archiver::METRIC_SUM_TIME_RECORD_NAME => $nbSumTimeGeneration,
+ Archiver::METRIC_HITS_TIMED_RECORD_NAME => $nbHitsWithTimeGeneration,
+ Archiver::METRIC_DOWNLOADS_RECORD_NAME => $nbDownloads,
+ Archiver::METRIC_UNIQ_DOWNLOADS_RECORD_NAME => $nbUniqDownloads,
+ ];
+ }
+
+ protected function deleteUnusedColumnsFromKeywordsDataTable(DataTable $dataTable): void
+ {
+ $columnsToDelete = array(
+ PiwikMetrics::INDEX_NB_UNIQ_VISITORS,
+ PiwikMetrics::INDEX_PAGE_IS_FOLLOWING_SITE_SEARCH_NB_HITS,
+ PiwikMetrics::INDEX_PAGE_ENTRY_NB_UNIQ_VISITORS,
+ PiwikMetrics::INDEX_PAGE_ENTRY_NB_ACTIONS,
+ PiwikMetrics::INDEX_PAGE_ENTRY_SUM_VISIT_LENGTH,
+ PiwikMetrics::INDEX_PAGE_ENTRY_NB_VISITS,
+ PiwikMetrics::INDEX_PAGE_ENTRY_BOUNCE_COUNT,
+ PiwikMetrics::INDEX_PAGE_EXIT_NB_UNIQ_VISITORS,
+ );
+ $dataTable->deleteColumns($columnsToDelete);
+ }
+
+ private function makeReportTables(): array
+ {
+ $result = [];
+ foreach (Metrics::$actionTypes as $type) {
+ $dataTable = new DataTable();
+ if ($type === Action::TYPE_SITE_SEARCH) {
+ $maxRows = ArchivingHelper::$maximumRowsInDataTableSiteSearch;
+ } else {
+ $maxRows = ArchivingHelper::$maximumRowsInDataTableLevelZero;
+ }
+ $dataTable->setMaximumAllowedRows($maxRows);
+
+ if (
+ $type == Action::TYPE_PAGE_URL
+ || $type == Action::TYPE_PAGE_TITLE
+ ) {
+ // for page urls and page titles, performance metrics exist and have to be aggregated correctly
+ $dataTable->setMetadata(DataTable::COLUMN_AGGREGATION_OPS_METADATA_NAME, Metrics::getColumnsAggregationOperation());
+ }
+
+ $result[$type] = $dataTable;
+ }
+ return $result;
+ }
+
+ private function makeFlatPageTables(): array
+ {
+ $tables = [];
+ $maxRowsInFlatTable = ArchivingHelper::$maximumRowsInDataTableFlat;
+ foreach ([Action::TYPE_PAGE_URL, Action::TYPE_PAGE_TITLE] as $type) {
+ $table = new DataTable();
+ $table->setMaximumAllowedRows($maxRowsInFlatTable);
+ $table->setMetadata(DataTable::COLUMN_AGGREGATION_OPS_METADATA_NAME, Metrics::getColumnsAggregationOperation());
+ $tables[$type] = $table;
+ }
+
+ return $tables;
+ }
+
+ protected function archiveDayActions(
+ ArchiveProcessor $archiveProcessor,
+ int $rankingQueryLimit,
+ array $actionsTablesByType,
+ $actionTypes,
+ bool $includePageNotDefined,
+ array $tableModesByType = []
+ ): void {
+ $logAggregator = $archiveProcessor->getLogAggregator();
+
+ $metricsConfig = Metrics::getActionMetrics();
+
+ $select = "log_action.name,
+ log_action.type,
+ log_action.idaction,
+ log_action.url_prefix";
+
+ $select = $this->addMetricsToSelect($select, $metricsConfig);
+
+ $from = array(
+ "log_link_visit_action",
+ array(
+ "table" => "log_action",
+ "joinOn" => "log_link_visit_action.%s = log_action.idaction",
+ ),
+ );
+
+ $where = $logAggregator->getWhereStatement('log_link_visit_action', 'server_time');
+ $where .= " AND log_link_visit_action.%s IS NOT NULL"
+ . $this->getWhereClauseActionIsNotEvent();
+
+ $actionTypesWhere = "log_action.type IN (" . implode(", ", $actionTypes) . ")";
+ if ($includePageNotDefined) {
+ $actionTypesWhere = "(" . $actionTypesWhere . " OR log_action.type IS NULL)";
+ }
+ $where .= " AND $actionTypesWhere";
+
+ $groupBy = "log_link_visit_action.%s";
+ $orderBy = "`" . PiwikMetrics::INDEX_PAGE_NB_HITS . "` DESC, name ASC";
+
+ $siteSearchEnabled = $archiveProcessor->getParams()->getSite()->isSiteSearchEnabled();
+
+ $rankingQuery = false;
+ if ($rankingQueryLimit > 0) {
+ $rankingQuery = new RankingQuery($rankingQueryLimit);
+ $rankingQuery->addLabelColumn(array('idaction', 'name'));
+ $rankingQuery->addColumn('url_prefix');
+
+ if ($siteSearchEnabled) {
+ $rankingQuery->addColumn(PiwikMetrics::INDEX_SITE_SEARCH_HAS_NO_RESULT, 'min');
+ $rankingQuery->addColumn(PiwikMetrics::INDEX_PAGE_IS_FOLLOWING_SITE_SEARCH_NB_HITS, 'sum');
+ }
+
+ $this->addMetricsToRankingQuery($rankingQuery, $metricsConfig);
+
+ $rankingQuery->partitionResultIntoMultipleGroups('type', $actionTypes);
+ }
+
+ // Special Magic to get
+ // 1) No result Keywords
+ // 2) For each page view, count number of times the referrer page was a Site Search
+ if ($siteSearchEnabled) {
+ $this->updateQuerySelectFromForSiteSearch($select, $from);
+ }
+
+ $this->archiveDayQueryProcess(
+ $logAggregator,
+ $actionsTablesByType,
+ $select,
+ $from,
+ $where,
+ $groupBy,
+ $orderBy,
+ "idaction_name",
+ $rankingQuery,
+ $metricsConfig,
+ $tableModesByType
+ );
+ $this->archiveDayQueryProcess(
+ $logAggregator,
+ $actionsTablesByType,
+ $select,
+ $from,
+ $where,
+ $groupBy,
+ $orderBy,
+ "idaction_url",
+ $rankingQuery,
+ $metricsConfig,
+ $tableModesByType
+ );
+ }
+
+ /**
+ * Entry actions for Page URLs and Page names
+ */
+ protected function archiveDayEntryActions(LogAggregator $logAggregator, array $actionsTablesByType, int $rankingQueryLimit, array $tableModesByType = [])
+ {
+ $rankingQuery = false;
+ if ($rankingQueryLimit > 0) {
+ $rankingQuery = new RankingQuery($rankingQueryLimit);
+ $rankingQuery->addLabelColumn('idaction');
+ $rankingQuery->addColumn(PiwikMetrics::INDEX_PAGE_ENTRY_NB_UNIQ_VISITORS);
+ $rankingQuery->addColumn(array(PiwikMetrics::INDEX_PAGE_ENTRY_NB_VISITS,
+ PiwikMetrics::INDEX_PAGE_ENTRY_NB_ACTIONS,
+ PiwikMetrics::INDEX_PAGE_ENTRY_SUM_VISIT_LENGTH,
+ PiwikMetrics::INDEX_PAGE_ENTRY_BOUNCE_COUNT), 'sum');
+ $rankingQuery->partitionResultIntoMultipleGroups('type', array_keys($actionsTablesByType));
+
+ $extraSelects = 'log_action.type, log_action.name,';
+ $from = array(
+ "log_visit",
+ array(
+ "table" => "log_action",
+ "joinOn" => "log_visit.%s = log_action.idaction",
+ ),
+ );
+ $orderBy = "`" . PiwikMetrics::INDEX_PAGE_ENTRY_NB_ACTIONS . "` DESC, log_action.name ASC";
+ } else {
+ $extraSelects = false;
+ $from = "log_visit";
+ $orderBy = false;
+ }
+
+ $select = "log_visit.%s as idaction, $extraSelects
+ count(distinct log_visit.idvisitor) as `" . PiwikMetrics::INDEX_PAGE_ENTRY_NB_UNIQ_VISITORS . "`,
+ count(*) as `" . PiwikMetrics::INDEX_PAGE_ENTRY_NB_VISITS . "`,
+ sum(log_visit.visit_total_actions) as `" . PiwikMetrics::INDEX_PAGE_ENTRY_NB_ACTIONS . "`,
+ sum(log_visit.visit_total_time) as `" . PiwikMetrics::INDEX_PAGE_ENTRY_SUM_VISIT_LENGTH . "`,
+ sum(case log_visit.visit_total_actions when 1 then 1 when 0 then 1 else 0 end) as `" . PiwikMetrics::INDEX_PAGE_ENTRY_BOUNCE_COUNT . "`";
+
+ $where = $logAggregator->getWhereStatement('log_visit', 'visit_last_action_time');
+ $where .= " AND log_visit.%s > 0";
+
+ $groupBy = "log_visit.%s";
+
+ $this->archiveDayQueryProcess(
+ $logAggregator,
+ $actionsTablesByType,
+ $select,
+ $from,
+ $where,
+ $groupBy,
+ $orderBy,
+ "visit_entry_idaction_url",
+ $rankingQuery,
+ [],
+ $tableModesByType
+ );
+
+ $this->archiveDayQueryProcess(
+ $logAggregator,
+ $actionsTablesByType,
+ $select,
+ $from,
+ $where,
+ $groupBy,
+ $orderBy,
+ "visit_entry_idaction_name",
+ $rankingQuery,
+ [],
+ $tableModesByType
+ );
+ }
+
+ /**
+ * Exit actions
+ */
+ protected function archiveDayExitActions(LogAggregator $logAggregator, array $actionsTablesByType, int $rankingQueryLimit, array $tableModesByType = [])
+ {
+ $rankingQuery = false;
+ if ($rankingQueryLimit > 0) {
+ $rankingQuery = new RankingQuery($rankingQueryLimit);
+ $rankingQuery->addLabelColumn('idaction');
+ $rankingQuery->addColumn(PiwikMetrics::INDEX_PAGE_EXIT_NB_UNIQ_VISITORS);
+ $rankingQuery->addColumn(PiwikMetrics::INDEX_PAGE_EXIT_NB_VISITS, 'sum');
+ $rankingQuery->partitionResultIntoMultipleGroups('type', array_keys($actionsTablesByType));
+
+ $extraSelects = 'log_action.type, log_action.name,';
+ $from = array(
+ "log_visit",
+ array(
+ "table" => "log_action",
+ "joinOn" => "log_visit.%s = log_action.idaction",
+ ),
+ );
+ $orderBy = "`" . PiwikMetrics::INDEX_PAGE_EXIT_NB_VISITS . "` DESC, log_action.name ASC";
+ } else {
+ $extraSelects = false;
+ $from = "log_visit";
+ $orderBy = false;
+ }
+
+ $select = "log_visit.%s as idaction, $extraSelects
+ count(distinct log_visit.idvisitor) as `" . PiwikMetrics::INDEX_PAGE_EXIT_NB_UNIQ_VISITORS . "`,
+ count(*) as `" . PiwikMetrics::INDEX_PAGE_EXIT_NB_VISITS . "`";
+
+ $where = $logAggregator->getWhereStatement('log_visit', 'visit_last_action_time');
+ $where .= " AND log_visit.%s > 0";
+
+ $groupBy = "log_visit.%s";
+
+ $this->archiveDayQueryProcess(
+ $logAggregator,
+ $actionsTablesByType,
+ $select,
+ $from,
+ $where,
+ $groupBy,
+ $orderBy,
+ "visit_exit_idaction_url",
+ $rankingQuery,
+ [],
+ $tableModesByType
+ );
+
+ $this->archiveDayQueryProcess(
+ $logAggregator,
+ $actionsTablesByType,
+ $select,
+ $from,
+ $where,
+ $groupBy,
+ $orderBy,
+ "visit_exit_idaction_name",
+ $rankingQuery,
+ [],
+ $tableModesByType
+ );
+
+ return array($rankingQuery, $extraSelects, $from, $orderBy, $select, $where, $groupBy);
+ }
+
+ /**
+ * Time per action
+ */
+ protected function archiveDayActionsTime(LogAggregator $logAggregator, array $actionsTablesByType, int $rankingQueryLimit, array $tableModesByType = [])
+ {
+ $rankingQuery = false;
+ if ($rankingQueryLimit > 0) {
+ $rankingQuery = new RankingQuery($rankingQueryLimit);
+ $rankingQuery->addLabelColumn('idaction');
+ $rankingQuery->addColumn(PiwikMetrics::INDEX_PAGE_SUM_TIME_SPENT, 'sum');
+ $rankingQuery->partitionResultIntoMultipleGroups('type', array_keys($actionsTablesByType));
+
+ $extraSelects = "log_action.type, log_action.name, count(*) as `" . PiwikMetrics::INDEX_PAGE_NB_HITS . "`,";
+ $from = array(
+ "log_link_visit_action",
+ array(
+ "table" => "log_action",
+ "joinOn" => "log_link_visit_action.%s = log_action.idaction",
+ ),
+ );
+ $orderBy = "`" . PiwikMetrics::INDEX_PAGE_NB_HITS . "` DESC, log_action.name ASC";
+ } else {
+ $extraSelects = false;
+ $from = "log_link_visit_action";
+ $orderBy = false;
+ }
+
+ $select = "log_link_visit_action.%s as idaction, $extraSelects
+ sum(log_link_visit_action.time_spent_ref_action) as `" . PiwikMetrics::INDEX_PAGE_SUM_TIME_SPENT . "`";
+
+ $where = $logAggregator->getWhereStatement('log_link_visit_action', 'server_time');
+ $where .= " AND log_link_visit_action.time_spent_ref_action > 0
+ AND log_link_visit_action.%s > 0"
+ . $this->getWhereClauseActionIsNotEvent();
+
+ $groupBy = "log_link_visit_action.%s";
+
+ $this->archiveDayQueryProcess(
+ $logAggregator,
+ $actionsTablesByType,
+ $select,
+ $from,
+ $where,
+ $groupBy,
+ $orderBy,
+ "idaction_url_ref",
+ $rankingQuery,
+ [],
+ $tableModesByType
+ );
+
+ $this->archiveDayQueryProcess(
+ $logAggregator,
+ $actionsTablesByType,
+ $select,
+ $from,
+ $where,
+ $groupBy,
+ $orderBy,
+ "idaction_name_ref",
+ $rankingQuery,
+ [],
+ $tableModesByType
+ );
+ }
+
+ protected function archiveDayQueryProcess(
+ LogAggregator $logAggregator,
+ array $actionsTablesByType,
+ string $select,
+ $from,
+ string $where,
+ string $groupBy,
+ $orderBy,
+ string $sprintfField,
+ ?RankingQuery $rankingQuery = null,
+ array $metricsConfig = array(),
+ array $tableModesByType = []
+ ): void {
+ $select = sprintf($select, $sprintfField);
+
+ // get query with segmentation
+ $query = $logAggregator->generateQuery($select, $from, $where, $groupBy, $orderBy);
+
+ // replace the rest of the %s
+ $querySql = str_replace("%s", $sprintfField, $query['sql']);
+
+ // apply ranking query
+ if ($rankingQuery) {
+ $querySql = $rankingQuery->generateRankingQuery($querySql);
+ }
+
+ // get result
+ $resultSet = $logAggregator->getDb()->query($querySql, $query['bind']);
+ ArchivingHelper::updateActionsTableWithRowQuery(
+ $resultSet,
+ $sprintfField,
+ $actionsTablesByType,
+ $metricsConfig,
+ $tableModesByType
+ );
+ }
+
+ protected function updateQuerySelectFromForSiteSearch(string &$select, array &$from): void
+ {
+ $selectFlagNoResultKeywords = ",
+ MAX(log_link_visit_action.search_count) = 0 AS `" . PiwikMetrics::INDEX_SITE_SEARCH_HAS_NO_RESULT . "`";
+
+ // we need an extra JOIN to know whether the referrer "idaction_name_ref" was a Site Search request
+ $from[] = array(
+ "table" => "log_action",
+ "tableAlias" => "log_action_name_ref",
+ "joinOn" => "log_link_visit_action.idaction_name_ref = log_action_name_ref.idaction",
+ );
+
+ $selectPageIsFollowingSiteSearch = ",
+ SUM( CASE WHEN log_action_name_ref.type = " . Action::TYPE_SITE_SEARCH . "
+ THEN 1 ELSE 0 END)
+ AS `" . PiwikMetrics::INDEX_PAGE_IS_FOLLOWING_SITE_SEARCH_NB_HITS . "`";
+
+ $select .= $selectFlagNoResultKeywords
+ . $selectPageIsFollowingSiteSearch;
+ }
+
+ private function addMetricsToRankingQuery(RankingQuery $rankingQuery, array $metricsConfig): void
+ {
+ foreach ($metricsConfig as $metric => $config) {
+ if (!empty($config['aggregation'])) {
+ $rankingQuery->addColumn($metric, $config['aggregation']);
+ } else {
+ $rankingQuery->addColumn($metric);
+ }
+ }
+ }
+
+ private function addMetricsToSelect(string $select, array $metricsConfig): string
+ {
+ if (!empty($metricsConfig)) {
+ foreach ($metricsConfig as $metric => $config) {
+ $select .= ', ' . $config['query'] . " as `" . $metric . "`";
+ }
+ }
+
+ return $select;
+ }
+
+ protected function getWhereClauseActionIsNotEvent(): string
+ {
+ return " AND log_link_visit_action.idaction_event_category IS NULL";
+ }
+
+ /**
+ * Add goals data for each combination of url / title and pageviews / entries
+ */
+ protected function archiveDayActionsGoals(ArchiveProcessor $archiveProcessor, int $rankingQueryLimit): void
+ {
+ $site = $archiveProcessor->getParams()->getSite();
+
+ if (
+ !\Piwik\Common::isGoalPluginEnabled() ||
+ GeneralConfig::getConfigValue('disable_archive_actions_goals', $site->getId())
+ ) {
+ return;
+ }
+
+ $goals = $this->getGoalsForSite($site->getId());
+
+ // Add orders and abandoned cart codes if the site is enabled for ecommerce
+ if ($site->isEcommerceEnabled()) {
+ $goals[] = GoalManager::IDGOAL_CART;
+ $goals[] = GoalManager::IDGOAL_ORDER;
+ }
+
+ foreach ($goals as $idGoal) {
+ $this->archiveDayActionsGoalsPages($archiveProcessor->getLogAggregator(), true, $idGoal);
+ $this->archiveDayActionsGoalsPages($archiveProcessor->getLogAggregator(), false, $idGoal);
+ }
+
+ $this->archiveDayActionsGoalsPagesEntry($archiveProcessor, $rankingQueryLimit, true);
+ $this->archiveDayActionsGoalsPagesEntry($archiveProcessor, $rankingQueryLimit, false);
+ }
+
+ /**
+ * Query goal page view data and update actions data table
+ *
+ * @param bool $isUrl If true then query goal data by url, else by name
+ * @param int $idGoal Goal to archive
+ *
+ * @return int|null Count of records processed
+ * @throws \Exception
+ */
+ protected function archiveDayActionsGoalsPages(LogAggregator $logAggregator, bool $isUrl, int $idGoal): ?int
+ {
+ $linkField = ($isUrl ? 'idaction_url' : 'idaction_name');
+ $resultSet = $logAggregator->queryConversionsByPageView($linkField, $idGoal);
+ if (!$resultSet) {
+ return null;
+ }
+ return ArchivingHelper::updateActionsTableWithGoals($resultSet, true);
+ }
+
+ /**
+ * Get a list of goal ids for a site
+ *
+ * @return array
+ */
+ private function getGoalsForSite(string $idSite): array
+ {
+ $cache = Cache::getTransientCache();
+ $key = 'ActionArchives_allGoalIds_' . $idSite;
+
+ if ($cache->contains($key)) {
+ return $cache->fetch($key);
+ }
+
+ $siteGoals = Request::processRequest('Goals.getGoals', ['idSite' => $idSite, 'filter_limit' => '-1'], $default = []);
+ $goalIds = array_column($siteGoals, 'idgoal');
+
+ $cache->save($key, $goalIds);
+ return $goalIds;
+ }
+
+ /**
+ * Query goal entry page data and update actions data table
+ *
+ * @param bool $isUrl If true then query goal data by url, else by name
+ *
+ * @return int|null Count of records processed
+ * @throws \Exception
+ */
+ protected function archiveDayActionsGoalsPagesEntry(ArchiveProcessor $archiveProcessor, int $rankingQueryLimit, bool $isUrl): ?int
+ {
+ if (GeneralConfig::getConfigValue('disable_archive_actions_goals', $archiveProcessor->getParams()->getSite()->getId())) {
+ return null;
+ }
+ $linkField = ($isUrl ? 'visit_entry_idaction_url' : 'visit_entry_idaction_name');
+ $resultSet = $archiveProcessor->getLogAggregator()->queryConversionsByEntryPageView($linkField, $rankingQueryLimit);
+ if (!$resultSet) {
+ return null;
+ }
+
+ return ArchivingHelper::updateActionsTableWithGoals($resultSet, false);
+ }
+}
diff --git a/plugins/Actions/RecordBuilders/Hits.php b/plugins/Actions/RecordBuilders/Hits.php
new file mode 100644
index 0000000000000000000000000000000000000000..80b0a38c2b0766753b34091cff469837945b5d9e
--- /dev/null
+++ b/plugins/Actions/RecordBuilders/Hits.php
@@ -0,0 +1,42 @@
+getLogAggregator()->queryActionsByDimension(
+ [],
+ '',
+ ['count(distinct log_link_visit_action.idlink_va) as `' . PiwikMetrics::INDEX_NB_HITS . '`'],
+ [],
+ null
+ );
+ $data = $query->fetch();
+ $nbHits = $data[PiwikMetrics::INDEX_NB_HITS];
+
+ return [
+ Archiver::METRIC_HITS_RECORD_NAME => $nbHits,
+ ];
+ }
+}
diff --git a/plugins/Actions/RecordBuilders/SearchCategories.php b/plugins/Actions/RecordBuilders/SearchCategories.php
new file mode 100644
index 0000000000000000000000000000000000000000..240074d6b70fc35c637e124efc4765c04a0627fa
--- /dev/null
+++ b/plugins/Actions/RecordBuilders/SearchCategories.php
@@ -0,0 +1,52 @@
+getLogAggregator();
+ $query = $logAggregator->queryActionsByDimension(['search_cat'], "%s.search_cat != '' AND %s.search_cat IS NOT NULL");
+
+ $table = new DataTable();
+
+ while ($row = $query->fetch()) {
+ $label = $row['search_cat'];
+ unset($row['search_cat']);
+
+ $row = new DataTable\Row([DataTable\Row::COLUMNS => ['label' => $label] + $row]);
+ $table->addRow($row);
+ }
+
+ return [
+ Archiver::SITE_SEARCH_CATEGORY_RECORD_NAME => $table,
+ ];
+ }
+
+ public function getRecordMetadata(ArchiveProcessor $archiveProcessor): array
+ {
+ return [
+ Record::make(Record::TYPE_BLOB, Archiver::SITE_SEARCH_CATEGORY_RECORD_NAME)
+ ->setMaxRowsInTable(ArchivingHelper::$maximumRowsInDataTableSiteSearch),
+ ];
+ }
+
+ public function isEnabled(ArchiveProcessor $archiveProcessor): bool
+ {
+ return $archiveProcessor->getParams()->getSite()->isSiteSearchEnabled();
+ }
+}
diff --git a/plugins/Actions/Reports/Base.php b/plugins/Actions/Reports/Base.php
new file mode 100644
index 0000000000000000000000000000000000000000..79c13a0cc13887d8e53159ae0d1b47e2a4bc84cd
--- /dev/null
+++ b/plugins/Actions/Reports/Base.php
@@ -0,0 +1,159 @@
+categoryId = 'General_Actions';
+ $this->processedMetrics = [];
+ $this->recursiveLabelSeparator = '/';
+ }
+
+ protected function addBaseDisplayProperties(ViewDataTable $view)
+ {
+ $view->config->datatable_js_type = 'ActionsDataTable';
+ $view->config->search_recursive = true;
+ $view->config->show_table_all_columns = false;
+ $view->requestConfig->filter_limit = Actions::ACTIONS_REPORT_ROWS_DISPLAY;
+ $view->config->show_all_views_icons = false;
+
+ if ($view->requestConfig->getRequestParam('performance') === '1') {
+ $view->requestConfig->filter_limit = 25;
+ // hide visualization selector
+ $view->config->footer_icons = [[
+ 'class' => 'tableAllColumnsSwitch',
+ 'buttons' => [],
+ ]];
+ }
+
+ if ($view->isViewDataTableId(HtmlTable::ID)) {
+ $view->config->show_embedded_subtable = true;
+ }
+
+ if (Request::shouldLoadExpanded()) {
+ if ($view->isViewDataTableId(HtmlTable::ID)) {
+ $view->config->show_expanded = true;
+ }
+
+ $view->config->filters[] = function ($dataTable) {
+ Actions::setDataTableRowLevels($dataTable);
+ };
+ }
+
+ $view->config->filters[] = function ($dataTable) use ($view) {
+ if ($view->isViewDataTableId(HtmlTable::ID)) {
+ $view->config->datatable_css_class = 'dataTableActions';
+ }
+ };
+ }
+
+ protected function addPageDisplayProperties(ViewDataTable $view)
+ {
+ $view->config->addTranslations(array(
+ 'nb_hits' => Piwik::translate('General_ColumnPageviews'),
+ 'nb_visits' => Piwik::translate('General_ColumnUniquePageviews'),
+ ));
+
+ $formatter = new Formatter();
+
+ // add avg_generation_time tooltip
+ $tooltipCallback = function ($hits, $min, $max) use ($formatter) {
+ if (!$hits) {
+ return false;
+ }
+
+ return Piwik::translate("Actions_AvgGenerationTimeTooltip", array(
+ $hits,
+ " ",
+ $formatter->getPrettyTimeFromSeconds($min, true),
+ $formatter->getPrettyTimeFromSeconds($max, true),
+ ));
+ };
+ $view->config->filters[] = array('ColumnCallbackAddMetadata',
+ array(
+ array('nb_hits_with_time_generation', 'min_time_generation', 'max_time_generation'),
+ 'avg_time_generation_tooltip',
+ $tooltipCallback,
+ ),
+ );
+
+ $this->addExcludeLowPopDisplayProperties($view);
+
+ // hide the performance columns viz in page reports when not displayed as widget
+ if ($view->requestConfig->getRequestParam('widget') != '1') {
+ $view->config->show_table_performance = false;
+ }
+ }
+
+ protected function addExcludeLowPopDisplayProperties(ViewDataTable $view)
+ {
+ if (Common::getRequestVar('enable_filter_excludelowpop', '0', 'string') != '0') {
+ if (Common::getRequestVar('flat', 0, 'int') === 1) {
+ $view->requestConfig->filter_excludelowpop = 'nb_hits';
+ } else {
+ $view->requestConfig->filter_excludelowpop = Metrics::INDEX_PAGE_NB_HITS;
+ }
+ $view->requestConfig->filter_excludelowpop_value = function () {
+ // computing minimum value to exclude (2 percent of the total number of actions)
+ $visitsInfo = \Piwik\Plugins\VisitsSummary\Controller::getVisitsSummary()->getFirstRow();
+ $nbActions = $visitsInfo->getColumn('nb_actions');
+ $nbActionsLowPopulationThreshold = floor(0.02 * $nbActions);
+
+ // we remove 1 to make sure some actions/downloads are displayed in the case we have a very few of them
+ // and each of them has 1 or 2 hits...
+ return min($visitsInfo->getColumn('max_actions') - 1, $nbActionsLowPopulationThreshold - 1);
+ };
+ }
+ }
+
+ public function getRecursiveLabelSeparator()
+ {
+ $legacyDelimiter = GeneralConfig::getConfigValue('action_category_delimiter');
+ if (!empty($legacyDelimiter)) {
+ return $legacyDelimiter;
+ }
+
+ if (
+ $this->dimension instanceof PageTitle
+ || $this->dimension instanceof EntryPageTitle
+ || $this->dimension instanceof ExitPageTitle
+ ) {
+ return GeneralConfig::getConfigValue('action_title_category_delimiter') ?: $this->recursiveLabelSeparator;
+ }
+
+ if (
+ $this->dimension instanceof PageUrl
+ || $this->dimension instanceof EntryPageUrl
+ || $this->dimension instanceof ExitPageUrl
+ ) {
+ return GeneralConfig::getConfigValue('action_url_category_delimiter') ?: $this->recursiveLabelSeparator;
+ }
+
+ return parent::getRecursiveLabelSeparator();
+ }
+}
diff --git a/plugins/Actions/Reports/Get.php b/plugins/Actions/Reports/Get.php
new file mode 100644
index 0000000000000000000000000000000000000000..8f5e7479e631a70588f9f922d59d5234f151b7c4
--- /dev/null
+++ b/plugins/Actions/Reports/Get.php
@@ -0,0 +1,39 @@
+name = Piwik::translate('General_Actions') . ' - ' . Piwik::translate('General_MainMetrics');
+ $this->documentation = Piwik::translate('Actions_MainMetricsReportDocumentation');
+ $this->order = 1;
+ $this->processedMetrics = array(
+ new AveragePageGenerationTime(),
+ );
+ $this->metrics = array(
+ 'nb_pageviews',
+ 'nb_uniq_pageviews',
+ 'nb_downloads',
+ 'nb_uniq_downloads',
+ 'nb_outlinks',
+ 'nb_uniq_outlinks',
+ 'nb_searches',
+ 'nb_keywords',
+ 'hits',
+ );
+ }
+}
diff --git a/plugins/Actions/Reports/GetDownloads.php b/plugins/Actions/Reports/GetDownloads.php
new file mode 100644
index 0000000000000000000000000000000000000000..ca5c2143da5a8e343e79069834e78b2cc5d18e4a
--- /dev/null
+++ b/plugins/Actions/Reports/GetDownloads.php
@@ -0,0 +1,56 @@
+dimension = new DownloadUrl();
+ $this->name = Piwik::translate('General_Downloads');
+ $this->documentation = Piwik::translate('Actions_DownloadsReportDocumentation', ' ');
+ $this->metrics = array('nb_visits', 'nb_hits');
+
+ $this->actionToLoadSubTables = $this->action;
+ $this->order = 9;
+
+ $this->subcategoryId = 'General_Downloads';
+ }
+
+ public function getMetrics()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnUniqueDownloads'),
+ 'nb_hits' => Piwik::translate('General_Downloads'),
+ );
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnUniqueClicksDocumentation'),
+ 'nb_hits' => Piwik::translate('Actions_ColumnClicksDocumentation'),
+ );
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->columns_to_display = array('label', 'nb_visits', 'nb_hits');
+ $view->config->show_exclude_low_population = false;
+
+ $this->addBaseDisplayProperties($view);
+ }
+}
diff --git a/plugins/Actions/Reports/GetEntryPageTitles.php b/plugins/Actions/Reports/GetEntryPageTitles.php
new file mode 100644
index 0000000000000000000000000000000000000000..6dcb5593d970cffa67f74c2b90906bc8cc60cf72
--- /dev/null
+++ b/plugins/Actions/Reports/GetEntryPageTitles.php
@@ -0,0 +1,95 @@
+dimension = new EntryPageTitle();
+ $this->name = Piwik::translate('Actions_EntryPageTitles');
+ $this->documentation = Piwik::translate('Actions_EntryPageTitlesReportDocumentation', ' ')
+ . ' ' . Piwik::translate('General_UsePlusMinusIconsDocumentation');
+ $this->metrics = array('entry_nb_visits', 'entry_bounce_count');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+ $this->order = 6;
+ $this->actionToLoadSubTables = $this->action;
+ $this->subcategoryId = 'Actions_SubmenuPagesEntry';
+ $this->hasGoalMetrics = true;
+ }
+
+ public function configureWidgets(WidgetsList $widgetsList, ReportWidgetFactory $factory)
+ {
+ $widgetsList->addWidgetConfig($factory->createWidget()->setName('Actions_WidgetEntryPageTitles'));
+ }
+
+ public function getProcessedMetrics()
+ {
+ $result = parent::getProcessedMetrics();
+
+ // these metrics are not displayed in the API.getProcessedReport version of this report,
+ // so they are removed here.
+ unset($result['avg_time_on_page']);
+ unset($result['exit_rate']);
+
+ return $result;
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ $metrics = parent::getMetricsDocumentation();
+ $metrics['bounce_rate'] = Piwik::translate('General_ColumnPageBounceRateDocumentation');
+
+ // remove these metrics from API.getProcessedReport version of this report
+ unset($metrics['avg_time_on_page']);
+ unset($metrics['exit_rate']);
+
+ return $metrics;
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->columns_to_display = array('label', 'entry_nb_visits', 'entry_bounce_count', 'bounce_rate');
+ $view->config->title = $this->name;
+
+ $view->requestConfig->filter_sort_column = 'entry_nb_visits';
+
+ $this->addPageDisplayProperties($view);
+ $this->addBaseDisplayProperties($view);
+
+ $view->config->show_goals = true;
+ }
+
+ public function getRelatedReports()
+ {
+ return array(
+ ReportsProvider::factory('Actions', 'getPageTitles'),
+ ReportsProvider::factory('Actions', 'getEntryPageUrls'),
+ );
+ }
+}
diff --git a/plugins/Actions/Reports/GetEntryPageUrls.php b/plugins/Actions/Reports/GetEntryPageUrls.php
new file mode 100644
index 0000000000000000000000000000000000000000..aa1e222e75ce01077fb5a2c6bcce8b6659339833
--- /dev/null
+++ b/plugins/Actions/Reports/GetEntryPageUrls.php
@@ -0,0 +1,88 @@
+dimension = new EntryPageUrl();
+ $this->name = Piwik::translate('Actions_SubmenuPagesEntry');
+ $this->documentation = Piwik::translate('Actions_EntryPagesReportDocumentation', ' ')
+ . ' ' . Piwik::translate('General_UsePlusMinusIconsDocumentation');
+
+ $this->metrics = array('entry_nb_visits', 'entry_bounce_count');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+ $this->order = 3;
+
+ $this->actionToLoadSubTables = $this->action;
+ $this->subcategoryId = 'Actions_SubmenuPagesEntry';
+ $this->hasGoalMetrics = true;
+ }
+
+ public function getProcessedMetrics()
+ {
+ $result = parent::getProcessedMetrics();
+
+ // these metrics are not displayed in the API.getProcessedReport version of this report,
+ // so they are removed here.
+ unset($result['avg_time_on_page']);
+ unset($result['exit_rate']);
+
+ return $result;
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ $metrics = parent::getMetricsDocumentation();
+ $metrics['bounce_rate'] = Piwik::translate('General_ColumnPageBounceRateDocumentation');
+
+ unset($metrics['avg_time_on_page']);
+ unset($metrics['exit_rate']);
+
+ return $metrics;
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->title = $this->name;
+ $view->config->columns_to_display = array('label', 'entry_nb_visits', 'entry_bounce_count', 'bounce_rate');
+ $view->requestConfig->filter_sort_column = 'entry_nb_visits';
+ $view->requestConfig->filter_sort_order = 'desc';
+
+ $this->addPageDisplayProperties($view);
+ $this->addBaseDisplayProperties($view);
+
+ $view->config->show_goals = true;
+ }
+
+ public function getRelatedReports()
+ {
+ return array(
+ ReportsProvider::factory('Actions', 'getEntryPageTitles'),
+ );
+ }
+}
diff --git a/plugins/Actions/Reports/GetExitPageTitles.php b/plugins/Actions/Reports/GetExitPageTitles.php
new file mode 100644
index 0000000000000000000000000000000000000000..addfd426146a3a6557528f7f5f6fa39717fe5dfe
--- /dev/null
+++ b/plugins/Actions/Reports/GetExitPageTitles.php
@@ -0,0 +1,101 @@
+dimension = new ExitPageTitle();
+ $this->name = Piwik::translate('Actions_ExitPageTitles');
+ $this->documentation = Piwik::translate('Actions_ExitPageTitlesReportDocumentation', ' ')
+ . ' ' . Piwik::translate('General_UsePlusMinusIconsDocumentation');
+ $this->subcategoryId = 'Actions_SubmenuPagesExit';
+
+ $this->metrics = array('exit_nb_visits', 'nb_visits');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+ $this->order = 7;
+
+ $this->actionToLoadSubTables = $this->action;
+ }
+
+ public function configureWidgets(WidgetsList $widgetsList, ReportWidgetFactory $factory)
+ {
+ // we have to do it manually since it's only done automatically if a subcategoryId is specified,
+ // we do not set a subcategoryId since this report is not supposed to be shown in the UI
+ $widgetsList->addWidgetConfig($factory->createWidget());
+ }
+
+ public function getProcessedMetrics()
+ {
+ $result = parent::getProcessedMetrics();
+
+ // these metrics are not displayed in the API.getProcessedReport version of this report,
+ // so they are removed here.
+ unset($result['bounce_rate']);
+ unset($result['avg_time_on_page']);
+
+ return $result;
+ }
+
+ public function getMetrics()
+ {
+ $metrics = parent::getMetrics();
+ $metrics['nb_visits'] = Piwik::translate('General_ColumnUniquePageviews');
+
+ return $metrics;
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ $metrics = parent::getMetricsDocumentation();
+ $metrics['nb_visits'] = Piwik::translate('General_ColumnUniquePageviewsDocumentation');
+
+ unset($metrics['bounce_rate']);
+ unset($metrics['avg_time_on_page']);
+
+ return $metrics;
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->title = $this->name;
+ $view->config->columns_to_display = array('label', 'exit_nb_visits', 'nb_visits', 'exit_rate');
+
+ $this->addPageDisplayProperties($view);
+ $this->addBaseDisplayProperties($view);
+ }
+
+ public function getRelatedReports()
+ {
+ return array(
+ ReportsProvider::factory('Actions', 'getPageTitles'),
+ ReportsProvider::factory('Actions', 'getExitPageUrls'),
+ );
+ }
+}
diff --git a/plugins/Actions/Reports/GetExitPageUrls.php b/plugins/Actions/Reports/GetExitPageUrls.php
new file mode 100644
index 0000000000000000000000000000000000000000..095395a6237a926b3b41b94e85572557fb64d7ba
--- /dev/null
+++ b/plugins/Actions/Reports/GetExitPageUrls.php
@@ -0,0 +1,101 @@
+dimension = new ExitPageUrl();
+ $this->name = Piwik::translate('Actions_SubmenuPagesExit');
+ $this->documentation = Piwik::translate('Actions_ExitPagesReportDocumentation', ' ')
+ . ' ' . Piwik::translate('General_UsePlusMinusIconsDocumentation');
+
+ $this->metrics = array('exit_nb_visits', 'nb_visits');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+ $this->actionToLoadSubTables = $this->action;
+
+ $this->order = 4;
+
+ $this->subcategoryId = 'Actions_SubmenuPagesExit';
+ }
+
+ public function getProcessedMetrics()
+ {
+ $result = parent::getProcessedMetrics();
+
+ // these metrics are not displayed in the API.getProcessedReport version of this report,
+ // so they are removed here.
+ unset($result['bounce_rate']);
+ unset($result['avg_time_on_page']);
+
+ return $result;
+ }
+
+ public function getMetrics()
+ {
+ $metrics = parent::getMetrics();
+ $metrics['nb_visits'] = Piwik::translate('General_ColumnUniquePageviews');
+
+ unset($metrics['bounce_rate']);
+ unset($metrics['avg_time_on_page']);
+
+ return $metrics;
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ $metrics = parent::getMetricsDocumentation();
+ $metrics['nb_visits'] = Piwik::translate('General_ColumnUniquePageviewsDocumentation');
+
+ return $metrics;
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->self_url = Request::getCurrentUrlWithoutGenericFilters(array(
+ 'module' => 'Actions',
+ 'action' => 'getExitPageUrls',
+ ));
+
+ $view->config->title = $this->name;
+
+ $view->config->columns_to_display = array('label', 'exit_nb_visits', 'nb_visits', 'exit_rate');
+ $view->requestConfig->filter_sort_column = 'exit_nb_visits';
+ $view->requestConfig->filter_sort_order = 'desc';
+
+ $this->addPageDisplayProperties($view);
+ $this->addBaseDisplayProperties($view);
+ }
+
+ public function getRelatedReports()
+ {
+ return array(
+ ReportsProvider::factory('Actions', 'getExitPageTitles'),
+ );
+ }
+}
diff --git a/plugins/Actions/Reports/GetOutlinks.php b/plugins/Actions/Reports/GetOutlinks.php
new file mode 100644
index 0000000000000000000000000000000000000000..9b2cda81d3d1ba80f02b5d40e4d1c2bfb3a46435
--- /dev/null
+++ b/plugins/Actions/Reports/GetOutlinks.php
@@ -0,0 +1,59 @@
+dimension = new ClickedUrl();
+ $this->name = Piwik::translate('General_Outlinks');
+ $this->documentation = Piwik::translate('Actions_OutlinksReportDocumentation') . ' '
+ . Piwik::translate('Actions_OutlinkDocumentation') . ' '
+ . Piwik::translate('General_UsePlusMinusIconsDocumentation');
+
+ $this->metrics = array('nb_visits', 'nb_hits');
+ $this->order = 8;
+
+ $this->actionToLoadSubTables = $this->action;
+
+ $this->subcategoryId = 'General_Outlinks';
+ }
+
+ public function getMetrics()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnUniqueClicks'),
+ 'nb_hits' => Piwik::translate('Actions_ColumnClicks'),
+ );
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnUniqueClicksDocumentation'),
+ 'nb_hits' => Piwik::translate('Actions_ColumnClicksDocumentation'),
+ );
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->columns_to_display = array('label', 'nb_visits', 'nb_hits');
+ $view->config->show_exclude_low_population = false;
+
+ $this->addBaseDisplayProperties($view);
+ }
+}
diff --git a/plugins/Actions/Reports/GetPageTitles.php b/plugins/Actions/Reports/GetPageTitles.php
new file mode 100644
index 0000000000000000000000000000000000000000..d08505d598ad6888fca9fd2499918d04d24e6fcf
--- /dev/null
+++ b/plugins/Actions/Reports/GetPageTitles.php
@@ -0,0 +1,96 @@
+dimension = new PageTitle();
+ $this->name = Piwik::translate('Actions_SubmenuPageTitles');
+ $this->documentation = Piwik::translate(
+ 'Actions_PageTitlesReportDocumentation',
+ [' ', htmlentities('', ENT_COMPAT | ENT_HTML401, 'UTF-8')]
+ );
+
+ $this->order = 5;
+ $this->metrics = array('nb_hits', 'nb_visits');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+
+ $this->actionToLoadSubTables = $this->action;
+ $this->subcategoryId = 'Actions_SubmenuPageTitles';
+ $this->hasGoalMetrics = true;
+ }
+
+ public function getMetrics()
+ {
+ $metrics = parent::getMetrics();
+ $metrics['nb_visits'] = Piwik::translate('General_ColumnUniquePageviews');
+
+ return $metrics;
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ $metrics = parent::getMetricsDocumentation();
+ $metrics['nb_visits'] = Piwik::translate('General_ColumnUniquePageviewsDocumentation');
+ $metrics['bounce_rate'] = Piwik::translate('General_ColumnPageBounceRateDocumentation');
+
+ return $metrics;
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->self_url = Request::getCurrentUrlWithoutGenericFilters(array(
+ 'module' => $this->module,
+ 'action' => 'getPageTitles',
+ ));
+
+ $view->config->title = $this->name;
+
+ $view->config->columns_to_display = array('label', 'nb_hits', 'nb_visits', 'bounce_rate',
+ 'avg_time_on_page', 'exit_rate');
+
+ if (version_compare(DbHelper::getInstallVersion(), '4.0.0-b1', '<')) {
+ $view->config->columns_to_display[] = 'avg_time_generation';
+ }
+
+ $this->addPageDisplayProperties($view);
+ $this->addBaseDisplayProperties($view);
+
+ $view->config->show_goals = true;
+ }
+
+ public function getRelatedReports()
+ {
+ return array(
+ ReportsProvider::factory('Actions', 'getEntryPageTitles'),
+ ReportsProvider::factory('Actions', 'getExitPageTitles'),
+ );
+ }
+}
diff --git a/plugins/Actions/Reports/GetPageTitlesFollowingSiteSearch.php b/plugins/Actions/Reports/GetPageTitlesFollowingSiteSearch.php
new file mode 100644
index 0000000000000000000000000000000000000000..59c344cb31860e4b0af340d887315964f2646d30
--- /dev/null
+++ b/plugins/Actions/Reports/GetPageTitlesFollowingSiteSearch.php
@@ -0,0 +1,87 @@
+dimension = new DestinationPage();
+ $this->name = Piwik::translate('Actions_WidgetPageTitlesFollowingSearch');
+ $this->documentation = Piwik::translate('Actions_SiteSearchFollowingPagesDoc') . ' ' . Piwik::translate('General_UsePlusMinusIconsDocumentation');
+ $this->metrics = array('nb_hits_following_search', 'nb_hits');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+ $this->order = 19;
+
+ $this->subcategoryId = 'Actions_SubmenuSitesearch';
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $title = Piwik::translate('Actions_WidgetPageUrlsFollowingSearch');
+
+ $this->configureViewForUrlAndTitle($view, $title);
+ }
+
+ public function getMetrics()
+ {
+ return array(
+ 'nb_hits_following_search' => Piwik::translate('General_ColumnViewedAfterSearch'),
+ 'nb_hits' => Piwik::translate('General_ColumnPageviews'),
+ );
+ }
+
+ public function getProcessedMetrics()
+ {
+ return array();
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ return array(
+ 'nb_hits_following_search' => Piwik::translate('General_ColumnViewedAfterSearchDocumentation'),
+ 'nb_hits' => Piwik::translate('General_ColumnPageviewsDocumentation'),
+ );
+ }
+
+ protected function configureViewForUrlAndTitle(ViewDataTable $view, $title)
+ {
+ $view->config->title = $title;
+ $view->config->columns_to_display = array('label', 'nb_hits_following_search', 'nb_hits');
+ $view->config->show_exclude_low_population = false;
+ $view->requestConfig->filter_sort_column = 'nb_hits_following_search';
+ $view->requestConfig->filter_sort_order = 'desc';
+
+ $this->addExcludeLowPopDisplayProperties($view);
+ $this->addBaseDisplayProperties($view);
+ }
+
+ public function getRelatedReports()
+ {
+ return array(
+ ReportsProvider::factory('Actions', 'getPageUrlsFollowingSiteSearch'),
+ );
+ }
+}
diff --git a/plugins/Actions/Reports/GetPageUrls.php b/plugins/Actions/Reports/GetPageUrls.php
new file mode 100644
index 0000000000000000000000000000000000000000..a00af4f077a377fb7680e252b75449e3e261be1a
--- /dev/null
+++ b/plugins/Actions/Reports/GetPageUrls.php
@@ -0,0 +1,98 @@
+dimension = new PageUrl();
+ $this->name = Piwik::translate('Actions_PageUrls');
+ $this->documentation = Piwik::translate('Actions_PagesReportDocumentation', ' ')
+ . ' ' . Piwik::translate('General_UsePlusMinusIconsDocumentation');
+
+ $this->actionToLoadSubTables = $this->action;
+ $this->order = 2;
+ $this->metrics = array('nb_hits', 'nb_visits');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+
+ $this->subcategoryId = 'General_Pages';
+ $this->hasGoalMetrics = true;
+ }
+
+ public function configureWidgets(WidgetsList $widgetsList, ReportWidgetFactory $factory)
+ {
+ $widgetsList->addWidgetConfig($factory->createWidget()->setName($this->subcategoryId));
+ }
+
+ public function getMetrics()
+ {
+ $metrics = parent::getMetrics();
+ $metrics['nb_visits'] = Piwik::translate('General_ColumnUniquePageviews');
+
+ return $metrics;
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ $metrics = parent::getMetricsDocumentation();
+ $metrics['nb_visits'] = Piwik::translate('General_ColumnUniquePageviewsDocumentation');
+ $metrics['bounce_rate'] = Piwik::translate('General_ColumnPageBounceRateDocumentation');
+
+ return $metrics;
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->columns_to_display = array('label', 'nb_hits', 'nb_visits', 'bounce_rate',
+ 'avg_time_on_page', 'exit_rate');
+
+ if (version_compare(DbHelper::getInstallVersion(), '4.0.0-b1', '<')) {
+ $view->config->columns_to_display[] = 'avg_time_generation';
+ }
+
+ $this->addPageDisplayProperties($view);
+ $this->addBaseDisplayProperties($view);
+
+ $view->config->show_goals = true;
+
+ // related reports are only shown on performance page
+ if ($view->requestConfig->getRequestParam('performance') !== '1') {
+ $view->config->related_reports = [];
+ }
+ }
+
+ public function getRelatedReports()
+ {
+ return [
+ ReportsProvider::factory('Actions', 'getEntryPageUrls'),
+ ReportsProvider::factory('Actions', 'getExitPageUrls'),
+ ];
+ }
+}
diff --git a/plugins/Actions/Reports/GetPageUrlsFollowingSiteSearch.php b/plugins/Actions/Reports/GetPageUrlsFollowingSiteSearch.php
new file mode 100644
index 0000000000000000000000000000000000000000..b661e6f650352b968322618ac475e6836e4860dc
--- /dev/null
+++ b/plugins/Actions/Reports/GetPageUrlsFollowingSiteSearch.php
@@ -0,0 +1,43 @@
+dimension = new DestinationPage();
+ $this->name = Piwik::translate('Actions_WidgetPageUrlsFollowingSearch');
+ $this->documentation = Piwik::translate('Actions_SiteSearchFollowingPagesDoc') . ' ' . Piwik::translate('General_UsePlusMinusIconsDocumentation');
+ $this->order = 16;
+
+ $this->subcategoryId = 'Actions_SubmenuSitesearch';
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $title = Piwik::translate('Actions_WidgetPageTitlesFollowingSearch');
+
+ $this->configureViewForUrlAndTitle($view, $title);
+ }
+
+ public function getRelatedReports()
+ {
+ return array(
+ ReportsProvider::factory('Actions', 'getPageTitlesFollowingSiteSearch'),
+ );
+ }
+}
diff --git a/plugins/Actions/Reports/GetSiteSearchCategories.php b/plugins/Actions/Reports/GetSiteSearchCategories.php
new file mode 100644
index 0000000000000000000000000000000000000000..cbed4c1a936a3678ed1639e6803c175f4ec07e8c
--- /dev/null
+++ b/plugins/Actions/Reports/GetSiteSearchCategories.php
@@ -0,0 +1,64 @@
+dimension = new SearchCategory();
+ $this->name = Piwik::translate('Actions_WidgetSearchCategories');
+ $this->documentation = Piwik::translate('Actions_SiteSearchCategories1') . ' ' . Piwik::translate('Actions_SiteSearchCategories2');
+ $this->metrics = array('nb_visits', 'nb_pages_per_search', 'exit_rate');
+ $this->order = 20;
+
+ $this->subcategoryId = 'Actions_SubmenuSitesearch';
+ }
+
+ protected function isEnabledForIdSites($idSites, $idSite)
+ {
+ return parent::isEnabledForIdSites($idSites, $idSite);
+ }
+
+ public function getMetrics()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnSearches'),
+ 'nb_pages_per_search' => Piwik::translate('Actions_ColumnPagesPerSearch'),
+ 'exit_rate' => Piwik::translate('Actions_ColumnSearchExits'),
+ );
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnSearchesDocumentation'),
+ 'nb_pages_per_search' => Piwik::translate('Actions_ColumnPagesPerSearchDocumentation'),
+ 'exit_rate' => Piwik::translate('Actions_ColumnSearchExitsDocumentation'),
+ );
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->columns_to_display = array('label', 'nb_visits', 'nb_pages_per_search');
+ $view->config->show_table_all_columns = false;
+ $view->config->show_bar_chart = false;
+
+ if ($view->isViewDataTableId(HtmlTable::ID)) {
+ $view->config->disable_row_evolution = false;
+ }
+ }
+}
diff --git a/plugins/Actions/Reports/GetSiteSearchKeywords.php b/plugins/Actions/Reports/GetSiteSearchKeywords.php
new file mode 100644
index 0000000000000000000000000000000000000000..bd376c7a8b9ba03c25b1fa9ad7e1af204c6bf8a3
--- /dev/null
+++ b/plugins/Actions/Reports/GetSiteSearchKeywords.php
@@ -0,0 +1,69 @@
+dimension = new Keyword();
+ $this->name = Piwik::translate('Actions_WidgetSearchKeywords');
+ $this->documentation = Piwik::translate('Actions_SiteSearchKeywordsDocumentation') . ' ' . Piwik::translate('Actions_SiteSearchIntro');
+ $this->metrics = array('nb_visits', 'nb_pages_per_search');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+ $this->order = 15;
+ $this->subcategoryId = 'Actions_SubmenuSitesearch';
+ }
+
+ public function getMetrics()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnSearches'),
+ 'nb_pages_per_search' => Piwik::translate('Actions_ColumnPagesPerSearch'),
+ );
+ }
+
+ public function getProcessedMetrics()
+ {
+ return array(
+ 'exit_rate' => Piwik::translate('Actions_ColumnSearchExits'),
+ );
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnSearchesDocumentation'),
+ 'nb_pages_per_search' => Piwik::translate('Actions_ColumnPagesPerSearchDocumentation'),
+ 'exit_rate' => Piwik::translate('Actions_ColumnSearchExitsDocumentation'),
+ );
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->columns_to_display = array('label', 'nb_visits', 'nb_pages_per_search', 'exit_rate');
+
+ $this->addSiteSearchDisplayProperties($view);
+ }
+}
diff --git a/plugins/Actions/Reports/GetSiteSearchNoResultKeywords.php b/plugins/Actions/Reports/GetSiteSearchNoResultKeywords.php
new file mode 100644
index 0000000000000000000000000000000000000000..5bdc192e2fc9ee8f31bcfea5603997ca586de6bf
--- /dev/null
+++ b/plugins/Actions/Reports/GetSiteSearchNoResultKeywords.php
@@ -0,0 +1,68 @@
+dimension = new KeywordwithNoSearchResult();
+ $this->name = Piwik::translate('Actions_WidgetSearchNoResultKeywords');
+ $this->documentation = Piwik::translate('Actions_SiteSearchIntro') . ' ' . Piwik::translate('Actions_SiteSearchKeywordsNoResultDocumentation');
+ $this->metrics = array('nb_visits');
+ $this->processedMetrics = array(
+ new AverageTimeOnPage(),
+ new BounceRate(),
+ new ExitRate(),
+ new AveragePageGenerationTime(),
+ );
+ $this->order = 18;
+
+ $this->subcategoryId = 'Actions_SubmenuSitesearch';
+ }
+
+ public function getMetrics()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnSearches'),
+ );
+ }
+
+ public function getProcessedMetrics()
+ {
+ return array(
+ 'exit_rate' => Piwik::translate('Actions_ColumnSearchExits'),
+ );
+ }
+
+ protected function getMetricsDocumentation()
+ {
+ return array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnSearchesDocumentation'),
+ 'exit_rate' => Piwik::translate('Actions_ColumnSearchExitsDocumentation'),
+ );
+ }
+
+ public function configureView(ViewDataTable $view)
+ {
+ $view->config->columns_to_display = array('label', 'nb_visits', 'exit_rate');
+
+ $this->addSiteSearchDisplayProperties($view);
+ }
+}
diff --git a/plugins/Actions/Reports/SiteSearchBase.php b/plugins/Actions/Reports/SiteSearchBase.php
new file mode 100644
index 0000000000000000000000000000000000000000..f69baaea2760f5f5bfcab3276afbb4b331096fac
--- /dev/null
+++ b/plugins/Actions/Reports/SiteSearchBase.php
@@ -0,0 +1,67 @@
+categoryId = 'General_Actions';
+ $this->onlineGuideUrl = Url::addCampaignParametersToMatomoLink('https://matomo.org/docs/site-search/');
+ }
+
+ public function isEnabled()
+ {
+ $idSites = Common::getRequestVar('idSites', '', 'string');
+ $idSite = Common::getRequestVar('idSite', 0, 'int');
+
+ return $this->isEnabledForIdSites($idSites, $idSite);
+ }
+
+ protected function isEnabledForIdSites($idSites, $idSite)
+ {
+ $actions = new Actions();
+ return $actions->isSiteSearchEnabled($idSites, $idSite);
+ }
+
+ public function configureReportMetadata(&$availableReports, $infos)
+ {
+ $idSite = array($infos['idSite']);
+
+ if (!$this->isEnabledForIdSites($idSite, Common::getRequestVar('idSite', 0, 'int'))) {
+ return;
+ }
+
+ $report = $this->buildReportMetadata();
+
+ if (!empty($report)) {
+ $availableReports[] = $report;
+ }
+ }
+
+ protected function addSiteSearchDisplayProperties(ViewDataTable $view)
+ {
+ $view->config->addTranslations(array(
+ 'nb_visits' => Piwik::translate('Actions_ColumnSearches'),
+ 'exit_rate' => str_replace("% ", "% ", Piwik::translate('Actions_ColumnSearchExits')),
+ 'nb_pages_per_search' => Piwik::translate('Actions_ColumnPagesPerSearch'),
+ ));
+
+ $view->config->show_bar_chart = false;
+ $view->config->show_table_all_columns = false;
+ }
+}
diff --git a/plugins/Actions/Segment.php b/plugins/Actions/Segment.php
new file mode 100644
index 0000000000000000000000000000000000000000..921613d57e600553cd7b8e291d71eead2c66212a
--- /dev/null
+++ b/plugins/Actions/Segment.php
@@ -0,0 +1,22 @@
+setCategory('General_Actions');
+ $this->setSqlFilter('\\Piwik\\Tracker\\TableLogAction::getIdActionFromSegment');
+ }
+}
diff --git a/plugins/Actions/Tracker/ActionsRequestProcessor.php b/plugins/Actions/Tracker/ActionsRequestProcessor.php
new file mode 100644
index 0000000000000000000000000000000000000000..0f7ed748c2b1cb43e21407e502d9d498939dff0d
--- /dev/null
+++ b/plugins/Actions/Tracker/ActionsRequestProcessor.php
@@ -0,0 +1,106 @@
+writeDebugInfo();
+
+ $request->setMetadata('Actions', 'action', $action);
+
+ // save the exit actions of the last action in this visit as the referrer actions for the action being tracked.
+ // when the visit is updated, these columns will be changed, so we have to do this before recordLogs
+ $request->setMetadata(
+ 'Actions',
+ 'idReferrerActionUrl',
+ $visitProperties->getProperty('visit_exit_idaction_url')
+ );
+ $request->setMetadata(
+ 'Actions',
+ 'idReferrerActionName',
+ $visitProperties->getProperty('visit_exit_idaction_name')
+ );
+
+ return false;
+ }
+
+ public function afterRequestProcessed(VisitProperties $visitProperties, Request $request)
+ {
+ /** @var Action $action */
+ $action = $request->getMetadata('Actions', 'action');
+
+ if (!empty($action)) { // other plugins can unset the action if they want
+ $action->loadIdsFromLogActionTable();
+ }
+
+ return false;
+ }
+
+ public function recordLogs(VisitProperties $visitProperties, Request $request)
+ {
+ /** @var Action $action */
+ $action = $request->getMetadata('Actions', 'action');
+
+ if (
+ $action !== null
+ && !$request->getMetadata('CoreHome', 'visitorNotFoundInDb')
+ ) {
+ $idReferrerActionUrl = 0;
+ $idReferrerActionName = 0;
+
+ if (!$request->getMetadata('CoreHome', 'isNewVisit')) {
+ $idReferrerActionUrl = $request->getMetadata('Actions', 'idReferrerActionUrl');
+ $idReferrerActionName = $request->getMetadata('Actions', 'idReferrerActionName');
+ }
+
+ $visitor = Visitor::makeFromVisitProperties($visitProperties, $request);
+ $action->record($visitor, $idReferrerActionUrl, $idReferrerActionName);
+ }
+ }
+}
diff --git a/plugins/Actions/VisitorDetails.php b/plugins/Actions/VisitorDetails.php
new file mode 100644
index 0000000000000000000000000000000000000000..6ee1ee922127cc0f68b878b89d4f393c4edd08d3
--- /dev/null
+++ b/plugins/Actions/VisitorDetails.php
@@ -0,0 +1,523 @@
+details['visit_total_searches'];
+ $visitor['actions'] = $this->details['visit_total_actions'];
+ $visitor['interactions'] = $this->details['visit_total_interactions'];
+ }
+
+ public function provideActionsForVisitIds(&$actions, $visitIds)
+ {
+ $actionDetails = $this->queryActionsForVisits($visitIds);
+ // use while / array_shift combination instead of foreach to save memory
+ while (is_array($actionDetails) && count($actionDetails)) {
+ $action = array_shift($actionDetails);
+ $idVisit = $action['idvisit'];
+ unset($action['idvisit']);
+ $actions[$idVisit][] = $action;
+ }
+ }
+
+
+ public function provideActionsForVisit(&$actions, $visitorDetails)
+ {
+ $actionDetails = $actions;
+
+ $formatter = new Formatter();
+
+ // Enrich with time spent per action
+ $nextActionId = 0;
+ foreach ($actionDetails as $idx => &$action) {
+ if ($idx < $nextActionId || !$this->isPageView($action)) {
+ unset($action['timeSpentRef']);
+ continue; // skip to next page view
+ }
+
+ $action['timeSpent'] = 0;
+
+ // search for next action with timeSpentRef
+ $nextActionId = $idx;
+ $nextAction = null;
+
+ do {
+ $nextActionId++;
+
+ $nextAction = isset($actionDetails[$nextActionId]) ? $actionDetails[$nextActionId] : null;
+
+ if (is_null($nextAction)) {
+ // Last action of a visit.
+ // By default, Matomo does not know how long the user stayed on the page
+ // If enableHeartBeatTimer() is used in piwik.js then we can find the accurate time on page for the last pageview
+ $visitTotalTime = $visitorDetails['visitDuration'];
+ $timeOfLastAction = Date::factory($action['serverTimePretty'])->getTimestamp();
+
+ $timeSpentOnAllActionsApartFromLastOne = ($timeOfLastAction - $visitorDetails['firstActionTimestamp']);
+ $timeSpentOnPage = $visitTotalTime - $timeSpentOnAllActionsApartFromLastOne;
+
+ // Safe net, we assume the time is correct when it's more than 10 seconds
+ if ($timeSpentOnPage > 10) {
+ $action['timeSpent'] = $timeSpentOnPage;
+ }
+ break;
+ }
+
+ if (!array_key_exists('timeSpentRef', $nextAction)) {
+ continue;
+ }
+
+ // Set the time spent for this action (which is the timeSpentRef of the next action)
+ if ($nextAction) {
+ $action['timeSpent'] += $nextAction['timeSpentRef'] ?? 0;
+ }
+
+ // sum spent time until next page view
+ if ($this->isPageView($nextAction)) {
+ break;
+ }
+ } while (isset($actionDetails[$nextActionId]));
+
+ if (isset($action['timeSpent'])) {
+ $action['timeSpentPretty'] = $formatter->getPrettyTimeFromSeconds($action['timeSpent'], true);
+ }
+
+ unset($action['timeSpentRef']);
+ }
+
+ $actions = $actionDetails;
+ }
+
+ private function shouldHandleAction($action)
+ {
+ $actionTypesToHandle = array(
+ Action::TYPE_PAGE_URL,
+ Action::TYPE_PAGE_TITLE,
+ Action::TYPE_SITE_SEARCH,
+ Action::TYPE_EVENT,
+ Action::TYPE_OUTLINK,
+ Action::TYPE_DOWNLOAD,
+ );
+
+ if (empty($action['type'])) {
+ return !empty($action['eventType']);
+ }
+
+ return in_array($action['type'], $actionTypesToHandle) || !empty($action['eventType']);
+ }
+
+ private function isPageView($action)
+ {
+ if (empty($action['type'])) {
+ return false;
+ }
+
+ $pageViewTypes = array(
+ Action::TYPE_PAGE_URL,
+ Action::TYPE_PAGE_TITLE,
+ );
+
+ return in_array($action['type'], $pageViewTypes);
+ }
+
+ public function extendActionDetails(&$action, $nextAction, $visitorDetails)
+ {
+ $actionType = '';
+ if (!empty($action['type'])) {
+ $actionType = $action['type'];
+ }
+
+ $formatter = new Formatter();
+
+ if ($actionType == Action::TYPE_SITE_SEARCH) {
+ // Handle Site Search
+ $action['siteSearchKeyword'] = $action['pageTitle'];
+ $action['siteSearchCategory'] = $action['search_cat'];
+ $action['siteSearchCount'] = $action['search_count'];
+ unset($action['pageTitle']);
+ }
+
+ unset($action['search_cat']);
+ unset($action['search_count']);
+
+ // Generation time
+ if ($this->shouldHandleAction($action) && empty($action['eventType']) && isset($action['custom_float']) && $action['custom_float'] > 0) {
+ $action['generationTimeMilliseconds'] = $action['custom_float'];
+ $action['generationTime'] = $formatter->getPrettyTimeFromSeconds($action['custom_float'] / 1000, true);
+ unset($action['custom_float']);
+ }
+
+ if (array_key_exists('custom_float', $action) && is_null($action['custom_float'])) {
+ unset($action['custom_float']);
+ }
+
+ if (!array_key_exists('pageLoadTime', $action) || $action['pageLoadTime'] <= 0) {
+ unset($action['pageLoadTime']);
+ } else {
+ $action['pageLoadTimeMilliseconds'] = $action['pageLoadTime'];
+ $action['pageLoadTime'] = $formatter->getPrettyTimeFromSeconds($action['pageLoadTime'] / 1000, true);
+ }
+
+ if (array_key_exists('pageview_position', $action)) {
+ $action['pageviewPosition'] = $action['pageview_position'];
+ unset($action['pageview_position']);
+ }
+
+ // Reconstruct url from prefix
+ if (array_key_exists('url', $action) && array_key_exists('url_prefix', $action)) {
+ if ($action['url'] && stripos($action['url'], 'http://') !== 0 && stripos($action['url'], 'https://') !== 0) {
+ $url = PageUrl::reconstructNormalizedUrl($action['url'], $action['url_prefix']);
+ $url = Common::unsanitizeInputValue($url);
+ $action['url'] = $url;
+ }
+
+ unset($action['url_prefix']);
+ }
+
+ if (!empty($action['url']) && strpos($action['url'], 'http://') === 0) {
+ $host = parse_url($action['url'], PHP_URL_HOST);
+
+ if ($host && PageUrl::shouldUseHttpsHost($visitorDetails['idSite'], $host)) {
+ $action['url'] = 'https://' . mb_substr($action['url'], 7 /* = strlen('http://') */);
+ }
+ }
+
+ switch ($actionType) {
+ case 'goal':
+ $action['icon'] = 'plugins/Morpheus/images/goal.png';
+ $action['iconSVG'] = 'plugins/Morpheus/images/goal.svg';
+ $action['title'] = Piwik::translate('Goals_GoalConversion');
+ $action['subtitle'] = $action['goalName'];
+ if (!empty($action['revenue'])) {
+ $action['subtitle'] .= ' (' . Piwik::translate('Goals_NRevenue', $formatter->getPrettyMoney($action['revenue'], $visitorDetails['idSite'])) . ')';
+ }
+ break;
+ case Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER:
+ case Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_CART:
+ $action['icon'] = 'plugins/Morpheus/images/' . $actionType . '.png';
+ $action['iconSVG'] = 'plugins/Morpheus/images/' . $actionType . '.svg';
+ if ($actionType == Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER) {
+ $action['title'] = Piwik::translate('CoreHome_VisitStatusOrdered') . ' (' . $action['orderId'] . ')';
+ } else {
+ $action['title'] = Piwik::translate('Goals_AbandonedCart');
+ }
+
+ $itemNames = implode(', ', array_column($action['itemDetails'], 'itemName'));
+ $action['subtitle'] = Piwik::translate('Goals_NRevenue', $formatter->getPrettyMoney($action['revenue'], $visitorDetails['idSite']));
+ $action['subtitle'] .= ' - ' . Piwik::translate('Goals_NItems', $action['items']) . ': ' . $itemNames . ')';
+ break;
+ case Action::TYPE_CONTENT:
+ if (!empty($action['contentInteraction'])) {
+ $action['icon'] = 'plugins/Morpheus/images/contentinteraction.png';
+ $action['iconSVG'] = 'plugins/Morpheus/images/contentinteraction.svg';
+ $action['title'] = Piwik::translate('Contents_ContentInteraction') . ' (' . $action['contentInteraction'] . ')';
+ } else {
+ $action['icon'] = 'plugins/Morpheus/images/contentimpression.png';
+ $action['iconSVG'] = 'plugins/Morpheus/images/contentimpression.svg';
+ $action['title'] = Piwik::translate('Contents_ContentImpression');
+ }
+
+ $action['subtitle'] = $action['contentName'];
+ if (!empty($action['contentPiece'])) {
+ $action['subtitle'] .= ' - ' . $action['contentPiece'];
+ }
+ break;
+ case Action::TYPE_DOWNLOAD:
+ $action['type'] = 'download';
+ $action['icon'] = 'plugins/Morpheus/images/download.png';
+ $action['iconSVG'] = 'plugins/Morpheus/images/download.svg';
+ $action['title'] = Piwik::translate('General_Download');
+ $action['subtitle'] = $action['url'];
+ break;
+ case Action::TYPE_OUTLINK:
+ $action['type'] = 'outlink';
+ $action['icon'] = 'plugins/Morpheus/images/link.png';
+ $action['iconSVG'] = 'plugins/Morpheus/images/link.svg';
+ $action['title'] = Piwik::translate('General_Outlink');
+ $action['subtitle'] = $action['url'];
+ break;
+ case Action::TYPE_SITE_SEARCH:
+ $action['type'] = 'search';
+ $action['icon'] = 'plugins/Morpheus/images/search.png';
+ $action['iconSVG'] = 'plugins/Morpheus/images/search.svg';
+ $action['title'] = Piwik::translate('Actions_SubmenuSitesearch');
+ $action['subtitle'] = $action['siteSearchKeyword'];
+
+ if (!empty($action['siteSearchCategory'])) {
+ $action['subtitle'] .= ' - ' . Piwik::translate('Actions_ColumnSearchCategory') . ': ' . $action['siteSearchCategory'];
+ }
+
+ if (!empty($action['siteSearchCount'])) {
+ $action['subtitle'] .= ' - ' . Piwik::translate('Actions_ColumnSearchResultsCount') . ': ' . $action['siteSearchCount'];
+ }
+
+ break;
+ case Action::TYPE_PAGE_URL:
+ case Action::TYPE_PAGE_TITLE:
+ case '':
+ if (!isset($action['title'])) {
+ $action['title'] = $action['pageTitle'];
+ $action['subtitle'] = $action['url'];
+ }
+ $action['type'] = 'action';
+ $action['icon'] = '';
+ $action['iconSVG'] = 'plugins/Morpheus/images/action.svg';
+ break;
+ }
+
+ // Convert datetimes to the site timezone
+ $dateTimeVisit = Date::factory(
+ $action['serverTimePretty'],
+ Site::getTimezoneFor($visitorDetails['idSite'])
+ );
+ $action['serverTimePretty'] = $dateTimeVisit->getLocalized(Date::DATETIME_FORMAT_SHORT);
+ $action['timestamp'] = $dateTimeVisit->getTimestamp();
+
+ unset($action['idlink_va']);
+ }
+
+ /**
+ * @param array $idVisits
+ * @return array
+ */
+ protected function queryActionsForVisits($idVisits)
+ {
+ $customFields = array();
+ $customJoins = array();
+
+ Piwik::postEvent('Actions.getCustomActionDimensionFieldsAndJoins', array(&$customFields, &$customJoins));
+
+ $customFields = array_filter($customFields);
+ array_unshift($customFields, ''); // add empty element at first
+ $customActionDimensionFields = implode(', ', $customFields);
+
+ // The second join is a LEFT join to allow returning records that don't have a matching page title
+ // eg. Downloads, Outlinks. For these, idaction_name is set to 0
+ $pagePerformanceSelect = '';
+ if (Plugin\Manager::getInstance()->isPluginActivated('PagePerformance')) {
+ $pagePerformanceSelect = '( log_link_visit_action.time_network +
+ log_link_visit_action.time_server +
+ log_link_visit_action.time_transfer +
+ log_link_visit_action.time_dom_completion +
+ log_link_visit_action.time_dom_processing +
+ log_link_visit_action.time_on_load ) AS pageLoadTime,';
+ }
+
+ $sql = "
+ SELECT
+ log_link_visit_action.idvisit,
+ COALESCE(log_action.type, log_action_title.type) AS type,
+ log_action.name AS url,
+ log_action.url_prefix,
+ log_action_title.name AS pageTitle,
+ log_action.idaction AS pageIdAction,
+ log_link_visit_action.idpageview,
+ log_link_visit_action.idlink_va,
+ log_link_visit_action.server_time as serverTimePretty,
+ log_link_visit_action.time_spent_ref_action as timeSpentRef,
+ log_link_visit_action.idlink_va AS pageId,
+ log_link_visit_action.custom_float,
+ $pagePerformanceSelect
+ log_link_visit_action.pageview_position,
+ log_link_visit_action.search_cat,
+ log_link_visit_action.search_count
+ " . $customActionDimensionFields . "
+ FROM `" . Common::prefixTable('log_link_visit_action') . "` AS log_link_visit_action
+ LEFT JOIN `" . Common::prefixTable('log_action') . "` AS log_action
+ ON log_link_visit_action.idaction_url = log_action.idaction
+ LEFT JOIN `" . Common::prefixTable('log_action') . "` AS log_action_title
+ ON log_link_visit_action.idaction_name = log_action_title.idaction
+ " . implode(" ", $customJoins) . "
+ WHERE log_link_visit_action.idvisit IN ('" . implode("','", $idVisits) . "')
+ ORDER BY log_link_visit_action.idvisit, log_link_visit_action.server_time, log_link_visit_action.idlink_va
+ ";
+ $actionDetails = $this->getDb()->fetchAll($sql);
+ return $actionDetails;
+ }
+
+
+ private $visitedPageUrls = array();
+ private $siteSearchKeywords = array();
+ private $pageGenerationTimeTotal = 0;
+ private $pageLoadTimeTotal = 0;
+
+ public function initProfile($visits, &$profile)
+ {
+ $this->visitedPageUrls = array();
+ $this->siteSearchKeywords = array();
+ $this->pageGenerationTimeTotal = 0;
+ $this->pageLoadTimeTotal = 0;
+ $profile['totalActions'] = 0;
+ $profile['totalOutlinks'] = 0;
+ $profile['totalDownloads'] = 0;
+ $profile['totalSearches'] = 0;
+ $profile['totalPageViews'] = 0;
+ $profile['totalUniquePageViews'] = 0;
+ $profile['totalRevisitedPages'] = 0;
+ $profile['totalPageViewsWithTiming'] = 0;
+ $profile['totalPageViewsWithLoadTime'] = 0;
+ $profile['searches'] = array();
+ }
+
+ public function handleProfileVisit($visit, &$profile)
+ {
+ $profile['totalActions'] += $visit->getColumn('actions');
+ }
+
+ public function handleProfileAction($action, &$profile)
+ {
+ $this->handleIfDownloadAction($action, $profile);
+ $this->handleIfOutlinkAction($action, $profile);
+ $this->handleIfSiteSearchAction($action, $profile);
+ $this->handleIfPageViewAction($action, $profile);
+ $this->handleIfPageGenerationTime($action, $profile);
+ $this->handleIfPageLoadTime($action, $profile);
+ }
+
+ public function finalizeProfile($visits, &$profile)
+ {
+ $profile['visitedPages'] = [];
+
+ foreach ($this->visitedPageUrls as $visitedPageUrl => $count) {
+ $profile['visitedPages'][] = [
+ 'url' => $visitedPageUrl,
+ 'count' => $count,
+ ];
+ }
+
+ usort($profile['visitedPages'], function ($a, $b) {
+ if ($a['count'] == $b['count']) {
+ return strcmp($a['url'], $b['url']);
+ }
+
+ return $a['count'] > $b['count'] ? -1 : 1;
+ });
+
+ $this->handleSiteSearches($profile);
+ $this->handleAveragePageGenerationTime($profile);
+ $this->handleAveragePageLoadTime($profile);
+ }
+
+ /**
+ * @param $action
+ */
+ private function handleIfDownloadAction($action, &$profile)
+ {
+ if (empty($action['type']) || $action['type'] != 'download') {
+ return;
+ }
+ $profile['totalDownloads']++;
+ }
+
+ /**
+ * @param $action
+ */
+ private function handleIfOutlinkAction($action, &$profile)
+ {
+ if (empty($action['type']) || $action['type'] != 'outlink') {
+ return;
+ }
+ $profile['totalOutlinks']++;
+ }
+
+ /**
+ * @param $action
+ */
+ private function handleIfPageViewAction($action, &$profile)
+ {
+ if (empty($action['type']) || $action['type'] != 'action') {
+ return;
+ }
+ $profile['totalPageViews']++;
+ $pageUrl = $action['url'];
+ if (!empty($pageUrl)) {
+ if (!array_key_exists($pageUrl, $this->visitedPageUrls)) {
+ $this->visitedPageUrls[$pageUrl] = 0;
+ $profile['totalUniquePageViews']++;
+ }
+ $this->visitedPageUrls[$pageUrl]++;
+ if ($this->visitedPageUrls[$pageUrl] == 2) {
+ $profile['totalRevisitedPages']++;
+ }
+ }
+ }
+
+ private function handleIfSiteSearchAction($action, &$profile)
+ {
+ if (!isset($action['siteSearchKeyword'])) {
+ return;
+ }
+ $keyword = $action['siteSearchKeyword'];
+
+ if (!isset($this->siteSearchKeywords[$keyword])) {
+ $this->siteSearchKeywords[$keyword] = 0;
+ ++$profile['totalSearches'];
+ }
+ ++$this->siteSearchKeywords[$keyword];
+ }
+
+ private function handleSiteSearches(&$profile)
+ {
+ // sort by visit/action
+ arsort($this->siteSearchKeywords);
+
+ foreach ($this->siteSearchKeywords as $keyword => $searchCount) {
+ $profile['searches'][] = array(
+ 'keyword' => $keyword,
+ 'searches' => $searchCount,
+ );
+ }
+ }
+
+ private function handleIfPageGenerationTime($action, &$profile)
+ {
+ if (isset($action['generationTimeMilliseconds'])) {
+ $this->pageGenerationTimeTotal += $action['generationTimeMilliseconds'];
+ ++$profile['totalPageViewsWithTiming'];
+ }
+ }
+
+ private function handleAveragePageGenerationTime(&$profile)
+ {
+ if ($profile['totalPageViewsWithTiming']) {
+ $profile['averagePageGenerationTime'] =
+ round($this->pageGenerationTimeTotal / (1000 * $profile['totalPageViewsWithTiming']), $precision = 3);
+ }
+ }
+
+ private function handleIfPageLoadTime($action, &$profile)
+ {
+ if (isset($action['pageLoadTimeMilliseconds'])) {
+ $this->pageLoadTimeTotal += $action['pageLoadTimeMilliseconds'];
+ ++$profile['totalPageViewsWithLoadTime'];
+ }
+ }
+
+ private function handleAveragePageLoadTime(&$profile)
+ {
+ if ($profile['totalPageViewsWithLoadTime']) {
+ $profile['averagePageLoadTime'] =
+ round($this->pageLoadTimeTotal / (1000 * $profile['totalPageViewsWithLoadTime']), $precision = 3);
+ }
+ }
+}
diff --git a/plugins/Actions/config/config.php b/plugins/Actions/config/config.php
new file mode 100644
index 0000000000000000000000000000000000000000..d5be5de26f92a935f318ed4c0a04fe01434bfe66
--- /dev/null
+++ b/plugins/Actions/config/config.php
@@ -0,0 +1,3 @@
+= 0) {
+ currentLevel = Number(style.slice(currentLevelIndex + 5, currentLevelIndex + 6));
+ }
+ return currentLevel;
+ }
+
+ /**
+ * UI control that handles extra functionality for Actions datatables.
+ *
+ * @constructor
+ */
+ exports.ActionsDataTable = function (element) {
+ this.parentAttributeParent = '';
+ this.parentId = '';
+ this.disabledRowDom = {}; // to handle double click on '+' row
+
+ DataTable.call(this, element);
+ };
+
+ $.extend(exports.ActionsDataTable.prototype, dataTablePrototype, {
+
+ //see dataTable::bindEventsAndApplyStyle
+ bindEventsAndApplyStyle: function (domElem, rows) {
+ var self = this;
+
+ self.cleanParams();
+ self.preBindEventsAndApplyStyleHook(domElem, rows);
+
+ if (!rows) {
+ rows = $('tr', domElem);
+ }
+
+ self.numberOfSubtables = rows.filter('.subDataTable').click(function () {
+ if (!self.param.filter_pattern_recursive) {
+ // we don't display the link on the row with subDataTable when we are already
+ // printing all the subTables (case of recursive search when the content is
+ // including recursively all the subtables
+ self.onClickActionSubDataTable(this);
+ }
+ }).length;
+ self.applyCosmetics(domElem, rows);
+ self.handleColumnHighlighting(domElem);
+ self.handleRowActions(domElem, rows);
+ self.handleLimit(domElem);
+ self.handlePeriod(domElem);
+ self.handleAnnotationsButton(domElem);
+ self.handleExportBox(domElem);
+ self.handleSort(domElem);
+ self.handleOffsetInformation(domElem);
+ if (self.workingDivId != undefined) {
+ var dataTableLoadedProxy = function (response) {
+ self.dataTableLoaded(response, self.workingDivId);
+ };
+
+ self.handleConfigurationBox(domElem, dataTableLoadedProxy);
+ self.handleSearchBox(domElem, dataTableLoadedProxy);
+ }
+
+ self.handleColumnDocumentation(domElem);
+ self.handleRelatedReports(domElem);
+ self.handleTriggeredEvents(domElem);
+ self.handleCellTooltips(domElem);
+ self.setFixWidthToMakeEllipsisWork(domElem);
+ self.handleSummaryRow(domElem);
+ self.openSubtableFromLevel0IfOnlyOneSubtableGiven(domElem);
+ self.postBindEventsAndApplyStyleHook(domElem, rows);
+ },
+
+ openSubtableFromLevel0IfOnlyOneSubtableGiven: function (domElem) {
+ var $subtables = domElem.find('.subDataTable');
+ var hasOnlyOneSubtable = $subtables.length === 1;
+
+ if (hasOnlyOneSubtable) {
+ var hasOnlyOneRow = domElem.find('tbody tr.level0').length === 1;
+
+ if (hasOnlyOneRow) {
+ var $labels = $subtables.find('.label');
+ if ($labels.length) {
+ $labels.first().click();
+ }
+ }
+ }
+ },
+
+ openSubtableFromSubtableIfOnlyOneSubtableGiven: function (domElem) {
+ var hasOnlyOneRow = domElem.length === 1;
+ var hasOnlyOneSubtable = domElem.hasClass('subDataTable');
+
+ if (hasOnlyOneRow && hasOnlyOneSubtable) {
+ // when subtable is loaded
+ var $labels = domElem.find('.label');
+ if ($labels.length) {
+ $labels.first().click();
+ }
+ }
+ },
+
+ //see dataTable::applyCosmetics
+ applyCosmetics: function (domElem, rows) {
+ var self = this;
+ var rowsWithSubtables = rows.filter('.subDataTable');
+
+ rowsWithSubtables.css('font-weight', 'bold');
+
+ $("th:first-child", domElem).addClass('label');
+ $(rowsWithSubtables)
+ .each(function () {
+ if (self.param.filter_pattern_recursive) {
+ $(this).addClass('expanded');
+ // remove tooltip "Click this row to expand or contract the subtable"
+ $(this).attr('title', '');
+ }
+ });
+
+ var rootRow = rows.first().prev();
+
+ // we look at the style of the row before the new rows to determine the rows'
+ // level
+ var level = rootRow.length ? getLevelFromClass(rootRow.attr('class')) + 1 : 0;
+
+ rows.each(function () {
+ var currentStyle = $(this).attr('class') || '';
+
+ if (currentStyle.indexOf('level') == -1) {
+ $(this).addClass('level' + level);
+ }
+
+ // we add an attribute parent that contains the ID of all the parent categories
+ // this ID is used when collapsing a parent row, it searches for all children rows
+ // which 'parent' attribute's value contains the collapsed row ID
+ $(this).prop('parent', function () {
+ return self.parentAttributeParent + ' ' + self.parentId;
+ });
+ });
+
+ self.addOddAndEvenClasses(domElem);
+ },
+
+ addOddAndEvenClasses: function(domElem) {
+ // empty
+ },
+
+ handleRowActions: function (domElem, rows) {
+ this.doHandleRowActions(rows);
+ },
+
+ // Called when the user click on an actionDataTable row
+ onClickActionSubDataTable: function (domElem) {
+ var self = this;
+
+ // get the idSubTable
+ var idSubTable = $(domElem).attr('id');
+
+ var divIdToReplaceWithSubTable = 'subDataTable_' + idSubTable;
+
+ var $insertAfter = $(domElem).nextUntil(':not(.comparePeriod):not(.comparisonRow)').last();
+ if (!$insertAfter.length) {
+ $insertAfter = $(domElem);
+ }
+
+ var NextStyle = $insertAfter.next().attr('class');
+ var CurrentStyle = $(domElem).attr('class');
+
+ var currentRowLevel = getLevelFromClass(CurrentStyle);
+ var nextRowLevel = getLevelFromClass(NextStyle);
+
+ // if the row has not been clicked
+ // which is the same as saying that the next row level is equal or less than the current row
+ // because when we click a row the level of the next rows is higher (level2 row gives level3 rows)
+ if (currentRowLevel >= nextRowLevel) {
+ //unbind click to avoid double click problem
+ $(domElem).off('click');
+ self.disabledRowDom = $(domElem);
+
+ var numberOfColumns = $(domElem).children().length;
+ $insertAfter.after('\
+ \
+ \
+ \
+ \
+ Loading...\
+ \
+ \
+ \
+ ');
+ var savedActionVariable = self.param.action;
+
+ // reset all the filters from the Parent table
+ var filtersToRestore = self.resetAllFilters();
+
+ // Do not reset the sorting filters that must be applied to sub tables
+ this.param['filter_sort_column'] = filtersToRestore['filter_sort_column'];
+ this.param['filter_sort_order'] = filtersToRestore['filter_sort_order'];
+ this.param['enable_filter_excludelowpop'] = filtersToRestore['enable_filter_excludelowpop'];
+
+ self.param.idSubtable = idSubTable;
+ self.param.action = self.props.subtable_controller_action;
+
+ var extraParams = {};
+ extraParams.comparisonIdSubtables = self.getComparisonIdSubtables($(domElem));
+
+ self.reloadAjaxDataTable(false, function (resp) {
+ self.actionsSubDataTableLoaded(resp, idSubTable);
+ self.repositionRowActions($(domElem));
+ }, extraParams);
+ self.param.action = savedActionVariable;
+
+ self.restoreAllFilters(filtersToRestore);
+
+ delete self.param.idSubtable;
+ }
+ // else we toggle all these rows
+ else {
+ var isExpanded = $(domElem).hasClass('subDataTable') && $(domElem).hasClass('expanded');
+
+ $(domElem).siblings().each(function () {
+ var parents = $(this).prop('parent').split(' ');
+ if (parents) {
+ if (parents.indexOf(idSubTable) >= 0
+ || parents.indexOf('subDataTable_' + idSubTable) >= 0) {
+ if (!isExpanded) {
+ $(this).css('display', '').removeClass('hidden');
+
+ // unroll everything if the row is already opened
+ var NextStyle = $(this).next().attr('class');
+ var CurrentStyle = $(this).attr('class');
+
+ var currentRowLevel = getLevelFromClass(CurrentStyle);
+ var nextRowLevel = getLevelFromClass(NextStyle);
+
+ if (currentRowLevel < nextRowLevel) {
+ $(this).addClass('expanded');
+ }
+ }
+ else {
+ $(this).css('display', 'none').addClass('hidden');
+ }
+ self.repositionRowActions($(domElem));
+ }
+ }
+ });
+
+ self.$element.trigger('piwik:actionsSubTableToggled');
+ }
+
+ // toggle the +/- image
+ $(domElem).toggleClass('expanded');
+ },
+
+ //called when the full table actions is loaded
+ dataTableLoaded: function (response, workingDivId) {
+ var content = $(response);
+ var idToReplace = workingDivId || $(content).attr('id');
+
+ //reset parents id
+ self.parentAttributeParent = '';
+ self.parentId = '';
+
+ var dataTableSel = $('#' + idToReplace);
+
+ // keep the original list of related reports
+ var oldReportsElem = $('.datatableRelatedReports', dataTableSel);
+ $('.datatableRelatedReports', content).replaceWith(oldReportsElem);
+
+ dataTableSel.replaceWith(content);
+
+ content.trigger('piwik:dataTableLoaded');
+
+ piwikHelper.compileVueEntryComponents(content);
+
+ piwikHelper.lazyScrollTo(content[0], 400);
+
+ return content;
+ },
+
+ // Called when a set of rows for a category of actions is loaded
+ actionsSubDataTableLoaded: function (response, idSubTable) {
+ var self = this;
+ var idToReplace = 'subDataTable_' + idSubTable;
+ var root = $('#' + self.workingDivId);
+
+ var response = $(response);
+ self.parentAttributeParent = $('tr#' + idToReplace).prev().prop('parent');
+ self.parentId = idToReplace;
+
+ $('tr#' + idToReplace, root).after(response).remove();
+
+ var requiredColumnCount = 0, availableColumnCount = 0;
+
+ response.prev().find('td').each(function(){ requiredColumnCount += $(this).attr('colspan') || 1; });
+ response.find('td').each(function(){ availableColumnCount += $(this).attr('colspan') || 1; });
+
+ var missingColumns = requiredColumnCount - availableColumnCount;
+ for (var i = 0; i < missingColumns; i++) {
+ // if the subtable has fewer columns than the parent table, add some columns.
+ // this happens for example, when the parent table has performance metrics and the subtable doesn't.
+ response.append('- ');
+ }
+
+ var re = /subDataTable_(\d+)/;
+ var ok = re.exec(self.parentId);
+ if (ok) {
+ self.parentId = ok[1];
+ }
+
+ // we execute the bindDataTableEvent function for the new DIV
+ self.bindEventsAndApplyStyle($('#' + self.workingDivId), response);
+
+ self.$element.trigger('piwik:actionsSubDataTableLoaded');
+
+ //bind back the click event (disabled to avoid double-click problem)
+ self.disabledRowDom.click(
+ function () {
+ self.onClickActionSubDataTable(this)
+ });
+
+ self.openSubtableFromSubtableIfOnlyOneSubtableGiven(response);
+ }
+ });
+
+})(jQuery, require);
diff --git a/plugins/Actions/javascripts/rowactions.js b/plugins/Actions/javascripts/rowactions.js
new file mode 100644
index 0000000000000000000000000000000000000000..71b2be68854384d93879b2310c6ecc23bf94e78d
--- /dev/null
+++ b/plugins/Actions/javascripts/rowactions.js
@@ -0,0 +1,99 @@
+$(function () {
+
+ function isActionsModule(params)
+ {
+ return params.module == 'Actions';
+ }
+
+ function isPageUrlReport(params) {
+ var action = params.action;
+
+ return isActionsModule(params) &&
+ (action == 'getPageUrls' || action == 'getEntryPageUrls' || action == 'getExitPageUrls' || action == 'getPageUrlsFollowingSiteSearch');
+ };
+
+ function isPageTitleReport(params) {
+ var action = params.action;
+
+ return isActionsModule(params) && (action == 'getPageTitles' || action == 'getPageTitlesFollowingSiteSearch');
+ };
+
+ function getLinkForTransitionAndOverlayPopover(tr)
+ {
+ tr = getRealRowIfComparisonRow(tr);
+
+ var link = tr.find('> td:first > a').attr('href');
+ // replace all &, that are not part of a named character reference with a tailing semicolon, with a &
+ // otherwise named character references without a tailing , (like ®) would be replaced
+ link = link.replace(/&([a-z]+[^a-z;])/, '&$1');
+ link = $('