AnalyticsCollectorTest.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. <?php
  2. /**
  3. * Hits through the collector into sessions and events, and back out through reports.
  4. * Test hits are dated in September 2001, far from real traffic, and deleted afterwards.
  5. */
  6. class AnalyticsCollectorTest extends BxDolIntegrationTestCase
  7. {
  8. // 2001-09-09 01:46:40 UTC
  9. const NOW = 1000000000;
  10. const UA_SAFARI = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15';
  11. protected $_oModule;
  12. protected $_aOptions = [];
  13. protected $_aGoals = [];
  14. protected $_aFunnels = [];
  15. protected function setUp(): void
  16. {
  17. parent::setUp();
  18. if (!BxDolModuleQuery::getInstance()->isEnabledByName('bx_analytics'))
  19. $this->markTestSkipped('bx_analytics is not installed');
  20. $this->_oModule = BxDolModule::getInstance('bx_analytics');
  21. $this->_oModule->getCollector(); // loads the collector classes
  22. $this->_oModule->getFilter([]);
  23. $this->_cleanup();
  24. foreach (['bx_analytics_track_actions' => 'on', 'bx_analytics_track_bots' => 'on', 'bx_analytics_tracking' => 'on', 'bx_analytics_platforms' => 'core-web,next-web,rn-ios,rn-android,api,core', 'bx_analytics_respect_dnt' => 'on', 'bx_analytics_link_members' => 'on', 'bx_analytics_identity' => 'cookieless', 'bx_analytics_exclude_ips' => '', 'bx_analytics_exclude_levels' => '', 'bx_analytics_exclude_paths' => '', 'bx_analytics_geo_source' => 'headers', 'bx_analytics_limit_hits' => '300', 'bx_analytics_limit_visits' => '100'] as $sName => $sValue)
  25. $this->_setOption($sName, $sValue);
  26. }
  27. protected function tearDown(): void
  28. {
  29. if ($this->_oModule) {
  30. $this->_cleanup();
  31. foreach ($this->_aOptions as $sName => $sValue)
  32. setParam($sName, $sValue);
  33. }
  34. parent::tearDown();
  35. }
  36. public function testPageviewsMakeOneSession()
  37. {
  38. $aServer = $this->_server('81.2.69.142', ['HTTP_CF_IPCOUNTRY' => 'GB']);
  39. $this->assertSame(1, $this->_collect($aServer, [
  40. 'platform' => 'core-web',
  41. 'referrer' => 'https://www.google.com/',
  42. 'language' => 'en-GB',
  43. 'screen' => '1440x900',
  44. 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/page/explore?utm_source=nl&utm_medium=email&gclid=1', 'title' => 'Explore']],
  45. ], self::NOW));
  46. $this->assertSame(2, $this->_collect($aServer, [
  47. 'platform' => 'core-web',
  48. 'hits' => [
  49. ['type' => 'leave', 'url' => 'http://una.test/page/explore', 'engaged' => 15000],
  50. ['type' => 'pageview', 'url' => 'http://una.test/page/view-post?id=5', 'title' => 'Post'],
  51. ],
  52. ], self::NOW + 60));
  53. $aSessions = $this->_sessions();
  54. $this->assertCount(1, $aSessions);
  55. $a = $aSessions[0];
  56. $this->assertSame('core-web', $a['platform']);
  57. $this->assertSame(2, (int)$a['pageviews']);
  58. $this->assertSame(0, (int)$a['bounce']);
  59. $this->assertSame(60, (int)$a['duration']);
  60. $this->assertSame('/page/explore', $a['entry_path'], 'campaign tags and click ids are not part of the path');
  61. $this->assertSame('/page/view-post?id=5', $a['exit_path']);
  62. $this->assertSame(['google.com', 'email', 'nl', 'GB', 'Safari', 'macOS', 'desktop', '1440x900'], [$a['referrer_host'], $a['channel'], $a['utm_source'], $a['country'], $a['browser'], $a['os'], $a['device'], $a['screen']]);
  63. $aEvents = BxDolDb::getInstance()->getAll("SELECT `path`, `engaged` FROM `bx_analytics_events` WHERE `session_id` = :id ORDER BY `id`", ['id' => $a['id']]);
  64. $this->assertEquals([['path' => '/page/explore', 'engaged' => 15000], ['path' => '/page/view-post?id=5', 'engaged' => 0]], $aEvents, 'engaged time goes to the page that was left');
  65. }
  66. public function testDroppedHits()
  67. {
  68. $aHit = ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]];
  69. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142', [], 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'), $aHit, self::NOW), 'bot');
  70. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142', ['HTTP_DNT' => '1']), $aHit, self::NOW), 'Do Not Track');
  71. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142'), ['platform' => 'core'] + $aHit, self::NOW), 'the server platform is not for clients');
  72. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142'), ['platform' => 'windows-phone'] + $aHit, self::NOW), 'unknown platform');
  73. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142'), ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'https://elsewhere.example/']]], self::NOW, ['same_origin' => true]), 'another site');
  74. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142', ['HTTP_SEC_FETCH_SITE' => 'cross-site']), $aHit, self::NOW, ['same_origin' => true]), 'cross-site request');
  75. $this->_setOption('bx_analytics_exclude_ips', '81.2.69.0/24');
  76. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW), 'excluded address');
  77. $this->_setOption('bx_analytics_platforms', 'next-web');
  78. $this->assertSame(0, $this->_collect($this->_server('93.184.216.34'), $aHit, self::NOW), 'platform switched off');
  79. $this->assertCount(0, $this->_sessions());
  80. }
  81. public function testNativeAppHit()
  82. {
  83. $this->assertSame(1, $this->_collect($this->_server('93.184.216.34', [], 'okhttp/4.12.0'), [
  84. 'platform' => 'rn-android',
  85. 'app' => 'com.neo.so',
  86. 'app_version' => '1.5.0',
  87. 'os_version' => '15',
  88. 'device' => 'tablet',
  89. 'hits' => [['type' => 'pageview', 'url' => '/page/explore', 'title' => 'Explore']],
  90. ], self::NOW), 'an HTTP library user agent is fine for an app');
  91. $a = $this->_sessions()[0];
  92. $this->assertSame(['rn-android', 'com.neo.so', '1.5.0', 'Android', '15', 'tablet', 'com.neo.so'], [$a['platform'], $a['app'], $a['app_version'], $a['os'], $a['os_version'], $a['device'], $a['hostname']]);
  93. }
  94. public function testTrackerConfig()
  95. {
  96. $this->assertTrue($this->_oModule->serviceIsSafeService('get_tracker_config'), 'NEO reads it over the API');
  97. $a = $this->_oModule->serviceGetTrackerConfig('rn-ios');
  98. $this->assertSame(['enabled', 'persistent', 'respect_dnt', 'session_timeout', 'errors', 'errors_ignore', 'vitals', 'vitals_sample'], array_keys($a), 'settings only, nothing about the site or the viewer');
  99. $this->assertTrue($a['enabled']);
  100. $this->assertFalse($a['persistent']);
  101. $this->assertTrue($a['respect_dnt']);
  102. $this->assertSame($this->_oModule->_oConfig->getSessionTimeout(), $a['session_timeout']);
  103. $this->assertFalse($this->_oModule->serviceGetTrackerConfig('core')['enabled'], 'the server platform is not for clients');
  104. $this->assertFalse($this->_oModule->serviceGetTrackerConfig('windows-phone')['enabled'], 'unknown platform');
  105. $this->_setOption('bx_analytics_identity', 'persistent');
  106. $this->assertTrue($this->_oModule->serviceGetTrackerConfig('next-web')['persistent']);
  107. $this->_setOption('bx_analytics_platforms', 'next-web');
  108. $this->assertFalse($this->_oModule->serviceGetTrackerConfig('rn-ios')['enabled'], 'platform switched off');
  109. // health: what NEO reports about errors and timings
  110. $this->_setOption('bx_analytics_track_errors', 'on');
  111. $this->_setOption('bx_analytics_track_vitals', 'on');
  112. $this->_setOption('bx_analytics_vitals_sample', '25');
  113. $this->_setOption('bx_analytics_errors_ignore', "ResizeObserver loop*\r\nScript error.*");
  114. $a = $this->_oModule->serviceGetTrackerConfig('next-web');
  115. $this->assertTrue($a['errors']);
  116. $this->assertTrue($a['vitals']);
  117. $this->assertSame(25, $a['vitals_sample']);
  118. $this->assertSame(['ResizeObserver loop*', 'Script error.*'], $a['errors_ignore'], 'one pattern per line');
  119. $this->_setOption('bx_analytics_vitals_sample', '0');
  120. $this->assertFalse($this->_oModule->serviceGetTrackerConfig('next-web')['vitals'], 'nothing sampled');
  121. $this->_setOption('bx_analytics_track_errors', '');
  122. $this->assertFalse($this->_oModule->serviceGetTrackerConfig('next-web')['errors']);
  123. $this->_setOption('bx_analytics_tracking', '');
  124. $a = $this->_oModule->serviceGetTrackerConfig('next-web');
  125. $this->assertFalse($a['enabled'], 'tracking off');
  126. $this->assertFalse($a['persistent'], 'no visitor id to keep when nothing is sent');
  127. $this->_setOption('bx_analytics_track_errors', 'on');
  128. $this->assertFalse($this->_oModule->serviceGetTrackerConfig('next-web')['errors'], 'no errors when nothing is sent');
  129. }
  130. public function testGuestSignsInAndIsForgotten()
  131. {
  132. $iProfileId = 987654321;
  133. $aServer = $this->_server('93.184.216.34');
  134. $aHit = ['platform' => 'next-web', 'hits' => [['type' => 'pageview', 'url' => 'https://neo.test/']]];
  135. $this->_collect($aServer, $aHit, self::NOW);
  136. $this->_collect($aServer, $aHit, self::NOW + 30, ['profile_id' => $iProfileId]);
  137. $aSessions = $this->_sessions();
  138. $this->assertCount(1, $aSessions, 'signing in continues the visit');
  139. $this->assertSame($iProfileId, (int)$aSessions[0]['profile_id']);
  140. $sMemberVisitor = $aSessions[0]['visitor'];
  141. $oDb = BxDolDb::getInstance();
  142. $sGuestVisitor = $oDb->getOne("SELECT `visitor` FROM `bx_analytics_events` WHERE `ts` = :ts", ['ts' => self::NOW]);
  143. $this->assertNotSame($sMemberVisitor, $sGuestVisitor, 'the page viewed before signing in keeps the guest\'s id');
  144. // site actions about the account and the profile, and another visit days later
  145. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer + ['REQUEST_METHOD' => 'POST']), self::NOW + 40);
  146. $this->assertTrue($oCollector->collectAction('login', 'account', 4242, $iProfileId, ['platform' => 'next-web']));
  147. $this->assertTrue($oCollector->collectAction('profile_add', 'bx_persons', $iProfileId, $iProfileId, ['platform' => 'next-web']));
  148. $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW + 2 * 86400, ['profile_id' => $iProfileId]);
  149. $this->assertCount(2, $this->_sessions());
  150. $this->_oModule->onProfileDelete($iProfileId);
  151. $aSessions = $this->_sessions();
  152. $this->assertSame([0, 0], array_map('intval', array_column($aSessions, 'profile_id')));
  153. $this->assertNotSame($sMemberVisitor, $aSessions[0]['visitor']);
  154. $this->assertNotSame($aSessions[0]['visitor'], $aSessions[1]['visitor'], 'its visits are not tied to one another');
  155. $this->assertSame(0, (int)$oDb->getOne("SELECT COUNT(*) FROM `bx_analytics_events` WHERE `profile_id` = :p", ['p' => $iProfileId]));
  156. $aEvents = $oDb->getAll("SELECT `e`.`visitor`, `e`.`object_id`, `s`.`visitor` AS `session_visitor` FROM `bx_analytics_events` AS `e` INNER JOIN `bx_analytics_sessions` AS `s` ON `s`.`id` = `e`.`session_id` WHERE `e`.`ts` < :to ORDER BY `e`.`id`", ['to' => self::NOW + 30 * 86400]);
  157. $this->assertCount(5, $aEvents);
  158. foreach ($aEvents as $a) {
  159. $this->assertSame($a['session_visitor'], $a['visitor'], 'every event is its visit\'s, the one before signing in too');
  160. $this->assertNotContains($a['visitor'], [$sMemberVisitor, $sGuestVisitor]);
  161. }
  162. $this->assertSame([0, 0], array_map('intval', $oDb->getColumn("SELECT `object_id` FROM `bx_analytics_events` WHERE `type` = 'una' AND `ts` < :to", ['to' => self::NOW + 30 * 86400])), 'the account and the profile the actions were about');
  163. // the profile's creation is found by a key, not among every profile created
  164. $aKey = $oDb->getAll("SHOW INDEX FROM `bx_analytics_events` WHERE `Key_name` = 'object'");
  165. $this->assertSame(['type', 'name', 'object_id'], array_column($aKey, 'Column_name'));
  166. $aPlan = $oDb->getRow("EXPLAIN SELECT `id` FROM `bx_analytics_events` WHERE `type` = 'una' AND `name` = 'profile_add' AND `object_id` = :profile", ['profile' => $iProfileId]);
  167. $this->assertContains('object', explode(',', (string)$aPlan['possible_keys']));
  168. }
  169. public function testSignInTakesOverOnlyARecentGuestVisit()
  170. {
  171. $aHit = ['platform' => 'next-web', 'hits' => [['type' => 'pageview', 'url' => 'https://neo.test/']]];
  172. $fProfiles = function () {
  173. return array_map('intval', array_column($this->_sessions(), 'profile_id'));
  174. };
  175. // someone else behind the same address with the same browser, 10 minutes before
  176. $aServer = $this->_server('93.184.216.34');
  177. $this->_collect($aServer, $aHit, self::NOW);
  178. $this->_collect($aServer, $aHit, self::NOW + 600, ['profile_id' => 987654321]);
  179. $this->assertSame([0, 987654321], $fProfiles(), 'a member doesn\'t take over an older guest visit');
  180. // the member's own visit comes first, while the guest's goes on
  181. $this->_collect($aServer, $aHit, self::NOW + 700);
  182. $this->_collect($aServer, $aHit, self::NOW + 720, ['profile_id' => 987654321]);
  183. $this->assertSame([0, 987654321], $fProfiles());
  184. $this->assertSame([2, 2], array_map('intval', array_column($this->_sessions(), 'pageviews')));
  185. // a guest visit active right before is the member's: they signed in during it
  186. $this->_collect($this->_server('93.184.216.35'), $aHit, self::NOW + 1000);
  187. $this->_collect($this->_server('93.184.216.35'), $aHit, self::NOW + 1060, ['profile_id' => 987654322]);
  188. $this->assertSame([0, 987654321, 987654322], $fProfiles());
  189. // a visitor id kept by the device is the device's own, however long ago
  190. $this->_setOption('bx_analytics_identity', 'persistent');
  191. $aDevice = $aHit + ['vid' => 'phpunit-device-0001'];
  192. $this->_collect($this->_server('93.184.216.36'), $aDevice, self::NOW + 2000);
  193. $this->_collect($this->_server('93.184.216.36'), $aDevice, self::NOW + 2900, ['profile_id' => 987654323]);
  194. $this->assertSame([0, 987654321, 987654322, 987654323], $fProfiles());
  195. }
  196. public function testSecretsAreNotStored()
  197. {
  198. $aServer = $this->_server('81.2.69.142');
  199. $aUrls = [
  200. 'http://una.test/page.php?i=forgot-password&key=abcDEF1234567890xyz',
  201. 'http://una.test/page.php?i=confirm-email&code=0123456789abcdef',
  202. 'http://una.test/page.php?i=unsubscribe-notifications&id=42&code=5f4dcc3b5aa765d61d8327deb882cf99',
  203. 'http://una.test/page/oauth-callback?code=4%2F0AX4XfWh&state=xyz&access_token=ya29.secret',
  204. 'http://una.test/page/invite?Email=jane%40example.com&api_key=k1&_hsenc=p2ANqtz',
  205. 'http://una.test/create-account?icode=Ab3kP9xQ&lang=en',
  206. 'http://una.test/page.php?i=pricing&promocode=SPRING26&apikey=k2&user_sid=9',
  207. 'http://una.test/page/search?q=jane%40example.com',
  208. ];
  209. foreach ($aUrls as $i => $sUrl)
  210. $this->_collect($aServer, ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => $sUrl]]], self::NOW + $i * 10);
  211. $aPaths = BxDolDb::getInstance()->getColumn("SELECT `path` FROM `bx_analytics_events` WHERE `ts` < :to ORDER BY `id`", ['to' => self::NOW + 86400]);
  212. $this->assertSame([
  213. '/page.php?i=forgot-password',
  214. '/page.php?i=confirm-email',
  215. '/page.php?i=unsubscribe-notifications&id=42',
  216. '/page/oauth-callback?state=xyz',
  217. '/page/invite',
  218. '/create-account?lang=en',
  219. '/page.php?i=pricing',
  220. '/page/search?q=<redacted>',
  221. ], $aPaths, 'keys, codes, tokens and addresses are dropped; what is left is redacted');
  222. $aSession = $this->_sessions()[0];
  223. $this->assertSame(['/page.php?i=forgot-password', '/page/search?q=<redacted>'], [$aSession['entry_path'], $aSession['exit_path']]);
  224. // link previews and mail scanners fetch these links too
  225. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('66.249.66.1')), self::NOW);
  226. $this->assertTrue($oCollector->collectBot('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', '/page.php?i=forgot-password&key=abcDEF1234567890xyz'));
  227. $this->assertSame(['/page.php?i=forgot-password'], BxDolDb::getInstance()->getColumn("SELECT `path` FROM `bx_analytics_bot_pages` WHERE `day` < '2002-01-01'"));
  228. }
  229. public function testLocationFromTheChosenEdge()
  230. {
  231. // behind Vercel, a visitor sends Cloudflare's country header too
  232. $aHeaders = ['HTTP_CF_IPCOUNTRY' => 'KP', 'HTTP_X_VERCEL_IP_COUNTRY' => 'DE', 'HTTP_X_VERCEL_IP_CITY' => 'Berlin'];
  233. $aHit = ['platform' => 'next-web', 'hits' => [['type' => 'pageview', 'url' => 'https://neo.test/']]];
  234. foreach (['vercel', 'headers', 'none'] as $i => $sSource) {
  235. $this->_setOption('bx_analytics_geo_source', $sSource);
  236. $this->_collect($this->_server('81.2.69.' . (150 + $i), $aHeaders), $aHit, self::NOW + $i * 10);
  237. }
  238. $aSessions = $this->_sessions();
  239. $this->assertSame([['DE', 'Berlin'], ['KP', 'Berlin'], ['', '']], array_map(function ($a) { return [$a['country'], $a['city']]; }, $aSessions));
  240. }
  241. public function testSiteActionsFollowTheVisitorsChoice()
  242. {
  243. $fAction = function ($aExtra = [], $sUserAgent = self::UA_SAFARI, $iProfileId = 987654321) {
  244. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('81.2.69.142', ['REQUEST_METHOD' => 'POST'] + $aExtra, $sUserAgent)), self::NOW);
  245. return $oCollector->collectAction('login', 'account', 1, $iProfileId, ['platform' => 'core-web']);
  246. };
  247. $this->assertFalse($fAction(['HTTP_DNT' => '1']), 'Do Not Track');
  248. $this->assertFalse($fAction(['HTTP_SEC_GPC' => '1']), 'Global Privacy Control');
  249. $this->assertFalse($fAction([], 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'), 'a bot');
  250. $this->_setOption('bx_analytics_exclude_ips', '81.2.69.0/24');
  251. $this->assertFalse($fAction(), 'an excluded address');
  252. $this->_setOption('bx_analytics_exclude_ips', '');
  253. $this->assertTrue($fAction());
  254. // a cron job has no visitor request: its headers don't apply
  255. $oCron = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest([]), self::NOW);
  256. $this->assertTrue($oCron->collectAction('renewal', 'account', 1, 987654321));
  257. // a guest's action, when guests aren't tracked
  258. $this->_setOption('bx_analytics_exclude_levels', (string)MEMBERSHIP_ID_NON_MEMBER);
  259. $this->assertFalse($fAction([], self::UA_SAFARI, 0));
  260. $this->assertSame(2, (int)BxDolDb::getInstance()->getOne("SELECT COUNT(*) FROM `bx_analytics_events` WHERE `type` = 'una' AND `ts` < :to", ['to' => self::NOW + 86400]));
  261. }
  262. public function testLargeCollectBodiesAreNotRead()
  263. {
  264. $iMax = $this->_oModule->_oConfig->CNF['MAX_COLLECT_BYTES'];
  265. $sPath = '/phpunit-collect-size';
  266. $fPayload = function ($iTitle) use ($sPath) {
  267. return json_encode(['platform' => 'api', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test' . $sPath, 'title' => str_repeat('a', $iTitle)]]]);
  268. };
  269. $this->assertTrue($this->_oModule->isCollectBodyAllowed($fPayload(100)));
  270. $this->assertFalse($this->_oModule->isCollectBodyAllowed($fPayload($iMax)));
  271. // the service stores now, with the request's own address: the rows are deleted after
  272. $oDb = BxDolDb::getInstance();
  273. try {
  274. $this->assertSame(['stored' => 0], $this->_oModule->serviceCollect($fPayload($iMax)), 'too large: refused before it is decoded');
  275. $this->assertSame(0, (int)$oDb->getOne("SELECT COUNT(*) FROM `bx_analytics_events` WHERE `path` = :path", ['path' => $sPath]));
  276. $this->assertSame(['stored' => 1], $this->_oModule->serviceCollect($fPayload(100)), 'the same hit, small enough');
  277. }
  278. finally {
  279. $oDb->query("DELETE FROM `bx_analytics_sessions` WHERE `entry_path` = :path AND `started` > :since", ['path' => $sPath, 'since' => time() - 3600]);
  280. $oDb->query("DELETE FROM `bx_analytics_events` WHERE `path` = :path AND `ts` > :since", ['path' => $sPath, 'since' => time() - 3600]);
  281. }
  282. }
  283. public function testCookielessVisitorsChangeDaily()
  284. {
  285. $aServer = $this->_server('93.184.216.34');
  286. $aHit = ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]];
  287. $this->_collect($aServer, $aHit, self::NOW);
  288. $this->_collect($aServer, $aHit, self::NOW + 2 * 86400);
  289. $aSessions = $this->_sessions();
  290. $this->assertCount(2, $aSessions);
  291. $this->assertNotSame($aSessions[0]['visitor'], $aSessions[1]['visitor']);
  292. }
  293. public function testReports()
  294. {
  295. // two visitors: one bounces from a search, one views two pages on iOS
  296. $this->_collect($this->_server('81.2.69.142'), ['platform' => 'core-web', 'referrer' => 'https://duckduckgo.com/', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/a']]], self::NOW);
  297. $this->_collect($this->_server('93.184.216.34', [], 'NEO/1 CFNetwork/1.0 Darwin/24.0.0'), ['platform' => 'rn-ios', 'app' => 'com.neo.so', 'hits' => [['type' => 'pageview', 'url' => '/a'], ['type' => 'pageview', 'url' => '/b']]], self::NOW + 10);
  298. $aParams = ['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'];
  299. $aOverview = $this->_oModule->getReports()->getOverview($this->_filter($aParams));
  300. $this->assertSame(2, $aOverview['kpis']['visitors']['value']);
  301. $this->assertSame(3, $aOverview['kpis']['pageviews']['value']);
  302. $this->assertEquals(50, $aOverview['kpis']['bounce_rate']['value']);
  303. $this->assertSame('hour', $aOverview['bucket']);
  304. $this->assertSame(24, count($aOverview['series']));
  305. $aIos = $this->_oModule->getReports()->getOverview($this->_filter($aParams + ['platform' => 'rn-ios']));
  306. $this->assertSame(1, $aIos['kpis']['visitors']['value']);
  307. $aPages = $this->_oModule->getReports()->getTop($this->_filter($aParams), ['group' => 'pages', 'tab' => 'pages']);
  308. $this->assertSame(['/a', '/b'], array_column($aPages['items'], 'value'));
  309. $this->assertSame([2, 1], array_column($aPages['items'], 'visitors'));
  310. $aChannels = $this->_oModule->getReports()->getTop($this->_filter($aParams + ['f' => ['path' => '/b']]), ['group' => 'sources', 'tab' => 'channels']);
  311. $this->assertSame(['direct'], array_column($aChannels['items'], 'value'), 'a page filter keeps the sessions that saw it');
  312. $aPlatforms = $this->_oModule->getReports()->getTop($this->_filter($aParams), ['group' => 'platforms', 'tab' => 'platforms']);
  313. $this->assertEqualsCanonicalizing(['core-web', 'rn-ios'], array_column($aPlatforms['items'], 'value'));
  314. $aTable = $this->_oModule->getReports()->getTable($this->_filter($aParams), ['table' => 'pages']);
  315. $this->assertSame(['/a', '/b'], array_column($aTable['rows'], 'label'));
  316. $this->assertSame(2, $aTable['rows'][0]['values']['entries'], 'both sessions entered on /a');
  317. $this->assertSame(1, $aTable['rows'][0]['values']['exits'], 'the one-page session left from /a');
  318. $this->assertEquals(50, $aTable['rows'][0]['values']['bounce_rate']);
  319. $this->assertSame(2, $aTable['total']);
  320. $this->assertFalse($this->_oModule->getReports()->getTable($this->_filter($aParams), ['table' => 'nope']));
  321. $this->assertFalse($this->_oModule->getReportData('nope', $aParams), 'unknown reports are refused');
  322. }
  323. public function testBotsAreCountedApart()
  324. {
  325. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('66.249.66.1')), self::NOW);
  326. $this->assertTrue($oCollector->collectBot('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', '/page/explore?utm_source=x'));
  327. $this->assertTrue($oCollector->collectBot('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', '/page/explore'));
  328. $this->assertTrue($oCollector->collectBot('Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ChatGPT-User/1.0; +https://openai.com/bot)', '/'));
  329. $this->assertFalse($oCollector->collectBot(self::UA_SAFARI, '/'), 'browsers are not bots');
  330. // a headless browser that runs the tracker is a bot, not a visit
  331. $this->assertSame(0, $this->_collect($this->_server('66.249.66.1', [], 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/120.0.0.0 Safari/537.36'), ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]], self::NOW));
  332. $this->assertCount(0, $this->_sessions());
  333. $aFilter = $this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'])->get();
  334. $this->assertEquals(['hits' => 4, 'bots' => 3], $this->_oModule->_oDb->getBotTotals($aFilter));
  335. $this->assertEquals(['hits' => 1, 'bots' => 1], $this->_oModule->_oDb->getBotTotals($aFilter, ['ai_agent']));
  336. $aPages = $this->_oModule->_oDb->getBotPages($aFilter, ['search'], 10);
  337. $this->assertEquals([['path' => '/page/explore', 'hits' => 2]], $aPages, 'campaign tags are not part of the path');
  338. $aReport = $this->_oModule->getReports()->getBots($this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09']), ['tab_bots' => 'ai']);
  339. $this->assertSame('ai', $aReport['tab']);
  340. $this->assertSame(['ChatGPT'], array_column($aReport['bots']['rows'], 'label'));
  341. }
  342. public function testSiteActionsJoinTheVisit()
  343. {
  344. $iProfileId = 987654321;
  345. $aServer = $this->_server('93.184.216.34', ['REQUEST_METHOD' => 'POST']);
  346. $this->_collect($aServer, ['platform' => 'rn-ios', 'app' => 'com.neo.so', 'hits' => [['type' => 'pageview', 'url' => '/page/create-post']]], self::NOW, ['profile_id' => $iProfileId]);
  347. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW + 20);
  348. $this->assertTrue($oCollector->collectAction('content_add', 'bx_posts', 77, $iProfileId, ['platform' => 'rn-ios']));
  349. // a renewal by cron has no visit and runs on the server's own platform
  350. $oCron = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest([]), self::NOW + 30);
  351. $this->assertTrue($oCron->collectAction('login', 'account', 1, $iProfileId));
  352. $aSessions = $this->_sessions();
  353. $this->assertCount(1, $aSessions);
  354. $this->assertSame(1, (int)$aSessions[0]['events']);
  355. $this->assertSame(0, (int)$aSessions[0]['bounce'], 'doing something is not a bounce');
  356. $aEvents = BxDolDb::getInstance()->getAll("SELECT `session_id`, `type`, `name`, `module`, `object_id`, `platform` FROM `bx_analytics_events` WHERE `type` = 'una' AND `ts` < :to ORDER BY `id`", ['to' => self::NOW + 86400]);
  357. $this->assertEquals([
  358. ['session_id' => $aSessions[0]['id'], 'type' => 'una', 'name' => 'content_add', 'module' => 'bx_posts', 'object_id' => 77, 'platform' => 'rn-ios'],
  359. ['session_id' => 0, 'type' => 'una', 'name' => 'login', 'module' => 'account', 'object_id' => 1, 'platform' => 'core'],
  360. ], $aEvents);
  361. $aParams = ['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'];
  362. $oReports = $this->_oModule->getReports();
  363. $aList = $oReports->getEvents($this->_filter($aParams), ['tab_events' => 'site']);
  364. $this->assertSame('list', $aList['view']);
  365. $this->assertCount(2, $aList['rows']);
  366. $aDetail = $oReports->getEvents($this->_filter($aParams), ['event' => 'una|content_add|bx_posts']);
  367. $this->assertSame('detail', $aDetail['view']);
  368. $this->assertSame(1, $aDetail['tiles'][0]['value']);
  369. $this->assertSame([['label' => $oReports->getLabel('platform', 'rn-ios'), 'count' => 1, 'share' => 100.0]], $aDetail['platforms']);
  370. $this->assertNull($oReports->getEvents($this->_filter($aParams), ['event' => 'pageview|x|y'])['event'] ?? null, 'pageviews are not events');
  371. $aSessionsList = $oReports->getSessions($this->_filter($aParams));
  372. $this->assertCount(1, $aSessionsList['rows']);
  373. $aSessionDetail = $oReports->getSessions($this->_filter($aParams), ['session' => $aSessions[0]['id']]);
  374. $this->assertSame(['pageview', 'una'], array_column($aSessionDetail['timeline'], 'type'));
  375. $this->assertSame(20, $aSessionDetail['timeline'][1]['offset']);
  376. $aUsers = $oReports->getUsers($this->_filter($aParams));
  377. $this->assertSame(1, count($aUsers['rows']));
  378. $this->assertSame(['param' => 'user', 'value' => $iProfileId], $aUsers['rows'][0]['open']);
  379. }
  380. public function testJourneysAndRetention()
  381. {
  382. // three members' visits: / -> /a -> /b, / -> /a -> /c, / -> /d, the first coming back a week later
  383. $aVisits = [
  384. [987654321, self::NOW, ['/', '/a', '/b']],
  385. [987654322, self::NOW + 100, ['/', '/a', '/a', '/c']],
  386. [987654323, self::NOW + 200, ['/', '/d']],
  387. [987654321, self::NOW + 7 * 86400, ['/']],
  388. ];
  389. foreach ($aVisits as list($iProfileId, $iTime, $aPages))
  390. foreach ($aPages as $i => $sPage)
  391. $this->_collect($this->_server('93.184.216.' . ($iProfileId % 100)), ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test' . $sPage]]], $iTime + $i * 10, ['profile_id' => $iProfileId]);
  392. $oReports = $this->_oModule->getReports();
  393. $oFilter = $this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09']);
  394. $aJourneys = $oReports->getJourneys($oFilter);
  395. $this->assertSame('/', $aJourneys['jfrom'], 'the top entry page by default');
  396. $this->assertSame(3, $aJourneys['from_sessions']);
  397. $this->assertSame([['page' => '/a', 'sessions' => 2, 'share' => 66.7], ['page' => '/d', 'sessions' => 1, 'share' => 33.3]], $aJourneys['next']);
  398. $aVia = $oReports->getJourneys($oFilter, ['via' => '/a']);
  399. $this->assertEqualsCanonicalizing(['/b', '/c'], array_column($aVia['after'], 'page'), 'a page reloaded in place counts once');
  400. // the start page has its own param, so it doesn't break a custom date range
  401. $aRequest = ['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09', 'jfrom' => '/a'];
  402. $oRequestFilter = $this->_filter($aRequest);
  403. $this->assertSame($oFilter->get()['from'], $oRequestFilter->get()['from'], 'jfrom keeps the custom range');
  404. $this->assertSame($oFilter->get()['to'], $oRequestFilter->get()['to']);
  405. $aFromA = $oReports->getJourneys($oRequestFilter, $aRequest);
  406. $this->assertSame('/a', $aFromA['jfrom']);
  407. $this->assertSame(2, $aFromA['from_sessions']);
  408. $aPaths = array_map(function ($a) { return implode(' ', $a['pages']); }, $aJourneys['paths']);
  409. $this->assertContains('/ /a /b', $aPaths);
  410. $aRetention = $oReports->getRetention(new BxAnalyticsFilter($this->_oModule, ['range' => '7d'], self::NOW + 8 * 86400));
  411. $aCohorts = array_values(array_filter($aRetention['rows'], function ($a) { return $a['size'] > 0; }));
  412. $this->assertCount(1, $aCohorts);
  413. $this->assertSame(3, $aCohorts[0]['size']);
  414. $this->assertEquals(100, $aCohorts[0]['weeks'][0]);
  415. $this->assertEquals(33.3, $aCohorts[0]['weeks'][1], 'one of three came back the next week');
  416. }
  417. public function testGoalsAndFunnels()
  418. {
  419. $oDb = $this->_oModule->_oDb;
  420. $iPricing = $oDb->saveGoal(0, ['name' => 'Test 2001 pricing', 'type' => 'page', 'pattern' => '/pricing*']);
  421. $iBuy = $oDb->saveGoal(0, ['name' => 'Test 2001 buy', 'type' => 'event', 'pattern' => 'buy']);
  422. $iFunnel = $oDb->saveFunnel(0, 'Test 2001 funnel', [
  423. ['type' => 'page', 'pattern' => '/'],
  424. ['type' => 'page', 'pattern' => '/pricing*'],
  425. ['type' => 'event', 'pattern' => 'buy'],
  426. ]);
  427. $this->_aGoals = [$iPricing, $iBuy];
  428. $this->_aFunnels = [$iFunnel];
  429. $this->assertGreaterThan(0, $iPricing);
  430. $this->assertGreaterThan(0, $iFunnel);
  431. // A: / -> /pricing -> buy, B: / -> buy -> /pricing?plan=pro, C: /pricing only
  432. $aVisits = [
  433. ['93.184.216.1', [['pageview', '/'], ['pageview', '/pricing'], ['event', '/pricing', 'buy']]],
  434. ['93.184.216.2', [['pageview', '/'], ['event', '/', 'buy'], ['pageview', '/pricing?plan=pro']]],
  435. ['93.184.216.3', [['pageview', '/pricing']]],
  436. ];
  437. foreach ($aVisits as $iVisit => list($sIp, $aHits))
  438. foreach ($aHits as $i => $aHit)
  439. $this->_collect($this->_server($sIp), ['platform' => 'core-web', 'hits' => [['type' => $aHit[0], 'url' => 'http://una.test' . $aHit[1], 'name' => isset($aHit[2]) ? $aHit[2] : '']]], self::NOW + $iVisit * 100 + $i * 10);
  440. $oReports = $this->_oModule->getReports();
  441. $oFilter = $this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09']);
  442. $aGoals = array_column($oReports->getGoals($oFilter)['goals'], null, 'id');
  443. $this->assertSame(3, $aGoals[$iPricing]['conversions'], 'a page goal with * matches the query string too');
  444. $this->assertEquals(100, $aGoals[$iPricing]['rate']);
  445. $this->assertSame(2, $aGoals[$iBuy]['conversions']);
  446. $this->assertEquals(66.67, $aGoals[$iBuy]['rate']);
  447. // goals are capped: the report counts each one in both periods
  448. $iMax = $this->_oModule->_oConfig->CNF['MAX_GOALS'];
  449. $this->assertSame($oDb->getGoalsCount() >= $iMax, $this->_oModule->isGoalLimitReached());
  450. for ($i = $oDb->getGoalsCount(); $i < $iMax + 1; $i++)
  451. $this->_aGoals[] = $oDb->saveGoal(0, ['name' => 'Test 2001 goal ' . $i, 'type' => 'page', 'pattern' => '/goal-' . $i]);
  452. $this->assertTrue($this->_oModule->isGoalLimitReached());
  453. $this->assertCount($iMax, $oDb->getGoals($iMax));
  454. $this->assertCount($iMax, $oReports->getGoals($oFilter)['goals']);
  455. $aFunnel = $oReports->getFunnels($oFilter, ['funnel' => $iFunnel]);
  456. $this->assertSame($iFunnel, $aFunnel['funnel']['id']);
  457. $this->assertSame([2, 2, 1], array_column($aFunnel['steps'], 'sessions'), 'a step counts only after the previous one');
  458. $this->assertEquals([100, 100, 50], array_column($aFunnel['steps'], 'rate'));
  459. $this->assertEquals([null, 0, 50], array_column($aFunnel['steps'], 'drop'));
  460. $this->assertTrue($oDb->deleteGoal($iBuy));
  461. $this->assertFalse((bool)$oDb->getGoal($iBuy));
  462. $this->assertTrue($oDb->deleteFunnel($iFunnel));
  463. $this->assertNotContains($iFunnel, array_column($oReports->getFunnels($oFilter)['funnels'], 'id'), 'a deleted funnel is not listed');
  464. }
  465. public function testHitsPerMinuteLimit()
  466. {
  467. $this->_setOption('bx_analytics_limit_hits', '5');
  468. $this->_setOption('bx_analytics_limit_visits', '0');
  469. $aServer = $this->_server('81.2.69.142');
  470. $fPayload = function ($iHits, $sPage = 'a') {
  471. return ['platform' => 'core-web', 'hits' => array_fill(0, $iHits, ['type' => 'pageview', 'url' => 'http://una.test/' . $sPage])];
  472. };
  473. // NOW is 40 seconds into its minute: NOW + 19 is the same minute, NOW + 20 the next
  474. $this->assertSame(3, $this->_collect($aServer, $fPayload(3), self::NOW));
  475. $this->assertSame(2, $this->_collect($aServer, $fPayload(2), self::NOW + 10), 'up to the limit');
  476. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW + 19);
  477. $this->assertSame(0, $oCollector->collect($fPayload(1, 'over'), ['platform' => 'api']), 'over the limit');
  478. $this->assertTrue($oCollector->isLimited());
  479. $this->assertContains('rate_limited', $oCollector->check($fPayload(1), ['platform' => 'api'])['reasons'], 'the Setup check tells');
  480. $this->assertSame(1, $this->_collect($this->_server('93.184.216.34'), $fPayload(1), self::NOW + 19), 'another address has its own limit');
  481. // site actions and server events are not limited
  482. $this->assertTrue($oCollector->collectAction('signup', 'account', 1, 0, ['platform' => 'core-web']));
  483. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW + 20);
  484. $this->assertSame(1, $oCollector->collect($fPayload(1, 'next'), ['platform' => 'api']), 'a new minute counts anew');
  485. $this->assertFalse($oCollector->isLimited());
  486. $aPaths = BxDolDb::getInstance()->getColumn("SELECT `path` FROM `bx_analytics_events` WHERE `ts` < :to AND `type` = 'pageview'", ['to' => self::NOW + 86400]);
  487. $this->assertNotContains('/over', $aPaths);
  488. $this->assertContains('/next', $aPaths);
  489. $this->assertSame(6, (int)$this->_sessions()[0]['pageviews'], 'the dropped hit is not in the visit');
  490. // the counters keep no address
  491. $aRows = BxDolDb::getInstance()->getAll("SELECT * FROM `bx_analytics_limits` WHERE `bucket` < 1009843200 ORDER BY `bucket`, `hits`");
  492. $this->assertSame([[self::NOW - 40, 1], [self::NOW - 40, 6], [self::NOW + 20, 1]], array_map(function ($a) { return [(int)$a['bucket'], (int)$a['hits']]; }, $aRows), 'dropped hits count too');
  493. foreach ($aRows as $a)
  494. $this->assertSame(8, strlen($a['key']));
  495. }
  496. public function testVisitsPerHourLimit()
  497. {
  498. $this->_setOption('bx_analytics_limit_hits', '0');
  499. $this->_setOption('bx_analytics_limit_visits', '2');
  500. $this->_setOption('bx_analytics_track_errors', 'on');
  501. $aHit = ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/'], ['type' => 'error', 'url' => 'http://una.test/', 'kind' => 'js', 'message' => 'Test 2001 limited error', 'stack' => "Error: x\n at f (/js/app.js:1:1)"]]];
  502. // a script that changes its user agent with every request
  503. $this->assertSame(2, $this->_collect($this->_server('81.2.69.142', [], self::UA_SAFARI . ' a'), $aHit, self::NOW));
  504. $this->assertSame(2, $this->_collect($this->_server('81.2.69.142', [], self::UA_SAFARI . ' b'), $aHit, self::NOW + 1));
  505. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('81.2.69.142', [], self::UA_SAFARI . ' c')), self::NOW + 2);
  506. $this->assertSame(0, $oCollector->collect($aHit, ['platform' => 'api']), 'a third visit in the hour');
  507. $this->assertTrue($oCollector->isLimited());
  508. $this->assertSame(0, (int)BxDolDb::getInstance()->getOne("SELECT COUNT(*) FROM `bx_analytics_error_hits` WHERE `ts` < :to AND `session_id` = 0", ['to' => self::NOW + 86400]), 'its errors are dropped too');
  509. $this->assertSame(1, $this->_collect($this->_server('81.2.69.142', [], self::UA_SAFARI . ' a'), ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/b']]], self::NOW + 3), 'a running visit goes on');
  510. $this->assertCount(2, $this->_sessions());
  511. // NOW is 2800 seconds into its hour
  512. $this->assertSame(2, $this->_collect($this->_server('81.2.69.142', [], self::UA_SAFARI . ' c'), $aHit, self::NOW + 800), 'a new hour counts anew');
  513. $this->assertCount(3, $this->_sessions());
  514. }
  515. public function testLimitAddresses()
  516. {
  517. $this->_setOption('bx_analytics_limit_hits', '2');
  518. $aHit = ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]];
  519. // one IPv6 /64 network is one address
  520. $this->assertSame(1, $this->_collect($this->_server('2001:db8:1:2::1'), $aHit, self::NOW));
  521. $this->assertSame(1, $this->_collect($this->_server('2001:db8:1:2::ffff'), $aHit, self::NOW));
  522. $this->assertSame(0, $this->_collect($this->_server('2001:db8:1:2:abcd::5'), $aHit, self::NOW));
  523. $this->assertSame(1, $this->_collect($this->_server('2001:db8:1:3::1'), $aHit, self::NOW), 'another network');
  524. // an IPv4 address written as IPv6 is that address
  525. $this->assertSame(1, $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW));
  526. $this->assertSame(1, $this->_collect($this->_server('::ffff:81.2.69.142'), $aHit, self::NOW));
  527. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW));
  528. // a bot that runs the tracker is limited too: no bot rows past the limit
  529. $sBot = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
  530. $this->_collect($this->_server('93.184.216.34', [], $sBot), $aHit, self::NOW);
  531. $this->_collect($this->_server('93.184.216.34', [], $sBot), $aHit, self::NOW);
  532. $this->_collect($this->_server('93.184.216.34', [], $sBot), $aHit, self::NOW);
  533. $this->assertSame(2, (int)BxDolDb::getInstance()->getOne("SELECT SUM(`hits`) FROM `bx_analytics_bots` WHERE `day` < '2002-01-01'"));
  534. $this->_setOption('bx_analytics_limit_hits', '0');
  535. $this->assertSame(1, $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW), 'no limit');
  536. }
  537. public function testLimitsArePruned()
  538. {
  539. $this->_setOption('bx_analytics_limit_hits', '100');
  540. $this->_setOption('bx_analytics_limit_visits', '100');
  541. $this->_collect($this->_server('81.2.69.142'), ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]], self::NOW);
  542. $fCount = function () {
  543. return (int)BxDolDb::getInstance()->getOne("SELECT COUNT(*) FROM `bx_analytics_limits` WHERE `bucket` < 1009843200");
  544. };
  545. $this->assertSame(2, $fCount(), 'a minute of hits and an hour of visits');
  546. $oDb = $this->_oModule->_oDb;
  547. $oDb->deleteLimitsBefore($this->_oModule->getPruningCutoffs(self::NOW + 3600)['deleteLimitsBefore'], 100);
  548. $this->assertSame(2, $fCount(), 'kept for 2 hours');
  549. // NOW is 40 seconds into its minute and 2800 seconds into its hour
  550. $oDb->deleteLimitsBefore($this->_oModule->getPruningCutoffs(self::NOW + 4401)['deleteLimitsBefore'], 100);
  551. $this->assertSame(1, $fCount(), 'the hour goes once it started over 2 hours ago, the later minute is kept');
  552. $oDb->deleteLimitsBefore($this->_oModule->getPruningCutoffs(self::NOW + 7200)['deleteLimitsBefore'], 100);
  553. $this->assertSame(0, $fCount());
  554. }
  555. protected function _collect($aServer, $aPayload, $iNow, $aContext = [])
  556. {
  557. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), $iNow);
  558. return $oCollector->collect($aPayload, $aContext + ['platform' => 'api']);
  559. }
  560. protected function _filter($aParams)
  561. {
  562. return new BxAnalyticsFilter($this->_oModule, $aParams, self::NOW + 86400);
  563. }
  564. protected function _server($sIp, $aExtra = [], $sUserAgent = self::UA_SAFARI)
  565. {
  566. return array_merge(['REMOTE_ADDR' => $sIp, 'HTTP_USER_AGENT' => $sUserAgent], $aExtra);
  567. }
  568. protected function _sessions()
  569. {
  570. return BxDolDb::getInstance()->getAll("SELECT * FROM `bx_analytics_sessions` WHERE `started` < :to ORDER BY `id`", ['to' => self::NOW + 30 * 86400]);
  571. }
  572. protected function _setOption($sName, $sValue)
  573. {
  574. if (!array_key_exists($sName, $this->_aOptions))
  575. $this->_aOptions[$sName] = getParam($sName);
  576. setParam($sName, $sValue);
  577. }
  578. protected function _cleanup()
  579. {
  580. $oDb = BxDolDb::getInstance();
  581. $iTo = self::NOW + 30 * 86400;
  582. $oDb->query("DELETE FROM `bx_analytics_events` WHERE `ts` < :to", ['to' => $iTo]);
  583. $oDb->query("DELETE FROM `bx_analytics_sessions` WHERE `started` < :to", ['to' => $iTo]);
  584. $oDb->query("DELETE FROM `bx_analytics_salts` WHERE `day` < '2002-01-01'");
  585. $oDb->query("DELETE FROM `bx_analytics_limits` WHERE `bucket` < 1009843200");
  586. $this->_oModule->cleanReportCache(); // reports of the test data cached by the run before
  587. $oDb->query("DELETE FROM `bx_analytics_error_hits` WHERE `ts` < :to", ['to' => $iTo]);
  588. $oDb->query("DELETE FROM `bx_analytics_errors` WHERE `message` = 'Test 2001 limited error'");
  589. $oDb->query("DELETE FROM `bx_analytics_bots` WHERE `day` < '2002-01-01'");
  590. $oDb->query("DELETE FROM `bx_analytics_bot_pages` WHERE `day` < '2002-01-01'");
  591. foreach ($this->_aGoals as $iId)
  592. $this->_oModule->_oDb->deleteGoal($iId);
  593. foreach ($this->_aFunnels as $iId)
  594. $this->_oModule->_oDb->deleteFunnel($iId);
  595. $this->_aGoals = $this->_aFunnels = [];
  596. }
  597. }