Repository navigation
Expand file tree
/
Copy pathNativeAnalyticsBehavior.module.php
More file actions
2068 lines (1930 loc) · 101 KB
/
Copy pathNativeAnalyticsBehavior.module.php
File metadata and controls
2068 lines (1930 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php namespace ProcessWire;
class NativeAnalyticsBehavior extends WireData implements Module, ConfigurableModule {
const EVENTS_TABLE = 'nab_events';
const COLLECT_ROUTE = '/nab-collect';
const SNAPSHOT_TABLE = 'nab_snapshots';
const SNAPSHOT_ROUTE = '/nab-snapshot';
const SNAPSHOT_MAX_BYTES = 4194304; // 4 MB raw upload cap (DOM + inlined CSS)
// Bump whenever ensureSchema() gains a new table, column, index, or backfill.
const SCHEMA_VERSION = 2;
protected $defaults = [
'enabled' => 1,
'enableHeatmaps' => 1,
'sampleRate' => 100, // percent of pageloads that collect
'retentionDays' => 60,
'excludedPaths' => '', // newline-separated path prefixes
'excludedTemplates' => '', // newline-separated template names
'excludedRoles' => '', // newline-separated role names (superuser always excluded)
'blockedIps' => '', // newline-separated IPs
'excludeNaBots' => 1, // hide sessions NativeAnalytics flagged as bots
'useLazyCron' => 1, // run the retention purge from LazyCron (else from cron via purgeExpired())
'snapshotMinHours' => 24, // at most one new snapshot version per page/device bucket in this window (0 = no cap)
'snapshotKeepVersions' => 5, // the purge trims each bucket to its newest N versions
'schemaVersion' => 0, // SCHEMA_VERSION that last completed ensureSchema()
];
public static function getModuleInfo() {
return [
'title' => 'NativeAnalyticsBehavior',
'summary' => 'Behavioral analytics companion for NativeAnalytics: heatmaps, insights and session recordings.',
'version' => '0.2.0',
'author' => 'Adrian Jones',
'icon' => 'fire',
'autoload' => true,
'singular' => true,
'requires' => ['ProcessWire>=3.0.173', 'PHP>=7.4', 'NativeAnalytics', 'LazyCron'],
];
}
public function init() {
$this->applyDefaults();
$this->ensureSchema();
$this->maybeHandleCollect();
$this->maybeHandleSnapshot();
// LazyCron piggybacks on a visitor's request and holds their PHP worker and
// session lock for the whole purge. Sites with a real crontab turn this off
// and call purgeExpired() from a CLI script instead.
if(!empty($this->useLazyCron)) {
$this->addHookAfter('LazyCron::everyDay', $this, 'handleDailyCron');
}
// Inject a "Behavior" tab into the main NativeAnalytics dashboard. The
// hooks are lazy (only fire when the dashboard renders its tabs), so
// registering them unconditionally here is cheap; per-user gating lives
// in the handlers.
$this->addHookAfter('ProcessNativeAnalytics::getTabLabels', $this, 'hookTabLabels');
$this->addHookAfter('ProcessNativeAnalytics::getTabs', $this, 'hookTabs');
}
protected function canViewBehaviorTab() {
if(!$this->enabled || !$this->enableHeatmaps) return false;
return $this->wire('user')->hasPermission('nativeanalyticsbehavior-view');
}
public function hookTabLabels(HookEvent $event) {
if(!$this->canViewBehaviorTab()) return;
$labels = $event->return;
if(!is_array($labels)) return;
$labels['behavior'] = 'Behavior';
$event->return = $labels;
}
public function hookTabs(HookEvent $event) {
if(!$this->canViewBehaviorTab()) return;
$tabs = $event->return;
if(!is_array($tabs)) return;
$proc = $this->wire('modules')->get('ProcessNativeAnalyticsBehavior');
if(!$proc) return;
$tabs['behavior'] = $proc->renderTabContent();
$event->return = $tabs;
}
public function ready() {
$this->applyDefaults();
if(!$this->enabled) return;
if($this->wire('config')->admin) return;
if($this->shouldInjectCurrentRequest()) {
$this->addHookAfter('Page::render', $this, 'injectCollector');
}
}
protected function applyDefaults() {
foreach($this->defaults as $key => $value) {
if($this->get($key) === null) $this->set($key, $value);
}
if(!$this->get('hashSalt')) {
$this->set('hashSalt', hash('sha256', $this->wire('config')->userAuthSalt . '|' . __FILE__));
}
}
// --- asset + CSP helpers (mirrors NativeAnalytics) ---
public function getModuleDirName() {
return basename(__DIR__);
}
public function getAssetUrl($relativePath) {
return $this->wire('config')->urls->siteModules . $this->getModuleDirName() . '/' . ltrim($relativePath, '/');
}
// Filename-based cache busting that matches the site's versionAsset() format:
// assets/foo.js -> assets/foo.<mtime>.js. The site .htaccess rewrites the
// versioned name back to the real file, so the URL path (not a query string)
// changes when the file does. CloudFront keys on the path, so it busts
// properly — a ?v= query string would be dropped/ignored at the CDN. The
// mtime is a 10-digit timestamp, which the rewrite rule requires.
public function getVersionedAssetUrl($relativePath) {
$relativePath = ltrim((string) $relativePath, '/');
$url = $this->getAssetUrl($relativePath);
$file = __DIR__ . '/' . $relativePath;
if(!is_file($file)) return $url;
$ext = strtolower(pathinfo($relativePath, PATHINFO_EXTENSION));
if($ext === '') return $url;
return preg_replace('/\.' . preg_quote($ext, '/') . '$/', '.' . filemtime($file) . '.' . $ext, $url);
}
public function getCspNonce() {
$nonce = '';
$config = $this->wire('config');
try {
if($config && method_exists($config, 'cspNonce')) {
$value = $config->cspNonce();
if(is_string($value) && $value !== '') $nonce = $value;
}
} catch(\Throwable $e) {
$nonce = '';
}
if($nonce === '' && $config) {
try {
$value = $config->get('cspNonce');
if(is_string($value) && $value !== '') $nonce = $value;
} catch(\Throwable $e) {
$nonce = '';
}
}
return is_string($nonce) ? $nonce : '';
}
protected function getScriptNonceAttribute() {
$nonce = $this->getCspNonce();
if($nonce === '') return '';
return ' nonce="' . $this->wire('sanitizer')->entities($nonce) . '"';
}
protected function normalizePath($path) {
$path = '/' . ltrim((string) $path, '/');
$root = (string) $this->wire('config')->urls->root;
if($root !== '/' && $root !== '' && strpos($path, $root) === 0) {
$path = '/' . ltrim(substr($path, strlen($root)), '/');
}
return $path;
}
public function getCollectEndpointUrl() {
return rtrim((string) $this->wire('config')->urls->root, '/') . self::COLLECT_ROUTE . '/';
}
public function getSnapshotEndpointUrl() {
return rtrim((string) $this->wire('config')->urls->root, '/') . self::SNAPSHOT_ROUTE . '/';
}
protected function ensureSchema($force = false) {
static $done = false;
if($done && !$force) return;
// Autoloaded, so init() runs this on every request. The sweep below is a
// CREATE TABLE, several SHOW queries, and an unindexed scan of the snapshot
// table, so it is skipped once the current SCHEMA_VERSION has completed.
// Install and upgrade force it; bumping SCHEMA_VERSION reruns it once.
if(!$force && (int) $this->get('schemaVersion') === self::SCHEMA_VERSION) {
$done = true;
return;
}
$db = $this->wire('database');
$db->exec("CREATE TABLE IF NOT EXISTS `" . self::EVENTS_TABLE . "` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`created_at` DATETIME NOT NULL,
`created_date` DATE NOT NULL,
`type` VARCHAR(16) NOT NULL DEFAULT '',
`path` VARCHAR(767) NOT NULL DEFAULT '',
`path_hash` CHAR(32) NOT NULL DEFAULT '',
`device` VARCHAR(16) NOT NULL DEFAULT '',
`x_frac` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`y_px` INT UNSIGNED NOT NULL DEFAULT 0,
`vw` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`dh` INT UNSIGNED NOT NULL DEFAULT 0,
`scroll_pct` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`selector` VARCHAR(255) NOT NULL DEFAULT '',
`offx` SMALLINT UNSIGNED NOT NULL DEFAULT 500,
`offy` SMALLINT UNSIGNED NOT NULL DEFAULT 500,
`label` VARCHAR(255) NOT NULL DEFAULT '',
`dead` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`rage` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`visitor_hash` CHAR(64) NOT NULL DEFAULT '',
`session_hash` CHAR(64) NOT NULL DEFAULT '',
`na_session_hash` CHAR(64) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `created_at` (`created_at`),
KEY `created_date` (`created_date`),
KEY `type_path_device` (`type`, `path_hash`, `device`),
KEY `visitor_hash` (`visitor_hash`),
KEY `session_hash` (`session_hash`),
KEY `na_session_hash` (`na_session_hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
// Versioned snapshots (D2): one row per DISTINCT DOM version of a
// (path, device), not one row per bucket. A version covers the time
// interval [captured_at, next version's captured_at); a session at time T
// selects the version with the greatest captured_at <= T. `dom_hash` is the
// sha256 of the stored DOM JSON, used at ingest to dedup an unchanged
// recapture against the latest version. No UNIQUE on (path_hash, device):
// multiple versions coexist.
$db->exec("CREATE TABLE IF NOT EXISTS `" . self::SNAPSHOT_TABLE . "` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`path` VARCHAR(767) NOT NULL DEFAULT '',
`path_hash` CHAR(32) NOT NULL DEFAULT '',
`device` VARCHAR(16) NOT NULL DEFAULT '',
`capture_width` SMALLINT UNSIGNED NOT NULL DEFAULT 0,
`dom_hash` CHAR(64) NOT NULL DEFAULT '',
`captured_at` DATETIME NOT NULL,
`dom_gz` MEDIUMBLOB NOT NULL,
PRIMARY KEY (`id`),
KEY `ver` (`path_hash`, `device`, `captured_at`),
KEY `captured_at` (`captured_at`),
KEY `bucket_hash` (`path_hash`, `device`, `dom_hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
// `label` was added after the events table shipped, so the CREATE above
// is a no-op on existing installs. Add it idempotently for those.
$col = $db->query("SHOW COLUMNS FROM `" . self::EVENTS_TABLE . "` LIKE 'label'");
if($col && $col->rowCount() === 0) {
$db->exec("ALTER TABLE `" . self::EVENTS_TABLE . "` ADD `label` VARCHAR(255) NOT NULL DEFAULT '' AFTER `selector`");
}
// `dead`/`rage` frustration flags shipped after labels, so add them
// idempotently on existing installs too.
$col = $db->query("SHOW COLUMNS FROM `" . self::EVENTS_TABLE . "` LIKE 'dead'");
if($col && $col->rowCount() === 0) {
$db->exec("ALTER TABLE `" . self::EVENTS_TABLE . "` ADD `dead` TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER `label`");
}
$col = $db->query("SHOW COLUMNS FROM `" . self::EVENTS_TABLE . "` LIKE 'rage'");
if($col && $col->rowCount() === 0) {
$db->exec("ALTER TABLE `" . self::EVENTS_TABLE . "` ADD `rage` TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER `dead`");
}
// `offx`/`offy` shipped with element-anchored density: where in the clicked
// element the cursor landed (0..1000 fractions of its box), so the density
// heatmap can pin each blob to the element in the rebuilt backdrop instead
// of to absolute page coordinates that drift. Add them idempotently on
// existing installs. Pre-existing rows default to the centre (500), which
// anchors them to their element's middle — drift-free location, just
// without intra-element spread.
$col = $db->query("SHOW COLUMNS FROM `" . self::EVENTS_TABLE . "` LIKE 'offx'");
if($col && $col->rowCount() === 0) {
$db->exec("ALTER TABLE `" . self::EVENTS_TABLE . "` ADD `offx` SMALLINT UNSIGNED NOT NULL DEFAULT 500 AFTER `selector`");
$db->exec("ALTER TABLE `" . self::EVENTS_TABLE . "` ADD `offy` SMALLINT UNSIGNED NOT NULL DEFAULT 500 AFTER `offx`");
}
// `na_session_hash` shipped with the bot-flag reuse: the session hash under
// NativeAnalytics' salt so we can exclude sessions NA flagged as bots. Add
// it (and its index) idempotently on existing installs. Pre-existing rows
// keep '' and are never treated as bots — we never stored the raw IDs to
// re-derive the NA-salted hash, so the filter is forward-only by design.
$col = $db->query("SHOW COLUMNS FROM `" . self::EVENTS_TABLE . "` LIKE 'na_session_hash'");
if($col && $col->rowCount() === 0) {
$db->exec("ALTER TABLE `" . self::EVENTS_TABLE . "` ADD `na_session_hash` CHAR(64) NOT NULL DEFAULT '' AFTER `session_hash`");
$db->exec("ALTER TABLE `" . self::EVENTS_TABLE . "` ADD KEY `na_session_hash` (`na_session_hash`)");
}
$this->migrateSnapshotVersioning($db);
$done = true;
// The string form of saveConfig() merges one key into the stored config.
// The array form replaces the whole config and would wipe every setting.
$this->set('schemaVersion', self::SCHEMA_VERSION);
$this->wire('modules')->saveConfig($this, 'schemaVersion', self::SCHEMA_VERSION);
}
/**
* Migrate an existing nab_snapshots table to the versioned model (D2). The
* CREATE TABLE above is a no-op on installs that already have the single-row-
* per-bucket schema, so convert it idempotently here: add `dom_hash`, drop the
* `bucket` UNIQUE (so versions can coexist), drop the now-unused
* `captured_modified`, add the `ver` index, and backfill `dom_hash` for the
* pre-existing rows so the first recapture of an unchanged page dedups instead
* of inserting a spurious duplicate version.
*/
protected function migrateSnapshotVersioning($db) {
$tbl = self::SNAPSHOT_TABLE;
$col = $db->query("SHOW COLUMNS FROM `$tbl` LIKE 'dom_hash'");
if($col && $col->rowCount() === 0) {
$db->exec("ALTER TABLE `$tbl` ADD `dom_hash` CHAR(64) NOT NULL DEFAULT '' AFTER `capture_width`");
}
$idx = $db->query("SHOW INDEX FROM `$tbl` WHERE Key_name='bucket'");
if($idx && $idx->rowCount() > 0) {
$db->exec("ALTER TABLE `$tbl` DROP INDEX `bucket`");
}
$idx = $db->query("SHOW INDEX FROM `$tbl` WHERE Key_name='ver'");
if($idx && $idx->rowCount() === 0) {
$db->exec("ALTER TABLE `$tbl` ADD KEY `ver` (`path_hash`, `device`, `captured_at`)");
}
// Backfill dom_hash over the same string ingest hashes (the gunzipped
// dom_gz IS that JSON), so an unchanged recapture matches the latest row.
$rows = $db->query("SELECT `id`,`dom_gz` FROM `$tbl` WHERE `dom_hash`=''");
if($rows) {
$upd = $db->prepare("UPDATE `$tbl` SET `dom_hash`=:h WHERE `id`=:id");
foreach($rows->fetchAll(\PDO::FETCH_ASSOC) as $r) {
$json = @gzdecode($r['dom_gz']);
if($json === false) continue;
$upd->execute([':h' => hash('sha256', $json), ':id' => (int) $r['id']]);
}
}
$col = $db->query("SHOW COLUMNS FROM `$tbl` LIKE 'captured_modified'");
if($col && $col->rowCount() > 0) {
$db->exec("ALTER TABLE `$tbl` DROP COLUMN `captured_modified`");
}
// Serves the "do you already hold this exact page?" check that runs before an upload.
$idx = $db->query("SHOW INDEX FROM `$tbl` WHERE Key_name='bucket_hash'");
if($idx && $idx->rowCount() === 0) {
$db->exec("ALTER TABLE `$tbl` ADD KEY `bucket_hash` (`path_hash`, `device`, `dom_hash`)");
}
}
protected function shouldInjectCurrentRequest() {
if(!$this->enabled || !$this->enableHeatmaps) return false;
if($this->wire('config')->ajax) return false;
// Never track superusers: their admin and testing browsing would pollute
// the data and cause confusion. Additional roles can be excluded via the
// "Excluded roles" setting (e.g. staff/editors); everyone else — including
// guests and ordinary logged-in members — is tracked normally.
$u = $this->wire('user');
if($u->isSuperuser() || $this->userHasExcludedRole($u)) return false;
$page = $this->wire('page');
if(!$page || !$page->id) return false;
if($this->isExcludedTemplate($page)) return false;
if($this->isExcludedPath()) return false;
return true;
}
protected function configLines($key) {
return $this->normalizeList($this->get($key));
}
/**
* Normalize a config value to a list of non-empty trimmed strings. Accepts an
* array (InputfieldAsmSelect) or a newline-separated string (InputfieldTextarea),
* so list settings read the same way regardless of input control.
*/
protected function normalizeList($val) {
if(is_array($val)) {
$out = [];
foreach($val as $v) {
$v = trim((string) $v);
if($v !== '') $out[] = $v;
}
return $out;
}
$raw = (string) $val;
if($raw === '') return [];
$out = [];
foreach(preg_split('/\r\n|\r|\n/', $raw) as $line) {
$line = trim($line);
if($line !== '') $out[] = $line;
}
return $out;
}
protected function userHasExcludedRole(User $u) {
$roles = $this->configLines('excludedRoles');
if(!$roles) return false;
foreach($roles as $role) {
if($u->hasRole($role)) return true;
}
return false;
}
protected function isExcludedTemplate(Page $page) {
$name = $page->template ? (string) $page->template->name : '';
if($name === '') return false;
return in_array($name, $this->configLines('excludedTemplates'), true);
}
protected function isExcludedPath() {
$uri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
$path = $this->normalizePath((string) parse_url($uri, PHP_URL_PATH));
foreach($this->configLines('excludedPaths') as $prefix) {
$prefix = $this->normalizePath($prefix);
if($prefix !== '/' && strpos($path, $prefix) === 0) return true;
}
return false;
}
public function injectCollector(HookEvent $event) {
$html = (string) $event->return;
if($html === '') return;
if(stripos($html, '</body>') === false) return;
if(stripos($html, 'data-nab-collector="1"') !== false) return;
$payload = [
'collectEndpoint' => $this->getCollectEndpointUrl(),
'sampleRate' => (int) $this->sampleRate,
'heatmaps' => (bool) $this->enableHeatmaps,
];
// Snapshot capture runs for every tracked visitor — guests and logged-in
// subscribers alike (staff/superuser are already excluded upstream).
// Logged-in pages (story forms, dashboards) are login-gated, so excluding
// them would leave those pages with no heatmap backdrop at all; instead we
// rely on the masking floor — maskAllInputs redacts every field value and
// [data-na-mask]/[data-na-block] redact rendered PII regions.
// The client captures once per session per path and always uploads; the
// ingest endpoint hash-dedups against the latest stored version, so there
// is no per-request freshness state to inject (D2 versioned snapshots).
$payload['snapshotEndpoint'] = $this->getSnapshotEndpointUrl();
$payload['snapshotLib'] = $this->getVersionedAssetUrl('assets/vendor/rrweb-snapshot.js');
$jsonFlags = JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
$configJson = json_encode($payload, $jsonFlags);
if($configJson === false) return;
$scriptUrl = $this->getVersionedAssetUrl('assets/collector.js');
$nonceAttr = $this->getScriptNonceAttribute();
$injected = "\n<script" . $nonceAttr . ">window.NAB_CONFIG = " . $configJson . ";</script>\n";
$injected .= '<script' . $nonceAttr . ' src="' . $this->wire('sanitizer')->entities($scriptUrl) . '" data-nab-collector="1" defer></script>' . "\n";
$event->return = preg_replace('~</body>~i', $injected . '</body>', $html, 1);
}
protected function maybeHandleCollect() {
$uri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
if($uri === '') return;
$path = rtrim($this->normalizePath((string) parse_url($uri, PHP_URL_PATH)), '/');
if($path !== self::COLLECT_ROUTE) return;
$this->handleCollectRequest();
}
protected function maybeHandleSnapshot() {
$uri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
if($uri === '') return;
$path = rtrim($this->normalizePath((string) parse_url($uri, PHP_URL_PATH)), '/');
if($path !== self::SNAPSHOT_ROUTE) return;
$this->handleSnapshotRequest();
}
protected function sendJson($status, array $data) {
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode($data);
exit;
}
protected function clientIp() {
return isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : '';
}
protected function hashId($value) {
$value = trim((string) $value);
if($value === '') return '';
return hash('sha256', (string) $this->get('hashSalt') . '|' . $value);
}
/**
* NativeAnalytics' effective hash salt, read from the live module instance
* (NA is autoload and sets this in init()/ready(), so it is populated by the
* time ingest runs). Cached per request. Returns '' if NA is unavailable.
* This is deliberately NOT our own hashSalt: matching NA's salt is what lets
* a session hash here line up with NA's session_hash for the bot-flag join.
*/
protected function naHashSalt() {
static $salt = null;
if($salt !== null) return $salt;
$salt = '';
$modules = $this->wire('modules');
if($modules->isInstalled('NativeAnalytics')) {
$na = $modules->get('NativeAnalytics');
if($na) $salt = (string) $na->get('hashSalt');
}
return $salt;
}
/**
* Session hash under NA's salt, matching NativeAnalytics::hashValue() exactly
* (sha256 of salt . '|' . rawId). Used only to join our rows to NA's bot
* flags. Returns '' when the raw id or NA's salt is missing, in which case
* the row is never excluded as a bot.
*/
protected function naSessionHash($sessionId) {
$sessionId = trim((string) $sessionId);
$salt = $this->naHashSalt();
if($sessionId === '' || $salt === '') return '';
return hash('sha256', $salt . '|' . $sessionId);
}
/**
* True when NativeAnalytics' hits table exists. Cached per request. The
* session-trail queries and the bot filter all depend on pwna_hits, so they
* degrade gracefully (empty result) when NA is not installed.
*/
protected function hasHitsTable() {
static $has = null;
if($has !== null) return $has;
$has = false;
try {
$t = $this->wire('database')->query("SHOW TABLES LIKE 'pwna_hits'");
$has = ($t && $t->rowCount() > 0);
} catch(\Throwable $e) {
$has = false;
}
return $has;
}
/**
* A " COLLATE <name>" fragment that forces our na_session_hash to the live
* collation of pwna_hits.session_hash, so a column-to-column comparison
* between the two is well-defined (a bare comparison raises MySQL error
* 1267 when their table-default collations differ). Returns '' when the
* column can't be inspected. Cached per request.
*/
protected function naHashCollation() {
static $collate = null;
if($collate !== null) return $collate;
$collate = '';
if(!$this->hasHitsTable()) return $collate;
try {
$col = $this->wire('database')->query("SHOW FULL COLUMNS FROM `pwna_hits` LIKE 'session_hash'");
} catch(\Throwable $e) {
return $collate;
}
if($col && $col->rowCount() > 0) {
$row = $col->fetch(\PDO::FETCH_ASSOC);
$c = isset($row['Collation']) ? (string) $row['Collation'] : '';
if($c !== '' && preg_match('/^[A-Za-z0-9_]+$/', $c)) $collate = " COLLATE $c";
}
return $collate;
}
/**
* WHERE fragment (with a leading AND) that drops rows whose session
* NativeAnalytics flagged as a bot, for appending to any events query.
* Returns '' (no filtering) when the toggle is off or NA's hits table is
* absent, so the dashboard degrades gracefully. Evaluated at query time
* against the live flags, so NA's hourly classifier backfilling is_bot is
* reflected on the next dashboard load with no sync job here.
*
* The filter only excludes rows POSITIVELY matched as a bot: a row with an
* empty na_session_hash (anything stored before this shipped) has no NA-salt
* hash to match and is always kept. The IN form (rather than NOT IN) also
* sidesteps the NULL-in-subquery trap. The bot-session subquery is on a
* separate table so there is no column-name collision with na_session_hash.
*/
protected function botExclusionSql() {
static $sql = null;
if($sql !== null) return $sql;
$sql = '';
if(empty($this->excludeNaBots)) return $sql;
if(!$this->hasHitsTable()) return $sql;
$collate = $this->naHashCollation();
$sql = " AND NOT (`na_session_hash` <> '' AND `na_session_hash`$collate IN ("
. "SELECT `session_hash` FROM `pwna_hits` WHERE `is_bot`=1 AND `session_hash` <> ''))";
return $sql;
}
/**
* Mirror the companion NativeAnalytics consent gate: when it requires consent
* and the consent cookie is absent, behavior data must not be stored either.
* Closes the direct-POST path; the client collector already gates on PWNA_CONFIG.
*/
protected function consentBlocked() {
$data = $this->wire('modules')->getModuleConfigData('NativeAnalytics');
if(empty($data['requireConsent'])) return false;
$name = !empty($data['consentCookieName']) ? (string) $data['consentCookieName'] : 'pwna_consent';
return empty($_COOKIE[$name]);
}
protected function handleCollectRequest() {
if(!$this->enabled || !$this->enableHeatmaps) $this->sendJson(204, ['ok' => true]);
if(($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') $this->sendJson(405, ['ok' => false]);
if(in_array($this->clientIp(), $this->configLines('blockedIps'), true)) $this->sendJson(204, ['ok' => true]);
if($this->consentBlocked()) $this->sendJson(204, ['ok' => true]);
$raw = file_get_contents('php://input');
if($raw === false || strlen($raw) > 262144) $this->sendJson(413, ['ok' => false]);
$data = json_decode($raw, true);
if(!is_array($data) || empty($data['events']) || !is_array($data['events'])) $this->sendJson(400, ['ok' => false]);
$sanitizer = $this->wire('sanitizer');
$db = $this->wire('database');
$now = date('Y-m-d H:i:s');
$today = date('Y-m-d');
$allowedTypes = ['click', 'scroll', 'copy'];
$allowedDevices = ['desktop', 'tablet', 'mobile'];
$sql = "INSERT INTO `" . self::EVENTS_TABLE . "`
(`created_at`,`created_date`,`type`,`path`,`path_hash`,`device`,`x_frac`,`y_px`,`vw`,`dh`,`scroll_pct`,`selector`,`offx`,`offy`,`label`,`dead`,`rage`,`visitor_hash`,`session_hash`,`na_session_hash`)
VALUES (:created_at,:created_date,:type,:path,:path_hash,:device,:x_frac,:y_px,:vw,:dh,:scroll_pct,:selector,:offx,:offy,:label,:dead,:rage,:visitor_hash,:session_hash,:na_session_hash)";
$stmt = $db->prepare($sql);
// Scroll depth is re-sent on every flush so it survives a missed
// pagehide; keep one max-depth row per (session, path, device) rather
// than inserting a row per flush, which would count one pageview many
// times. Clicks stay plain multi-row inserts.
$findScroll = $db->prepare("SELECT `id`,`scroll_pct` FROM `" . self::EVENTS_TABLE . "`
WHERE `type`='scroll' AND `session_hash`=:sh AND `path_hash`=:ph AND `device`=:dev LIMIT 1");
$bumpScroll = $db->prepare("UPDATE `" . self::EVENTS_TABLE . "`
SET `scroll_pct`=:pct, `created_at`=:ca WHERE `id`=:id");
$inserted = 0;
foreach(array_slice($data['events'], 0, 200) as $ev) {
if(!is_array($ev)) continue;
$type = (string) ($ev['type'] ?? '');
if(!in_array($type, $allowedTypes, true)) continue;
$path = '/' . ltrim((string) ($ev['path'] ?? '/'), '/');
$path = substr($path, 0, 767);
$pathHash = md5($path);
$device = (string) ($ev['device'] ?? '');
if(!in_array($device, $allowedDevices, true)) $device = 'desktop';
$rawSessionId = $ev['sessionId'] ?? '';
$sessionHash = $this->hashId($rawSessionId);
$naSessionHash = $this->naSessionHash($rawSessionId);
$scrollPct = max(0, min(100, (int) ($ev['scroll_pct'] ?? 0)));
if($type === 'scroll' && $sessionHash !== '') {
$findScroll->execute([':sh' => $sessionHash, ':ph' => $pathHash, ':dev' => $device]);
$existing = $findScroll->fetch(\PDO::FETCH_ASSOC);
if($existing) {
if($scrollPct > (int) $existing['scroll_pct']) {
$bumpScroll->execute([':pct' => $scrollPct, ':ca' => $now, ':id' => $existing['id']]);
}
continue;
}
}
$stmt->execute([
':created_at' => $now,
':created_date' => $today,
':type' => $type,
':path' => $path,
':path_hash' => $pathHash,
':device' => $device,
':x_frac' => max(0, min(1000, (int) ($ev['x_frac'] ?? 0))),
':y_px' => max(0, (int) ($ev['y_px'] ?? 0)),
':vw' => max(0, min(65535, (int) ($ev['vw'] ?? 0))),
':dh' => max(0, (int) ($ev['dh'] ?? 0)),
':scroll_pct' => $scrollPct,
':selector' => substr($sanitizer->text((string) ($ev['selector'] ?? '')), 0, 255),
':offx' => max(0, min(1000, (int) ($ev['offx'] ?? 500))),
':offy' => max(0, min(1000, (int) ($ev['offy'] ?? 500))),
':label' => substr($sanitizer->text((string) ($ev['label'] ?? '')), 0, 255),
':dead' => !empty($ev['dead']) ? 1 : 0,
':rage' => !empty($ev['rage']) ? 1 : 0,
':visitor_hash' => $this->hashId($ev['visitorId'] ?? ''),
':session_hash' => $sessionHash,
':na_session_hash' => $naSessionHash,
]);
$inserted++;
}
$this->sendJson(200, ['ok' => true, 'stored' => $inserted]);
}
/**
* Two request shapes share this endpoint. Without `dom` it is a check: the client
* has hashed its canonical snapshot and asks whether to send the body, which
* with inlined CSS runs to hundreds of KB. With `dom` it is the upload. Both
* answer the same question through snapshotWanted(), so a client that skips the
* check (or two racing uploads) cannot store what the check would have refused.
*
* The hash is the client's, over its identity form of the tree (no ids, no
* rr_* attributes, volatile subtrees reduced to their tag). The server cannot
* recompute it from the re-encoded JSON it stores, so it is trusted as a dedup
* key only: a forged one can add at most one version per cap window, or skip
* storing a page that would have been stored, and neither is worth defending.
*/
protected function handleSnapshotRequest() {
if(!$this->enabled || !$this->enableHeatmaps) $this->sendJson(204, ['ok' => true]);
if(($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') $this->sendJson(405, ['ok' => false]);
if(in_array($this->clientIp(), $this->configLines('blockedIps'), true)) $this->sendJson(204, ['ok' => true]);
if($this->consentBlocked()) $this->sendJson(204, ['ok' => true]);
$raw = file_get_contents('php://input');
if($raw === false || strlen($raw) > self::SNAPSHOT_MAX_BYTES) $this->sendJson(413, ['ok' => false]);
$data = json_decode($raw, true);
if(!is_array($data)) $this->sendJson(400, ['ok' => false]);
$allowedDevices = ['desktop', 'tablet', 'mobile'];
$device = (string) ($data['device'] ?? '');
if(!in_array($device, $allowedDevices, true)) $device = 'desktop';
$path = '/' . ltrim((string) ($data['path'] ?? '/'), '/');
$path = substr($path, 0, 767);
$width = max(0, min(65535, (int) ($data['capture_width'] ?? 0)));
$pathHash = md5($path);
$domHash = (string) ($data['dom_hash'] ?? '');
if($domHash !== '' && !preg_match('/^[0-9a-f]{64}$/', $domHash)) $this->sendJson(400, ['ok' => false]);
$isCheck = !isset($data['dom']);
if($isCheck) {
if($domHash === '') $this->sendJson(400, ['ok' => false]);
$this->sendJson(200, ['ok' => true, 'wanted' => $this->snapshotWanted($pathHash, $device, $domHash)]);
}
if(!is_array($data['dom'])) $this->sendJson(400, ['ok' => false]);
// JSON_HEX_TAG escapes < and > so the stored DOM can be safely embedded in a
// <script type="application/json"> block on the admin dashboard; without it,
// page text containing the literal "</script>" would break out of the tag.
$domJson = json_encode($data['dom'], JSON_UNESCAPED_SLASHES | JSON_HEX_TAG);
if($domJson === false) $this->sendJson(400, ['ok' => false]);
// Collectors cached from before the hash-first flow upload without a hash.
if($domHash === '') $domHash = hash('sha256', $domJson);
if(!$this->snapshotWanted($pathHash, $device, $domHash)) $this->sendJson(200, ['ok' => true, 'unchanged' => true]);
$gz = gzencode($domJson, 6);
if($gz === false) $this->sendJson(500, ['ok' => false]);
$db = $this->wire('database');
$sql = "INSERT INTO `" . self::SNAPSHOT_TABLE . "`
(`path`,`path_hash`,`device`,`capture_width`,`dom_hash`,`captured_at`,`dom_gz`)
VALUES (:path,:ph,:device,:w,:dh,:now,:dom)";
$stmt = $db->prepare($sql);
$stmt->bindValue(':path', $path);
$stmt->bindValue(':ph', $pathHash);
$stmt->bindValue(':device', $device);
$stmt->bindValue(':w', $width, \PDO::PARAM_INT);
$stmt->bindValue(':dh', $domHash);
$stmt->bindValue(':now', date('Y-m-d H:i:s'));
$stmt->bindValue(':dom', $gz, \PDO::PARAM_LOB);
$stmt->execute();
$this->sendJson(200, ['ok' => true]);
}
/**
* Should a snapshot with this identity hash be stored for this bucket?
*
* No when the bucket already holds a version with the same hash, whatever its
* age: a page that alternates between a few states (banner shown or not, a
* shuffled list) should settle on those few versions, not grow one per session.
* No when a version was stored within the last snapshotMinHours: the heatmap
* backdrop needs a representative page, not every visitor's variant, and this
* bounds what any one bucket can accumulate. Yes otherwise.
*/
protected function snapshotWanted($pathHash, $device, $domHash) {
$this->applyDefaults();
$db = $this->wire('database');
$tbl = self::SNAPSHOT_TABLE;
$same = $db->prepare("SELECT 1 FROM `$tbl` WHERE `path_hash`=:ph AND `device`=:dev AND `dom_hash`=:dh LIMIT 1");
$same->execute([':ph' => $pathHash, ':dev' => $device, ':dh' => $domHash]);
if($same->fetchColumn()) return false;
$minHours = max(0, (int) $this->snapshotMinHours);
if($minHours > 0) {
$recent = $db->prepare("SELECT 1 FROM `$tbl` WHERE `path_hash`=:ph AND `device`=:dev AND `captured_at` > :since LIMIT 1");
$recent->execute([':ph' => $pathHash, ':dev' => $device, ':since' => date('Y-m-d H:i:s', time() - $minHours * 3600)]);
if($recent->fetchColumn()) return false;
}
return true;
}
public function handleDailyCron(?HookEvent $event = null) {
$this->purgeExpired();
}
/**
* Delete events and snapshot versions older than the retention window, in
* batches so no single statement locks a large blob table for long. The newest
* snapshot version of every bucket is always kept: a page that has not changed
* in the whole window would otherwise lose its only heatmap backdrop.
*
* Callable from LazyCron (see handleDailyCron) or from a CLI cron script.
*
* @param int $batchSize Rows per DELETE statement.
* @param int $maxSeconds Stop after this many seconds (0 = no limit); the next
* run picks up where this one left off.
* @return array events, snapshots (rows deleted), complete (bool), seconds (float).
*/
public function purgeExpired($batchSize = 2000, $maxSeconds = 0) {
$batchSize = max(1, (int) $batchSize);
$maxSeconds = max(0, (int) $maxSeconds);
$cutoff = $this->retentionCutoff();
$started = microtime(true);
$result = ['events' => 0, 'snapshots' => 0, 'trimmed' => 0, 'complete' => false, 'seconds' => 0.0];
$outOfTime = function() use ($started, $maxSeconds) {
return $maxSeconds > 0 && (microtime(true) - $started) >= $maxSeconds;
};
try {
$db = $this->wire('database');
$events = $db->prepare("DELETE FROM `" . self::EVENTS_TABLE . "` WHERE `created_at` < :cutoff LIMIT " . $batchSize);
do {
$events->execute([':cutoff' => $cutoff]);
$deleted = $events->rowCount();
$result['events'] += $deleted;
} while($deleted === $batchSize && !$outOfTime());
$eventsComplete = $deleted < $batchSize;
// Two statements rather than a multi-table DELETE, which cannot take a LIMIT.
$expired = $db->prepare("SELECT s.`id` FROM `" . self::SNAPSHOT_TABLE . "` s
JOIN (SELECT `path_hash`, `device`, MAX(`id`) AS keep_id FROM `" . self::SNAPSHOT_TABLE . "` GROUP BY `path_hash`, `device`) k
ON k.`path_hash` = s.`path_hash` AND k.`device` = s.`device`
WHERE s.`captured_at` < :cutoff AND s.`id` <> k.keep_id
ORDER BY s.`id` LIMIT " . $batchSize);
$snapshotsComplete = false;
while(!$outOfTime()) {
$expired->execute([':cutoff' => $cutoff]);
$ids = $expired->fetchAll(\PDO::FETCH_COLUMN);
if($ids) {
$marks = implode(',', array_fill(0, count($ids), '?'));
$delete = $db->prepare("DELETE FROM `" . self::SNAPSHOT_TABLE . "` WHERE `id` IN ($marks)");
$delete->execute(array_map('intval', $ids));
$result['snapshots'] += $delete->rowCount();
}
if(count($ids) < $batchSize) {
$snapshotsComplete = true;
break;
}
}
// Then trim every bucket to its newest snapshotKeepVersions versions, whatever
// their age. A session resolves to the version live at its time, or failing
// that the earliest later one, so a handful per bucket serves the whole
// event window; more than that is duplicate copies of the same page.
$keep = max(1, (int) $this->snapshotKeepVersions);
$excess = $db->prepare("SELECT s.`id` FROM `" . self::SNAPSHOT_TABLE . "` s
JOIN (SELECT `id`, ROW_NUMBER() OVER (PARTITION BY `path_hash`, `device` ORDER BY `captured_at` DESC, `id` DESC) AS rn
FROM `" . self::SNAPSHOT_TABLE . "`) r ON r.`id` = s.`id`
WHERE r.rn > :keep
ORDER BY s.`id` LIMIT " . $batchSize);
$trimComplete = false;
while(!$outOfTime()) {
$excess->bindValue(':keep', $keep, \PDO::PARAM_INT);
$excess->execute();
$ids = $excess->fetchAll(\PDO::FETCH_COLUMN);
if($ids) {
$marks = implode(',', array_fill(0, count($ids), '?'));
$delete = $db->prepare("DELETE FROM `" . self::SNAPSHOT_TABLE . "` WHERE `id` IN ($marks)");
$delete->execute(array_map('intval', $ids));
$result['trimmed'] += $delete->rowCount();
}
if(count($ids) < $batchSize) {
$trimComplete = true;
break;
}
}
$result['complete'] = $eventsComplete && $snapshotsComplete && $trimComplete;
} catch(\Throwable $e) {
$this->wire('log')->save('native-analytics-behavior', 'Purge failed: ' . $e->getMessage());
}
$result['seconds'] = round(microtime(true) - $started, 2);
$this->wire('log')->save('native-analytics-behavior', 'Purge: ' . $result['events'] . ' events, '
. $result['snapshots'] . ' expired snapshot versions, ' . $result['trimmed'] . ' excess snapshot versions deleted in ' . $result['seconds'] . 's'
. ($result['complete'] ? '' : ' (stopped at time limit, more remain)'));
return $result;
}
/**
* Rows purgeExpired() would delete right now, for dry runs and monitoring.
*
* @return array events, snapshots (expired), trimmed (excess versions per bucket).
*/
public function countExpired() {
$cutoff = $this->retentionCutoff();
$db = $this->wire('database');
$events = $db->prepare("SELECT COUNT(*) FROM `" . self::EVENTS_TABLE . "` WHERE `created_at` < :cutoff");
$events->execute([':cutoff' => $cutoff]);
$snapshots = $db->prepare("SELECT COUNT(*) FROM `" . self::SNAPSHOT_TABLE . "` s
JOIN (SELECT `path_hash`, `device`, MAX(`id`) AS keep_id FROM `" . self::SNAPSHOT_TABLE . "` GROUP BY `path_hash`, `device`) k
ON k.`path_hash` = s.`path_hash` AND k.`device` = s.`device`
WHERE s.`captured_at` < :cutoff AND s.`id` <> k.keep_id");
$snapshots->execute([':cutoff' => $cutoff]);
$keep = max(1, (int) $this->snapshotKeepVersions);
$excess = $db->prepare("SELECT COUNT(*) FROM (SELECT ROW_NUMBER() OVER (PARTITION BY `path_hash`, `device` ORDER BY `captured_at` DESC, `id` DESC) AS rn
FROM `" . self::SNAPSHOT_TABLE . "`) r WHERE r.rn > :keep");
$excess->bindValue(':keep', $keep, \PDO::PARAM_INT);
$excess->execute();
return ['events' => (int) $events->fetchColumn(), 'snapshots' => (int) $snapshots->fetchColumn(), 'trimmed' => (int) $excess->fetchColumn()];
}
protected function retentionCutoff() {
// Public callers may reach this before init() has applied defaults.
$this->applyDefaults();
$days = max(1, (int) $this->retentionDays);
return date('Y-m-d H:i:s', strtotime('-' . $days . ' days'));
}
/**
* Delete all collected events for a given raw visitor or session ID.
* Pass the same un-hashed ID the client used (e.g. the pwna_vid value).
* Returns the number of rows deleted.
*/
public function eraseVisitor($visitorId) {
$hash = $this->hashId($visitorId);
if($hash === '') return 0;
$db = $this->wire('database');
$stmt = $db->prepare("DELETE FROM `" . self::EVENTS_TABLE . "` WHERE `visitor_hash`=:h");
$stmt->execute([':h' => $hash]);
return $stmt->rowCount();
}
/** Distinct paths that have collected data, most-active first. */
public function getTrackedPaths($limit = 200) {
$db = $this->wire('database');
$stmt = $db->prepare("SELECT `path`, COUNT(*) AS c FROM `" . self::EVENTS_TABLE . "`
GROUP BY `path` ORDER BY c DESC LIMIT :lim");
$stmt->bindValue(':lim', (int) $limit, \PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* Pages with the most distinct sessions, descending. Backs the dashboard's
* "top pages" quick-jump dropdown. Counts unique session_hash values across
* all event types and honors the bot-exclusion setting so the ranking matches
* the heatmaps.
*
* @return array<int,array{path:string,c:int}>
*/
public function getTopPagesBySessions($limit = 25, $from = null, $to = null) {
$limit = max(1, min(100, (int) $limit));
$db = $this->wire('database');
$params = [];
$dateSql = '';
if($from !== null && $to !== null) {
$dateSql = " AND `created_date` BETWEEN :from AND :to";
$params[':from'] = (string) $from;
$params[':to'] = (string) $to;
}
$stmt = $db->prepare("SELECT `path`, COUNT(DISTINCT `session_hash`) AS c FROM `" . self::EVENTS_TABLE . "`
WHERE `session_hash` <> ''" . $dateSql . $this->botExclusionSql() . "
GROUP BY `path` ORDER BY c DESC LIMIT " . $limit);
$stmt->execute($params);
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
$out = [];
foreach($rows as $row) {
$out[] = ['path' => (string) $row['path'], 'c' => (int) $row['c']];
}
return $out;
}
/**
* Tracked paths matching a search term, most-collected first. Backs the
* dashboard's path autocomplete: searching keeps the long tail reachable
* where the volume-capped getTrackedPaths() list would drop it.
*
* @return array<int,array{path:string,c:int}>
*/
public function searchTrackedPaths($term, $limit = 20) {
$term = trim((string) $term);
$len = function_exists('mb_strlen') ? mb_strlen($term) : strlen($term);
if($len < 1) return [];
$limit = max(1, min(50, (int) $limit));
$like = '%' . $this->escapeLikeTerm($term) . '%';
$db = $this->wire('database');
$stmt = $db->prepare("SELECT `path`, COUNT(*) AS c FROM `" . self::EVENTS_TABLE . "`
WHERE `path` LIKE :like
GROUP BY `path` ORDER BY c DESC LIMIT " . $limit);
$stmt->execute([':like' => $like]);
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
$out = [];
foreach($rows as $row) {
$out[] = ['path' => (string) $row['path'], 'c' => (int) $row['c']];
}
return $out;
}
// Escape MySQL LIKE wildcards (% and _) and the escape char itself so a
// user-typed term matches literally. Backslash first, so escapes added for
// % and _ are not doubled.
protected function escapeLikeTerm($term) {
return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], (string) $term);
}
/**
* Click buckets for a path/device/date range.
* Returns rows: ['x_bucket'=>0..99, 'y_bucket'=>(floor(y_px/20)), 'c'=>count, 'dh'=>maxDocHeight].
*/
public function getClickHeatmap($path, $device, $fromDate, $toDate) {
$db = $this->wire('database');
$sql = "SELECT FLOOR(`x_frac`/10) AS x_bucket, FLOOR(`y_px`/20) AS y_bucket, COUNT(*) AS c, MAX(`dh`) AS dh
FROM `" . self::EVENTS_TABLE . "`
WHERE `type`='click' AND `path_hash`=:ph AND `device`=:dev
AND `created_date` BETWEEN :from AND :to" . $this->botExclusionSql() . "
GROUP BY x_bucket, y_bucket";
$stmt = $db->prepare($sql);
$stmt->execute([
':ph' => md5('/' . ltrim((string) $path, '/')),