Repository navigation
Expand file tree
/
Copy pathProcessNativeAnalytics.module.php
More file actions
2984 lines (2807 loc) · 161 KB
/
Copy pathProcessNativeAnalytics.module.php
File metadata and controls
2984 lines (2807 loc) · 161 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 ProcessNativeAnalytics extends Process {
public static function getModuleInfo() {
return [
'title' => 'NativeAnalytics Dashboard',
'summary' => 'Dashboard for the NativeAnalytics module.',
'version' => 1036,
'author' => 'Pyxios - Roych (www.pyxios.com)',
'permission' => 'nativeanalytics-view',
'icon' => 'area-chart',
'requires' => ['NativeAnalytics'],
'page' => [
'name' => 'native-analytics',
'title' => 'Analytics',
],
];
}
/**
* Return the nonce attribute for inline admin scripts when a CSP nonce exists.
*/
protected function getScriptNonceAttribute() {
try {
$analytics = $this->wire('modules')->get('NativeAnalytics');
if($analytics && method_exists($analytics, 'getScriptNonceAttribute')) {
return (string) $analytics->getScriptNonceAttribute();
}
} catch(\Throwable $e) {
}
$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;
elseif($value === null) {
$value = $config->cspNonce;
if(is_string($value) && $value !== '') $nonce = $value;
}
} catch(\Throwable $e) {
$nonce = '';
}
}
if($nonce === '') {
$headers = function_exists('headers_list') ? headers_list() : [];
if($headers) {
$headerText = implode("\n", $headers);
if(preg_match('#^Content-Security-Policy(?:-Report-Only)?:.*\s(?:script-src|script-src-elem)\s+(?:[^;]+\s)?\'nonce-([A-Za-z0-9+/_=-]+)\'#mi', $headerText, $m)) {
$nonce = (string) $m[1];
}
}
}
$nonce = trim((string) $nonce);
if($nonce === '' || !preg_match('/^[A-Za-z0-9+\/_=-]+$/', $nonce)) return '';
return ' nonce="' . $this->sanitizer->entities($nonce) . '"';
}
public function uninstall() {
// The dashboard/process module must only remove its own admin page and registry
// data. It must not cascade into uninstalling NativeAnalytics itself, because
// the main module uninstall is the operation that intentionally drops stored
// analytics tables. This keeps a direct dashboard uninstall non-destructive.
try {
$this->cleanupAdminPages();
$this->cleanupModuleRegistry(['ProcessNativeAnalytics']);
try {
$this->wire('modules')->refresh();
} catch(\Throwable $e) {
$this->wire('log')->save('native-analytics', 'Modules refresh after dashboard uninstall failed: ' . $e->getMessage());
}
} finally {
try {
$session = $this->wire('session');
if((string) $session->getFor('NativeAnalytics', 'uninstall_mode') === 'dashboard-direct') {
$session->removeFor('NativeAnalytics', 'uninstall_mode');
}
} catch(\Throwable $e) {
// non-fatal during uninstall cleanup
}
}
}
protected function cleanupAdminPages() {
try {
$pages = $this->wire('pages');
$adminRoot = (int) $this->wire('config')->adminRootPageID;
$candidates = [];
foreach(['native-analytics', 'analytics'] as $name) {
try {
$found = $pages->find('template=admin, include=all, name=' . $name . ', sort=-id');
foreach($found as $item) $candidates[$item->id] = $item;
} catch(\Throwable $e) {
}
}
if($adminRoot) {
try {
$admin = $pages->get($adminRoot);
if($admin && $admin->id) {
foreach($admin->children('include=all, sort=-id') as $item) {
$processName = '';
try {
$proc = $item->get('process');
if(is_object($proc)) {
if(isset($proc->className)) $processName = (string) $proc->className;
elseif(isset($proc->name)) $processName = (string) $proc->name;
else $processName = get_class($proc);
} else {
$processName = (string) $proc;
}
} catch(\Throwable $e) {
$processName = '';
}
if($item->name === 'native-analytics' || ($item->name === 'analytics' && stripos($processName, 'ProcessNativeAnalytics') !== false) || stripos($processName, 'ProcessNativeAnalytics') !== false) {
$candidates[$item->id] = $item;
}
}
}
} catch(\Throwable $e) {
}
}
foreach($candidates as $item) {
try {
foreach($item->children('include=all, sort=-id') as $child) {
$child->delete(true);
}
} catch(\Throwable $e) {
}
try {
if(method_exists($item, 'setOutputFormatting')) $item->setOutputFormatting(false);
if(defined('ProcessWire\Page::statusSystem') && isset($item->status)) {
$item->status = $item->status & ~Page::statusSystem;
}
$item->delete(true);
} catch(\Throwable $e) {
$this->wire('log')->save('native-analytics', 'Dashboard admin page delete failed for #' . (int) $item->id . ': ' . $e->getMessage());
}
}
} catch(\Throwable $e) {
$this->wire('log')->save('native-analytics', 'Dashboard admin page cleanup failed: ' . $e->getMessage());
}
}
protected function cleanupModuleRegistry(array $classes) {
try {
$db = $this->wire('database');
$prefix = (string) ($this->wire('config')->dbTablePrefix ?? '');
$table = $prefix . 'modules';
foreach($classes as $class) {
$stmt = $db->prepare('DELETE FROM `' . $table . '` WHERE `class` = :class');
$stmt->execute([':class' => $class]);
}
} catch(\Throwable $e) {
$this->wire('log')->save('native-analytics', 'Module registry cleanup failed: ' . $e->getMessage());
}
}
public function ___execute() {
/** @var NativeAnalytics $analytics */
$analytics = $this->modules->get('NativeAnalytics');
if(!$analytics) return '<p>NativeAnalytics is not available.</p>';
if($this->user->hasPermission('nativeanalytics-manage') && $this->input->post('pwna_action')) {
$this->handlePostActions($analytics);
}
$rangeMeta = $this->getRangeMeta($analytics);
$rangeSpec = $rangeMeta['rangeSpec'];
$pageId = (int) $this->input->get('page_id');
$template = $this->sanitizer->name($this->input->get('template'));
$activeTab = $this->getActiveTab();
$filters = [];
if($pageId > 0) $filters['page_id'] = $pageId;
if($template !== '') $filters['template'] = $template;
$summary = $analytics->getSummary($rangeSpec, $filters);
$quality = $analytics->getSessionQuality($rangeSpec, $filters);
$current = $analytics->getCurrentVisitorsSummary((int) $analytics->realtimeWindowMinutes, $filters);
$summary404 = $analytics->get404Summary($rangeSpec);
$series = $analytics->getDailySeries($rangeSpec, $filters);
$hourlySeries = $analytics->getHourlySeries($rangeMeta['rangeSpec']['end_date'] ?? date('Y-m-d'), $filters);
$pages = $analytics->getTopPages($rangeSpec, 15, $filters);
$landing = $analytics->getTopLandingPages($rangeSpec, 10, $filters);
$exits = $analytics->getTopExitPages($rangeSpec, 10, $filters);
$currentVisitors = $analytics->getCurrentVisitors((int) $analytics->realtimeWindowMinutes, 25, $filters);
$top404 = $analytics->getTop404Paths($rangeSpec, 12);
$referrers = $analytics->getTopReferrers($rangeSpec, 10, $filters);
$searchTerms = $analytics->getTopSearchTerms($rangeSpec, 10, $filters);
$campaigns = $analytics->getTopCampaigns($rangeSpec, 10, $filters);
$channels = $analytics->getTopChannels($rangeSpec, 12, $filters);
$attributedCampaigns = $analytics->getAttributedCampaigns($rangeSpec, 10, $filters);
$browsers = $analytics->getBreakdown('browser', $rangeSpec, 10, $filters);
$devices = $analytics->getBreakdown('device_type', $rangeSpec, 10, $filters);
$os = $analytics->getBreakdown('os', $rangeSpec, 10, $filters);
$templates = $analytics->getBreakdown('template', $rangeSpec, 20, []);
$health = $analytics->getHealthSnapshot();
$compareMeta = $this->getCompareMeta($analytics, $rangeMeta);
$compareSummary = [];
$compareQuality = [];
$compareSummary404 = [];
$compareSeries = [];
if($compareMeta['enabled']) {
$compareSummary = $analytics->getSummary($compareMeta['rangeSpec'], $filters);
$compareQuality = $analytics->getSessionQuality($compareMeta['rangeSpec'], $filters);
$compareSummary404 = $analytics->get404Summary($compareMeta['rangeSpec']);
$compareSeries = $analytics->getDailySeries($compareMeta['rangeSpec'], $filters);
}
$eventSummary = $analytics->getEventSummary($rangeSpec, $filters);
$eventFormSummary = $analytics->getEventSummary($rangeSpec, $filters, 'form');
$eventDownloadSummary = $analytics->getEventSummary($rangeSpec, $filters, 'download');
$eventContactSummary = $analytics->getEventSummary($rangeSpec, $filters, 'contact');
$eventNavigationSummary = $analytics->getEventSummary($rangeSpec, $filters, 'navigation');
$eventSeries = $analytics->getEventDailySeries($rangeSpec, $filters);
$topEvents = $analytics->getTopEvents($rangeSpec, 12, $filters);
$topDownloads = $analytics->getTopEvents($rangeSpec, 10, $filters, 'download');
$topForms = $analytics->getTopEvents($rangeSpec, 10, $filters, 'form');
$topContacts = $analytics->getTopEvents($rangeSpec, 10, $filters, 'contact');
$topEventTargets = $analytics->getTopEventTargets($rangeSpec, 12, $filters);
$goalStats = $analytics->getGoalStats($rangeSpec, $filters, true);
$goalSeries = $analytics->getGoalDailySeries($rangeSpec, $filters);
$this->config->styles->add($analytics->getAssetUrl('assets/admin.css') . '?v=' . rawurlencode($analytics->getAssetVersion('assets/admin.css')));
$wireTabs = null;
try {
$wireTabs = $this->modules->get('JqueryWireTabs');
} catch(\Throwable $e) {
$wireTabs = null;
}
$this->headline($this->_('Analytics'));
$out = '';
$out .= $this->renderInlineCssFallback();
$out .= '<div class="pwna-app">';
$out .= $this->renderBrandHeader($analytics);
$engagementView = $this->getEngagementView();
$overviewContent = $this->renderToolbar($rangeMeta, $pageId, $template, $templates, 'overview');
$overviewContent .= $this->renderCards($summary, $current, $summary404, $quality);
$overviewContent .= '<div class="pwna-grid-2">';
$overviewContent .= '<div class="pwna-panel"><h2>Traffic trend</h2><p class="pwna-note">Daily totals for the selected period.</p>' . $analytics->renderLineChart($series, 'views', 'Traffic trend by day', [], 'daily') . '</div>';
$overviewContent .= '<div class="pwna-panel"><h2>Traffic by hour</h2><p class="pwna-note">Hover a point to see the hour, views, uniques and sessions for the last day in the selected range.</p>' . $analytics->renderLineChart($hourlySeries, 'views', 'Traffic by hour for selected day', [], 'hourly') . '</div>';
$overviewContent .= '</div>';
$overviewContent .= '<div class="pwna-grid-2">';
$overviewContent .= $this->renderSimpleTable('Top pages', ['Page', 'Views', 'Uniques', 'Sessions'], $this->mapTopPages($pages), true);
$overviewContent .= $this->renderCurrentVisitorsPanel($analytics, $currentVisitors, (int) $analytics->realtimeWindowMinutes);
$overviewContent .= '</div>';
$overviewContent .= '<div class="pwna-grid-2">';
$overviewContent .= $this->renderSimpleTable('Top landing pages', ['Landing page', 'Sessions started'], $this->mapSessionPageRows($landing));
$overviewContent .= $this->renderSimpleTable('Top exit pages', ['Exit page', 'Sessions ended'], $this->mapSessionPageRows($exits));
$overviewContent .= '</div>';
$compareContent = $this->renderCompareToolbar($rangeMeta, $compareMeta, $pageId, $template, $templates);
$compareContent .= $this->renderComparePanel($analytics, $rangeMeta, $compareMeta, $summary, $compareSummary, $quality, $compareQuality, $summary404, $compareSummary404, $series, $compareSeries, $pageId, $template, $templates);
$engagementMetricsContent = $this->renderEventCards($eventSummary, $eventFormSummary, $eventDownloadSummary, $eventContactSummary, $eventNavigationSummary);
$engagementMetricsContent .= '<div class="pwna-panel"><h2>Engagement trend</h2><p class="pwna-note">Tracked actions over time for the selected period.</p>' . $analytics->renderLineChart($eventSeries, 'views', 'Tracked actions by day', ['views' => 'Events', 'uniques' => 'Uniques', 'sessions' => 'Sessions'], 'events') . '</div>';
$engagementMetricsContent .= '<div class="pwna-grid-2">';
$engagementMetricsContent .= $this->renderSimpleTable('Top tracked actions', ['Action', 'Events', 'Unique visitors', 'Sessions'], $this->mapEventRows($topEvents), true);
$engagementMetricsContent .= $this->renderSimpleTable('Top action targets', ['Target', 'Group', 'Events', 'Sessions'], $this->mapEventTargetRows($topEventTargets), true);
$engagementMetricsContent .= '</div>';
$engagementMetricsContent .= '<div class="pwna-grid-3">';
$engagementMetricsContent .= $this->renderSimpleTable('Top form submits', ['Action', 'Events', 'Sessions'], $this->mapEventRowsCompact($topForms));
$engagementMetricsContent .= $this->renderSimpleTable('Top downloads', ['Action', 'Events', 'Sessions'], $this->mapEventRowsCompact($topDownloads));
$engagementMetricsContent .= $this->renderSimpleTable('Top contact clicks', ['Action', 'Events', 'Sessions'], $this->mapEventRowsCompact($topContacts));
$engagementMetricsContent .= '</div>';
$engagementContent = $this->renderToolbar($rangeMeta, $pageId, $template, $templates, 'engagement');
$engagementContent .= $this->renderEngagementSubnav($engagementView);
$engagementContent .= $this->renderEngagementPanels($engagementMetricsContent, $this->renderEventHelperPanel(), $engagementView);
$goalSuggestions = $this->buildGoalSuggestions($topEvents, $topEventTargets, $pages, $landing);
$goalsContent = $this->renderToolbar($rangeMeta, $pageId, $template, $templates, 'goals');
$goalsContent .= $this->renderGoalsIntroPanel();
$goalsContent .= $this->renderGoalCards($goalStats);
$goalsContent .= $this->renderGoalTrendPanel($analytics, $goalSeries, $goalStats);
$goalsContent .= '<div class="pwna-grid-2">';
$goalsContent .= $this->renderSimpleTable('Goals and conversion rates', ['Goal', 'Rule', 'Type', 'Conversions', 'Unique visitors', 'Sessions', 'Rate'], $this->mapGoalRows($goalStats));
$goalsContent .= $this->renderGoalQuickGuidePanel();
$goalsContent .= '</div>';
$goalsContent .= $this->renderGoalBuilderPanel($analytics, $goalStats, $goalSuggestions);
$funnelContent = $this->renderToolbar($rangeMeta, $pageId, $template, $templates, 'funnel');
$funnelContent .= $this->renderFunnelPanel($analytics, $rangeSpec, $filters);
$sourcesContent = $this->renderToolbar($rangeMeta, $pageId, $template, $templates, 'sources');
$sourcesContent .= '<div class="pwna-grid-2">';
$sourcesContent .= $this->renderSimpleTable('Channels (first-touch sessions)', ['Channel', 'Sessions', 'Unique visitors'], $this->mapSessionRows($channels));
$sourcesContent .= $this->renderSimpleTable('Campaigns (first-touch sessions)', ['Campaign', 'Sessions', 'Unique visitors'], $this->mapSessionRows($attributedCampaigns));
$sourcesContent .= '</div>';
$sourcesContent .= '<div class="pwna-grid-2">';
$sourcesContent .= $this->renderSimpleTable('Top referrers', ['Referrer', 'Views'], $this->mapGenericRows($referrers, 'referrer_host'), true);
$sourcesContent .= $this->renderSimpleTable('Internal search terms', ['Search term', 'Views'], $this->mapGenericRows($searchTerms, 'search_term'));
$sourcesContent .= '</div>';
$sourcesContent .= '<div class="pwna-grid-2">';
$sourcesContent .= $this->renderSimpleTable('Campaigns / UTM traffic', ['Campaign', 'Views', 'Uniques', 'Sessions'], $this->mapCampaignRows($campaigns));
$sourcesContent .= $this->renderSimpleTable('404 pages', ['Missing path', 'Hits', 'Unique visitors'], $this->map404Rows($top404), true);
$sourcesContent .= '</div>';
$techContent = $this->renderToolbar($rangeMeta, $pageId, $template, $templates, 'tech');
$techContent .= '<div class="pwna-grid-3">';
$techContent .= $this->renderSimpleTable('Browsers', ['Browser', 'Views'], $this->mapGenericRows($browsers));
$techContent .= $this->renderSimpleTable('Devices', ['Device', 'Views'], $this->mapGenericRows($devices));
$techContent .= $this->renderSimpleTable('Operating systems', ['OS', 'Views'], $this->mapGenericRows($os));
$techContent .= '</div>';
if($this->user->hasPermission('nativeanalytics-manage')) {
$techContent .= $this->renderManageActions();
$techContent .= $this->renderHealthPanel($health);
}
$tabLabels = $this->getTabLabels();
$tabContent = $this->getTabs([
'overview' => $overviewContent,
'engagement' => $engagementContent,
'goals' => $goalsContent,
'funnel' => $funnelContent,
'compare' => $compareContent,
'sources' => $sourcesContent,
'tech' => $techContent,
]);
if(!isset($tabContent[$activeTab])) {
$keys = array_keys($tabContent);
$activeTab = $keys ? (string) reset($keys) : 'overview';
}
$activeContent = $tabContent[$activeTab] ?? '';
if($wireTabs) {
$wireTabItems = [];
foreach($tabContent as $key => $content) {
$wireTabItems[$tabLabels[$key] ?? ucfirst((string) $key)] = $content;
}
$out .= '<div id="pwna-wiretabs" class="pwna-wiretabs pwna-tabs-booting">';
$out .= $wireTabs->render($wireTabItems);
$out .= '</div>';
} else {
$out .= '<div id="pwna-wiretabs" class="pwna-wiretabs">';
$out .= $this->renderTabNav($activeTab, $rangeMeta, $pageId, $template, $compareMeta['selected']);
$out .= '<div class="pwna-tab-panels"><section class="pwna-tab-panel">' . $activeContent . '</section></div>';
$out .= '</div>';
}
$out .= $this->renderChartTooltipScript();
$out .= $this->renderTableSearchScript();
$out .= $this->renderExportDropdownScript();
$out .= $this->renderHelperToolsScript();
$out .= $this->renderAutoRefreshScript($rangeMeta, (int) $analytics->realtimeWindowMinutes, $pageId, $template);
$out .= $this->renderPageSearchScript();
if($wireTabs) $out .= $this->renderWireTabsScript($activeTab, $engagementView);
$out .= '</div>';
return $out;
}
public function ___executeExport() {
/** @var NativeAnalytics $analytics */
$analytics = $this->modules->get('NativeAnalytics');
$rangeMeta = $this->getRangeMeta($analytics);
$pageId = (int) $this->input->get('page_id');
$template = $this->sanitizer->name($this->input->get('template'));
$exportType = $this->sanitizer->name($this->input->get('export_type') ?: 'pages');
$filters = [];
if($pageId > 0) $filters['page_id'] = $pageId;
if($template !== '') $filters['template'] = $template;
$fp = fopen('php://temp', 'r+');
fputcsv($fp, ['range', $rangeMeta['label']], ',', '"', '\\');
if($exportType === 'referrers') {
$rows = $analytics->getTopReferrers($rangeMeta['rangeSpec'], 500, $filters);
fputcsv($fp, ['referrer', 'views'], ',', '"', '\\');
foreach($rows as $row) fputcsv($fp, [$row['referrer_host'], $row['views']], ',', '"', '\\');
} elseif($exportType === '404s') {
$rows = $analytics->getTop404Paths($rangeMeta['rangeSpec'], 500);
fputcsv($fp, ['path', 'hits', 'unique_visitors'], ',', '"', '\\');
foreach($rows as $row) fputcsv($fp, [$row['path'], $row['views'], $row['uniques']], ',', '"', '\\');
} elseif($exportType === 'events') {
$rows = $analytics->getTopEvents($rangeMeta['rangeSpec'], 500, $filters);
fputcsv($fp, ['event_name', 'event_group', 'event_label', 'events', 'unique_visitors', 'sessions'], ',', '"', '\\');
foreach($rows as $row) fputcsv($fp, [$row['event_name'], $row['event_group'], $row['event_label'], $row['events'], $row['uniques'], $row['sessions']], ',', '"', '\\');
} else {
// Default: pages
$rows = $analytics->getTopPages($rangeMeta['rangeSpec'], 500, $filters);
fputcsv($fp, ['page_id', 'title', 'template', 'path', 'views', 'uniques', 'sessions'], ',', '"', '\\');
foreach($rows as $row) fputcsv($fp, [$row['page_id'], $row['page_title'], $row['template'], $row['path'], $row['views'], $row['uniques'], $row['sessions']], ',', '"', '\\');
}
rewind($fp);
$csv = stream_get_contents($fp);
fclose($fp);
$this->sendDownloadResponse((string) $csv, 'text/csv; charset=utf-8', 'native-analytics-' . $exportType . '-' . date('Ymd-His') . '.csv');
}
public function ___executePdf() {
/** @var NativeAnalytics $analytics */
$analytics = $this->modules->get('NativeAnalytics');
$report = $this->buildReportData($analytics);
$lines = $this->buildReportLines($report);
$pdf = $this->buildSimplePdf($lines);
$this->sendDownloadResponse($pdf, 'application/pdf', 'native-analytics-report-' . date('Ymd-His') . '.pdf');
}
public function ___executeDocx() {
/** @var NativeAnalytics $analytics */
$analytics = $this->modules->get('NativeAnalytics');
if(!class_exists('ZipArchive')) {
throw new WireException('ZipArchive is required for DOCX export.');
}
$report = $this->buildReportData($analytics);
$lines = $this->buildReportLines($report);
$docx = $this->buildSimpleDocx($lines);
$this->sendDownloadResponse($docx, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'native-analytics-report-' . date('Ymd-His') . '.docx');
}
protected function sendJsonResponse(array $payload, $statusCode = 200) {
if(function_exists('session_write_close')) @session_write_close();
while(ob_get_level() > 0) {
@ob_end_clean();
}
http_response_code((int) $statusCode);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('X-Content-Type-Options: nosniff');
echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
exit;
}
public function ___executePageSearch() {
if(!$this->user->hasPermission('nativeanalytics-view')) {
$this->sendJsonResponse(['ok' => false, 'results' => []], 403);
}
/** @var NativeAnalytics $analytics */
$analytics = $this->modules->get('NativeAnalytics');
$term = trim((string) $this->input->get('q'));
$limit = max(1, min(20, (int) ($this->input->get('limit') ?: 10)));
$termLength = function_exists('mb_strlen') ? mb_strlen($term) : strlen($term);
if($term === '' || $termLength < 2 || !$analytics || !method_exists($analytics, 'searchPagesWithData')) {
$this->sendJsonResponse(['ok' => true, 'results' => []]);
}
$rows = $analytics->searchPagesWithData($term, $limit);
$results = [];
foreach($rows as $row) {
$pageId = (int) ($row['page_id'] ?? 0);
$title = trim(strip_tags((string) ($row['page_title'] ?? '')));
$path = (string) ($row['path'] ?? '');
$template = (string) ($row['template'] ?? '');
$label = ($title !== '' ? $title : ($path !== '' ? $path : ('Page #' . $pageId)));
if($path !== '') $label .= ' — ' . $path;
$results[] = [
'page_id' => $pageId,
'title' => $title,
'path' => $path,
'template' => $template,
'views' => (int) ($row['views'] ?? 0),
'label' => $label,
];
}
$this->sendJsonResponse(['ok' => true, 'results' => $results]);
}
protected function sendDownloadResponse($content, $contentType, $filename) {
if(function_exists('session_write_close')) @session_write_close();
while(ob_get_level() > 0) {
@ob_end_clean();
}
header('Content-Type: ' . $contentType);
header('Content-Disposition: attachment; filename="' . str_replace('"', '', (string) $filename) . '"');
header('Content-Length: ' . strlen((string) $content));
header('Cache-Control: private, must-revalidate');
header('Pragma: public');
header('X-Content-Type-Options: nosniff');
echo $content;
exit;
}
protected function buildReportData(NativeAnalytics $analytics) {
$rangeMeta = $this->getRangeMeta($analytics);
$pageId = (int) $this->input->get('page_id');
$template = $this->sanitizer->name($this->input->get('template'));
$filters = [];
if($pageId > 0) $filters['page_id'] = $pageId;
if($template !== '') $filters['template'] = $template;
$compareMeta = $this->getCompareMeta($analytics, $rangeMeta);
$report = [
'generated_at' => $analytics->formatDisplayDateTime(date('Y-m-d H:i:s')),
'range_label' => $rangeMeta['label'],
'filters_label' => $this->buildFilterLabel($filters),
'compare_meta' => $compareMeta,
'summary' => $analytics->getSummary($rangeMeta['rangeSpec'], $filters),
'quality' => $analytics->getSessionQuality($rangeMeta['rangeSpec'], $filters),
'summary404' => $analytics->get404Summary($rangeMeta['rangeSpec']),
'top_pages' => $analytics->getTopPages($rangeMeta['rangeSpec'], 10, $filters),
'landing' => $analytics->getTopLandingPages($rangeMeta['rangeSpec'], 10, $filters),
'exits' => $analytics->getTopExitPages($rangeMeta['rangeSpec'], 10, $filters),
'referrers' => $analytics->getTopReferrers($rangeMeta['rangeSpec'], 10, $filters),
'search_terms' => $analytics->getTopSearchTerms($rangeMeta['rangeSpec'], 10, $filters),
'campaigns' => $analytics->getTopCampaigns($rangeMeta['rangeSpec'], 10, $filters),
'paths404' => $analytics->getTop404Paths($rangeMeta['rangeSpec'], 10),
'event_summary' => $analytics->getEventSummary($rangeMeta['rangeSpec'], $filters),
'top_events' => $analytics->getTopEvents($rangeMeta['rangeSpec'], 10, $filters),
'top_event_targets' => $analytics->getTopEventTargets($rangeMeta['rangeSpec'], 10, $filters),
];
if($compareMeta['enabled']) {
$report['compare'] = [
'label' => $compareMeta['label'],
'summary' => $analytics->getSummary($compareMeta['rangeSpec'], $filters),
'quality' => $analytics->getSessionQuality($compareMeta['rangeSpec'], $filters),
'summary404' => $analytics->get404Summary($compareMeta['rangeSpec']),
];
}
return $report;
}
protected function buildReportLines(array $report) {
$lines = [];
$lines[] = 'NativeAnalytics report';
$lines[] = 'Generated: ' . $report['generated_at'];
$lines[] = 'Range: ' . $report['range_label'];
$lines[] = 'Filters: ' . $report['filters_label'];
$lines[] = '';
$lines[] = 'Summary';
$lines[] = 'Views: ' . number_format((int) ($report['summary']['views'] ?? 0));
$lines[] = 'Unique visitors: ' . number_format((int) ($report['summary']['uniques'] ?? 0));
$lines[] = 'Sessions: ' . number_format((int) ($report['summary']['sessions'] ?? 0));
$lines[] = 'Avg pages / session: ' . number_format((float) ($report['quality']['avg_pages_per_session'] ?? 0), 2);
$lines[] = 'Single-page rate: ' . number_format((float) ($report['quality']['single_page_rate'] ?? 0), 1) . '%';
$lines[] = '404 hits: ' . number_format((int) ($report['summary404']['views'] ?? 0));
$lines[] = 'Tracked actions: ' . number_format((int) ($report['event_summary']['events'] ?? 0));
$lines[] = 'Action sessions: ' . number_format((int) ($report['event_summary']['sessions'] ?? 0));
$lines[] = '';
if(!empty($report['compare'])) {
$lines[] = 'Comparison';
$lines[] = 'Compared against: ' . (string) ($report['compare']['label'] ?? '');
$lines[] = 'Views: ' . number_format((int) ($report['compare']['summary']['views'] ?? 0)) . ' (' . $this->formatDeltaText((float) ($report['summary']['views'] ?? 0), (float) ($report['compare']['summary']['views'] ?? 0)) . ')';
$lines[] = 'Unique visitors: ' . number_format((int) ($report['compare']['summary']['uniques'] ?? 0)) . ' (' . $this->formatDeltaText((float) ($report['summary']['uniques'] ?? 0), (float) ($report['compare']['summary']['uniques'] ?? 0)) . ')';
$lines[] = 'Sessions: ' . number_format((int) ($report['compare']['summary']['sessions'] ?? 0)) . ' (' . $this->formatDeltaText((float) ($report['summary']['sessions'] ?? 0), (float) ($report['compare']['summary']['sessions'] ?? 0)) . ')';
$lines[] = 'Avg pages / session: ' . number_format((float) ($report['compare']['quality']['avg_pages_per_session'] ?? 0), 2) . ' (' . $this->formatDeltaText((float) ($report['quality']['avg_pages_per_session'] ?? 0), (float) ($report['compare']['quality']['avg_pages_per_session'] ?? 0), 1) . ')';
$lines[] = 'Single-page rate: ' . number_format((float) ($report['compare']['quality']['single_page_rate'] ?? 0), 1) . '% (' . $this->formatDeltaText((float) ($report['quality']['single_page_rate'] ?? 0), (float) ($report['compare']['quality']['single_page_rate'] ?? 0), 1) . ')';
$lines[] = '404 hits: ' . number_format((int) ($report['compare']['summary404']['views'] ?? 0)) . ' (' . $this->formatDeltaText((float) ($report['summary404']['views'] ?? 0), (float) ($report['compare']['summary404']['views'] ?? 0)) . ')';
$lines[] = '';
}
$sections = [
'Top pages' => [$report['top_pages'], 'page'],
'Top landing pages' => [$report['landing'], 'session_page'],
'Top exit pages' => [$report['exits'], 'session_page'],
'Top referrers' => [$report['referrers'], 'referrer'],
'Internal search terms' => [$report['search_terms'], 'search'],
'Campaigns / UTM traffic' => [$report['campaigns'], 'campaign'],
'404 pages' => [$report['paths404'], '404'],
'Top tracked actions' => [$report['top_events'], 'event'],
'Top action targets' => [$report['top_event_targets'], 'event_target'],
];
foreach($sections as $title => $bundle) {
[$rows, $type] = $bundle;
$lines[] = $title;
if(!$rows) {
$lines[] = 'No data.';
$lines[] = '';
continue;
}
$i = 1;
foreach($rows as $row) {
$lines[] = $this->formatReportRow($row, $type, $i);
$i++;
}
$lines[] = '';
}
return $lines;
}
protected function formatReportRow(array $row, $type, $index) {
if($type === 'page') {
$label = trim(strip_tags((string) (($row['page_title'] ?? '') ?: ($row['path'] ?? ''))));
return $index . '. ' . $label . ' | ' . (string) ($row['path'] ?? '/') . ' | views ' . (int) ($row['views'] ?? 0) . ', uniques ' . (int) ($row['uniques'] ?? 0) . ', sessions ' . (int) ($row['sessions'] ?? 0);
}
if($type === 'session_page') {
$label = trim(strip_tags((string) (($row['page_title'] ?? '') ?: ($row['path'] ?? ''))));
return $index . '. ' . $label . ' | ' . (string) ($row['path'] ?? '/') . ' | sessions ' . (int) ($row['sessions'] ?? 0);
}
if($type === 'referrer') {
return $index . '. ' . (string) ($row['referrer_host'] ?? '—') . ' | views ' . (int) ($row['views'] ?? 0);
}
if($type === 'search') {
return $index . '. ' . (string) ($row['search_term'] ?? '—') . ' | views ' . (int) ($row['views'] ?? 0);
}
if($type === 'campaign') {
return $index . '. ' . (string) ($row['label'] ?? '—') . ' | views ' . (int) ($row['views'] ?? 0) . ', uniques ' . (int) ($row['uniques'] ?? 0) . ', sessions ' . (int) ($row['sessions'] ?? 0);
}
if($type === '404') {
return $index . '. ' . (string) ($row['path'] ?? '—') . ' | hits ' . (int) ($row['views'] ?? 0) . ', uniques ' . (int) ($row['uniques'] ?? 0);
}
if($type === 'event') {
return $index . '. ' . (string) ($row['event_group'] ?? 'custom') . ' / ' . (string) ($row['event_name'] ?? 'event') . ' | ' . (string) ($row['event_label'] ?? '') . ' | events ' . (int) ($row['events'] ?? 0) . ', sessions ' . (int) ($row['sessions'] ?? 0);
}
if($type === 'event_target') {
return $index . '. ' . (string) ($row['event_target'] ?? '—') . ' | ' . (string) ($row['event_group'] ?? '') . ' | events ' . (int) ($row['events'] ?? 0) . ', sessions ' . (int) ($row['sessions'] ?? 0);
}
return $index . '. ' . json_encode($row);
}
protected function buildSimplePdf(array $lines) {
$pages = array_chunk($lines, 44);
$objects = [];
$objects[1] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
$objects[2] = 'PAGES_PLACEHOLDER';
$pageNum = 3;
$kids = [];
foreach($pages as $pageLines) {
$pageObj = $pageNum;
$contentObj = $pageNum + 1;
$kids[] = $pageObj . ' 0 R';
$stream = "BT
/F1 10 Tf
14 TL
50 790 Td
";
foreach($pageLines as $line) {
$stream .= '(' . $this->escapePdfText($this->toPdfEncoding($line)) . ") Tj
T*
";
}
$stream .= "ET";
$objects[$pageObj] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 1 0 R >> >> /Contents ' . $contentObj . ' 0 R >>';
$objects[$contentObj] = '<< /Length ' . strlen($stream) . " >>
stream
" . $stream . "
endstream";
$pageNum += 2;
}
$objects[2] = '<< /Type /Pages /Kids [' . implode(' ', $kids) . '] /Count ' . count($kids) . ' >>';
$catalogNum = $pageNum;
$objects[$catalogNum] = '<< /Type /Catalog /Pages 2 0 R >>';
ksort($objects);
$pdf = "%PDF-1.4
";
$offsets = [0];
foreach($objects as $num => $obj) {
$offsets[$num] = strlen($pdf);
$pdf .= $num . " 0 obj
" . $obj . "
endobj
";
}
$xrefPos = strlen($pdf);
$pdf .= 'xref' . "
0 " . (count($objects) + 1) . "
";
$pdf .= sprintf("%010d %05d f
", 0, 65535);
for($i = 1; $i <= count($objects); $i++) {
$pdf .= sprintf("%010d %05d n
", $offsets[$i], 0);
}
$pdf .= 'trailer << /Size ' . (count($objects) + 1) . ' /Root ' . $catalogNum . " 0 R >>
startxref
" . $xrefPos . "
%%EOF";
return $pdf;
}
protected function buildSimpleDocx(array $lines) {
$tmp = tempnam(sys_get_temp_dir(), 'pwna_docx_');
$zip = new \ZipArchive();
$zip->open($tmp, \ZipArchive::OVERWRITE);
$docBody = '';
foreach($lines as $line) {
if($line === '') {
$docBody .= '<w:p/>';
continue;
}
$docBody .= '<w:p><w:r><w:t xml:space="preserve">' . htmlspecialchars($line, ENT_XML1 | ENT_COMPAT, 'UTF-8') . '</w:t></w:r></w:p>';
}
$zip->addFromString('[Content_Types].xml', '<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>');
$zip->addFromString('_rels/.rels', '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>');
$zip->addFromString('word/document.xml', '<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>' . $docBody . '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>');
$zip->close();
$binary = file_get_contents($tmp);
@unlink($tmp);
return $binary === false ? '' : $binary;
}
protected function escapePdfText($text) {
return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $text);
}
protected function toPdfEncoding($text) {
$converted = @iconv('UTF-8', 'Windows-1252//TRANSLIT//IGNORE', (string) $text);
return $converted !== false ? $converted : (string) $text;
}
protected function handlePostActions(NativeAnalytics $analytics) {
$this->session->CSRF->validate();
$action = $this->input->post('pwna_action');
if($action === 'save_goal') {
$analytics->saveGoal($this->input->post->getArray());
$this->message('Goal saved.');
}
if($action === 'delete_goal') {
$analytics->deleteGoal((int) $this->input->post('goal_id'));
$this->warning('Goal deleted.');
}
if($action === 'save_funnel') {
$analytics->saveFunnelSteps((string) $this->input->post('funnel_steps'));
$this->message('Funnel updated.');
}
if($action === 'rebuild_today') {
$day = date('Y-m-d');
$analytics->rebuildDailyAggregate($day);
$analytics->rebuildEventDailyAggregate($day);
$analytics->rebuildGoalDailyAggregate($day);
$this->message("Rebuilt today's aggregate data.");
}
if($action === 'rebuild_yesterday') {
$day = date('Y-m-d', strtotime('-1 day'));
$analytics->rebuildDailyAggregate($day);
$analytics->rebuildEventDailyAggregate($day);
$analytics->rebuildGoalDailyAggregate($day);
$this->message("Rebuilt yesterday's aggregate data.");
}
if($action === 'purge_hits') {
$analytics->purgeOldHits();
$this->message('Old raw hits purged.');
}
if($action === 'purge_events') {
$analytics->purgeOldEvents();
$this->message('Old raw events purged.');
}
if($action === 'purge_realtime') {
$analytics->purgeOldRealtimeSessions();
$this->message('Old realtime sessions purged.');
}
if($action === 'cleanup_404s') {
$removed = $analytics->cleanupResolvable404s();
if($removed > 0) {
$this->message("Cleaned up {$removed} resolvable 404 record(s) — these paths now redirect to valid pages.");
} else {
$this->message('No resolvable 404 records found.');
}
}
if($action === 'cleanup_suspicious') {
$removed = $analytics->cleanupSuspiciousPaths();
if($removed > 0) {
$this->message("Cleaned up {$removed} suspicious probe record(s) from analytics data.");
} else {
$this->message('No suspicious probe records found.');
}
}
if($action === 'block_ip') {
$ipHash = trim((string) $this->input->post('ip_hash'));
if($ipHash !== '' && preg_match('/^[a-f0-9]{40,128}$/i', $ipHash)) {
$analytics->addIpToBlocklist('hash:' . $ipHash);
// Also remove this visitor's data from live sessions so they disappear immediately.
// The sessions table doesn't store ip_hash, so we bridge through hits via visitor_hash.
try {
$db = $this->wire('database');
$vstmt = $db->prepare("SELECT DISTINCT visitor_hash FROM `pwna_hits` WHERE ip_hash = :h");
$vstmt->execute([':h' => $ipHash]);
$visitors = $vstmt->fetchAll(\PDO::FETCH_COLUMN) ?: [];
if($visitors) {
$ph = implode(',', array_fill(0, count($visitors), '?'));
$del = $db->prepare("DELETE FROM `pwna_sessions` WHERE visitor_hash IN ({$ph})");
$del->execute($visitors);
}
} catch(\Throwable $e) {}
$this->message('IP blocked. This visitor will no longer be tracked.');
} else {
$this->error('Invalid IP hash.');
}
}
if($action === 'reset_analytics_data') {
$analytics->resetAnalyticsData();
$this->warning('All analytics data has been reset.');
}
}
protected function formatDate(NativeAnalytics $analytics, $value) {
return $analytics->formatDisplayDate($value);
}
protected function formatDateTime(NativeAnalytics $analytics, $value) {
return $analytics->formatDisplayDateTime($value);
}
protected function getRangeMeta(NativeAnalytics $analytics) {
$selectedRange = (string) $this->input->get('range');
if($selectedRange === '') $selectedRange = (string) $analytics->dashboardDefaultRange;
$rangeDays = ['7d' => 7, '30d' => 30, '90d' => 90, '365d' => 365][$selectedRange] ?? 30;
$fromDate = trim((string) $this->input->get('from_date'));
$toDate = trim((string) $this->input->get('to_date'));
$custom = ($fromDate !== '' || $toDate !== '');
$rangeSpec = $custom ? $analytics->getDateRangeBetween($fromDate, $toDate, $rangeDays) : $analytics->getDateRangeForDays($rangeDays);
$label = $custom ? $analytics->formatDisplayRange($rangeSpec) : ('Last ' . $rangeDays . ' days');
return [
'selectedRange' => $selectedRange,
'rangeDays' => $rangeDays,
'fromDate' => $custom ? $rangeSpec['start_date'] : '',
'toDate' => $custom ? $rangeSpec['end_date'] : '',
'rangeSpec' => $rangeSpec,
'label' => $label,
];
}
protected function renderBrandHeader(NativeAnalytics $analytics) {
$version = 'v' . NativeAnalytics::VERSION;
$sponsorUrl = 'https://github.com/sponsors/Roychgod';
$settingsUrl = $this->wire('config')->urls->admin . 'module/edit?name=NativeAnalytics';
$canManageModules = $this->user->isSuperuser() || $this->user->hasPermission('module-admin');
$out = '<section class="pwna-brand pwna-panel">';
$out .= '<div class="pwna-brand-title">';
$out .= '<i class="fa fa-bar-chart pwna-brand-icon" aria-hidden="true"></i>';
$out .= '<span>NativeAnalytics</span>';
$out .= '<span class="pwna-brand-version">' . $this->sanitizer->entities($version) . '</span>';
$out .= '<a class="pwna-donate-btn pwna-sponsor-btn" href="' . $this->sanitizer->entities($sponsorUrl) . '" target="_blank" rel="noopener noreferrer" title="Support NativeAnalytics development on GitHub Sponsors"><span aria-hidden="true">♥</span> Sponsor</a>';
$out .= '</div>';
if($canManageModules) {
$out .= '<div class="pwna-brand-actions">';
$out .= '<a class="pwna-settings-btn" href="' . $this->sanitizer->entities($settingsUrl) . '" title="Open NativeAnalytics module settings"><i class="fa fa-cog" aria-hidden="true"></i><span>Module settings</span></a>';
$out .= '</div>';
}
$out .= '</section>';
return $out;
}
protected function renderInlineCssFallback() {
$file = __DIR__ . '/assets/admin.css';
if(!is_file($file) || !is_readable($file)) return '';
$css = (string) file_get_contents($file);
if($css === '') return '';
$css = preg_replace('!\/\*.*?\*\/!s', '', $css);
$css = preg_replace('/\s+/', ' ', $css);
return '<style>' . trim($css) . '</style>';
}
protected function renderHealthPanel(array $health) {
$rows = [
['Module folder', $this->sanitizer->entities((string) ($health['module_dir'] ?? ''))],
['Raw hits rows', '<span id="pwna-health-hits">' . number_format((int) ($health['hits_count'] ?? 0)) . '</span>'],
['Realtime sessions rows', '<span id="pwna-health-sessions">' . number_format((int) ($health['sessions_count'] ?? 0)) . '</span>'],
['Daily aggregate rows', '<span id="pwna-health-daily">' . number_format((int) ($health['daily_count'] ?? 0)) . '</span>'],
['Tracked events rows', '<span id="pwna-health-events">' . number_format((int) ($health['events_count'] ?? 0)) . '</span>'],
['Event aggregate rows', number_format((int) ($health['event_daily_count'] ?? 0))],
['Configured goals', number_format((int) ($health['goals_count'] ?? 0))],
['Goal aggregate rows', number_format((int) ($health['goal_daily_count'] ?? 0))],
['Last raw hit', '<span id="pwna-health-last-hit">' . $this->sanitizer->entities((string) ($health['last_hit_at'] ?? '—')) . '</span>'],
['Last realtime session', '<span id="pwna-health-last-session">' . $this->sanitizer->entities((string) ($health['last_session_at'] ?? '—')) . '</span>'],
['Last tracked event', '<span id="pwna-health-last-event">' . $this->sanitizer->entities((string) ($health['last_event_at'] ?? '—')) . '</span>'],
];
return $this->renderSimpleTable('Diagnostics', ['Check', 'Value'], $rows);
}
protected function renderToolbar(array $rangeMeta, $pageId, $template, array $templates, $activeTab = 'overview') {
$params = [
'range' => $rangeMeta['selectedRange'],
'from_date' => $rangeMeta['fromDate'],
'to_date' => $rangeMeta['toDate'],
'tab' => $activeTab,
];
$engagementView = $activeTab === 'engagement' ? $this->getEngagementView() : 'metrics';
if($activeTab === 'engagement' && $engagementView !== 'metrics') $params['engage_view'] = $engagementView;
if($pageId > 0) $params['page_id'] = (int) $pageId;
if($template !== '') $params['template'] = $template;
$csvUrl = './export/?' . http_build_query($params);
$pdfUrl = './pdf/?' . http_build_query($params);
$docxUrl = './docx/?' . http_build_query($params);
$out = '<form class="pwna-toolbar pwna-panel pwna-toolbar-panel" method="get">';
$out .= $this->renderHelpIcon('The From and To fields override the quick range dropdown for the main analytics view.', 'Overview filters help', 'pwna-help-tip-corner pwna-help-tip-panel-corner');
$out .= '<input type="hidden" name="tab" value="' . $this->sanitizer->entities($activeTab) . '">';
if($activeTab === 'engagement') {
$out .= '<input type="hidden" name="engage_view" value="' . $this->sanitizer->entities($engagementView) . '" data-pwna-engage-input="1">';
}
$out .= '<div class="pwna-toolbar-main">';
$out .= '<div class="pwna-toolbar-left">';
$out .= '<label>Quick range <select name="range">';
foreach($this->getRangeOptions() as $value => $label) {
$out .= '<option value="' . $this->sanitizer->entities($value) . '"' . ($rangeMeta['selectedRange'] === $value ? ' selected' : '') . '>' . $this->sanitizer->entities($label) . '</option>';
}
$out .= '</select></label>';
$out .= '<label>From <input type="date" name="from_date" value="' . $this->sanitizer->entities($rangeMeta['fromDate']) . '"></label>';
$out .= '<label>To <input type="date" name="to_date" value="' . $this->sanitizer->entities($rangeMeta['toDate']) . '"></label>';
$out .= '<label>Page ID <input type="number" min="1" name="page_id" value="' . ($pageId > 0 ? (int) $pageId : '') . '"></label>';
$out .= '<label class="pwna-pagefinder-label">Find page <input type="search" class="pwna-pagefinder" data-pwna-page-search="./page-search/" data-pwna-page-target="page_id" placeholder="Title, path or ID" autocomplete="off"></label>';
$out .= '<label>Template <select name="template"><option value="">All templates</option>';
foreach($templates as $row) {
$value = $row['label'];
$out .= '<option value="' . $this->sanitizer->entities($value) . '"' . ($template === $value ? ' selected' : '') . '>' . $this->sanitizer->entities($value) . ' (' . (int) $row['views'] . ')</option>';
}
$out .= '</select></label>';
$out .= '<button class="ui-button" type="submit">Apply</button></div>';
$out .= '<div class="pwna-toolbar-right"><div class="pwna-export-actions">';
$out .= '<button class="pwna-secondary-btn pwna-refresh-btn" type="submit">Refresh now</button>';
$ddId = 'pwna-export-dd-' . $this->sanitizer->name($activeTab);
$menuId = $ddId . '-menu';
$out .= '<div class="pwna-export-dropdown" id="' . $ddId . '">';
$out .= '<button type="button" class="pwna-secondary-btn pwna-export-dropdown-btn" aria-haspopup="true" aria-expanded="false" aria-controls="' . $menuId . '">Export</button>';
$out .= '<div class="pwna-export-dropdown-menu" id="' . $menuId . '" role="menu">';
$out .= '<span class="pwna-export-dropdown-label">Full report</span>';
$out .= '<a href="' . $this->sanitizer->entities($pdfUrl) . '" role="menuitem">Export PDF (all data)</a>';
$out .= '<a href="' . $this->sanitizer->entities($docxUrl) . '" role="menuitem">Export DOCX (all data)</a>';
$out .= '<div class="pwna-export-dropdown-divider"></div>';
$out .= '<span class="pwna-export-dropdown-label">CSV by section</span>';
$out .= '<a href="' . $this->sanitizer->entities($csvUrl) . '" role="menuitem">Pages CSV</a>';
$out .= '<a href="' . $this->sanitizer->entities($csvUrl . '&export_type=referrers') . '" role="menuitem">Referrers CSV</a>';
$out .= '<a href="' . $this->sanitizer->entities($csvUrl . '&export_type=404s') . '" role="menuitem">404 pages CSV</a>';
$out .= '<a href="' . $this->sanitizer->entities($csvUrl . '&export_type=events') . '" role="menuitem">Events CSV</a>';
$out .= '</div></div>';
$out .= '</div></div>';
$out .= '</div>';
$out .= '<div class="pwna-toolbar-meta">';
$out .= '<div class="pwna-toolbar-status"><span class="pwna-note">Range: ' . $this->sanitizer->entities($rangeMeta['label']) . '</span></div>';
$out .= '</div>';
$out .= '</form>';
return $out;
}
protected function renderCompareToolbar(array $rangeMeta, array $compareMeta, $pageId, $template, array $templates) {
$params = [
'range' => $rangeMeta['selectedRange'],
'from_date' => $rangeMeta['fromDate'],
'to_date' => $rangeMeta['toDate'],
'tab' => 'compare',
'compare' => $compareMeta['selected'],
];
if($pageId > 0) $params['page_id'] = (int) $pageId;
if($template !== '') $params['template'] = $template;
$csvUrl = './export/?' . http_build_query($params);
$pdfUrl = './pdf/?' . http_build_query($params);
$docxUrl = './docx/?' . http_build_query($params);
$out = '<form class="pwna-toolbar pwna-panel pwna-toolbar-panel" method="get">';
$out .= $this->renderHelpIcon('Quick compare buttons apply ready-made period pairs. Use From and To only when you want a custom main period, then choose how it should be compared.', 'Compare help', 'pwna-help-tip-corner pwna-help-tip-panel-corner');
$out .= '<input type="hidden" name="tab" value="compare">';
$out .= '<input type="hidden" name="range" value="' . $this->sanitizer->entities($rangeMeta['selectedRange']) . '">';
$out .= '<div class="pwna-toolbar-main">';
$out .= '<div class="pwna-toolbar-left">';
$out .= '<label>From <input type="date" name="from_date" value="' . $this->sanitizer->entities($rangeMeta['fromDate']) . '"></label>';
$out .= '<label>To <input type="date" name="to_date" value="' . $this->sanitizer->entities($rangeMeta['toDate']) . '"></label>';
$out .= '<label>Compare against <select name="compare">';
foreach(['previous_period' => 'Previous period', 'previous_year' => 'Same period last year', 'none' => 'No comparison'] as $value => $label) {
$out .= '<option value="' . $this->sanitizer->entities($value) . '"' . ($compareMeta['selected'] === $value ? ' selected' : '') . '>' . $this->sanitizer->entities($label) . '</option>';
}
$out .= '</select></label>';
$out .= '<label>Page ID <input type="number" min="1" name="page_id" value="' . ($pageId > 0 ? (int) $pageId : '') . '"></label>';
$out .= '<label class="pwna-pagefinder-label">Find page <input type="search" class="pwna-pagefinder" data-pwna-page-search="./page-search/" data-pwna-page-target="page_id" placeholder="Title, path or ID" autocomplete="off"></label>';
$out .= '<label>Template <select name="template"><option value="">All templates</option>';
foreach($templates as $row) {
$value = $row['label'];
$out .= '<option value="' . $this->sanitizer->entities($value) . '"' . ($template === $value ? ' selected' : '') . '>' . $this->sanitizer->entities($value) . ' (' . (int) $row['views'] . ')</option>';
}
$out .= '</select></label>';
$out .= '<button class="ui-button" type="submit">Apply comparison</button></div>';
$out .= '<div class="pwna-toolbar-right"><div class="pwna-export-actions">';
$out .= '<button class="pwna-secondary-btn pwna-refresh-btn" type="submit">Refresh now</button>';
$out .= '<div class="pwna-export-dropdown" id="pwna-export-dd-compare">';
$out .= '<button type="button" class="pwna-secondary-btn pwna-export-dropdown-btn" aria-haspopup="true" aria-expanded="false" aria-controls="pwna-export-dd-compare-menu">Export</button>';
$out .= '<div class="pwna-export-dropdown-menu" id="pwna-export-dd-compare-menu" role="menu">';
$out .= '<span class="pwna-export-dropdown-label">Full report</span>';
$out .= '<a href="' . $this->sanitizer->entities($pdfUrl) . '" role="menuitem">Export PDF (all data)</a>';
$out .= '<a href="' . $this->sanitizer->entities($docxUrl) . '" role="menuitem">Export DOCX (all data)</a>';
$out .= '<div class="pwna-export-dropdown-divider"></div>';
$out .= '<span class="pwna-export-dropdown-label">CSV by section</span>';
$out .= '<a href="' . $this->sanitizer->entities($csvUrl) . '" role="menuitem">Pages CSV</a>';
$out .= '</div></div>';
$out .= '</div></div>';
$out .= '</div>';
$out .= '<div class="pwna-toolbar-meta">';
$out .= '<div class="pwna-toolbar-status">';
$out .= '<span class="pwna-note">Selected period: ' . $this->sanitizer->entities($rangeMeta['label']) . '</span>';
if($compareMeta['enabled']) {
$out .= '<span class="pwna-note">Compared with: ' . $this->sanitizer->entities($compareMeta['label']) . '</span>';
}
$out .= '</div>';
$out .= '<div class="pwna-export-actions">';
$out .= '</div>';
$out .= '<div class="pwna-quick-links">';