Repository navigation
Expand file tree
/
Copy pathNativeForum.module.php
More file actions
8446 lines (7568 loc) · 372 KB
/
Copy pathNativeForum.module.php
File metadata and controls
8446 lines (7568 loc) · 372 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;
/**
* Sanitize a CSS color value while keeping support for transparency and modern formats.
* Allows: hex (#RGB/#RGBA/#RRGGBB/#RRGGBBAA), rgb()/rgba(), hsl()/hsla(),
* CSS variables (var(--x)), and common keywords like transparent/currentColor.
* Blocks obvious CSS injection characters.
*/
if(!function_exists(__NAMESPACE__ . '\\sf_sanitize_css_color')) {
function sf_sanitize_css_color($value, $fallback = '') {
$v = trim((string) $value);
if($v === '') return $fallback;
// block obvious injection vectors
if(preg_match('/[;{}<>]/', $v)) return $fallback;
// keywords
$kw = strtolower($v);
$allowedKw = [
'transparent','currentcolor','inherit','initial','unset','revert','revert-layer'
];
if(in_array($kw, $allowedKw, true)) return $v;
// CSS variable
if(preg_match('/^var\(\s*--[a-z0-9_-]+\s*(?:,\s*[^)]+)?\)$/i', $v)) return $v;
// hex (#RGB/#RGBA/#RRGGBB/#RRGGBBAA)
if(preg_match('/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i', $v)) return $v;
// rgb/rgba/hsl/hsla (keep permissive but safe-ish)
if(preg_match('/^(?:rgb|rgba|hsl|hsla)\(\s*[-0-9.%\s,\/]+\)$/i', $v)) return $v;
return $fallback;
}
}
class NativeForum extends WireData implements Module, ConfigurableModule {
/**
* Prevent recursive tree-preset saves (saveConfig inside saveConfig hook).
*/
protected bool $sfApplyingTreePreset = false;
public static function getModuleInfo() {
return [
'title' => 'Native Forum',
'version' => 100,
'summary' => 'A complete community forum for ProcessWire: groups, categories, topics, replies, private messages, moderation, anti-spam, SEO/GEO and ready-made designs.',
'author' => 'Gregor Rojko (Pyxios)',
'href' => 'https://processwire.com/modules/native-forum/',
'icon' => 'comments',
'installs' => ['ProcessNativeForum'], // installing Native Forum also installs its admin
'autoload' => true, // autoload needed for reliable AJAX uploads
'singular' => true,
'requires' => ['ProcessWire>=3.0.200', 'PHP>=7.4'],
];
}
/**
* Autoload hook: catch attachment uploads before any template output.
*/
public function init() {
// Code/templates written for the module's former name keep working
$this->wire('modules')->setSubstitutes(['Simple' . 'Forum' => 'NativeForum', 'ProcessSimple' . 'Forum' => 'ProcessNativeForum']);
// NOTE: init() runs on EVERY request (front + admin). Keep it cheap:
// no filesystem writes, no field/template creation (that lives in install/upgrade).
$this->ensurePurifierCachePath();
// Apply forum tree preset on settings save
$this->addHookAfter('Modules::saveConfig', $this, 'hookAfterSaveConfig');
$this->addHookBefore('Modules::saveConfig', $this, 'hookBeforeSaveConfig');
// Front-end: upload endpoint, layout mode, SEO/GEO head, feeds, sitemap, llms.txt
$this->addHookBefore('Page::render', $this, 'hookBeforePageRender');
$this->addHookAfter('Page::render', $this, 'hookAfterPageRender', ['priority' => 200]);
$this->addHookBefore('TemplateFile::render', $this, 'hookBeforeTemplateFileRender');
// Keep reply counters / last activity fresh + clean up on delete
$this->addHookAfter('Pages::saved', $this, 'hookPageSaved');
// members imported from another site: their old password works once, then it is re-hashed for this site
$this->addHookAfter('Session::authenticate', $this, 'hookLegacyPassword');
$this->addHookAfter('Pages::deleted', $this, 'hookPageDeleted');
$this->registerUrlHooks();
}
/**
* Boolean setting that defaults to ON when never saved.
*/
public function cfgOn(string $key, bool $default = true): bool {
$v = $this->get($key);
if($v === null || $v === '') return $default;
return (int) $v === 1;
}
/**
* Is this page rendered by one of our front-end templates?
*/
public function isForumPage($page): bool {
if(!$page instanceof Page || !$page->id || !$page->template) return false;
return in_array((string) $page->template->name, $this->sfForumTemplateNames(), true);
}
/**
* Layout mode: 'standalone' = forum renders its own full HTML document (default, works everywhere),
* 'site' = forum output is wrapped by the site's _main.php (delayed output / markup regions).
*/
public function layoutMode(): string {
$m = (string) $this->get('layoutMode');
if($m === 'standalone') return 'standalone';
// 'site' or 'auto' (default): use the site's own layout (_main.php) when there is one.
$config = $this->wire('config');
$main = (string) $config->appendTemplateFile;
if($main === '' || !is_file($config->paths->templates . $main)) return 'standalone';
return 'site';
}
/**
* Before a forum page renders: AJAX upload endpoint, markdown view, layout switches.
*/
public function hookBeforePageRender(HookEvent $event) {
$page = $event->object;
if(!$this->isForumPage($page)) return;
// Only the main request page (not $page->render() of other pages inside templates)
if($page !== $this->wire('page')) return;
$input = $this->wire('input');
// 0a) Topic view counter (beacon/pixel): answered before any template/_init.php runs
if($page->template->name === 'forum-topic' && (int) $input->get('sf_view') === 1) {
$ua = (string) ($_SERVER['HTTP_USER_AGENT'] ?? '');
if($ua !== '' && !preg_match('~bot|crawl|spider|slurp|preview|monitor|curl|wget|python|headless~i', $ua)) {
$session = $this->wire('session');
$k = 'sf_topic_view_' . (int) $page->id;
$last = (int) $session->get($k);
if(!$last || (time() - $last) > 3600) { $session->set($k, time()); $this->bumpTopicViews($page); }
}
header('Content-Type: image/gif');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0, private');
header('X-Robots-Tag: noindex');
echo "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";
exit;
}
// 0) Anti-spam form token (JSON, never cached). Forms on cacheable pages (ProCache) carry no
// session data; the browser fetches a fresh token when the visitor starts using the form.
if($input->get('sf_token')) {
$this->respondFormToken((string) $input->get('sf_token'));
}
// 1) Attachment upload endpoint (JSON)
if((int) $input->post('sf_upload_attachment') === 1) {
$this->respondUpload();
}
// 2) GEO: clean markdown version of a topic for AI crawlers / LLM tools (?format=md)
if($page->template->name === 'forum-topic' && $input->get('format') === 'md' && $this->cfgOn('seoMarkdown')) {
if($this->canReadForum($this->wire('user'), $page) && $page->isPublic()) {
$event->replace = true;
$this->sfRawOutput = true;
header('Content-Type: text/markdown; charset=utf-8');
header('X-Robots-Tag: noindex');
$event->return = $this->seo()->topicMarkdown($page);
return;
}
}
// 2b) E-mail confirmation link (forum-register?verify=TOKEN)
if($page->template->name === 'forum-register' && $input->get('verify')) {
list($u, $ret, $err) = $this->confirmRegistration((string) $input->get('verify'));
$session = $this->wire('session');
if($u) {
$dest = $ret && strpos($ret, '/') === 0 && strpos($ret, '//') !== 0 ? $ret : $this->forumRoot()->url;
$session->setFor('NativeForum', 'flash', 'welcome');
$session->redirect($dest, false);
}
$session->redirect($page->url . '?verify_status=' . $err, false);
}
// 3) Replies have no page of their own: 301 to the post inside its topic
if($page->template->name === 'forum-reply') {
$ua = (string) ($_SERVER['HTTP_USER_AGENT'] ?? '');
if(preg_match('~facebookexternalhit|facebookcatalog|Facebot|Twitterbot|LinkedInBot|Slackbot|Discordbot|TelegramBot|WhatsApp|Viber|SkypeUriPreview|Pinterest|redditbot|Applebot|vkShare|Embedly|Iframely~i', $ua)
&& $this->canReadForum($this->wire('user'), $page->parent)) {
// link preview card for this reply (title, the reply's text, image)
// sent directly: never stored by ProCache/other page caches (it must always show the current post)
$html = $this->seo()->replySharePage($page, $this->replyUrl($page, true));
while(ob_get_level() > 0) @ob_end_clean();
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, max-age=0');
header('X-Robots-Tag: noindex');
echo $html;
exit;
}
$this->wire('session')->redirect($this->replyUrl($page), true);
}
// 4) Standalone layout: do not let the site's _init/_main wrap the forum.
// Runtime only (never saved): the forum template renders alone; in "site" mode the
// site's _main.php is rendered afterwards around it (see hookAfterPageRender).
$page->template->noAppendTemplateFile = 1;
$page->template->noPrependTemplateFile = 1; // _init.php runs once, together with _main.php
}
/**
* Inject fallback closures into forum-root.php scope for old site copies (prevents fatals).
*/
public function hookBeforeTemplateFileRender(HookEvent $event) {
$tf = $event->object;
if(!$tf || basename((string) $tf->filename) !== 'forum-root.php') return;
$vars = $event->arguments(0);
if(!is_array($vars)) $vars = [];
if(!isset($vars['renderBlock']) || !is_callable($vars['renderBlock'])) {
$sanitizer = $this->wire('sanitizer');
$vars['renderBlock'] = function($title, $cats, $isVipGroup = false) use ($sanitizer) {
echo "<div class='sf-panel sf-group'><div class='sf-card'><div class='sf-card-h'>" . $sanitizer->entities((string) $title) . "</div><div class='sf-card-b'>";
if($cats) foreach($cats as $cat) echo "<div class='sf-cat'><a class='sf-link-title' href='{$cat->url}'>" . $sanitizer->entities((string) $cat->title) . "</a></div>";
echo "</div></div></div>";
};
$event->setArgument(0, $vars);
}
}
/**
* After render: build a complete HTML document (standalone) and inject SEO/GEO head tags.
*/
public function hookAfterPageRender(HookEvent $event) {
$page = $event->object;
if(!$this->isForumPage($page) || $page !== $this->wire('page')) return;
if($this->sfRawOutput) return;
$html = (string) $event->return;
if($html === '' || strpos(ltrim($html), '{') === 0) return; // JSON responses
try { $html = $this->applyTextOverrides($html); } catch(\Throwable $e) {}
if($this->layoutMode() === 'site' && stripos($html, '<html') === false) {
$html = $this->wrapInSiteLayout($page, $html);
}
if($html === '' || strpos(ltrim($html), '{') === 0) return; // JSON responses
$ct = (string) $page->template->contentType;
if($ct !== '' && stripos($ct, 'html') === false) return;
// One-time welcome message after confirming the e-mail
try {
$flash = $this->wire('session')->getFor('NativeForum', 'flash');
if($flash === 'welcome') {
$this->wire('session')->removeFor('NativeForum', 'flash');
$name = $this->wire('sanitizer')->entities($this->displayName($this->wire('user')));
$alert = "<div class='sf-alert sf-alert-success sf-flash' role='status'>Welcome, <strong>{$name}</strong>! Your account is confirmed and you are logged in.</div>";
$html = preg_replace("~(class=['\"]sf-container['\"][^>]*>)~", '$1' . str_replace('$', '\\$', $alert), $html, 1);
}
} catch(\Throwable $e) {}
// Bootstrap theme on a site without Bootstrap ("Auto" mode): load Bootstrap 5 so the forum looks right
try { $html = $this->ensureBootstrapAssets($html); } catch(\Throwable $e) {}
// No site loader on forum pages: hide it from the very first paint (in <head>)
if((int) $this->get('disableSitePreloaderOnForum')) {
$pre = $this->preloaderBypassHtml();
if($pre !== '') {
if(preg_match('~<head\b[^>]*>~i', $html)) $html = preg_replace('~(<head\b[^>]*>)~i', '$1' . str_replace('$', '\\$', $pre), $html, 1);
else $html = $pre . $html;
}
}
try {
$html = $this->seo()->processDocument($page, $html, $this->layoutMode());
} catch(\Throwable $e) {
$this->wire('log')->save('native-forum', 'SEO: ' . $e->getMessage());
}
// Server timing (visible in the browser's DevTools → Network → Timing)
$ms = isset($_SERVER['REQUEST_TIME_FLOAT']) ? round((microtime(true) - (float) $_SERVER['REQUEST_TIME_FLOAT']) * 1000) : 0;
if($ms && !headers_sent()) header('Server-Timing: sf;desc="Native Forum page";dur=' . $ms, false);
if($ms && $this->wire('user')->isSuperuser()) $html .= "\n<!-- NativeForum: page built in {$ms} ms -->";
$event->return = $html;
}
/**
* Bootstrap theme, integration "Auto": when the page loads no Bootstrap stylesheet of its own,
* add Bootstrap 5 (CSS at the top of <head>, so site and forum styles still win; JS bundle at the end).
* Pages that already include Bootstrap (any version) are left alone. "Off" never loads anything.
*/
protected function ensureBootstrapAssets(string $html): string {
if((string) $this->get('frontendTheme') !== 'bootstrap') return $html;
$mode = (string) $this->get('bootstrapIntegration');
if($mode === '') $mode = ((int) $this->get('bootstrapAutoLoad')) ? 'force' : 'auto';
if($mode !== 'auto') return $html;
if(stripos($html, '<head') === false) return $html;
$cssUrl = trim((string) ($this->get('bootstrapCssUrl') ?: 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css'));
$jsUrl = trim((string) ($this->get('bootstrapJsUrl') ?: 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js'));
$isOurs = function($u) { return stripos($u, 'native-forum-bootstrap') !== false || stripos($u, 'sf-bs-compat') !== false || stripos($u, '/NativeForum/') !== false; };
$hasCss = false;
if(preg_match_all('~<link\b[^>]*href=["\']([^"\']*bootstrap[^"\']*\.css[^"\']*)~i', $html, $mm)) {
foreach($mm[1] as $u) if(!$isOurs($u)) { $hasCss = true; break; }
}
if(!$hasCss && $cssUrl !== '') {
$tag = "<link rel='stylesheet' id='sf-bootstrap-css' href='" . htmlspecialchars($cssUrl, ENT_QUOTES) . "' />";
if(preg_match('~<head\b[^>]*>(\s*<meta\b[^>]*>)*~i', $html)) $html = preg_replace('~(<head\b[^>]*>(\s*<meta\b[^>]*>)*)~i', '$1' . str_replace('$', '\\$', $tag), $html, 1);
}
$hasJs = false;
if(preg_match_all('~<script\b[^>]*src=["\']([^"\']*bootstrap[^"\']*\.js[^"\']*)~i', $html, $mm)) {
foreach($mm[1] as $u) if(!$isOurs($u)) { $hasJs = true; break; }
}
if(!$hasJs && !$hasCss && $jsUrl !== '') {
$tag = "<script src='" . htmlspecialchars($jsUrl, ENT_QUOTES) . "' defer></script>";
$pos = strripos($html, '</body>');
$html = $pos !== false ? substr($html, 0, $pos) . $tag . substr($html, $pos) : $html . $tag;
}
return $html;
}
/** CSS + JS that hide/remove the site's loader on forum pages. */
protected function preloaderBypassHtml(): string {
$raw = (string) ($this->get('preloaderHideSelectors') ?? '');
if(trim($raw) === '') $raw = "#preloader\n.preloader\n.page-loader\n#loader-wrapper";
$sels = [];
foreach(preg_split('/[\r\n,]+/', $raw) as $l) {
$l = trim($l);
if($l === '' || preg_match('~[{}<>;]~', $l)) continue;
if(preg_match('~^[A-Za-z][\w-]*$~', $l)) { $sels[] = '#' . $l; $sels[] = '.' . $l; } // bare name: id or class
else $sels[] = $l;
}
if(!$sels) return '';
$css = implode(',', $sels);
$js = json_encode(array_values(array_unique($sels)));
return "<style id='sf-no-loader'>{$css}{display:none!important;opacity:0!important;visibility:hidden!important;pointer-events:none!important}</style>"
. "<script>window.SF_DISABLE_SITE_PRELOADER=true;document.documentElement.classList.add('sf-disable-preloader');(function(){var s={$js};"
. "function k(){s.forEach(function(q){try{document.querySelectorAll(q).forEach(function(n){n.parentNode&&n.parentNode.removeChild(n);});}catch(e){}});"
. "var b=document.body;if(b&&getComputedStyle(b).overflow==='hidden'&&!document.querySelector('dialog[open]'))b.style.overflow='';}"
. "document.addEventListener('DOMContentLoaded',function(){k();try{var o=new MutationObserver(k);o.observe(document.body,{childList:true});setTimeout(function(){o.disconnect();},4000);}catch(e){}});window.addEventListener('load',k);})();</script>";
}
/**
* Render the site's own layout around the forum, exactly like ProcessWire would:
* _init.php (prepend) + a tiny stub template + _main.php (append), in ONE scope.
* Works with Markup Regions and with delayed output ($content). The forum markup is
* never parsed by Markup Regions and never touches the site's variables/functions;
* it is inserted at the marker afterwards.
*/
protected function wrapInSiteLayout(Page $page, string $forumHtml): string {
$config = $this->wire('config');
$marker = 'SFFORUMOUTPUT9c41x';
// Let CSS know the forum lives inside the site's layout (blend: transparent background, inherited font)
$forumHtml = preg_replace("~class=(['\"])sf-wrap ~", 'class=$1sf-wrap sf-in-site' . (trim((string) $this->get('designForumBg')) === '' && trim((string) $this->get('ds_global_colors_bg')) === '' && !(int) $this->get('designForumBgTransparent') ? ' sf-blend' : '') . ' ', $forumHtml, 1);
// Inside the site's layout the forum often sits in a narrower column than the screen: switch its own
// mobile layout by the forum's width (sf-container.css + a tiny width observer right after the markup).
$cqFile = __DIR__ . '/assets/css/sf-container.css';
if(is_file($cqFile)) {
$cqUrl = $config->urls($this) . 'assets/css/sf-container.css?v=' . (int) @filemtime($cqFile);
$bp = [];
if(preg_match('~Breakpoints: (\[[\d, ]*\])~', (string) @file_get_contents($cqFile, false, null, 0, 600), $bm)) $bp = (array) json_decode($bm[1], true);
if($bp) {
$forumHtml = "<link rel='stylesheet' href='" . $this->wire('sanitizer')->entities($cqUrl) . "' />" . $forumHtml
. "<script>(function(){var B=" . json_encode(array_values(array_map('intval', $bp))) . ";"
. "function f(w){var x=w.getBoundingClientRect().width;if(!x)return;B.forEach(function(n){w.classList.toggle('sf-cq-'+n,x<=Math.round(n*0.8));});}"
. "document.querySelectorAll('.sf-wrap.sf-in-site').forEach(function(w){f(w);if(window.ResizeObserver)new ResizeObserver(function(){f(w);}).observe(w);else window.addEventListener('resize',function(){f(w);});});})();</script>";
}
}
$rid = preg_replace('/[^A-Za-z0-9_-]/', '', (string) ($this->get('siteRegionId') ?: 'content')) ?: 'content';
$var = preg_replace('/[^A-Za-z0-9_]/', '', (string) ($this->get('siteContentVar') ?: 'content')) ?: 'content';
// Layouts that print the page body directly ($page->body) get the marker there too.
$bodyField = preg_replace('/[^A-Za-z0-9_]/', '', (string) ($this->get('siteBodyField') ?: 'body')) ?: 'body';
$prevBody = $page->getUnformatted($bodyField);
$page->setQuietly($bodyField, $marker);
// The site's _init.php/_main.php use paths relative to /site/templates/ (e.g. include("./_func.php")),
// exactly like ProcessWire renders them: run them from that directory. Any partial output of a
// failing layout is discarded so it never leaks into the page.
$obLevel = ob_get_level();
$cwd = getcwd();
try {
$tf = new TemplateFile(__DIR__ . '/template-files/sf-site-stub.php');
$this->wire($tf);
$tpl = $config->paths->templates;
if(method_exists($tf, 'setChdir')) $tf->setChdir(rtrim($tpl, '/'));
@chdir($tpl);
if($config->prependTemplateFile && is_file($tpl . $config->prependTemplateFile)) $tf->setPrependFilename($tpl . $config->prependTemplateFile);
$tf->setAppendFilename($tpl . $config->appendTemplateFile);
$tf->set('page', $page);
$tf->set('sfMarker', $marker);
$tf->set('sfRegionId', $rid);
$tf->set('sfContentVar', $var);
$tf->set('sfRegions', (bool) $config->useMarkupRegions);
$tf->setThrowExceptions(true);
$doc = (string) $tf->render();
if($cwd) @chdir($cwd);
} catch(\Throwable $e) {
while(ob_get_level() > $obLevel) @ob_end_clean();
if($cwd) @chdir($cwd);
$page->setQuietly($bodyField, $prevBody);
$this->wire('log')->save('native-forum', 'site layout: ' . $e->getMessage());
return $forumHtml;
}
$page->setQuietly($bodyField, $prevBody);
if($config->useMarkupRegions) {
$pos = stripos($doc, '<!DOCTYPE');
if($pos === false) $pos = stripos($doc, '<html');
if($pos !== false && $pos > 0) {
$before = substr($doc, 0, $pos);
$doc = substr($doc, $pos);
$mr = new WireMarkupRegions();
$this->wire($mr);
$mr->populate($doc, $before, ['useClassActions' => $config->installed < 1498132609]);
}
}
if(stripos($doc, '<html') === false) return $forumHtml;
return $this->placeForumInDocument($doc, $forumHtml, $marker, $rid);
}
/**
* Put the forum where the page content belongs:
* 1) where the layout printed the marker ($content / $page->body / region) — inside <body> only
* 2) inside the content region (configured id, then common ids, then <main>)
* 3) between </header> and <footer>
* Never above the site's header.
*/
protected function placeForumInDocument(string $doc, string $forumHtml, string $marker, string $rid): string {
$bodyPos = stripos($doc, '<body');
$bodyPos = $bodyPos === false ? 0 : $bodyPos;
$head = substr($doc, 0, $bodyPos);
$body = substr($doc, $bodyPos);
// Marker may also end up in <title>/meta (layouts that excerpt $page->body): remove it there.
$head = str_replace($marker, '', $head);
$p = strpos($body, $marker);
if($p !== false) {
// Use the first occurrence that is not inside an HTML attribute/tag
$ok = false;
while($p !== false) {
$lt = strrpos(substr($body, 0, $p), '<');
$gt = strrpos(substr($body, 0, $p), '>');
if($lt === false || ($gt !== false && $gt > $lt)) { $ok = true; break; }
$p = strpos($body, $marker, $p + 1);
}
if($ok) {
$body = substr($body, 0, $p) . $forumHtml . substr($body, $p + strlen($marker));
return $head . str_replace($marker, '', $body);
}
}
$body = str_replace($marker, '', $body);
// Content container by id (configured first), then the <main> element
$ids = array_unique([$rid, 'content', 'main', 'main-content', 'maincontent', 'page-content', 'primary', 'site-content', 'body-content']);
foreach($ids as $id) {
if(preg_match('~<([a-z][a-z0-9]*)\b[^>]*\bid=["\']' . preg_quote($id, '~') . '["\'][^>]*>~i', $body, $m, PREG_OFFSET_CAPTURE)) {
$res = $this->replaceElementInner($body, (int) $m[0][1], strtolower($m[1][0]), strlen($m[0][0]), $forumHtml);
if($res !== null) return $head . $res;
}
}
if(preg_match('~<main\b[^>]*>~i', $body, $m, PREG_OFFSET_CAPTURE)) {
$res = $this->replaceElementInner($body, (int) $m[0][1], 'main', strlen($m[0][0]), $forumHtml);
if($res !== null) return $head . $res;
}
// Between header and footer
$hp = stripos($body, '</header>');
if($hp !== false) {
$hp += 9;
return $head . substr($body, 0, $hp) . $forumHtml . substr($body, $hp);
}
$fp = stripos($body, '<footer');
if($fp !== false) return $head . substr($body, 0, $fp) . $forumHtml . substr($body, $fp);
return $head . preg_replace_callback('~<body\b[^>]*>~i', function($m) use ($forumHtml) { return $m[0] . $forumHtml; }, $body, 1);
}
/**
* Replace the inner HTML of the element whose opening tag starts at $openPos.
* Returns null when the closing tag cannot be found.
*/
protected function replaceElementInner(string $html, int $openPos, string $tag, int $openLen, string $inner): ?string {
$start = $openPos + $openLen;
$depth = 1;
$offset = $start;
$re = '~<(/?)' . preg_quote($tag, '~') . '\b[^>]*>~i';
while($depth > 0 && preg_match($re, $html, $m, PREG_OFFSET_CAPTURE, $offset)) {
$depth += $m[1][0] === '/' ? -1 : 1;
$offset = $m[0][1] + strlen($m[0][0]);
if($depth === 0) {
return substr($html, 0, $start) . $inner . substr($html, $m[0][1]);
}
}
return null;
}
/**
* URL hooks: {forum}/sitemap.xml, {forum}/feed.xml (RSS), /llms.txt (GEO)
*/
protected function registerUrlHooks(): void {
if(!method_exists($this->wire(), 'addHook')) return;
$self = $this;
$this->wire()->addHook('/(.*)/sitemap\.xml', function($e) use ($self) {
return $self->seo()->routeIfForum((string) $e->arguments(1), 'sitemap');
});
$this->wire()->addHook('/(.*)/feed\.xml', function($e) use ($self) {
return $self->seo()->routeIfForum((string) $e->arguments(1), 'feed');
});
if($this->cfgOn('seoLlmsTxt')) {
$this->wire()->addHook('/llms\.txt', function($e) use ($self) {
return $self->seo()->llmsTxt();
});
}
}
/** @var string|null Forum output held back from Markup Regions */
protected $sfStash = null;
/** @var bool Output is not HTML (markdown etc.) */
protected $sfRawOutput = false;
/** true while a bulk import runs (skips per-save cache clearing) */
public $sfBulk = false;
/** @var NativeForumTransfer|null */
protected $sfTransfer = null;
public function transfer(): NativeForumTransfer {
if(!$this->sfTransfer) {
require_once __DIR__ . '/NativeForumTransfer.php';
$this->sfTransfer = new NativeForumTransfer($this);
$this->wire($this->sfTransfer);
}
return $this->sfTransfer;
}
/** @var NativeForumSeo|null */
protected $sfSeo = null;
public function seo(): NativeForumSeo {
if(!$this->sfSeo) {
require_once __DIR__ . '/NativeForumSeo.php';
$this->sfSeo = new NativeForumSeo($this);
$this->wire($this->sfSeo);
}
return $this->sfSeo;
}
/** Per-request memo for the batched helpers below. */
protected $sfMemo = ['ustats' => [], 'tstats' => [], 'rurl' => [], 'users' => []];
protected function sfTplId(string $name): int {
static $ids = [];
if(!isset($ids[$name])) {
$t = $this->wire('templates')->get($name);
$ids[$name] = ($t && $t->id) ? (int) $t->id : 0;
}
return $ids[$name];
}
protected function sfFieldTable(string $name): string {
$f = $this->wire('fields')->get($name);
return ($f && $f->id) ? $f->getTable() : '';
}
/**
* Forum statistics for several users with a few aggregate SQL queries (no page loading).
* Returns [uid => ['messages','topics','replies','reaction','points','ratings']].
*/
public function userStats(array $uids): array {
$uids = array_values(array_unique(array_filter(array_map('intval', $uids))));
$out = [];
$need = [];
foreach($uids as $id) {
if(isset($this->sfMemo['ustats'][$id])) $out[$id] = $this->sfMemo['ustats'][$id];
else $need[] = $id;
}
if(!$need) return $out;
$empty = ['messages' => 0, 'topics' => 0, 'replies' => 0, 'reaction' => 0, 'points' => 0, 'ratings' => 0];
$res = array_fill_keys($need, $empty);
$tt = $this->sfTplId('forum-topic');
$rt = $this->sfTplId('forum-reply');
$aT = $this->sfFieldTable('forum_author');
if($aT && ($tt || $rt)) {
$db = $this->wire('database');
$in = implode(',', $need);
$tpl = implode(',', array_filter([$tt, $rt]));
$base = "FROM `$aT` a JOIN pages p ON p.id=a.pages_id WHERE a.data IN ($in) AND p.templates_id IN ($tpl) AND p.status<1024";
try {
$vT = $this->sfFieldTable('forum_vote_score');
$sql = "SELECT a.data AS uid, SUM(p.templates_id=$tt) AS t, SUM(p.templates_id=$rt) AS r" . ($vT ? ", COALESCE(SUM(v.data),0) AS vs" : ", 0 AS vs")
. " FROM `$aT` a JOIN pages p ON p.id=a.pages_id" . ($vT ? " LEFT JOIN `$vT` v ON v.pages_id=p.id" : "")
. " WHERE a.data IN ($in) AND p.templates_id IN ($tpl) AND p.status<1024 GROUP BY a.data";
foreach($db->query($sql)->fetchAll(\PDO::FETCH_ASSOC) as $row) {
$u = (int) $row['uid'];
$res[$u]['topics'] = (int) $row['t'];
$res[$u]['replies'] = (int) $row['r'];
$res[$u]['messages'] = (int) $row['t'] + (int) $row['r'];
$res[$u]['reaction'] = (int) $row['vs'];
}
foreach(['points' => 'forum_like_users', 'ratings' => 'forum_vote_users'] as $key => $fname) {
$xT = $this->sfFieldTable($fname);
if(!$xT) continue;
$sql = "SELECT a.data AS uid, COUNT(x.data) AS n FROM `$aT` a JOIN pages p ON p.id=a.pages_id JOIN `$xT` x ON x.pages_id=p.id"
. " WHERE a.data IN ($in) AND p.templates_id IN ($tpl) AND p.status<1024 GROUP BY a.data";
foreach($db->query($sql)->fetchAll(\PDO::FETCH_ASSOC) as $row) $res[(int) $row['uid']][$key] = (int) $row['n'];
}
} catch(\Throwable $e) {
// leave zeros
}
unset($base);
}
foreach($res as $id => $s) { $this->sfMemo['ustats'][$id] = $s; $out[$id] = $s; }
return $out;
}
/**
* Reply count + newest reply for many topics in two SQL queries.
* Returns [topicId => ['replies' => int, 'last_id' => int, 'last_created' => int]].
* Visible replies only (same as a normal $pages->count() for guests).
*/
public function topicStats(array $topicIds, bool $includeHidden = false): array {
$ids = array_values(array_unique(array_filter(array_map('intval', $topicIds))));
$memoKey = $includeHidden ? 'h' : 'v';
$out = [];
$need = [];
foreach($ids as $id) {
if(isset($this->sfMemo['tstats'][$memoKey][$id])) $out[$id] = $this->sfMemo['tstats'][$memoKey][$id];
else $need[] = $id;
}
if(!$need) return $out;
$res = array_fill_keys($need, ['replies' => 0, 'last_id' => 0, 'last_created' => 0]);
$rt = $this->sfTplId('forum-reply');
if($rt) {
$db = $this->wire('database');
$in = implode(',', $need);
$st = $includeHidden ? 'p.status<8192' : 'p.status<1024';
try {
$sql = "SELECT p.parent_id AS tid, COUNT(*) AS n, MAX(p.created) AS mc FROM pages p WHERE p.parent_id IN ($in) AND p.templates_id=$rt AND $st GROUP BY p.parent_id";
$mc = [];
foreach($db->query($sql)->fetchAll(\PDO::FETCH_ASSOC) as $row) {
$res[(int) $row['tid']]['replies'] = (int) $row['n'];
$res[(int) $row['tid']]['last_created'] = strtotime((string) $row['mc']) ?: 0;
$mc[(int) $row['tid']] = (string) $row['mc'];
}
if($mc) {
$sql = "SELECT p.parent_id AS tid, MAX(p.id) AS id FROM pages p JOIN (SELECT parent_id, MAX(created) AS mc FROM pages p WHERE p.parent_id IN ($in) AND p.templates_id=$rt AND $st GROUP BY parent_id) m"
. " ON m.parent_id=p.parent_id AND m.mc=p.created WHERE p.templates_id=$rt AND $st GROUP BY p.parent_id";
foreach($db->query($sql)->fetchAll(\PDO::FETCH_ASSOC) as $row) $res[(int) $row['tid']]['last_id'] = (int) $row['id'];
}
} catch(\Throwable $e) {}
}
foreach($res as $id => $s) { $this->sfMemo['tstats'][$memoKey][$id] = $s; $out[$id] = $s; }
return $out;
}
/**
* Load many users at once (one query, forum fields joined) and keep them for the request.
* @return User[] keyed by id
*/
public function preloadUsers(array $uids): array {
$uids = array_values(array_unique(array_filter(array_map('intval', $uids))));
$need = array_values(array_diff($uids, array_keys($this->sfMemo['users'])));
if($need) {
$join = [];
foreach(['roles', 'forum_nickname', 'forum_rank', 'forum_post_count', 'forum_rank_manual_override', 'forum_signature', 'forum_country'] as $fn) {
if($this->wire('fields')->get($fn)) $join[] = $fn;
}
$pagesApi = $this->wire('pages');
$todo = [];
foreach($need as $id) {
$c = $pagesApi->getCache($id); // already in memory: no query
if($c instanceof User && $c->id) $this->sfMemo['users'][$id] = $c; else $todo[] = $id;
}
$found = [];
if($todo) {
try {
$found = $pagesApi->getById($todo, ['joinFields' => $join]);
} catch(\Throwable $e) {
$found = $this->wire('users')->find('id=' . implode('|', $todo) . ', include=all, check_access=0');
}
}
foreach($found as $u) if($u instanceof User) $this->sfMemo['users'][(int) $u->id] = $u;
foreach($need as $id) if(!isset($this->sfMemo['users'][$id])) $this->sfMemo['users'][$id] = null;
if(count($need) > 1) $this->userStats($need); // prime stats for user cards in one go
}
$out = [];
foreach($uids as $id) if(!empty($this->sfMemo['users'][$id])) $out[$id] = $this->sfMemo['users'][$id];
return $out;
}
/** [pageId => authorUserId] for many topics/replies, straight from the field table. */
public function authorIds(array $pageIds): array {
$ids = array_values(array_unique(array_filter(array_map('intval', $pageIds))));
$t = $this->sfFieldTable('forum_author');
if(!$ids || !$t) return [];
$out = [];
try {
foreach($this->wire('database')->query("SELECT pages_id, data FROM `$t` WHERE pages_id IN (" . implode(',', $ids) . ")")->fetchAll(\PDO::FETCH_NUM) as $r) $out[(int) $r[0]] = (int) $r[1];
} catch(\Throwable $e) {}
return $out;
}
/** Preload the authors of these topics/replies (one query each for ids and users). */
public function preloadAuthors($pages): void {
$ids = [];
foreach($pages as $p) if($p instanceof Page) $ids[] = (int) $p->id;
$map = $this->authorIds($ids);
if($map) $this->preloadUsers(array_values($map));
}
/** Get one user by id (request cache, no access checks). */
public function userById(int $id): ?User {
if($id <= 0) return null;
if(!array_key_exists($id, $this->sfMemo['users'])) $this->preloadUsers([$id]);
$u = $this->sfMemo['users'][$id] ?? null;
return ($u instanceof User && $u->id) ? $u : null;
}
/**
* +1 topic view without a page save (no hooks, no cache clearing, no ProCache flush).
*/
public function bumpTopicViews(Page $topic): void {
$t = $this->sfFieldTable('forum_views');
if(!$t || !$topic->id || !$topic->template->hasField('forum_views')) return;
try {
$q = $this->wire('database')->prepare("INSERT INTO `$t` (pages_id, data) VALUES (:id, 1) ON DUPLICATE KEY UPDATE data=data+1");
$q->execute([':id' => (int) $topic->id]);
} catch(\Throwable $e) {}
}
/**
* Store a user's read-tracking map without a full page save (it changes on almost every topic view).
*/
public function saveReadMap(User $u, array $map): void {
if(!$u->id || !$u->hasField('forum_read_topics')) return;
if(count($map) > 3000) { arsort($map); $map = array_slice($map, 0, 3000, true); }
$json = json_encode($map);
$t = $this->sfFieldTable('forum_read_topics');
try {
if(!$t) throw new WireException('no table');
$q = $this->wire('database')->prepare("INSERT INTO `$t` (pages_id, data) VALUES (:id, :d) ON DUPLICATE KEY UPDATE data=VALUES(data)");
$q->execute([':id' => (int) $u->id, ':d' => $json]);
$of = $u->of(); $u->of(false);
$u->setQuietly('forum_read_topics', $json);
$u->untrackChange('forum_read_topics');
$u->of($of);
} catch(\Throwable $e) {
$u->of(false); $u->set('forum_read_topics', $json); $u->save('forum_read_topics', ['quiet' => true, 'noHooks' => true]);
}
}
/** Templates can tell us a reply URL they already know (avoids position queries). */
public function primeReplyUrl(int $replyId, string $url): void {
$this->sfMemo['rurl'][$replyId] = $url;
}
/**
* Canonical URL of a reply: topic URL + page number + anchor.
*/
public function replyUrl(Page $reply, bool $http = false): string {
$topic = $reply->parent;
if(!$topic || !$topic->id) return $http ? $reply->httpUrl : $reply->url;
if(isset($this->sfMemo['rurl'][(int) $reply->id])) {
$rel = $this->sfMemo['rurl'][(int) $reply->id];
return $http ? substr($topic->httpUrl, 0, -strlen($topic->url)) . $rel : $rel;
}
$per = $this->postsPerPage();
// Position of the reply among replies (one SQL query; topic post itself is #1)
$pos = 0;
try {
$rt = $this->sfTplId('forum-reply');
$q = $this->wire('database')->prepare("SELECT COUNT(*) FROM pages WHERE parent_id=:t AND templates_id=:rt AND status<2048 AND (created<:c OR (created=:c2 AND id<:id))");
$c = date('Y-m-d H:i:s', (int) $reply->created);
$q->execute([':t' => (int) $topic->id, ':rt' => $rt, ':c' => $c, ':c2' => $c, ':id' => (int) $reply->id]);
$pos = (int) $q->fetchColumn();
} catch(\Throwable $e) { $pos = 0; }
$postIndex = $pos + 2; // 1-based, topic post = 1
$pageNum = (int) ceil($postIndex / $per);
$url = ($http ? $topic->httpUrl : $topic->url) . ($pageNum > 1 ? '?p=' . $pageNum : '');
$url .= '#reply-' . (int) $reply->id;
if(!$http) $this->sfMemo['rurl'][(int) $reply->id] = $url;
else $this->sfMemo['rurl'][(int) $reply->id] = $topic->url . ($pageNum > 1 ? '?p=' . $pageNum : '') . '#reply-' . (int) $reply->id;
return $url;
}
public function postsPerPage(): int {
$n = (int) ($this->get('postsPerPage') ?: 11);
return max(3, min(200, $n));
}
/**
* JSON upload endpoint (images/files attached in the editor).
*/
protected function respondUpload(): void {
while(ob_get_level()) ob_end_clean();
if(class_exists('\\Tracy\\Debugger')) { \Tracy\Debugger::$showBar = false; }
header('Content-Type: application/json; charset=utf-8');
header('X-Robots-Tag: noindex');
$input = $this->wire('input');
try {
$this->wire('session')->CSRF->validate('sfupl');
// nothing below needs the session: release its lock so parallel uploads don't queue
if(session_status() === PHP_SESSION_ACTIVE) @session_write_close();
if((int) $input->post('sf_upload_delete') === 1) {
echo json_encode($this->deleteTempUpload($this->wire('user'), $input));
} else {
echo json_encode($this->handleTempUpload($this->wire('user'), $input));
}
} catch(\Throwable $e) {
echo json_encode(['ok' => false, 'error' => 'Security check failed or the server rejected the upload. Refresh the page and try again.']);
}
exit;
}
/**
* Keep topic "last activity" fresh (used for sorting + unread) and clear index caches.
*/
/**
* Login of a member imported with "Passwords" (Export / Import): ProcessWire's check failed because
* the hash was made on the old site (with that site's userAuthSalt). Verify against the stored old
* hash; on success save the password with this site's hashing and forget the old hash.
*/
public function hookLegacyPassword(HookEvent $event) {
$user = $event->arguments(0);
$pass = (string) $event->arguments(1);
if(!$user instanceof User || !$user->id) return;
try {
$legacy = $user->meta('nf_legacy_pass');
if(!$legacy) return;
if($event->return) { $user->meta()->remove('nf_legacy_pass'); return; } // already has a working password here
if($pass === '' || !is_array($legacy) || empty($legacy['h']) || empty($legacy['s'])) return;
if(!$this->legacyPassMatches($pass, $legacy)) return;
$user->of(false);
$user->pass = $pass;
$this->wire('users')->save($user, ['quiet' => true]);
$user->meta()->remove('nf_legacy_pass');
$this->wire('log')->save('native-forum', 'Imported password upgraded for ' . $user->name);
$event->return = true;
} catch(\Throwable $e) {}
}
/** Same algorithm as ProcessWire's Password::hash(), with the old site's salt. */
protected function legacyPassMatches(string $pass, array $d): bool {
$salt1 = (string) $d['s'];
$salt2 = (string) ($d['a'] ?? '');
$stored = (string) $d['h'];
$isBlowfish = strpos($salt1, '$2y$') === 0 || strpos($salt1, '$2a$') === 0;
if($isBlowfish) {
$full = crypt($pass . $salt2, $salt1);
if(!is_string($full) || strlen($full) < 30) return false;
return hash_equals($stored, substr($full, 29));
}
$type = (string) ($d['t'] ?? '');
if($type === '') return hash_equals($stored, md5($pass));
$split = str_split($pass, (int) (strlen($pass) / 2) + 1);
return hash_equals($stored, hash($type, $salt1 . $split[0] . $salt2 . ($split[1] ?? ''), false));
}
public function hookPageSaved(HookEvent $event) {
if($this->sfBulk) return; // import: caches are cleared once at the end
$p = $event->arguments(0);
if(!$p instanceof Page || !$p->template) return;
$t = (string) $p->template->name;
if(!in_array($t, ['forum-topic','forum-reply','forum-category','forum-group'], true)) return;
// Render caches only (pending registrations / flood control live in the 'NativeForum' namespace)
try { $this->wire('cache')->deleteFor('NativeForumView'); } catch(\Throwable $e) {}
$this->clearProCacheFor($p);
}
/************************************************************
* REPORTS (moderation queue)
* Stored in their own small table: nativeforum_reports
************************************************************/
public function ensureReportsTable(): bool {
static $ok = null;
if($ok !== null) return $ok;
try {
$this->wire('database')->exec("CREATE TABLE IF NOT EXISTS nativeforum_reports (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
post_id INT UNSIGNED NOT NULL,
topic_id INT UNSIGNED NOT NULL DEFAULT 0,
post_author INT UNSIGNED NOT NULL DEFAULT 0,
reporter_id INT UNSIGNED NOT NULL DEFAULT 0,
reason VARCHAR(32) NOT NULL DEFAULT 'other',
comment TEXT NULL,
status VARCHAR(16) NOT NULL DEFAULT 'open',
created INT UNSIGNED NOT NULL DEFAULT 0,
handled_by INT UNSIGNED NOT NULL DEFAULT 0,
handled_at INT UNSIGNED NOT NULL DEFAULT 0,
action VARCHAR(32) NOT NULL DEFAULT '',
KEY post_id (post_id), KEY status (status), KEY created (created)
) DEFAULT CHARSET=utf8mb4");
$ok = true;
} catch(\Throwable $e) {
$ok = false;
}
return $ok;
}
public function reportReasons(): array {
return ['spam' => 'Spam / advertising', 'offensive' => 'Offensive or abusive', 'offtopic' => 'Off-topic / wrong forum', 'illegal' => 'Illegal content / copyright', 'other' => 'Other'];
}
/** Save a report (one open report per member and post). Returns the report id or 0. */
public function addReport(Page $post, User $reporter, string $reason, string $comment = ''): int {
if(!$this->ensureReportsTable() || !$post->id) return 0;
$reasons = $this->reportReasons();
if(!isset($reasons[$reason])) $reason = 'other';
$comment = trim($this->wire('sanitizer')->textarea($comment, ['maxLength' => 1000]));
$topicId = $post->template->name === 'forum-topic' ? (int) $post->id : (int) $post->parent_id;
$author = 0;
try { $a = $post->getUnformatted('forum_author'); if($a instanceof PageArray) $a = $a->first(); if($a instanceof Page) $author = (int) $a->id; } catch(\Throwable $e) {}
$db = $this->wire('database');
try {
$q = $db->prepare("SELECT id FROM nativeforum_reports WHERE post_id=:p AND reporter_id=:r AND status='open' LIMIT 1");
$q->execute([':p' => (int) $post->id, ':r' => (int) $reporter->id]);
$existing = (int) $q->fetchColumn();
if($existing) {
$q = $db->prepare("UPDATE nativeforum_reports SET reason=:reason, comment=:c, created=:t WHERE id=:id");
$q->execute([':reason' => $reason, ':c' => $comment, ':t' => time(), ':id' => $existing]);
return $existing;
}
$q = $db->prepare("INSERT INTO nativeforum_reports (post_id, topic_id, post_author, reporter_id, reason, comment, status, created) VALUES (:p,:t,:a,:r,:reason,:c,'open',:time)");
$q->execute([':p' => (int) $post->id, ':t' => $topicId, ':a' => $author, ':r' => (int) $reporter->id, ':reason' => $reason, ':c' => $comment, ':time' => time()]);
return (int) $db->lastInsertId();
} catch(\Throwable $e) {
return 0;
}
}
/** Reports grouped by post: [post_id => ['post_id','topic_id','post_author','count','last','reasons'=>[], 'items'=>[rows]]] */
public function reportsByPost(string $status = 'open', int $limit = 100): array {
if(!$this->ensureReportsTable()) return [];
$where = $status === 'all' ? '1' : ($status === 'closed' ? "status<>'open'" : "status='open'");
$out = [];
try {
$rows = $this->wire('database')->query("SELECT * FROM nativeforum_reports WHERE $where ORDER BY created DESC LIMIT " . (int) max(1, $limit * 5))->fetchAll(\PDO::FETCH_ASSOC);
foreach($rows as $r) {
$pid = (int) $r['post_id'];
if(!isset($out[$pid])) {
if(count($out) >= $limit) continue;
$out[$pid] = ['post_id' => $pid, 'topic_id' => (int) $r['topic_id'], 'post_author' => (int) $r['post_author'], 'count' => 0, 'last' => 0, 'reasons' => [], 'items' => [], 'status' => $r['status'], 'action' => $r['action'], 'handled_by' => (int) $r['handled_by'], 'handled_at' => (int) $r['handled_at']];
}
$out[$pid]['count']++;
$out[$pid]['last'] = max($out[$pid]['last'], (int) $r['created']);
$out[$pid]['reasons'][$r['reason']] = ($out[$pid]['reasons'][$r['reason']] ?? 0) + 1;
$out[$pid]['items'][] = $r;
}
} catch(\Throwable $e) {}
return $out;
}
public function openReportCount(): int {
if(!$this->ensureReportsTable()) return 0;
try { return (int) $this->wire('database')->query("SELECT COUNT(DISTINCT post_id) FROM nativeforum_reports WHERE status='open'")->fetchColumn(); }
catch(\Throwable $e) { return 0; }
}
/**
* Moderator action on all open reports of a post.
* $action: resolve | dismiss | hide | restore | lock | unlock | delete
*/
public function handleReport(int $postId, string $action, User $mod): string {
if(!$this->isModerator($mod) && !$mod->isSuperuser()) throw new WireException('Not allowed.');
$post = $this->wire('pages')->get($postId);
$msg = '';
if($post && $post->id && in_array($post->template->name, ['forum-topic', 'forum-reply'], true)) {
$post->of(false);
switch($action) {
case 'hide':
if($post->template->name === 'forum-reply' && $post->hasField('forum_is_deleted')) { $post->set('forum_is_deleted', 1); $post->save('forum_is_deleted'); }
else { $post->addStatus(Page::statusUnpublished); $post->save(); }
$msg = 'Post hidden.';
break;
case 'restore':
if($post->template->name === 'forum-reply' && $post->hasField('forum_is_deleted')) { $post->set('forum_is_deleted', 0); $post->save('forum_is_deleted'); }
$post->removeStatus(Page::statusUnpublished); $post->save();
$msg = 'Post restored.';
break;
case 'lock':
case 'unlock':
$t = $post->template->name === 'forum-topic' ? $post : $post->parent;
if($t && $t->id && $t->hasField('forum_is_locked')) { $t->of(false); $t->set('forum_is_locked', $action === 'lock' ? 1 : 0); $t->save('forum_is_locked'); }
$msg = $action === 'lock' ? 'Topic locked.' : 'Topic unlocked.';
break;
case 'delete':
$this->wire('pages')->trash($post);
$msg = 'Post moved to the trash.';
break;
}
}
if(in_array($action, ['resolve', 'dismiss', 'hide', 'delete', 'lock'], true)) {
try {
$q = $this->wire('database')->prepare("UPDATE nativeforum_reports SET status=:s, handled_by=:u, handled_at=:t, action=:a WHERE post_id=:p AND status='open'");
$q->execute([':s' => $action === 'dismiss' ? 'dismissed' : 'resolved', ':u' => (int) $mod->id, ':t' => time(), ':a' => $action, ':p' => $postId]);
} catch(\Throwable $e) {}
if($msg === '') $msg = $action === 'dismiss' ? 'Report dismissed.' : 'Report resolved.';
}
try { $this->wire('cache')->deleteFor('NativeForumView'); } catch(\Throwable $e) {}
return $msg;
}
/** Clear the whole ProCache cache (after an update or a settings change, so guests and link-preview crawlers get the new HTML). */
public function clearProCacheAll(): void {
try {
$m = $this->wire('modules');
if(!$m->isInstalled('ProCache')) return;
$pc = $m->get('ProCache');
if($pc && method_exists($pc, 'clearAll')) $pc->clearAll();
} catch(\Throwable $e) {}
}
/**
* ProCache: a new/edited post must show up for guests right away. Clear the post's topic,
* its category/group, the forum index and the feeds (only when ProCache is installed).
*/
protected function clearProCacheFor(Page $p): void {
static $done = [];
$modules = $this->wire('modules');