-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathMaintenance.php
More file actions
2333 lines (2006 loc) · 74 KB
/
Maintenance.php
File metadata and controls
2333 lines (2006 loc) · 74 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
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines https://www.simplemachines.org
* @copyright 2026 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* @version 3.0 Alpha 4
*/
declare(strict_types=1);
namespace SMF\Actions\Admin;
use SMF\ActionInterface;
use SMF\Actions\TopicRemove;
use SMF\ActionTrait;
use SMF\Cache\CacheApi;
use SMF\Category;
use SMF\Config;
use SMF\Db\DatabaseApi as Db;
use SMF\Draft;
use SMF\ErrorHandler;
use SMF\Group;
use SMF\IntegrationHook;
use SMF\ItemList;
use SMF\Lang;
use SMF\Logging;
use SMF\Menu;
use SMF\Sapi;
use SMF\SecurityToken;
use SMF\TaskRunner;
use SMF\Theme;
use SMF\Topic;
use SMF\User;
use SMF\Utils;
/**
* Forum maintenance. Important stuff.
*/
class Maintenance implements ActionInterface
{
use ActionTrait;
/*******************
* Public properties
*******************/
/**
* @var string
*
* The requested sub-action.
* This should be set by the constructor.
*/
public string $subaction = 'routine';
/**
* @var string
*
* The requested activity within the sub-action.
* This should be set by the constructor.
*/
public string $activity;
/**************************
* Public static properties
**************************/
/**
* @var array
*
* Available sub-actions.
*/
public static array $subactions = [
'routine' => [
'function' => 'routine',
'activities' => [
'version' => 'version',
'repair' => 'repair',
'recount' => 'recountBoards',
'rebuild_settings' => 'rebuildSettings',
'logs' => 'emptyLogs',
'cleancache' => 'cleanCache',
],
],
'database' => [
'function' => 'database',
'activities' => [
'optimize' => 'optimize',
'convertentities' => 'entitiesToUnicode',
'convertmsgbody' => 'changeMsgBodyLength',
],
],
'members' => [
'function' => 'members',
'template' => 'maintain_members',
'activities' => [
'reattribute' => 'reattribute',
'purgeinactive' => 'purgeInactiveMembers',
'recountposts' => 'recountPosts',
],
],
'topics' => [
'function' => 'topics',
'template' => 'maintain_topics',
'activities' => [
'massmove' => 'massMove',
'pruneold' => 'prunePosts',
'olddrafts' => 'pruneDrafts',
],
],
'hooks' => [
'function' => 'hooks',
],
'destroy' => [
'function' => 'destroy',
'activities' => [],
],
];
/****************
* Public methods
****************/
/**
* Dispatcher to whichever sub-action method is necessary.
*/
public function execute(): void
{
// You absolutely must be an admin by here!
User::$me->isAllowedTo('admin_forum');
// Need something to talk about?
Theme::loadTemplate('ManageMaintenance');
// This uses admin tabs - as it should!
Menu::$loaded['admin']->tab_data = [
'title' => Lang::getTxt('maintain_title', file: 'Admin'),
'description' => Lang::getTxt('maintain_info', file: 'Admin'),
'tabs' => [
'routine' => [],
'database' => [],
'members' => [],
'topics' => [],
],
];
// Set a few things.
Utils::$context['page_title'] = Lang::getTxt('maintain_title', file: 'Admin');
Utils::$context['sub_action'] = $this->subaction;
Utils::$context['sub_template'] = self::$subactions[$this->subaction]['template'] ?? 'options';
$call = \is_string(self::$subactions[$this->subaction]['function']) && method_exists($this, self::$subactions[$this->subaction]['function']) ? [$this, self::$subactions[$this->subaction]['function']] : Utils::getCallable(self::$subactions[$this->subaction]['function']);
if (!empty($call)) {
\call_user_func($call);
}
// Any special activity?
if (!empty($this->activity)) {
$call = \is_string(self::$subactions[$this->subaction]['activities'][$this->activity]) && method_exists($this, self::$subactions[$this->subaction]['activities'][$this->activity]) ? [$this, self::$subactions[$this->subaction]['activities'][$this->activity]] : Utils::getCallable(self::$subactions[$this->subaction]['activities'][$this->activity]);
if (!empty($call)) {
\call_user_func($call);
}
}
// Create a maintenance token. Kinda hard to do it any other way.
SecurityToken::create('admin-maint');
}
/**
* Supporting function for the routine maintenance area.
*/
public function routine(): void
{
if (isset($_GET['done']) && \in_array($_GET['done'], ['recount', 'rebuild_settings'])) {
Utils::$context['maintenance_finished'] = Lang::getTxt('maintain_' . $_GET['done'], file: 'ManageMaintenance');
}
Utils::$context['template_layers'][] = 'maintain';
Utils::$context['options'] = array_combine(
array_keys(self::$subactions[$this->subaction]['activities']),
array_fill(0, \count(self::$subactions[$this->subaction]['activities']), []),
);
Utils::$context['post_url'] = Config::$scripturl . '?action=admin;area=maintain';
}
/**
* Supporting function for the database maintenance area.
*/
public function database(): void
{
Utils::$context['template_layers'][] = 'maintain';
Utils::$context['options'] = array_combine(
array_keys(self::$subactions[$this->subaction]['activities']),
array_fill(0, \count(self::$subactions[$this->subaction]['activities']), []),
);
Utils::$context['post_url'] = Config::$scripturl . '?action=admin;area=maintain;sa=database';
// Show some conversion options?
Utils::$context['convert_entities'] = true;
if (Config::$db_type == 'mysql') {
$body_type = array_column(Db::$db->list_columns('{db_prefix}messages', true), 'type', 'name')['body'];
Utils::$context['options']['convertmsgbody']['title'] = Lang::getTxt(($body_type == 'text' ? 'mediumtext' : 'text') . '_title', file: 'ManageMaintenance');
Utils::$context['options']['convertmsgbody']['info'] = Lang::getTxt('mediumtext_info', file: 'ManageMaintenance');
if ($body_type != 'text' && !empty(Config::$modSettings['max_messageLength']) && Config::$modSettings['max_messageLength'] < 65536) {
Utils::$context['options']['convertmsgbody']['after'] = '<p class="infobox">' . Lang::getTxt('convert_to_suggest_text', file: 'ManageMaintenance') . '</p>';
}
} else {
unset(Utils::$context['options']['convertmsgbody']);
}
if (isset($_GET['done']) && $_GET['done'] == 'convertentities') {
Utils::$context['maintenance_finished'] = Lang::getTxt('maintain_convertentities_title', file: 'ManageMaintenance');
}
}
/**
* Supporting function for the members maintenance area.
*/
public function members(): void
{
// Get membergroups - for deleting members and the like.
Utils::$context['membergroups'] = array_merge(
[new Group(Group::REGULAR, ['name' => Lang::getTxt('maintain_members_ungrouped', file: 'ManageMaintenance')])],
Group::load(),
);
if (isset($_GET['done']) && $_GET['done'] == 'recountposts') {
Utils::$context['maintenance_finished'] = Lang::getTxt('maintain_recountposts', file: 'ManageMaintenance');
}
Theme::loadJavaScriptFile('suggest.js', ['defer' => false, 'minimize' => true], 'smf_suggest');
}
/**
* Supporting function for the topics maintenance area.
*/
public function topics(): void
{
// Let's load up the boards in case they are useful.
Utils::$context['categories'] = [];
$result = Db::$db->query(
'SELECT b.id_board, b.name, b.child_level, c.name AS cat_name, c.id_cat
FROM {db_prefix}boards AS b
LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
WHERE {query_see_board}
AND redirect = {string:blank_redirect}',
[
'blank_redirect' => '',
],
identifier: 'order_by_board_order',
);
while ($row = Db::$db->fetch_assoc($result)) {
if (!isset(Utils::$context['categories'][$row['id_cat']])) {
Utils::$context['categories'][$row['id_cat']] = [
'name' => $row['cat_name'],
'boards' => [],
];
}
Utils::$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = [
'id' => $row['id_board'],
'name' => $row['name'],
'child_level' => $row['child_level'],
];
}
Db::$db->free_result($result);
Category::sort(Utils::$context['categories']);
if (isset($_GET['done']) && $_GET['done'] == 'purgeold') {
Utils::$context['maintenance_finished'] = Lang::getTxt('maintain_old', file: 'ManageMaintenance');
} elseif (isset($_GET['done']) && $_GET['done'] == 'massmove') {
Utils::$context['maintenance_finished'] = Lang::getTxt('move_topics_maintenance', file: 'ManageMaintenance');
}
}
/**
* Oh noes! I'd document this but that would give it away.
*/
public function destroy(): void
{
echo '<!DOCTYPE html>
<html', Utils::$context['right_to_left'] ? ' dir="rtl"' : '', '><head><title>', Utils::$context['forum_name_html_safe'], ' deleted!</title></head>
<body style="background-color: orange; font-family: arial, sans-serif; text-align: center;">
<div style="margin-top: 8%; font-size: 400%; color: black;">Oh my, you killed ', Utils::$context['forum_name_html_safe'], '!</div>
<div style="margin-top: 7%; font-size: 500%; color: red;"><strong>You lazy bum!</strong></div>
</body></html>';
Utils::obExit(false);
}
/**
* Perform a detailed version check. A very good thing ;).
* The function parses the comment headers in all files for their version information,
* and outputs that for some javascript to check with simplemachines.org.
* It does not connect directly with simplemachines.org, but rather expects the client to.
*
* It requires the admin_forum permission.
* Uses the view_versions admin area.
* Accessed through ?action=admin;area=maintain;sa=routine;activity=version.
*/
public function version(): void
{
User::$me->isAllowedTo('admin_forum');
// Call the function that'll get all the version info we need.
$versionOptions = [
'include_root' => true,
'include_tasks' => true,
'sort_results' => true,
];
$version_info = ACP::getFileVersions($versionOptions);
// Add the new info to the template context.
Utils::$context += [
'root_versions' => $version_info['root_versions'],
'file_versions' => $version_info['file_versions'],
'default_template_versions' => $version_info['default_template_versions'],
'template_versions' => $version_info['template_versions'],
'default_language_versions' => $version_info['default_language_versions'],
'default_known_languages' => array_keys($version_info['default_language_versions']),
'tasks_versions' => $version_info['tasks_versions'],
];
// Make it easier to manage for the template.
Utils::$context['forum_version'] = SMF_FULL_VERSION;
Utils::$context['sub_template'] = 'view_versions';
Utils::$context['page_title'] = Lang::getTxt('admin_version_check', file: 'Admin');
}
/**
* Find and fix all errors on the forum.
*/
public function repair(): void
{
// Honestly, this should be done in the sub function.
SecurityToken::validate('admin-maint');
RepairBoards::call();
}
/**
* Recount many forum totals that can be recounted automatically without harm.
* it requires the admin_forum permission.
* It shows the maintain_forum admin area.
*
* Totals recounted:
* - fixes for topics with wrong num_replies.
* - updates for num_posts and num_topics of all boards.
* - recounts instant_messages but not unread_messages.
* - repairs messages pointing to boards with topics pointing to other boards.
* - updates the last message posted in boards and children.
* - updates member count, latest member, topic count, and message count.
*
* The function redirects back to ?action=admin;area=maintain when complete.
* It is accessed via ?action=admin;area=maintain;sa=database;activity=recount.
*/
public function recountBoards(): void
{
User::$me->isAllowedTo('admin_forum');
User::$me->checkSession('request');
// validate the request or the loop
SecurityToken::validate(!isset($_REQUEST['step']) ? 'admin-maint' : 'admin-boardrecount');
Utils::$context['not_done_token'] = 'admin-boardrecount';
SecurityToken::create(Utils::$context['not_done_token']);
Utils::$context['page_title'] = Lang::getTxt('not_done_title', file: 'Admin');
Utils::$context['continue_post_data'] = '';
Utils::$context['continue_countdown'] = 3;
Utils::$context['sub_template'] = 'not_done';
// Try for as much time as possible.
@set_time_limit(600);
// Step the number of topics at a time so things don't time out...
$request = Db::$db->query(
'SELECT MAX(id_topic)
FROM {db_prefix}topics',
[
],
);
list($max_topics) = Db::$db->fetch_row($request);
Db::$db->free_result($request);
$increment = min(max(50, ceil($max_topics / 4)), 2000);
if (empty($_REQUEST['start'])) {
$_REQUEST['start'] = 0;
}
$total_steps = 8;
// Get each topic with a wrong reply count and fix it - let's just do some at a time, though.
if (empty($_REQUEST['step'])) {
$_REQUEST['step'] = 0;
while ($_REQUEST['start'] < $max_topics) {
// Recount approved messages
$request = Db::$db->query(
'SELECT t.id_topic, MAX(t.num_replies) AS num_replies,
GREATEST(COUNT(ma.id_msg) - 1, 0) AS real_num_replies
FROM {db_prefix}topics AS t
LEFT JOIN {db_prefix}messages AS ma ON (ma.id_topic = t.id_topic AND ma.approved = {int:is_approved})
WHERE t.id_topic > {int:start}
AND t.id_topic <= {int:max_id}
GROUP BY t.id_topic
HAVING GREATEST(COUNT(ma.id_msg) - 1, 0) != MAX(t.num_replies)',
[
'is_approved' => 1,
'start' => $_REQUEST['start'],
'max_id' => $_REQUEST['start'] + $increment,
],
);
while ($row = Db::$db->fetch_assoc($request)) {
Db::$db->query(
'UPDATE {db_prefix}topics
SET num_replies = {int:num_replies}
WHERE id_topic = {int:id_topic}',
[
'num_replies' => $row['real_num_replies'],
'id_topic' => $row['id_topic'],
],
);
}
Db::$db->free_result($request);
// Recount unapproved messages
$request = Db::$db->query(
'SELECT t.id_topic, MAX(t.unapproved_posts) AS unapproved_posts,
COUNT(mu.id_msg) AS real_unapproved_posts
FROM {db_prefix}topics AS t
LEFT JOIN {db_prefix}messages AS mu ON (mu.id_topic = t.id_topic AND mu.approved = {int:not_approved})
WHERE t.id_topic > {int:start}
AND t.id_topic <= {int:max_id}
GROUP BY t.id_topic
HAVING COUNT(mu.id_msg) != MAX(t.unapproved_posts)',
[
'not_approved' => 0,
'start' => $_REQUEST['start'],
'max_id' => $_REQUEST['start'] + $increment,
],
);
while ($row = Db::$db->fetch_assoc($request)) {
Db::$db->query(
'UPDATE {db_prefix}topics
SET unapproved_posts = {int:unapproved_posts}
WHERE id_topic = {int:id_topic}',
[
'unapproved_posts' => $row['real_unapproved_posts'],
'id_topic' => $row['id_topic'],
],
);
}
Db::$db->free_result($request);
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3) {
Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=0;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
Utils::$context['continue_percent'] = round((100 * $_REQUEST['start'] / $max_topics) / $total_steps);
return;
}
}
$_REQUEST['start'] = 0;
}
// Update the post count of each board.
if ($_REQUEST['step'] <= 1) {
if (empty($_REQUEST['start'])) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET num_posts = {int:num_posts}
WHERE redirect = {string:redirect}',
[
'num_posts' => 0,
'redirect' => '',
],
);
}
while ($_REQUEST['start'] < $max_topics) {
$request = Db::$db->query(
'SELECT m.id_board, COUNT(*) AS real_num_posts
FROM {db_prefix}messages AS m
WHERE m.id_topic > {int:id_topic_min}
AND m.id_topic <= {int:id_topic_max}
AND m.approved = {int:is_approved}
GROUP BY m.id_board',
[
'id_topic_min' => $_REQUEST['start'],
'id_topic_max' => $_REQUEST['start'] + $increment,
'is_approved' => 1,
],
);
while ($row = Db::$db->fetch_assoc($request)) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET num_posts = num_posts + {int:real_num_posts}
WHERE id_board = {int:id_board}',
[
'id_board' => $row['id_board'],
'real_num_posts' => $row['real_num_posts'],
],
);
}
Db::$db->free_result($request);
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3) {
Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=1;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
Utils::$context['continue_percent'] = round((200 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
return;
}
}
$_REQUEST['start'] = 0;
}
// Update the topic count of each board.
if ($_REQUEST['step'] <= 2) {
if (empty($_REQUEST['start'])) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET num_topics = {int:num_topics}',
[
'num_topics' => 0,
],
);
}
while ($_REQUEST['start'] < $max_topics) {
$request = Db::$db->query(
'SELECT t.id_board, COUNT(*) AS real_num_topics
FROM {db_prefix}topics AS t
WHERE t.approved = {int:is_approved}
AND t.id_topic > {int:id_topic_min}
AND t.id_topic <= {int:id_topic_max}
GROUP BY t.id_board',
[
'is_approved' => 1,
'id_topic_min' => $_REQUEST['start'],
'id_topic_max' => $_REQUEST['start'] + $increment,
],
);
while ($row = Db::$db->fetch_assoc($request)) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET num_topics = num_topics + {int:real_num_topics}
WHERE id_board = {int:id_board}',
[
'id_board' => $row['id_board'],
'real_num_topics' => $row['real_num_topics'],
],
);
}
Db::$db->free_result($request);
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3) {
Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=2;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
Utils::$context['continue_percent'] = round((300 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
return;
}
}
$_REQUEST['start'] = 0;
}
// Update the unapproved post count of each board.
if ($_REQUEST['step'] <= 3) {
if (empty($_REQUEST['start'])) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET unapproved_posts = {int:unapproved_posts}',
[
'unapproved_posts' => 0,
],
);
}
while ($_REQUEST['start'] < $max_topics) {
$request = Db::$db->query(
'SELECT m.id_board, COUNT(*) AS real_unapproved_posts
FROM {db_prefix}messages AS m
WHERE m.id_topic > {int:id_topic_min}
AND m.id_topic <= {int:id_topic_max}
AND m.approved = {int:is_approved}
GROUP BY m.id_board',
[
'id_topic_min' => $_REQUEST['start'],
'id_topic_max' => $_REQUEST['start'] + $increment,
'is_approved' => 0,
],
);
while ($row = Db::$db->fetch_assoc($request)) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET unapproved_posts = unapproved_posts + {int:unapproved_posts}
WHERE id_board = {int:id_board}',
[
'id_board' => $row['id_board'],
'unapproved_posts' => $row['real_unapproved_posts'],
],
);
}
Db::$db->free_result($request);
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3) {
Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=3;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
Utils::$context['continue_percent'] = round((400 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
return;
}
}
$_REQUEST['start'] = 0;
}
// Update the unapproved topic count of each board.
if ($_REQUEST['step'] <= 4) {
if (empty($_REQUEST['start'])) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET unapproved_topics = {int:unapproved_topics}',
[
'unapproved_topics' => 0,
],
);
}
while ($_REQUEST['start'] < $max_topics) {
$request = Db::$db->query(
'SELECT t.id_board, COUNT(*) AS real_unapproved_topics
FROM {db_prefix}topics AS t
WHERE t.approved = {int:is_approved}
AND t.id_topic > {int:id_topic_min}
AND t.id_topic <= {int:id_topic_max}
GROUP BY t.id_board',
[
'is_approved' => 0,
'id_topic_min' => $_REQUEST['start'],
'id_topic_max' => $_REQUEST['start'] + $increment,
],
);
while ($row = Db::$db->fetch_assoc($request)) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET unapproved_topics = unapproved_topics + {int:real_unapproved_topics}
WHERE id_board = {int:id_board}',
[
'id_board' => $row['id_board'],
'real_unapproved_topics' => $row['real_unapproved_topics'],
],
);
}
Db::$db->free_result($request);
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3) {
Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=4;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
Utils::$context['continue_percent'] = round((500 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
return;
}
}
$_REQUEST['start'] = 0;
}
// Get all members with wrong number of personal messages.
if ($_REQUEST['step'] <= 5) {
$request = Db::$db->query(
'SELECT mem.id_member, COUNT(pmr.id_pm) AS real_num,
MAX(mem.instant_messages) AS instant_messages
FROM {db_prefix}members AS mem
LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted})
GROUP BY mem.id_member
HAVING COUNT(pmr.id_pm) != MAX(mem.instant_messages)',
[
'is_not_deleted' => 0,
],
);
while ($row = Db::$db->fetch_assoc($request)) {
User::updateMemberData($row['id_member'], ['instant_messages' => $row['real_num']]);
}
Db::$db->free_result($request);
$request = Db::$db->query(
'SELECT mem.id_member, COUNT(pmr.id_pm) AS real_num,
MAX(mem.unread_messages) AS unread_messages
FROM {db_prefix}members AS mem
LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted} AND pmr.is_read = {int:is_not_read})
GROUP BY mem.id_member
HAVING COUNT(pmr.id_pm) != MAX(mem.unread_messages)',
[
'is_not_deleted' => 0,
'is_not_read' => 0,
],
);
while ($row = Db::$db->fetch_assoc($request)) {
User::updateMemberData($row['id_member'], ['unread_messages' => $row['real_num']]);
}
Db::$db->free_result($request);
if (microtime(true) - TIME_START > 3) {
Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=0;' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
Utils::$context['continue_percent'] = round(700 / $total_steps);
return;
}
}
// Any messages pointing to the wrong board?
if ($_REQUEST['step'] <= 6) {
while ($_REQUEST['start'] < Config::$modSettings['maxMsgID']) {
$request = Db::$db->query(
'SELECT t.id_board, m.id_msg
FROM {db_prefix}messages AS m
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic AND t.id_board != m.id_board)
WHERE m.id_msg > {int:id_msg_min}
AND m.id_msg <= {int:id_msg_max}',
[
'id_msg_min' => $_REQUEST['start'],
'id_msg_max' => $_REQUEST['start'] + $increment,
],
);
$boards = [];
while ($row = Db::$db->fetch_assoc($request)) {
$boards[$row['id_board']][] = $row['id_msg'];
}
Db::$db->free_result($request);
foreach ($boards as $board_id => $messages) {
Db::$db->query(
'UPDATE {db_prefix}messages
SET id_board = {int:id_board}
WHERE id_msg IN ({array_int:id_msg_array})',
[
'id_msg_array' => $messages,
'id_board' => $board_id,
],
);
}
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3) {
Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
Utils::$context['continue_percent'] = round((700 + 100 * $_REQUEST['start'] / Config::$modSettings['maxMsgID']) / $total_steps);
return;
}
}
$_REQUEST['start'] = 0;
}
// Update the latest message of each board.
$request = Db::$db->query(
'SELECT m.id_board, MAX(m.id_msg) AS local_last_msg
FROM {db_prefix}messages AS m
WHERE m.approved = {int:is_approved}
GROUP BY m.id_board',
[
'is_approved' => 1,
],
);
$realBoardCounts = [];
while ($row = Db::$db->fetch_assoc($request)) {
$realBoardCounts[$row['id_board']] = $row['local_last_msg'];
}
Db::$db->free_result($request);
$request = Db::$db->query(
'SELECT id_board, id_parent, id_last_msg, child_level, id_msg_updated
FROM {db_prefix}boards',
[
],
);
$resort_me = [];
while ($row = Db::$db->fetch_assoc($request)) {
$row['local_last_msg'] = $realBoardCounts[$row['id_board']] ?? 0;
$resort_me[$row['child_level']][] = $row;
}
Db::$db->free_result($request);
krsort($resort_me);
$lastModifiedMsg = [];
foreach ($resort_me as $rows) {
foreach ($rows as $row) {
// The latest message is the latest of the current board and its children.
if (isset($lastModifiedMsg[$row['id_board']])) {
$curLastModifiedMsg = max($row['local_last_msg'], $lastModifiedMsg[$row['id_board']]);
} else {
$curLastModifiedMsg = $row['local_last_msg'];
}
// If what is and what should be the latest message differ, an update is necessary.
if ($row['local_last_msg'] != $row['id_last_msg'] || $curLastModifiedMsg != $row['id_msg_updated']) {
Db::$db->query(
'UPDATE {db_prefix}boards
SET id_last_msg = {int:id_last_msg}, id_msg_updated = {int:id_msg_updated}
WHERE id_board = {int:id_board}',
[
'id_last_msg' => $row['local_last_msg'],
'id_msg_updated' => $curLastModifiedMsg,
'id_board' => $row['id_board'],
],
);
}
// Parent boards inherit the latest modified message of their children.
if (isset($lastModifiedMsg[$row['id_parent']])) {
$lastModifiedMsg[$row['id_parent']] = max($row['local_last_msg'], $lastModifiedMsg[$row['id_parent']]);
} else {
$lastModifiedMsg[$row['id_parent']] = $row['local_last_msg'];
}
}
}
// Update all the basic statistics.
Logging::updateStats('member');
Logging::updateStats('message');
Logging::updateStats('topic');
// Finally, update the latest event times.
TaskRunner::calculateNextTrigger();
Utils::redirectexit('action=admin;area=maintain;sa=routine;done=recount');
}
/**
* Rebuilds Settings.php to make it nice and pretty.
*/
public function rebuildSettings(): void
{
User::$me->isAllowedTo('admin_forum');
Config::updateSettingsFile([], false, true);
Utils::redirectexit('action=admin;area=maintain;sa=routine;done=rebuild_settings');
}
/**
* Empties all unimportant logs
*/
public function emptyLogs(): void
{
User::$me->checkSession();
SecurityToken::validate('admin-maint');
// No one's online now.... MUHAHAHAHA :P.
Db::$db->query('DELETE FROM {db_prefix}log_online');
// Dump the banning logs.
Db::$db->query('DELETE FROM {db_prefix}log_banned');
// Start id_error back at 0 and dump the error log.
Db::$db->query(
'TRUNCATE {db_prefix}log_errors',
identifier: 'truncate_table',
);
// Clear out the spam log.
Db::$db->query('DELETE FROM {db_prefix}log_floodcontrol');
// Last but not least, the search logs!
Db::$db->query(
'TRUNCATE {db_prefix}log_search_topics',
identifier: 'truncate_table',
);
Db::$db->query(
'TRUNCATE {db_prefix}log_search_messages',
identifier: 'truncate_table',
);
Db::$db->query(
'TRUNCATE {db_prefix}log_search_results',
identifier: 'truncate_table',
);
Config::updateModSettings(['search_pointer' => 0]);
Utils::$context['maintenance_finished'] = Lang::getTxt('maintain_logs', file: 'ManageMaintenance');
}
/**
* Wipes the whole cache.
*/
public function cleanCache(): void
{
User::$me->checkSession();
SecurityToken::validate('admin-maint');
// Just wipe the whole cache!
CacheApi::clean();
Utils::$context['maintenance_finished'] = Lang::getTxt('maintain_cache', file: 'ManageMaintenance');
}
/**
* Optimizes all tables in the database and lists how much was saved.
* It requires the admin_forum permission.
* It shows as the maintain_forum admin area.
* It is accessed from ?action=admin;area=maintain;sa=database;activity=optimize.
* It also updates the optimize scheduled task such that the tables are not automatically optimized again too soon.
*
* @uses template_optimize()
*/
public function optimize(): void
{
User::$me->isAllowedTo('admin_forum');
User::$me->checkSession('request');
if (!isset($_SESSION['optimized_tables'])) {
SecurityToken::validate('admin-maint');
} else {
SecurityToken::validate('admin-optimize', 'post', false);
}
ignore_user_abort(true);
Utils::$context['page_title'] = Lang::getTxt('database_optimize', file: 'ManageMaintenance');
Utils::$context['sub_template'] = 'optimize';
Utils::$context['continue_post_data'] = '';
Utils::$context['continue_countdown'] = 3;
// Only optimize the tables related to this smf install, not all the tables in the db
$real_prefix = preg_match('~^(`?)(.+?)\1\.(.*?)$~', Db::$db->prefix, $match) === 1 ? $match[3] : Db::$db->prefix;
// Get a list of tables, as well as how many there are.
$temp_tables = Db::$db->list_tables(false, $real_prefix . '%');
$tables = [];
foreach ($temp_tables as $table) {
$tables[] = ['table_name' => $table];
}
// If there aren't any tables then I believe that would mean the world has exploded...
Utils::$context['num_tables'] = \count($tables);
if (Utils::$context['num_tables'] == 0) {
ErrorHandler::fatal('You appear to be running SMF in a flat file mode... fantastic!', false);
}
$_REQUEST['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
// Try for extra time due to large tables.
@set_time_limit(100);
// For each table....
$_SESSION['optimized_tables'] = !empty($_SESSION['optimized_tables']) ? $_SESSION['optimized_tables'] : [];
for ($key = $_REQUEST['start']; Utils::$context['num_tables'] - 1; $key++) {
if (empty($tables[$key])) {
break;
}
// Continue?
if (microtime(true) - TIME_START > 10) {
$_REQUEST['start'] = $key;
Utils::$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=optimize;start=' . $_REQUEST['start'] . ';' . Utils::$context['session_var'] . '=' . Utils::$context['session_id'];
Utils::$context['continue_percent'] = round(100 * $_REQUEST['start'] / Utils::$context['num_tables']);
Utils::$context['sub_template'] = 'not_done';