forked from SimpleMachines/SMF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathManageMaintenance.php
2328 lines (2010 loc) · 72.6 KB
/
ManageMaintenance.php
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
/**
* Forum maintenance. Important stuff.
*
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines https://www.simplemachines.org
* @copyright 2020 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.1 RC3
*/
if (!defined('SMF'))
die('No direct access...');
/**
* Main dispatcher, the maintenance access point.
* This, as usual, checks permissions, loads language files, and forwards to the actual workers.
*/
function ManageMaintenance()
{
global $txt, $context;
// You absolutely must be an admin by here!
isAllowedTo('admin_forum');
// Need something to talk about?
loadLanguage('ManageMaintenance');
loadTemplate('ManageMaintenance');
// This uses admin tabs - as it should!
$context[$context['admin_menu_name']]['tab_data'] = array(
'title' => $txt['maintain_title'],
'description' => $txt['maintain_info'],
'tabs' => array(
'routine' => array(),
'database' => array(),
'members' => array(),
'topics' => array(),
),
);
// So many things you can do - but frankly I won't let you - just these!
$subActions = array(
'routine' => array(
'function' => 'MaintainRoutine',
'template' => 'maintain_routine',
'activities' => array(
'version' => 'VersionDetail',
'repair' => 'MaintainFindFixErrors',
'recount' => 'AdminBoardRecount',
'logs' => 'MaintainEmptyUnimportantLogs',
'cleancache' => 'MaintainCleanCache',
),
),
'database' => array(
'function' => 'MaintainDatabase',
'template' => 'maintain_database',
'activities' => array(
'optimize' => 'OptimizeTables',
'convertentities' => 'ConvertEntities',
'convertmsgbody' => 'ConvertMsgBody',
),
),
'members' => array(
'function' => 'MaintainMembers',
'template' => 'maintain_members',
'activities' => array(
'reattribute' => 'MaintainReattributePosts',
'purgeinactive' => 'MaintainPurgeInactiveMembers',
'recountposts' => 'MaintainRecountPosts',
),
),
'topics' => array(
'function' => 'MaintainTopics',
'template' => 'maintain_topics',
'activities' => array(
'massmove' => 'MaintainMassMoveTopics',
'pruneold' => 'MaintainRemoveOldPosts',
'olddrafts' => 'MaintainRemoveOldDrafts',
),
),
'hooks' => array(
'function' => 'list_integration_hooks',
),
'destroy' => array(
'function' => 'Destroy',
'activities' => array(),
),
);
call_integration_hook('integrate_manage_maintenance', array(&$subActions));
// Yep, sub-action time!
if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
$subAction = $_REQUEST['sa'];
else
$subAction = 'routine';
// Doing something special?
if (isset($_REQUEST['activity']) && isset($subActions[$subAction]['activities'][$_REQUEST['activity']]))
$activity = $_REQUEST['activity'];
// Set a few things.
$context['page_title'] = $txt['maintain_title'];
$context['sub_action'] = $subAction;
$context['sub_template'] = !empty($subActions[$subAction]['template']) ? $subActions[$subAction]['template'] : '';
// Finally fall through to what we are doing.
call_helper($subActions[$subAction]['function']);
// Any special activity?
if (isset($activity))
call_helper($subActions[$subAction]['activities'][$activity]);
// Create a maintenance token. Kinda hard to do it any other way.
createToken('admin-maint');
}
/**
* Supporting function for the database maintenance area.
*/
function MaintainDatabase()
{
global $context, $db_type, $db_character_set, $modSettings, $smcFunc, $txt;
// Show some conversion options?
$context['convert_entities'] = isset($modSettings['global_character_set']) && $modSettings['global_character_set'] === 'UTF-8';
if ($db_type == 'mysql')
{
db_extend('packages');
$colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
foreach ($colData as $column)
if ($column['name'] == 'body')
$body_type = $column['type'];
$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
$context['convert_to_suggest'] = ($body_type != 'text' && !empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] < 65536);
}
if (isset($_GET['done']) && $_GET['done'] == 'convertentities')
$context['maintenance_finished'] = $txt['entity_convert_title'];
}
/**
* Supporting function for the routine maintenance area.
*/
function MaintainRoutine()
{
global $context, $txt;
if (isset($_GET['done']) && $_GET['done'] == 'recount')
$context['maintenance_finished'] = $txt['maintain_recount'];
}
/**
* Supporting function for the members maintenance area.
*/
function MaintainMembers()
{
global $context, $smcFunc, $txt;
// Get membergroups - for deleting members and the like.
$result = $smcFunc['db_query']('', '
SELECT id_group, group_name
FROM {db_prefix}membergroups',
array(
)
);
$context['membergroups'] = array(
array(
'id' => 0,
'name' => $txt['maintain_members_ungrouped']
),
);
while ($row = $smcFunc['db_fetch_assoc']($result))
{
$context['membergroups'][] = array(
'id' => $row['id_group'],
'name' => $row['group_name']
);
}
$smcFunc['db_free_result']($result);
if (isset($_GET['done']) && $_GET['done'] == 'recountposts')
$context['maintenance_finished'] = $txt['maintain_recountposts'];
loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
}
/**
* Supporting function for the topics maintenance area.
*/
function MaintainTopics()
{
global $context, $smcFunc, $txt, $sourcedir;
// Let's load up the boards in case they are useful.
$result = $smcFunc['db_query']('order_by_board_order', '
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}',
array(
'blank_redirect' => '',
)
);
$context['categories'] = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
if (!isset($context['categories'][$row['id_cat']]))
$context['categories'][$row['id_cat']] = array(
'name' => $row['cat_name'],
'boards' => array()
);
$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
'id' => $row['id_board'],
'name' => $row['name'],
'child_level' => $row['child_level']
);
}
$smcFunc['db_free_result']($result);
require_once($sourcedir . '/Subs-Boards.php');
sortCategories($context['categories']);
if (isset($_GET['done']) && $_GET['done'] == 'purgeold')
$context['maintenance_finished'] = $txt['maintain_old'];
elseif (isset($_GET['done']) && $_GET['done'] == 'massmove')
$context['maintenance_finished'] = $txt['move_topics_maintenance'];
}
/**
* Find and fix all errors on the forum.
*/
function MaintainFindFixErrors()
{
global $sourcedir;
// Honestly, this should be done in the sub function.
validateToken('admin-maint');
require_once($sourcedir . '/RepairBoards.php');
RepairBoards();
}
/**
* Wipes the whole cache directory.
* This only applies to SMF's own cache directory, though.
*/
function MaintainCleanCache()
{
global $context, $txt;
checkSession();
validateToken('admin-maint');
// Just wipe the whole cache directory!
clean_cache();
$context['maintenance_finished'] = $txt['maintain_cache'];
}
/**
* Empties all uninmportant logs
*/
function MaintainEmptyUnimportantLogs()
{
global $context, $smcFunc, $txt;
checkSession();
validateToken('admin-maint');
// No one's online now.... MUHAHAHAHA :P.
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}log_online');
// Dump the banning logs.
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}log_banned');
// Start id_error back at 0 and dump the error log.
$smcFunc['db_query']('truncate_table', '
TRUNCATE {db_prefix}log_errors');
// Clear out the spam log.
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}log_floodcontrol');
// Last but not least, the search logs!
$smcFunc['db_query']('truncate_table', '
TRUNCATE {db_prefix}log_search_topics');
$smcFunc['db_query']('truncate_table', '
TRUNCATE {db_prefix}log_search_messages');
$smcFunc['db_query']('truncate_table', '
TRUNCATE {db_prefix}log_search_results');
updateSettings(array('search_pointer' => 0));
$context['maintenance_finished'] = $txt['maintain_logs'];
}
/**
* Oh noes! I'd document this but that would give it away
*/
function Destroy()
{
global $context;
echo '<!DOCTYPE html>
<html', $context['right_to_left'] ? ' dir="rtl"' : '', '><head><title>', $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 ', $context['forum_name_html_safe'], '!</div>
<div style="margin-top: 7%; font-size: 500%; color: red;"><strong>You lazy bum!</strong></div>
</body></html>';
obExit(false);
}
/**
* Convert the column "body" of the table {db_prefix}messages from TEXT to MEDIUMTEXT and vice versa.
* It requires the admin_forum permission.
* This is needed only for MySQL.
* During the conversion from MEDIUMTEXT to TEXT it check if any of the posts exceed the TEXT length and if so it aborts.
* This action is linked from the maintenance screen (if it's applicable).
* Accessed by ?action=admin;area=maintain;sa=database;activity=convertmsgbody.
*
* @uses template_convert_msgbody()
*/
function ConvertMsgBody()
{
global $scripturl, $context, $txt, $db_type;
global $modSettings, $smcFunc;
// Show me your badge!
isAllowedTo('admin_forum');
if ($db_type != 'mysql')
return;
db_extend('packages');
$colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
foreach ($colData as $column)
if ($column['name'] == 'body')
$body_type = $column['type'];
$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
if ($body_type == 'text' || ($body_type != 'text' && isset($_POST['do_conversion'])))
{
checkSession();
validateToken('admin-maint');
// Make it longer so we can do their limit.
if ($body_type == 'text')
$smcFunc['db_change_column']('{db_prefix}messages', 'body', array('type' => 'mediumtext'));
// Shorten the column so we can have a bit (literally per record) less space occupied
else
$smcFunc['db_change_column']('{db_prefix}messages', 'body', array('type' => 'text'));
// 3rd party integrations may be interested in knowning about this.
call_integration_hook('integrate_convert_msgbody', array($body_type));
$colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
foreach ($colData as $column)
if ($column['name'] == 'body')
$body_type = $column['type'];
$context['maintenance_finished'] = $txt[$context['convert_to'] . '_title'];
$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
$context['convert_to_suggest'] = ($body_type != 'text' && !empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] < 65536);
return;
}
elseif ($body_type != 'text' && (!isset($_POST['do_conversion']) || isset($_POST['cont'])))
{
checkSession();
if (empty($_REQUEST['start']))
validateToken('admin-maint');
else
validateToken('admin-convertMsg');
$context['page_title'] = $txt['not_done_title'];
$context['continue_post_data'] = '';
$context['continue_countdown'] = 3;
$context['sub_template'] = 'not_done';
$increment = 500;
$id_msg_exceeding = isset($_POST['id_msg_exceeding']) ? explode(',', $_POST['id_msg_exceeding']) : array();
$request = $smcFunc['db_query']('', '
SELECT COUNT(*) as count
FROM {db_prefix}messages',
array()
);
list($max_msgs) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
// Try for as much time as possible.
@set_time_limit(600);
while ($_REQUEST['start'] < $max_msgs)
{
$request = $smcFunc['db_query']('', '
SELECT id_msg
FROM {db_prefix}messages
WHERE id_msg BETWEEN {int:start} AND {int:start} + {int:increment}
AND LENGTH(body) > 65535',
array(
'start' => $_REQUEST['start'],
'increment' => $increment - 1,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$id_msg_exceeding[] = $row['id_msg'];
$smcFunc['db_free_result']($request);
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3)
{
createToken('admin-convertMsg');
$context['continue_post_data'] = '
<input type="hidden" name="' . $context['admin-convertMsg_token_var'] . '" value="' . $context['admin-convertMsg_token'] . '">
<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '">
<input type="hidden" name="id_msg_exceeding" value="' . implode(',', $id_msg_exceeding) . '">';
$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertmsgbody;start=' . $_REQUEST['start'];
$context['continue_percent'] = round(100 * $_REQUEST['start'] / $max_msgs);
return;
}
}
createToken('admin-maint');
$context['page_title'] = $txt[$context['convert_to'] . '_title'];
$context['sub_template'] = 'convert_msgbody';
if (!empty($id_msg_exceeding))
{
if (count($id_msg_exceeding) > 100)
{
$query_msg = array_slice($id_msg_exceeding, 0, 100);
$context['exceeding_messages_morethan'] = sprintf($txt['exceeding_messages_morethan'], count($id_msg_exceeding));
}
else
$query_msg = $id_msg_exceeding;
$context['exceeding_messages'] = array();
$request = $smcFunc['db_query']('', '
SELECT id_msg, id_topic, subject
FROM {db_prefix}messages
WHERE id_msg IN ({array_int:messages})',
array(
'messages' => $query_msg,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$context['exceeding_messages'][] = '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>';
$smcFunc['db_free_result']($request);
}
}
}
/**
* Converts HTML-entities to their UTF-8 character equivalents.
* This requires the admin_forum permission.
* Pre-condition: UTF-8 has been set as database and global character set.
*
* It is divided in steps of 10 seconds.
* This action is linked from the maintenance screen (if applicable).
* It is accessed by ?action=admin;area=maintain;sa=database;activity=convertentities.
*
* @uses template_convert_entities()
*/
function ConvertEntities()
{
global $db_character_set, $modSettings, $context, $smcFunc, $db_type, $db_prefix;
isAllowedTo('admin_forum');
// Check to see if UTF-8 is currently the default character set.
if ($modSettings['global_character_set'] !== 'UTF-8')
fatal_lang_error('entity_convert_only_utf8');
// Some starting values.
$context['table'] = empty($_REQUEST['table']) ? 0 : (int) $_REQUEST['table'];
$context['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
$context['start_time'] = time();
$context['first_step'] = !isset($_REQUEST[$context['session_var']]);
$context['last_step'] = false;
// The first step is just a text screen with some explanation.
if ($context['first_step'])
{
validateToken('admin-maint');
createToken('admin-maint');
$context['sub_template'] = 'convert_entities';
return;
}
// Otherwise use the generic "not done" template.
$context['sub_template'] = 'not_done';
$context['continue_post_data'] = '';
$context['continue_countdown'] = 3;
// Now we're actually going to convert...
checkSession('request');
validateToken('admin-maint');
createToken('admin-maint');
$context['not_done_token'] = 'admin-maint';
// A list of tables ready for conversion.
$tables = array(
'ban_groups',
'ban_items',
'boards',
'calendar',
'calendar_holidays',
'categories',
'log_errors',
'log_search_subjects',
'membergroups',
'members',
'message_icons',
'messages',
'package_servers',
'personal_messages',
'pm_recipients',
'polls',
'poll_choices',
'smileys',
'themes',
);
$context['num_tables'] = count($tables);
// Loop through all tables that need converting.
for (; $context['table'] < $context['num_tables']; $context['table']++)
{
$cur_table = $tables[$context['table']];
$primary_key = '';
// Make sure we keep stuff unique!
$primary_keys = array();
if (function_exists('apache_reset_timeout'))
@apache_reset_timeout();
// Get a list of text columns.
$columns = array();
if ($db_type == 'postgresql')
$request = $smcFunc['db_query']('', '
SELECT column_name "Field", data_type "Type"
FROM information_schema.columns
WHERE table_name = {string:cur_table}
AND (data_type = \'character varying\' or data_type = \'text\')',
array(
'cur_table' => $db_prefix . $cur_table,
)
);
else
$request = $smcFunc['db_query']('', '
SHOW FULL COLUMNS
FROM {db_prefix}{raw:cur_table}',
array(
'cur_table' => $cur_table,
)
);
while ($column_info = $smcFunc['db_fetch_assoc']($request))
if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false)
$columns[] = strtolower($column_info['Field']);
// Get the column with the (first) primary key.
if ($db_type == 'postgresql')
$request = $smcFunc['db_query']('', '
SELECT a.attname "Column_name", \'PRIMARY\' "Key_name", attnum "Seq_in_index"
FROM pg_index i
JOIN pg_attribute a ON a.attrelid = i.indrelid
AND a.attnum = ANY(i.indkey)
WHERE i.indrelid = {string:cur_table}::regclass
AND i.indisprimary',
array(
'cur_table' => $db_prefix . $cur_table,
)
);
else
$request = $smcFunc['db_query']('', '
SHOW KEYS
FROM {db_prefix}{raw:cur_table}',
array(
'cur_table' => $cur_table,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
{
if ($row['Key_name'] === 'PRIMARY')
{
if ((empty($primary_key) || $row['Seq_in_index'] == 1) && !in_array(strtolower($row['Column_name']), $columns))
$primary_key = $row['Column_name'];
$primary_keys[] = $row['Column_name'];
}
}
$smcFunc['db_free_result']($request);
// No primary key, no glory.
// Same for columns. Just to be sure we've work to do!
if (empty($primary_key) || empty($columns))
continue;
// Get the maximum value for the primary key.
$request = $smcFunc['db_query']('', '
SELECT MAX({identifier:key})
FROM {db_prefix}{raw:cur_table}',
array(
'key' => $primary_key,
'cur_table' => $cur_table,
)
);
list($max_value) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
if (empty($max_value))
continue;
while ($context['start'] <= $max_value)
{
// Retrieve a list of rows that has at least one entity to convert.
$request = $smcFunc['db_query']('', '
SELECT {raw:primary_keys}, {raw:columns}
FROM {db_prefix}{raw:cur_table}
WHERE {raw:primary_key} BETWEEN {int:start} AND {int:start} + 499
AND {raw:like_compare}
LIMIT 500',
array(
'primary_keys' => implode(', ', $primary_keys),
'columns' => implode(', ', $columns),
'cur_table' => $cur_table,
'primary_key' => $primary_key,
'start' => $context['start'],
'like_compare' => '(' . implode(' LIKE \'%&#%\' OR ', $columns) . ' LIKE \'%&#%\')',
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
{
$insertion_variables = array();
$changes = array();
foreach ($row as $column_name => $column_value)
if ($column_name !== $primary_key && strpos($column_value, '&#') !== false)
{
$changes[] = $column_name . ' = {string:changes_' . $column_name . '}';
$insertion_variables['changes_' . $column_name] = preg_replace_callback('~&#(\d{1,5}|x[0-9a-fA-F]{1,4});~', 'fixchardb__callback', $column_value);
}
$where = array();
foreach ($primary_keys as $key)
{
$where[] = $key . ' = {string:where_' . $key . '}';
$insertion_variables['where_' . $key] = $row[$key];
}
// Update the row.
if (!empty($changes))
$smcFunc['db_query']('', '
UPDATE {db_prefix}' . $cur_table . '
SET
' . implode(',
', $changes) . '
WHERE ' . implode(' AND ', $where),
$insertion_variables
);
}
$smcFunc['db_free_result']($request);
$context['start'] += 500;
// After ten seconds interrupt.
if (time() - $context['start_time'] > 10)
{
// Calculate an approximation of the percentage done.
$context['continue_percent'] = round(100 * ($context['table'] + ($context['start'] / $max_value)) / $context['num_tables'], 1);
$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertentities;table=' . $context['table'] . ';start=' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
return;
}
}
$context['start'] = 0;
}
// If we're here, we must be done.
$context['continue_percent'] = 100;
$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;done=convertentities';
$context['last_step'] = true;
$context['continue_countdown'] = 3;
}
/**
* 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()
*/
function OptimizeTables()
{
global $db_prefix, $txt, $context, $smcFunc;
isAllowedTo('admin_forum');
checkSession('request');
if (!isset($_SESSION['optimized_tables']))
validateToken('admin-maint');
else
validateToken('admin-optimize', 'post', false);
ignore_user_abort(true);
db_extend();
$context['page_title'] = $txt['database_optimize'];
$context['sub_template'] = 'optimize';
$context['continue_post_data'] = '';
$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_prefix, $match) === 1 ? $match[3] : $db_prefix;
// Get a list of tables, as well as how many there are.
$temp_tables = $smcFunc['db_list_tables'](false, $real_prefix . '%');
$tables = array();
foreach ($temp_tables as $table)
$tables[] = array('table_name' => $table);
// If there aren't any tables then I believe that would mean the world has exploded...
$context['num_tables'] = count($tables);
if ($context['num_tables'] == 0)
fatal_error('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'] : array();
for ($key = $_REQUEST['start']; $context['num_tables'] - 1; $key++)
{
if (empty($tables[$key]))
break;
// Continue?
if (microtime(true) - TIME_START > 10)
{
$_REQUEST['start'] = $key;
$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=optimize;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
$context['continue_percent'] = round(100 * $_REQUEST['start'] / $context['num_tables']);
$context['sub_template'] = 'not_done';
$context['page_title'] = $txt['not_done_title'];
createToken('admin-optimize');
$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-optimize_token_var'] . '" value="' . $context['admin-optimize_token'] . '">';
if (function_exists('apache_reset_timeout'))
apache_reset_timeout();
return;
}
// Optimize the table! We use backticks here because it might be a custom table.
$data_freed = $smcFunc['db_optimize_table']($tables[$key]['table_name']);
if ($data_freed > 0)
$_SESSION['optimized_tables'][] = array(
'name' => $tables[$key]['table_name'],
'data_freed' => $data_freed,
);
}
// Number of tables, etc...
$txt['database_numb_tables'] = sprintf($txt['database_numb_tables'], $context['num_tables']);
$context['num_tables_optimized'] = count($_SESSION['optimized_tables']);
$context['optimized_tables'] = $_SESSION['optimized_tables'];
unset($_SESSION['optimized_tables']);
}
/**
* 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.
*/
function AdminBoardRecount()
{
global $txt, $context, $modSettings, $sourcedir, $smcFunc;
isAllowedTo('admin_forum');
checkSession('request');
// validate the request or the loop
if (!isset($_REQUEST['step']))
validateToken('admin-maint');
else
validateToken('admin-boardrecount');
$context['page_title'] = $txt['not_done_title'];
$context['continue_post_data'] = '';
$context['continue_countdown'] = 3;
$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 = $smcFunc['db_query']('', '
SELECT MAX(id_topic)
FROM {db_prefix}topics',
array(
)
);
list ($max_topics) = $smcFunc['db_fetch_row']($request);
$smcFunc['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 = $smcFunc['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)',
array(
'is_approved' => 1,
'start' => $_REQUEST['start'],
'max_id' => $_REQUEST['start'] + $increment,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$smcFunc['db_query']('', '
UPDATE {db_prefix}topics
SET num_replies = {int:num_replies}
WHERE id_topic = {int:id_topic}',
array(
'num_replies' => $row['real_num_replies'],
'id_topic' => $row['id_topic'],
)
);
$smcFunc['db_free_result']($request);
// Recount unapproved messages
$request = $smcFunc['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)',
array(
'not_approved' => 0,
'start' => $_REQUEST['start'],
'max_id' => $_REQUEST['start'] + $increment,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$smcFunc['db_query']('', '
UPDATE {db_prefix}topics
SET unapproved_posts = {int:unapproved_posts}
WHERE id_topic = {int:id_topic}',
array(
'unapproved_posts' => $row['real_unapproved_posts'],
'id_topic' => $row['id_topic'],
)
);
$smcFunc['db_free_result']($request);
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3)
{
createToken('admin-boardrecount');
$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=0;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
$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']))
$smcFunc['db_query']('', '
UPDATE {db_prefix}boards
SET num_posts = {int:num_posts}
WHERE redirect = {string:redirect}',
array(
'num_posts' => 0,
'redirect' => '',
)
);
while ($_REQUEST['start'] < $max_topics)
{
$request = $smcFunc['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',
array(
'id_topic_min' => $_REQUEST['start'],
'id_topic_max' => $_REQUEST['start'] + $increment,
'is_approved' => 1,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$smcFunc['db_query']('', '
UPDATE {db_prefix}boards
SET num_posts = num_posts + {int:real_num_posts}
WHERE id_board = {int:id_board}',
array(
'id_board' => $row['id_board'],
'real_num_posts' => $row['real_num_posts'],
)
);
$smcFunc['db_free_result']($request);
$_REQUEST['start'] += $increment;
if (microtime(true) - TIME_START > 3)
{
createToken('admin-boardrecount');
$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=1;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
$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']))
$smcFunc['db_query']('', '
UPDATE {db_prefix}boards
SET num_topics = {int:num_topics}',
array(
'num_topics' => 0,
)
);
while ($_REQUEST['start'] < $max_topics)
{
$request = $smcFunc['db_query']('', '
SELECT t.id_board, COUNT(*) AS real_num_topics