1
0

AnalyticsCollectorTest.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. $oDb = BxDolDb::getInstance();
  136. $this->_collect($aServer, $aHit, self::NOW);
  137. $this->_collect($aServer, ['platform' => 'next-web', 'hits' => [['type' => 'event', 'url' => 'https://neo.test/', 'name' => 'cta_click']]], self::NOW + 5);
  138. $sGuestVisitor = $oDb->getOne("SELECT `visitor` FROM `bx_analytics_events` WHERE `ts` = :ts", ['ts' => self::NOW]);
  139. $this->_collect($aServer, $aHit, self::NOW + 30, ['profile_id' => $iProfileId]);
  140. $aSessions = $this->_sessions();
  141. $this->assertCount(1, $aSessions, 'signing in continues the visit');
  142. $this->assertSame($iProfileId, (int)$aSessions[0]['profile_id']);
  143. $sMemberVisitor = $aSessions[0]['visitor'];
  144. $this->assertNotSame($sMemberVisitor, $sGuestVisitor);
  145. $aBefore = $oDb->getAll("SELECT `visitor`, `profile_id` FROM `bx_analytics_events` WHERE `ts` < :ts ORDER BY `id`", ['ts' => self::NOW + 30]);
  146. $this->assertCount(2, $aBefore);
  147. foreach ($aBefore as $a)
  148. $this->assertSame([$sMemberVisitor, $iProfileId], [$a['visitor'], (int)$a['profile_id']], 'what happened before signing in is the member\'s too');
  149. // one visit is one person in the page and event reports, and the member's actions include those before signing in
  150. $aFilter = $this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'])->get();
  151. $aPages = $this->_oModule->_oDb->getPageStats($aFilter, 'path', 10);
  152. $this->assertSame([['/', 1, 2]], array_map(function ($a) { return [$a['value'], (int)$a['visitors'], (int)$a['pageviews']]; }, $aPages));
  153. $aActions = $this->_oModule->_oDb->getMemberActions($iProfileId, $aFilter);
  154. $this->assertSame([['cta_click', 1]], array_map(function ($a) { return [$a['name'], (int)$a['count']]; }, $aActions));
  155. // site actions about the account and the profile, and another visit days later
  156. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer + ['REQUEST_METHOD' => 'POST']), self::NOW + 40);
  157. $this->assertTrue($oCollector->collectAction('login', 'account', 4242, $iProfileId, ['platform' => 'next-web']));
  158. $this->assertTrue($oCollector->collectAction('profile_add', 'bx_persons', $iProfileId, $iProfileId, ['platform' => 'next-web']));
  159. $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW + 2 * 86400, ['profile_id' => $iProfileId]);
  160. $this->assertCount(2, $this->_sessions());
  161. $this->_oModule->onProfileDelete($iProfileId);
  162. $aSessions = $this->_sessions();
  163. $this->assertSame([0, 0], array_map('intval', array_column($aSessions, 'profile_id')));
  164. $this->assertNotSame($sMemberVisitor, $aSessions[0]['visitor']);
  165. $this->assertNotSame($aSessions[0]['visitor'], $aSessions[1]['visitor'], 'its visits are not tied to one another');
  166. $this->assertSame(0, (int)$oDb->getOne("SELECT COUNT(*) FROM `bx_analytics_events` WHERE `profile_id` = :p", ['p' => $iProfileId]));
  167. $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]);
  168. $this->assertCount(6, $aEvents);
  169. foreach ($aEvents as $a) {
  170. $this->assertSame($a['session_visitor'], $a['visitor'], 'every event is its visit\'s, the one before signing in too');
  171. $this->assertNotContains($a['visitor'], [$sMemberVisitor, $sGuestVisitor]);
  172. }
  173. $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');
  174. // the profile's creation is found by a key, not among every profile created
  175. $aKey = $oDb->getAll("SHOW INDEX FROM `bx_analytics_events` WHERE `Key_name` = 'object'");
  176. $this->assertSame(['type', 'name', 'object_id'], array_column($aKey, 'Column_name'));
  177. $aPlan = $oDb->getRow("EXPLAIN SELECT `id` FROM `bx_analytics_events` WHERE `type` = 'una' AND `name` = 'profile_add' AND `object_id` = :profile", ['profile' => $iProfileId]);
  178. $this->assertContains('object', explode(',', (string)$aPlan['possible_keys']));
  179. }
  180. public function testSignInTakesOverOnlyARecentGuestVisit()
  181. {
  182. $aHit = ['platform' => 'next-web', 'hits' => [['type' => 'pageview', 'url' => 'https://neo.test/']]];
  183. $fProfiles = function () {
  184. return array_map('intval', array_column($this->_sessions(), 'profile_id'));
  185. };
  186. // someone else behind the same address with the same browser, 10 minutes before
  187. $aServer = $this->_server('93.184.216.34');
  188. $this->_collect($aServer, $aHit, self::NOW);
  189. $this->_collect($aServer, $aHit, self::NOW + 600, ['profile_id' => 987654321]);
  190. $this->assertSame([0, 987654321], $fProfiles(), 'a member doesn\'t take over an older guest visit');
  191. $aGuestEvents = BxDolDb::getInstance()->getAll("SELECT `visitor`, `profile_id` FROM `bx_analytics_events` WHERE `session_id` = :id", ['id' => $this->_sessions()[0]['id']]);
  192. $this->assertSame([[$this->_sessions()[0]['visitor'], 0]], array_map(function ($a) { return [$a['visitor'], (int)$a['profile_id']]; }, $aGuestEvents), 'nor its events');
  193. // the member's own visit comes first, while the guest's goes on
  194. $this->_collect($aServer, $aHit, self::NOW + 700);
  195. $this->_collect($aServer, $aHit, self::NOW + 720, ['profile_id' => 987654321]);
  196. $this->assertSame([0, 987654321], $fProfiles());
  197. $this->assertSame([2, 2], array_map('intval', array_column($this->_sessions(), 'pageviews')));
  198. // a guest visit active right before is the member's: they signed in during it
  199. $this->_collect($this->_server('93.184.216.35'), $aHit, self::NOW + 1000);
  200. $this->_collect($this->_server('93.184.216.35'), $aHit, self::NOW + 1060, ['profile_id' => 987654322]);
  201. $this->assertSame([0, 987654321, 987654322], $fProfiles());
  202. // a visitor id kept by the device is the device's own, however long ago
  203. $this->_setOption('bx_analytics_identity', 'persistent');
  204. $aDevice = $aHit + ['vid' => 'phpunit-device-0001'];
  205. $this->_collect($this->_server('93.184.216.36'), $aDevice, self::NOW + 2000);
  206. $this->_collect($this->_server('93.184.216.36'), $aDevice, self::NOW + 2900, ['profile_id' => 987654323]);
  207. $this->assertSame([0, 987654321, 987654322, 987654323], $fProfiles());
  208. }
  209. public function testSignInActionTakesOverTheGuestVisit()
  210. {
  211. $iProfileId = 987654321;
  212. $aServer = $this->_server('93.184.216.34');
  213. $this->_collect($aServer, ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/login']]], self::NOW);
  214. // the sign-in request records the action before the member's first page
  215. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer + ['REQUEST_METHOD' => 'POST']), self::NOW + 10);
  216. $this->assertTrue($oCollector->collectAction('login', 'account', 4242, $iProfileId, ['platform' => 'core-web']));
  217. $aSessions = $this->_sessions();
  218. $this->assertCount(1, $aSessions);
  219. $this->assertSame($iProfileId, (int)$aSessions[0]['profile_id']);
  220. $this->assertSame(1, (int)$aSessions[0]['events']);
  221. $aEvents = BxDolDb::getInstance()->getAll("SELECT `session_id`, `visitor`, `profile_id` FROM `bx_analytics_events` WHERE `ts` < :to ORDER BY `id`", ['to' => self::NOW + 86400]);
  222. $this->assertCount(2, $aEvents);
  223. foreach ($aEvents as $a)
  224. $this->assertSame([(int)$aSessions[0]['id'], $aSessions[0]['visitor'], $iProfileId], [(int)$a['session_id'], $a['visitor'], (int)$a['profile_id']]);
  225. }
  226. public function testPersistentSiteActionsJoinTheDeviceVisit()
  227. {
  228. $this->_setOption('bx_analytics_identity', 'persistent');
  229. $iProfileId = 987654321;
  230. $sVid = 'phpunit-device-0002';
  231. $aHit = ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]];
  232. $oDb = BxDolDb::getInstance();
  233. $this->_collect($this->_server('93.184.216.40'), $aHit + ['vid' => $sVid], self::NOW);
  234. // another guest behind the same address with the same browser, and no visitor id
  235. $this->_collect($this->_server('93.184.216.40'), $aHit, self::NOW + 1);
  236. $aSessions = $this->_sessions();
  237. $this->assertCount(2, $aSessions);
  238. $iDevice = (int)$aSessions[0]['id'];
  239. // the site's own requests carry the id in the classic tracker's cookie; signing in
  240. // comes later than a guest visit is taken over by address and browser
  241. $aServer = $this->_server('93.184.216.40', ['REQUEST_METHOD' => 'POST', 'HTTP_COOKIE' => 'bx_analytics_vid=' . $sVid]);
  242. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW + 10);
  243. $this->assertTrue($oCollector->collectAction('signup', 'account', 1, 0, ['platform' => 'core-web']));
  244. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW + 300);
  245. $this->assertTrue($oCollector->collectAction('login', 'account', 1, $iProfileId, ['platform' => 'core-web']));
  246. // without the cookie, from elsewhere: the device's visit isn't found
  247. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('93.184.216.41', ['REQUEST_METHOD' => 'POST'])), self::NOW + 20);
  248. $this->assertTrue($oCollector->collectAction('vote', 'bx_posts', 5, 0, ['platform' => 'core-web']));
  249. $aEvents = $oDb->getPairs("SELECT `name`, `session_id` FROM `bx_analytics_events` WHERE `type` = 'una' AND `ts` < :to ORDER BY `ts`", 'name', 'session_id', ['to' => self::NOW + 86400]);
  250. $this->assertSame(['signup' => $iDevice, 'vote' => 0, 'login' => $iDevice], array_map('intval', $aEvents));
  251. $aSessions = $this->_sessions();
  252. $this->assertSame([2, 0], array_map('intval', array_column($aSessions, 'events')), 'not the other guest\'s visit');
  253. $this->assertSame([$iProfileId, 0], array_map('intval', array_column($aSessions, 'profile_id')), 'signing in on the device takes its visit over');
  254. $aFunnel = $this->_oModule->_oDb->getFunnelCounts($this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'])->get(), [['type' => 'page', 'pattern' => '/'], ['type' => 'event', 'pattern' => 'signup']]);
  255. $this->assertSame([2, 1], $aFunnel);
  256. }
  257. public function testSecretsAreNotStored()
  258. {
  259. $aServer = $this->_server('81.2.69.142');
  260. $aUrls = [
  261. 'http://una.test/page.php?i=forgot-password&key=abcDEF1234567890xyz',
  262. 'http://una.test/page.php?i=confirm-email&code=0123456789abcdef',
  263. 'http://una.test/page.php?i=unsubscribe-notifications&id=42&code=5f4dcc3b5aa765d61d8327deb882cf99',
  264. 'http://una.test/page/oauth-callback?code=4%2F0AX4XfWh&state=xyz&access_token=ya29.secret',
  265. 'http://una.test/page/invite?Email=jane%40example.com&api_key=k1&_hsenc=p2ANqtz',
  266. 'http://una.test/create-account?icode=Ab3kP9xQ&lang=en',
  267. 'http://una.test/page.php?i=pricing&promocode=SPRING26&apikey=k2&user_sid=9',
  268. 'http://una.test/page/search?q=jane%40example.com',
  269. ];
  270. foreach ($aUrls as $i => $sUrl)
  271. $this->_collect($aServer, ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => $sUrl]]], self::NOW + $i * 10);
  272. $aPaths = BxDolDb::getInstance()->getColumn("SELECT `path` FROM `bx_analytics_events` WHERE `ts` < :to ORDER BY `id`", ['to' => self::NOW + 86400]);
  273. $this->assertSame([
  274. '/page.php?i=forgot-password',
  275. '/page.php?i=confirm-email',
  276. '/page.php?i=unsubscribe-notifications&id=42',
  277. '/page/oauth-callback?state=xyz',
  278. '/page/invite',
  279. '/create-account?lang=en',
  280. '/page.php?i=pricing',
  281. '/page/search?q=<redacted>',
  282. ], $aPaths, 'keys, codes, tokens and addresses are dropped; what is left is redacted');
  283. $aSession = $this->_sessions()[0];
  284. $this->assertSame(['/page.php?i=forgot-password', '/page/search?q=<redacted>'], [$aSession['entry_path'], $aSession['exit_path']]);
  285. // link previews and mail scanners fetch these links too
  286. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('66.249.66.1')), self::NOW);
  287. $this->assertTrue($oCollector->collectBot('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', '/page.php?i=forgot-password&key=abcDEF1234567890xyz'));
  288. $this->assertSame(['/page.php?i=forgot-password'], BxDolDb::getInstance()->getColumn("SELECT `path` FROM `bx_analytics_bot_pages` WHERE `day` < '2002-01-01'"));
  289. }
  290. public function testLocationFromTheChosenEdge()
  291. {
  292. // behind Vercel, a visitor sends Cloudflare's country header too
  293. $aHeaders = ['HTTP_CF_IPCOUNTRY' => 'KP', 'HTTP_X_VERCEL_IP_COUNTRY' => 'DE', 'HTTP_X_VERCEL_IP_CITY' => 'Berlin'];
  294. $aHit = ['platform' => 'next-web', 'hits' => [['type' => 'pageview', 'url' => 'https://neo.test/']]];
  295. foreach (['vercel', 'headers', 'none'] as $i => $sSource) {
  296. $this->_setOption('bx_analytics_geo_source', $sSource);
  297. $this->_collect($this->_server('81.2.69.' . (150 + $i), $aHeaders), $aHit, self::NOW + $i * 10);
  298. }
  299. $aSessions = $this->_sessions();
  300. $this->assertSame([['DE', 'Berlin'], ['KP', 'Berlin'], ['', '']], array_map(function ($a) { return [$a['country'], $a['city']]; }, $aSessions));
  301. }
  302. public function testSiteActionsFollowTheVisitorsChoice()
  303. {
  304. $fAction = function ($aExtra = [], $sUserAgent = self::UA_SAFARI, $iProfileId = 987654321) {
  305. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('81.2.69.142', ['REQUEST_METHOD' => 'POST'] + $aExtra, $sUserAgent)), self::NOW);
  306. return $oCollector->collectAction('login', 'account', 1, $iProfileId, ['platform' => 'core-web']);
  307. };
  308. $this->assertFalse($fAction(['HTTP_DNT' => '1']), 'Do Not Track');
  309. $this->assertFalse($fAction(['HTTP_SEC_GPC' => '1']), 'Global Privacy Control');
  310. $this->assertFalse($fAction([], 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'), 'a bot');
  311. $this->_setOption('bx_analytics_exclude_ips', '81.2.69.0/24');
  312. $this->assertFalse($fAction(), 'an excluded address');
  313. $this->_setOption('bx_analytics_exclude_ips', '');
  314. $this->assertTrue($fAction());
  315. // a cron job has no visitor request: its headers don't apply
  316. $oCron = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest([]), self::NOW);
  317. $this->assertTrue($oCron->collectAction('renewal', 'account', 1, 987654321));
  318. // a guest's action, when guests aren't tracked
  319. $this->_setOption('bx_analytics_exclude_levels', (string)MEMBERSHIP_ID_NON_MEMBER);
  320. $this->assertFalse($fAction([], self::UA_SAFARI, 0));
  321. $this->assertSame(2, (int)BxDolDb::getInstance()->getOne("SELECT COUNT(*) FROM `bx_analytics_events` WHERE `type` = 'una' AND `ts` < :to", ['to' => self::NOW + 86400]));
  322. }
  323. public function testLargeCollectBodiesAreNotRead()
  324. {
  325. $iMax = $this->_oModule->_oConfig->CNF['MAX_COLLECT_BYTES'];
  326. $sPath = '/phpunit-collect-size';
  327. $fPayload = function ($iTitle) use ($sPath) {
  328. return json_encode(['platform' => 'api', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test' . $sPath, 'title' => str_repeat('a', $iTitle)]]]);
  329. };
  330. $this->assertTrue($this->_oModule->isCollectBodyAllowed($fPayload(100)));
  331. $this->assertFalse($this->_oModule->isCollectBodyAllowed($fPayload($iMax)));
  332. // the service stores now, with the request's own address: the rows are deleted after
  333. $oDb = BxDolDb::getInstance();
  334. try {
  335. $this->assertSame(['stored' => 0], $this->_oModule->serviceCollect($fPayload($iMax)), 'too large: refused before it is decoded');
  336. $this->assertSame(0, (int)$oDb->getOne("SELECT COUNT(*) FROM `bx_analytics_events` WHERE `path` = :path", ['path' => $sPath]));
  337. $this->assertSame(['stored' => 1], $this->_oModule->serviceCollect($fPayload(100)), 'the same hit, small enough');
  338. }
  339. finally {
  340. $oDb->query("DELETE FROM `bx_analytics_sessions` WHERE `entry_path` = :path AND `started` > :since", ['path' => $sPath, 'since' => time() - 3600]);
  341. $oDb->query("DELETE FROM `bx_analytics_events` WHERE `path` = :path AND `ts` > :since", ['path' => $sPath, 'since' => time() - 3600]);
  342. }
  343. }
  344. public function testCookielessVisitorsChangeDaily()
  345. {
  346. $aServer = $this->_server('93.184.216.34');
  347. $aHit = ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]];
  348. $this->_collect($aServer, $aHit, self::NOW);
  349. $this->_collect($aServer, $aHit, self::NOW + 2 * 86400);
  350. $aSessions = $this->_sessions();
  351. $this->assertCount(2, $aSessions);
  352. $this->assertNotSame($aSessions[0]['visitor'], $aSessions[1]['visitor']);
  353. }
  354. public function testReports()
  355. {
  356. // two visitors: one bounces from a search, one views two pages on iOS
  357. $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);
  358. $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);
  359. $aParams = ['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'];
  360. $aOverview = $this->_oModule->getReports()->getOverview($this->_filter($aParams));
  361. $this->assertSame(2, $aOverview['kpis']['visitors']['value']);
  362. $this->assertSame(3, $aOverview['kpis']['pageviews']['value']);
  363. $this->assertEquals(50, $aOverview['kpis']['bounce_rate']['value']);
  364. $this->assertSame('hour', $aOverview['bucket']);
  365. $this->assertSame(24, count($aOverview['series']));
  366. $aIos = $this->_oModule->getReports()->getOverview($this->_filter($aParams + ['platform' => 'rn-ios']));
  367. $this->assertSame(1, $aIos['kpis']['visitors']['value']);
  368. $aPages = $this->_oModule->getReports()->getTop($this->_filter($aParams), ['group' => 'pages', 'tab' => 'pages']);
  369. $this->assertSame(['/a', '/b'], array_column($aPages['items'], 'value'));
  370. $this->assertSame([2, 1], array_column($aPages['items'], 'visitors'));
  371. $aChannels = $this->_oModule->getReports()->getTop($this->_filter($aParams + ['f' => ['path' => '/b']]), ['group' => 'sources', 'tab' => 'channels']);
  372. $this->assertSame(['direct'], array_column($aChannels['items'], 'value'), 'a page filter keeps the sessions that saw it');
  373. $aPlatforms = $this->_oModule->getReports()->getTop($this->_filter($aParams), ['group' => 'platforms', 'tab' => 'platforms']);
  374. $this->assertEqualsCanonicalizing(['core-web', 'rn-ios'], array_column($aPlatforms['items'], 'value'));
  375. $aTable = $this->_oModule->getReports()->getTable($this->_filter($aParams), ['table' => 'pages']);
  376. $this->assertSame(['/a', '/b'], array_column($aTable['rows'], 'label'));
  377. $this->assertSame(2, $aTable['rows'][0]['values']['entries'], 'both sessions entered on /a');
  378. $this->assertSame(1, $aTable['rows'][0]['values']['exits'], 'the one-page session left from /a');
  379. $this->assertEquals(50, $aTable['rows'][0]['values']['bounce_rate']);
  380. $this->assertSame(2, $aTable['total']);
  381. $this->assertFalse($this->_oModule->getReports()->getTable($this->_filter($aParams), ['table' => 'nope']));
  382. $this->assertFalse($this->_oModule->getReportData('nope', $aParams), 'unknown reports are refused');
  383. }
  384. public function testBotsAreCountedApart()
  385. {
  386. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('66.249.66.1')), self::NOW);
  387. $this->assertTrue($oCollector->collectBot('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', '/page/explore?utm_source=x'));
  388. $this->assertTrue($oCollector->collectBot('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', '/page/explore'));
  389. $this->assertTrue($oCollector->collectBot('Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ChatGPT-User/1.0; +https://openai.com/bot)', '/'));
  390. $this->assertFalse($oCollector->collectBot(self::UA_SAFARI, '/'), 'browsers are not bots');
  391. // a headless browser that runs the tracker is a bot, not a visit
  392. $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));
  393. $this->assertCount(0, $this->_sessions());
  394. $aFilter = $this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'])->get();
  395. $this->assertEquals(['hits' => 4, 'bots' => 3], $this->_oModule->_oDb->getBotTotals($aFilter));
  396. $this->assertEquals(['hits' => 1, 'bots' => 1], $this->_oModule->_oDb->getBotTotals($aFilter, ['ai_agent']));
  397. $aPages = $this->_oModule->_oDb->getBotPages($aFilter, ['search'], 10);
  398. $this->assertEquals([['path' => '/page/explore', 'hits' => 2]], $aPages, 'campaign tags are not part of the path');
  399. $aReport = $this->_oModule->getReports()->getBots($this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09']), ['tab_bots' => 'ai']);
  400. $this->assertSame('ai', $aReport['tab']);
  401. $this->assertSame(['ChatGPT'], array_column($aReport['bots']['rows'], 'label'));
  402. }
  403. public function testSiteActionsJoinTheVisit()
  404. {
  405. $iProfileId = 987654321;
  406. $aServer = $this->_server('93.184.216.34', ['REQUEST_METHOD' => 'POST']);
  407. $this->_collect($aServer, ['platform' => 'rn-ios', 'app' => 'com.neo.so', 'hits' => [['type' => 'pageview', 'url' => '/page/create-post']]], self::NOW, ['profile_id' => $iProfileId]);
  408. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW + 20);
  409. $this->assertTrue($oCollector->collectAction('content_add', 'bx_posts', 77, $iProfileId, ['platform' => 'rn-ios']));
  410. // a renewal by cron has no visit and runs on the server's own platform
  411. $oCron = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest([]), self::NOW + 30);
  412. $this->assertTrue($oCron->collectAction('login', 'account', 1, $iProfileId));
  413. $aSessions = $this->_sessions();
  414. $this->assertCount(1, $aSessions);
  415. $this->assertSame(1, (int)$aSessions[0]['events']);
  416. $this->assertSame(0, (int)$aSessions[0]['bounce'], 'doing something is not a bounce');
  417. $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]);
  418. $this->assertEquals([
  419. ['session_id' => $aSessions[0]['id'], 'type' => 'una', 'name' => 'content_add', 'module' => 'bx_posts', 'object_id' => 77, 'platform' => 'rn-ios'],
  420. ['session_id' => 0, 'type' => 'una', 'name' => 'login', 'module' => 'account', 'object_id' => 1, 'platform' => 'core'],
  421. ], $aEvents);
  422. $aParams = ['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'];
  423. $oReports = $this->_oModule->getReports();
  424. $aList = $oReports->getEvents($this->_filter($aParams), ['tab_events' => 'site']);
  425. $this->assertSame('list', $aList['view']);
  426. $this->assertCount(2, $aList['rows']);
  427. $aDetail = $oReports->getEvents($this->_filter($aParams), ['event' => 'una|content_add|bx_posts']);
  428. $this->assertSame('detail', $aDetail['view']);
  429. $this->assertSame(1, $aDetail['tiles'][0]['value']);
  430. $this->assertSame([['label' => $oReports->getLabel('platform', 'rn-ios'), 'count' => 1, 'share' => 100.0]], $aDetail['platforms']);
  431. $this->assertNull($oReports->getEvents($this->_filter($aParams), ['event' => 'pageview|x|y'])['event'] ?? null, 'pageviews are not events');
  432. $aSessionsList = $oReports->getSessions($this->_filter($aParams));
  433. $this->assertCount(1, $aSessionsList['rows']);
  434. $aSessionDetail = $oReports->getSessions($this->_filter($aParams), ['session' => $aSessions[0]['id']]);
  435. $this->assertSame(['pageview', 'una'], array_column($aSessionDetail['timeline'], 'type'));
  436. $this->assertSame(20, $aSessionDetail['timeline'][1]['offset']);
  437. $aUsers = $oReports->getUsers($this->_filter($aParams));
  438. $this->assertSame(1, count($aUsers['rows']));
  439. $this->assertSame(['param' => 'user', 'value' => $iProfileId], $aUsers['rows'][0]['open']);
  440. }
  441. public function testJourneysAndRetention()
  442. {
  443. // three members' visits: / -> /a -> /b, / -> /a -> /c, / -> /d, the first coming back a week later
  444. $aVisits = [
  445. [987654321, self::NOW, ['/', '/a', '/b']],
  446. [987654322, self::NOW + 100, ['/', '/a', '/a', '/c']],
  447. [987654323, self::NOW + 200, ['/', '/d']],
  448. [987654321, self::NOW + 7 * 86400, ['/']],
  449. ];
  450. foreach ($aVisits as list($iProfileId, $iTime, $aPages))
  451. foreach ($aPages as $i => $sPage)
  452. $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]);
  453. $oReports = $this->_oModule->getReports();
  454. $oFilter = $this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09']);
  455. $aJourneys = $oReports->getJourneys($oFilter);
  456. $this->assertSame('/', $aJourneys['jfrom'], 'the top entry page by default');
  457. $this->assertSame(3, $aJourneys['from_sessions']);
  458. $this->assertSame([['page' => '/a', 'sessions' => 2, 'share' => 66.7], ['page' => '/d', 'sessions' => 1, 'share' => 33.3]], $aJourneys['next']);
  459. $aVia = $oReports->getJourneys($oFilter, ['via' => '/a']);
  460. $this->assertEqualsCanonicalizing(['/b', '/c'], array_column($aVia['after'], 'page'), 'a page reloaded in place counts once');
  461. // the start page has its own param, so it doesn't break a custom date range
  462. $aRequest = ['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09', 'jfrom' => '/a'];
  463. $oRequestFilter = $this->_filter($aRequest);
  464. $this->assertSame($oFilter->get()['from'], $oRequestFilter->get()['from'], 'jfrom keeps the custom range');
  465. $this->assertSame($oFilter->get()['to'], $oRequestFilter->get()['to']);
  466. $aFromA = $oReports->getJourneys($oRequestFilter, $aRequest);
  467. $this->assertSame('/a', $aFromA['jfrom']);
  468. $this->assertSame(2, $aFromA['from_sessions']);
  469. $aPaths = array_map(function ($a) { return implode(' ', $a['pages']); }, $aJourneys['paths']);
  470. $this->assertContains('/ /a /b', $aPaths);
  471. $aRetention = $oReports->getRetention(new BxAnalyticsFilter($this->_oModule, ['range' => '7d'], self::NOW + 8 * 86400));
  472. $aCohorts = array_values(array_filter($aRetention['rows'], function ($a) { return $a['size'] > 0; }));
  473. $this->assertCount(1, $aCohorts);
  474. $this->assertSame(3, $aCohorts[0]['size']);
  475. $this->assertEquals(100, $aCohorts[0]['weeks'][0]);
  476. $this->assertEquals(33.3, $aCohorts[0]['weeks'][1], 'one of three came back the next week');
  477. }
  478. public function testGoalsAndFunnels()
  479. {
  480. $oDb = $this->_oModule->_oDb;
  481. $iPricing = $oDb->saveGoal(0, ['name' => 'Test 2001 pricing', 'type' => 'page', 'pattern' => '/pricing*']);
  482. $iBuy = $oDb->saveGoal(0, ['name' => 'Test 2001 buy', 'type' => 'event', 'pattern' => 'buy']);
  483. $iFunnel = $oDb->saveFunnel(0, 'Test 2001 funnel', [
  484. ['type' => 'page', 'pattern' => '/'],
  485. ['type' => 'page', 'pattern' => '/pricing*'],
  486. ['type' => 'event', 'pattern' => 'buy'],
  487. ]);
  488. $this->_aGoals = [$iPricing, $iBuy];
  489. $this->_aFunnels = [$iFunnel];
  490. $this->assertGreaterThan(0, $iPricing);
  491. $this->assertGreaterThan(0, $iFunnel);
  492. // A: / -> /pricing -> buy, B: / -> buy -> /pricing?plan=pro, C: /pricing only
  493. $aVisits = [
  494. ['93.184.216.1', [['pageview', '/'], ['pageview', '/pricing'], ['event', '/pricing', 'buy']]],
  495. ['93.184.216.2', [['pageview', '/'], ['event', '/', 'buy'], ['pageview', '/pricing?plan=pro']]],
  496. ['93.184.216.3', [['pageview', '/pricing']]],
  497. ];
  498. foreach ($aVisits as $iVisit => list($sIp, $aHits))
  499. foreach ($aHits as $i => $aHit)
  500. $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);
  501. $oReports = $this->_oModule->getReports();
  502. $oFilter = $this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09']);
  503. $aGoals = array_column($oReports->getGoals($oFilter)['goals'], null, 'id');
  504. $this->assertSame(3, $aGoals[$iPricing]['conversions'], 'a page goal with * matches the query string too');
  505. $this->assertEquals(100, $aGoals[$iPricing]['rate']);
  506. $this->assertSame(2, $aGoals[$iBuy]['conversions']);
  507. $this->assertEquals(66.67, $aGoals[$iBuy]['rate']);
  508. // a purchase by webhook, outside any visit (session_id 0), is no visit that converted
  509. $oWebhook = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest([]), self::NOW + 500);
  510. $this->assertTrue($oWebhook->collectAction('buy', '', 0, 0, ['type' => 'event', 'platform' => 'core', 'request' => false]));
  511. $this->_oModule->cleanReportCache();
  512. $aGoals = array_column($oReports->getGoals($oFilter)['goals'], null, 'id');
  513. $this->assertSame(2, $aGoals[$iBuy]['conversions'], 'an action outside a visit adds no visit');
  514. $this->assertEquals(66.67, $aGoals[$iBuy]['rate']);
  515. $aBuyTotals = $oDb->getGoalTotals($this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09', 'platform' => 'core'])->get(), ['type' => 'event', 'pattern' => 'buy']);
  516. $this->assertSame([0, 1], [(int)$aBuyTotals['sessions'], (int)$aBuyTotals['visitors']], 'but its visitor reached the goal');
  517. // goals are capped: the report counts each one in both periods
  518. $iMax = $this->_oModule->_oConfig->CNF['MAX_GOALS'];
  519. $this->assertSame($oDb->getGoalsCount() >= $iMax, $this->_oModule->isGoalLimitReached());
  520. for ($i = $oDb->getGoalsCount(); $i < $iMax + 1; $i++)
  521. $this->_aGoals[] = $oDb->saveGoal(0, ['name' => 'Test 2001 goal ' . $i, 'type' => 'page', 'pattern' => '/goal-' . $i]);
  522. $this->assertTrue($this->_oModule->isGoalLimitReached());
  523. $this->assertCount($iMax, $oDb->getGoals($iMax));
  524. $this->assertCount($iMax, $oReports->getGoals($oFilter)['goals']);
  525. $aFunnel = $oReports->getFunnels($oFilter, ['funnel' => $iFunnel]);
  526. $this->assertSame($iFunnel, $aFunnel['funnel']['id']);
  527. $this->assertSame([2, 2, 1], array_column($aFunnel['steps'], 'sessions'), 'a step counts only after the previous one');
  528. $this->assertEquals([100, 100, 50], array_column($aFunnel['steps'], 'rate'));
  529. $this->assertEquals([null, 0, 50], array_column($aFunnel['steps'], 'drop'));
  530. $this->assertTrue($oDb->deleteGoal($iBuy));
  531. $this->assertFalse((bool)$oDb->getGoal($iBuy));
  532. $this->assertTrue($oDb->deleteFunnel($iFunnel));
  533. $this->assertNotContains($iFunnel, array_column($oReports->getFunnels($oFilter)['funnels'], 'id'), 'a deleted funnel is not listed');
  534. }
  535. public function testFunnelStepsFollowTheEventOrder()
  536. {
  537. $oDb = $this->_oModule->_oDb;
  538. $fPage = function ($sPath) { return ['type' => 'pageview', 'url' => 'http://una.test' . $sPath]; };
  539. // /pricing before / in the same second; one /shop page; two /shop pages in one second
  540. $this->_collect($this->_server('93.184.216.1'), ['platform' => 'core-web', 'hits' => [$fPage('/pricing'), $fPage('/')]], self::NOW);
  541. $this->_collect($this->_server('93.184.216.2'), ['platform' => 'core-web', 'hits' => [$fPage('/shop/1')]], self::NOW);
  542. $this->_collect($this->_server('93.184.216.3'), ['platform' => 'core-web', 'hits' => [$fPage('/shop/2'), $fPage('/shop/3')]], self::NOW);
  543. $this->_collect($this->_server('93.184.216.4'), ['platform' => 'core-web', 'hits' => [['type' => 'event', 'url' => 'http://una.test/', 'name' => 'buy']]], self::NOW);
  544. $aFilter = $this->_filter(['range' => 'custom', 'from' => '2001-09-09', 'to' => '2001-09-09'])->get();
  545. $this->assertSame([1, 0], $oDb->getFunnelCounts($aFilter, [['type' => 'page', 'pattern' => '/'], ['type' => 'page', 'pattern' => '/pricing']]), 'a step recorded before the one before it in the same second');
  546. $this->assertSame([1, 1], $oDb->getFunnelCounts($aFilter, [['type' => 'page', 'pattern' => '/pricing'], ['type' => 'page', 'pattern' => '/']]), 'steps in the same second in order');
  547. $this->assertSame([2, 1], $oDb->getFunnelCounts($aFilter, [['type' => 'page', 'pattern' => '/shop/*'], ['type' => 'page', 'pattern' => '/shop/*']]), 'one view counts for one step');
  548. $this->assertSame([1, 0], $oDb->getFunnelCounts($aFilter, [['type' => 'event', 'pattern' => 'buy'], ['type' => 'event', 'pattern' => 'buy']]));
  549. }
  550. public function testConcurrentHitsOfAVisitAllCount()
  551. {
  552. $aServer = $this->_server('93.184.216.20');
  553. $fPage = function ($sPath) { return ['type' => 'pageview', 'url' => 'http://una.test' . $sPath]; };
  554. $this->_collect($aServer, ['platform' => 'core-web', 'hits' => [$fPage('/a')]], self::NOW);
  555. $aStale = $this->_sessions()[0];
  556. $this->_collect($aServer, ['platform' => 'core-web', 'hits' => [$fPage('/b')]], self::NOW + 30);
  557. // requests that read the visit before /b was stored and are written after it
  558. $fStale = function ($iNow) use ($aServer, $aStale) {
  559. $oCollector = new class($this->_oModule, new BxAnalyticsRequest($aServer), $iNow) extends BxAnalyticsCollector {
  560. public $aStale = [];
  561. protected function _findSession($aVisitor, $sPlatform, $iSince, $iUntil = 0, $iAt = 0)
  562. {
  563. return $this->aStale;
  564. }
  565. protected function _getRequestVisit($sPlatform, $iLinkedProfileId, $bApiKey)
  566. {
  567. return [parent::_getRequestVisit($sPlatform, $iLinkedProfileId, $bApiKey)[0], $this->aStale];
  568. }
  569. };
  570. $oCollector->aStale = $aStale;
  571. return $oCollector;
  572. };
  573. $this->assertSame(1, $fStale(self::NOW + 20)->collect(['platform' => 'core-web', 'hits' => [['type' => 'leave', 'url' => 'http://una.test/a', 'engaged' => 1000]]], ['platform' => 'api']));
  574. $a = $this->_sessions()[0];
  575. $this->assertSame([2, 0, '/b', self::NOW + 30, 30], [(int)$a['pageviews'], (int)$a['bounce'], $a['exit_path'], (int)$a['last_seen'], (int)$a['duration']], 'a late leave keeps the pageview, the exit page and the time');
  576. $this->assertSame(1, $fStale(self::NOW + 10)->collect(['platform' => 'core-web', 'hits' => [$fPage('/c')]], ['platform' => 'api']));
  577. $a = $this->_sessions()[0];
  578. $this->assertSame([3, '/b', self::NOW + 30], [(int)$a['pageviews'], $a['exit_path'], (int)$a['last_seen']], 'an older pageview written last is not the exit page');
  579. $this->assertTrue($fStale(self::NOW + 25)->collectAction('content_add', 'bx_posts', 1, 0, ['platform' => 'core-web']));
  580. $a = $this->_sessions()[0];
  581. $this->assertCount(1, $this->_sessions());
  582. $this->assertSame([3, 1, self::NOW + 30], [(int)$a['pageviews'], (int)$a['events'], (int)$a['last_seen']], 'a site action adds to the counters');
  583. }
  584. public function testConcurrentFirstHitsMakeOneVisit()
  585. {
  586. $aServer = $this->_server('93.184.216.21');
  587. $aEvent = ['platform' => 'core-web', 'hits' => [['type' => 'event', 'url' => 'http://una.test/', 'name' => 'cta_click']]];
  588. // the event's request starts the visit between this request's lookup and its insert
  589. $oCollector = new class($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW) extends BxAnalyticsCollector {
  590. public $fConcurrent;
  591. public $sLock;
  592. protected function _findSession($aVisitor, $sPlatform, $iSince, $iUntil = 0, $iAt = 0)
  593. {
  594. if($this->fConcurrent) {
  595. $fConcurrent = $this->fConcurrent;
  596. $this->fConcurrent = null;
  597. $fConcurrent();
  598. return [];
  599. }
  600. return parent::_findSession($aVisitor, $sPlatform, $iSince, $iUntil, $iAt);
  601. }
  602. protected function _getVisitLockName($sPlatform, $aVisitor)
  603. {
  604. return $this->sLock = parent::_getVisitLockName($sPlatform, $aVisitor);
  605. }
  606. };
  607. $oCollector->fConcurrent = function () use ($aServer, $aEvent) {
  608. $this->_collect($aServer, $aEvent, self::NOW);
  609. };
  610. $this->assertSame(1, $oCollector->collect(['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]], ['platform' => 'api']));
  611. $aSessions = $this->_sessions();
  612. $this->assertCount(1, $aSessions, 'one visit');
  613. $this->assertSame([1, 1, 0], [(int)$aSessions[0]['pageviews'], (int)$aSessions[0]['events'], (int)$aSessions[0]['bounce']]);
  614. $this->assertLessThanOrEqual(64, strlen($oCollector->sLock));
  615. $this->assertSame(1, (int)BxDolDb::getInstance()->getOne("SELECT IS_FREE_LOCK(:name)", ['name' => $oCollector->sLock]), 'the lock is released');
  616. // a visit refused by the rate limit releases the lock too
  617. $this->_setOption('bx_analytics_limit_visits', '1');
  618. $oCollector->sLock = null;
  619. $this->assertSame(0, $oCollector->collect(['platform' => 'next-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]], ['platform' => 'api']));
  620. $this->assertTrue($oCollector->isLimited());
  621. $this->assertNotNull($oCollector->sLock);
  622. $this->assertSame(1, (int)BxDolDb::getInstance()->getOne("SELECT IS_FREE_LOCK(:name)", ['name' => $oCollector->sLock]));
  623. // a request without a hit that starts a visit takes no lock
  624. $oCollector->sLock = null;
  625. $this->assertSame(0, $oCollector->collect(['platform' => 'next-web', 'hits' => [['type' => 'leave', 'url' => 'http://una.test/', 'engaged' => 1000]]], ['platform' => 'api']));
  626. $this->assertNull($oCollector->sLock);
  627. }
  628. public function testFirstHitWithoutTheLockStillFindsTheVisit()
  629. {
  630. $aServer = $this->_server('93.184.216.22');
  631. $aEvent = ['platform' => 'core-web', 'hits' => [['type' => 'event', 'url' => 'http://una.test/', 'name' => 'cta_click']]];
  632. // the lock times out because another request holds it while it starts the visit
  633. $oDb = new class($this->_oModule->_oConfig) extends BxAnalyticsDb {
  634. public function lockVisit($sName, $iTimeout)
  635. {
  636. return false;
  637. }
  638. };
  639. $oCollector = new class($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW) extends BxAnalyticsCollector {
  640. public $fConcurrent;
  641. public function setDb($oDb)
  642. {
  643. $this->_oDb = $oDb;
  644. }
  645. protected function _findSession($aVisitor, $sPlatform, $iSince, $iUntil = 0, $iAt = 0)
  646. {
  647. if($this->fConcurrent) {
  648. $fConcurrent = $this->fConcurrent;
  649. $this->fConcurrent = null;
  650. $fConcurrent();
  651. return [];
  652. }
  653. return parent::_findSession($aVisitor, $sPlatform, $iSince, $iUntil, $iAt);
  654. }
  655. };
  656. $oCollector->setDb($oDb);
  657. $oCollector->fConcurrent = function () use ($aServer, $aEvent) {
  658. $this->_collect($aServer, $aEvent, self::NOW);
  659. };
  660. $this->assertSame(1, $oCollector->collect(['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]], ['platform' => 'api']));
  661. $aSessions = $this->_sessions();
  662. $this->assertCount(1, $aSessions, 'one visit');
  663. $this->assertSame([1, 1], [(int)$aSessions[0]['pageviews'], (int)$aSessions[0]['events']]);
  664. }
  665. public function testHitsPerMinuteLimit()
  666. {
  667. $this->_setOption('bx_analytics_limit_hits', '5');
  668. $this->_setOption('bx_analytics_limit_visits', '0');
  669. $aServer = $this->_server('81.2.69.142');
  670. $fPayload = function ($iHits, $sPage = 'a') {
  671. return ['platform' => 'core-web', 'hits' => array_fill(0, $iHits, ['type' => 'pageview', 'url' => 'http://una.test/' . $sPage])];
  672. };
  673. // NOW is 40 seconds into its minute: NOW + 19 is the same minute, NOW + 20 the next
  674. $this->assertSame(3, $this->_collect($aServer, $fPayload(3), self::NOW));
  675. $this->assertSame(2, $this->_collect($aServer, $fPayload(2), self::NOW + 10), 'up to the limit');
  676. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW + 19);
  677. $this->assertSame(0, $oCollector->collect($fPayload(1, 'over'), ['platform' => 'api']), 'over the limit');
  678. $this->assertTrue($oCollector->isLimited());
  679. $this->assertContains('rate_limited', $oCollector->check($fPayload(1), ['platform' => 'api'])['reasons'], 'the Setup check tells');
  680. $this->assertSame(1, $this->_collect($this->_server('93.184.216.34'), $fPayload(1), self::NOW + 19), 'another address has its own limit');
  681. // site actions and server events are not limited
  682. $this->assertTrue($oCollector->collectAction('signup', 'account', 1, 0, ['platform' => 'core-web']));
  683. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), self::NOW + 20);
  684. $this->assertSame(1, $oCollector->collect($fPayload(1, 'next'), ['platform' => 'api']), 'a new minute counts anew');
  685. $this->assertFalse($oCollector->isLimited());
  686. $aPaths = BxDolDb::getInstance()->getColumn("SELECT `path` FROM `bx_analytics_events` WHERE `ts` < :to AND `type` = 'pageview'", ['to' => self::NOW + 86400]);
  687. $this->assertNotContains('/over', $aPaths);
  688. $this->assertContains('/next', $aPaths);
  689. $this->assertSame(6, (int)$this->_sessions()[0]['pageviews'], 'the dropped hit is not in the visit');
  690. // the counters keep no address
  691. $aRows = BxDolDb::getInstance()->getAll("SELECT * FROM `bx_analytics_limits` WHERE `bucket` < 1009843200 ORDER BY `bucket`, `hits`");
  692. $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');
  693. foreach ($aRows as $a)
  694. $this->assertSame(8, strlen($a['key']));
  695. }
  696. public function testVisitsPerHourLimit()
  697. {
  698. $this->_setOption('bx_analytics_limit_hits', '0');
  699. $this->_setOption('bx_analytics_limit_visits', '2');
  700. $this->_setOption('bx_analytics_track_errors', 'on');
  701. $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)"]]];
  702. // a script that changes its user agent with every request
  703. $this->assertSame(2, $this->_collect($this->_server('81.2.69.142', [], self::UA_SAFARI . ' a'), $aHit, self::NOW));
  704. $this->assertSame(2, $this->_collect($this->_server('81.2.69.142', [], self::UA_SAFARI . ' b'), $aHit, self::NOW + 1));
  705. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($this->_server('81.2.69.142', [], self::UA_SAFARI . ' c')), self::NOW + 2);
  706. $this->assertSame(0, $oCollector->collect($aHit, ['platform' => 'api']), 'a third visit in the hour');
  707. $this->assertTrue($oCollector->isLimited());
  708. $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');
  709. $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');
  710. $this->assertCount(2, $this->_sessions());
  711. // NOW is 2800 seconds into its hour
  712. $this->assertSame(2, $this->_collect($this->_server('81.2.69.142', [], self::UA_SAFARI . ' c'), $aHit, self::NOW + 800), 'a new hour counts anew');
  713. $this->assertCount(3, $this->_sessions());
  714. }
  715. public function testLimitAddresses()
  716. {
  717. $this->_setOption('bx_analytics_limit_hits', '2');
  718. $aHit = ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]];
  719. // one IPv6 /64 network is one address
  720. $this->assertSame(1, $this->_collect($this->_server('2001:db8:1:2::1'), $aHit, self::NOW));
  721. $this->assertSame(1, $this->_collect($this->_server('2001:db8:1:2::ffff'), $aHit, self::NOW));
  722. $this->assertSame(0, $this->_collect($this->_server('2001:db8:1:2:abcd::5'), $aHit, self::NOW));
  723. $this->assertSame(1, $this->_collect($this->_server('2001:db8:1:3::1'), $aHit, self::NOW), 'another network');
  724. // an IPv4 address written as IPv6 is that address
  725. $this->assertSame(1, $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW));
  726. $this->assertSame(1, $this->_collect($this->_server('::ffff:81.2.69.142'), $aHit, self::NOW));
  727. $this->assertSame(0, $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW));
  728. // a bot that runs the tracker is limited too: no bot rows past the limit
  729. $sBot = 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
  730. $this->_collect($this->_server('93.184.216.34', [], $sBot), $aHit, self::NOW);
  731. $this->_collect($this->_server('93.184.216.34', [], $sBot), $aHit, self::NOW);
  732. $this->_collect($this->_server('93.184.216.34', [], $sBot), $aHit, self::NOW);
  733. $this->assertSame(2, (int)BxDolDb::getInstance()->getOne("SELECT SUM(`hits`) FROM `bx_analytics_bots` WHERE `day` < '2002-01-01'"));
  734. $this->_setOption('bx_analytics_limit_hits', '0');
  735. $this->assertSame(1, $this->_collect($this->_server('81.2.69.142'), $aHit, self::NOW), 'no limit');
  736. }
  737. public function testLimitsArePruned()
  738. {
  739. $this->_setOption('bx_analytics_limit_hits', '100');
  740. $this->_setOption('bx_analytics_limit_visits', '100');
  741. $this->_collect($this->_server('81.2.69.142'), ['platform' => 'core-web', 'hits' => [['type' => 'pageview', 'url' => 'http://una.test/']]], self::NOW);
  742. $fCount = function () {
  743. return (int)BxDolDb::getInstance()->getOne("SELECT COUNT(*) FROM `bx_analytics_limits` WHERE `bucket` < 1009843200");
  744. };
  745. $this->assertSame(2, $fCount(), 'a minute of hits and an hour of visits');
  746. $oDb = $this->_oModule->_oDb;
  747. $oDb->deleteLimitsBefore($this->_oModule->getPruningCutoffs(self::NOW + 3600)['deleteLimitsBefore'], 100);
  748. $this->assertSame(2, $fCount(), 'kept for 2 hours');
  749. // NOW is 40 seconds into its minute and 2800 seconds into its hour
  750. $oDb->deleteLimitsBefore($this->_oModule->getPruningCutoffs(self::NOW + 4401)['deleteLimitsBefore'], 100);
  751. $this->assertSame(1, $fCount(), 'the hour goes once it started over 2 hours ago, the later minute is kept');
  752. $oDb->deleteLimitsBefore($this->_oModule->getPruningCutoffs(self::NOW + 7200)['deleteLimitsBefore'], 100);
  753. $this->assertSame(0, $fCount());
  754. }
  755. protected function _collect($aServer, $aPayload, $iNow, $aContext = [])
  756. {
  757. $oCollector = new BxAnalyticsCollector($this->_oModule, new BxAnalyticsRequest($aServer), $iNow);
  758. return $oCollector->collect($aPayload, $aContext + ['platform' => 'api']);
  759. }
  760. protected function _filter($aParams)
  761. {
  762. return new BxAnalyticsFilter($this->_oModule, $aParams, self::NOW + 86400);
  763. }
  764. protected function _server($sIp, $aExtra = [], $sUserAgent = self::UA_SAFARI)
  765. {
  766. return array_merge(['REMOTE_ADDR' => $sIp, 'HTTP_USER_AGENT' => $sUserAgent], $aExtra);
  767. }
  768. protected function _sessions()
  769. {
  770. return BxDolDb::getInstance()->getAll("SELECT * FROM `bx_analytics_sessions` WHERE `started` < :to ORDER BY `id`", ['to' => self::NOW + 30 * 86400]);
  771. }
  772. protected function _setOption($sName, $sValue)
  773. {
  774. if (!array_key_exists($sName, $this->_aOptions))
  775. $this->_aOptions[$sName] = getParam($sName);
  776. setParam($sName, $sValue);
  777. }
  778. protected function _cleanup()
  779. {
  780. $oDb = BxDolDb::getInstance();
  781. $iTo = self::NOW + 30 * 86400;
  782. $oDb->query("DELETE FROM `bx_analytics_events` WHERE `ts` < :to", ['to' => $iTo]);
  783. $oDb->query("DELETE FROM `bx_analytics_sessions` WHERE `started` < :to", ['to' => $iTo]);
  784. $oDb->query("DELETE FROM `bx_analytics_salts` WHERE `day` < '2002-01-01'");
  785. $oDb->query("DELETE FROM `bx_analytics_limits` WHERE `bucket` < 1009843200");
  786. $this->_oModule->cleanReportCache(); // reports of the test data cached by the run before
  787. $oDb->query("DELETE FROM `bx_analytics_error_hits` WHERE `ts` < :to", ['to' => $iTo]);
  788. $oDb->query("DELETE FROM `bx_analytics_errors` WHERE `message` = 'Test 2001 limited error'");
  789. $oDb->query("DELETE FROM `bx_analytics_bots` WHERE `day` < '2002-01-01'");
  790. $oDb->query("DELETE FROM `bx_analytics_bot_pages` WHERE `day` < '2002-01-01'");
  791. foreach ($this->_aGoals as $iId)
  792. $this->_oModule->_oDb->deleteGoal($iId);
  793. foreach ($this->_aFunnels as $iId)
  794. $this->_oModule->_oDb->deleteFunnel($iId);
  795. $this->_aGoals = $this->_aFunnels = [];
  796. }
  797. }