Passed
Pull Request — release-2.1 (#7164)
by John
04:10
created

get_integration_hooks_data()   C

Complexity

Conditions 14
Paths 196

Size

Total Lines 50
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 36
c 1
b 0
f 0
nc 196
nop 6
dl 0
loc 50
rs 5.4666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Forum maintenance. Important stuff.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines https://www.simplemachines.org
10
 * @copyright 2021 Simple Machines and individual contributors
11
 * @license https://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 RC4
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
/**
20
 * Main dispatcher, the maintenance access point.
21
 * This, as usual, checks permissions, loads language files, and forwards to the actual workers.
22
 */
23
function ManageMaintenance()
24
{
25
	global $txt, $context;
26
27
	// You absolutely must be an admin by here!
28
	isAllowedTo('admin_forum');
29
30
	// Need something to talk about?
31
	loadLanguage('ManageMaintenance');
32
	loadTemplate('ManageMaintenance');
33
34
	// This uses admin tabs - as it should!
35
	$context[$context['admin_menu_name']]['tab_data'] = array(
36
		'title' => $txt['maintain_title'],
37
		'description' => $txt['maintain_info'],
38
		'tabs' => array(
39
			'routine' => array(),
40
			'database' => array(),
41
			'members' => array(),
42
			'topics' => array(),
43
		),
44
	);
45
46
	// So many things you can do - but frankly I won't let you - just these!
47
	$subActions = array(
48
		'routine' => array(
49
			'function' => 'MaintainRoutine',
50
			'template' => 'maintain_routine',
51
			'activities' => array(
52
				'version' => 'VersionDetail',
53
				'repair' => 'MaintainFindFixErrors',
54
				'recount' => 'AdminBoardRecount',
55
				'logs' => 'MaintainEmptyUnimportantLogs',
56
				'cleancache' => 'MaintainCleanCache',
57
			),
58
		),
59
		'database' => array(
60
			'function' => 'MaintainDatabase',
61
			'template' => 'maintain_database',
62
			'activities' => array(
63
				'optimize' => 'OptimizeTables',
64
				'convertentities' => 'ConvertEntities',
65
				'convertmsgbody' => 'ConvertMsgBody',
66
			),
67
		),
68
		'members' => array(
69
			'function' => 'MaintainMembers',
70
			'template' => 'maintain_members',
71
			'activities' => array(
72
				'reattribute' => 'MaintainReattributePosts',
73
				'purgeinactive' => 'MaintainPurgeInactiveMembers',
74
				'recountposts' => 'MaintainRecountPosts',
75
			),
76
		),
77
		'topics' => array(
78
			'function' => 'MaintainTopics',
79
			'template' => 'maintain_topics',
80
			'activities' => array(
81
				'massmove' => 'MaintainMassMoveTopics',
82
				'pruneold' => 'MaintainRemoveOldPosts',
83
				'olddrafts' => 'MaintainRemoveOldDrafts',
84
			),
85
		),
86
		'hooks' => array(
87
			'function' => 'list_integration_hooks',
88
		),
89
		'destroy' => array(
90
			'function' => 'Destroy',
91
			'activities' => array(),
92
		),
93
	);
94
95
	call_integration_hook('integrate_manage_maintenance', array(&$subActions));
96
97
	// Yep, sub-action time!
98
	if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
99
		$subAction = $_REQUEST['sa'];
100
	else
101
		$subAction = 'routine';
102
103
	// Doing something special?
104
	if (isset($_REQUEST['activity']) && isset($subActions[$subAction]['activities'][$_REQUEST['activity']]))
105
		$activity = $_REQUEST['activity'];
106
107
	// Set a few things.
108
	$context['page_title'] = $txt['maintain_title'];
109
	$context['sub_action'] = $subAction;
110
	$context['sub_template'] = !empty($subActions[$subAction]['template']) ? $subActions[$subAction]['template'] : '';
111
112
	// Finally fall through to what we are doing.
113
	call_helper($subActions[$subAction]['function']);
114
115
	// Any special activity?
116
	if (isset($activity))
117
		call_helper($subActions[$subAction]['activities'][$activity]);
118
119
	// Create a maintenance token.  Kinda hard to do it any other way.
120
	createToken('admin-maint');
121
}
122
123
/**
124
 * Supporting function for the database maintenance area.
125
 */
126
function MaintainDatabase()
127
{
128
	global $context, $db_type, $db_character_set, $modSettings, $smcFunc, $txt;
129
130
	// Show some conversion options?
131
	$context['convert_entities'] = isset($modSettings['global_character_set']) && $modSettings['global_character_set'] === 'UTF-8';
132
133
	if ($db_type == 'mysql')
134
	{
135
		db_extend('packages');
136
137
		$colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
138
		foreach ($colData as $column)
139
			if ($column['name'] == 'body')
140
				$body_type = $column['type'];
141
142
		$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $body_type does not seem to be defined for all execution paths leading up to this point.
Loading history...
143
		$context['convert_to_suggest'] = ($body_type != 'text' && !empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] < 65536);
144
	}
145
146
	if (isset($_GET['done']) && $_GET['done'] == 'convertentities')
147
		$context['maintenance_finished'] = $txt['entity_convert_title'];
148
}
149
150
/**
151
 * Supporting function for the routine maintenance area.
152
 */
153
function MaintainRoutine()
154
{
155
	global $context, $txt;
156
157
	if (isset($_GET['done']) && $_GET['done'] == 'recount')
158
		$context['maintenance_finished'] = $txt['maintain_recount'];
159
}
160
161
/**
162
 * Supporting function for the members maintenance area.
163
 */
164
function MaintainMembers()
165
{
166
	global $context, $smcFunc, $txt;
167
168
	// Get membergroups - for deleting members and the like.
169
	$result = $smcFunc['db_query']('', '
170
		SELECT id_group, group_name
171
		FROM {db_prefix}membergroups',
172
		array(
173
		)
174
	);
175
	$context['membergroups'] = array(
176
		array(
177
			'id' => 0,
178
			'name' => $txt['maintain_members_ungrouped']
179
		),
180
	);
181
	while ($row = $smcFunc['db_fetch_assoc']($result))
182
	{
183
		$context['membergroups'][] = array(
184
			'id' => $row['id_group'],
185
			'name' => $row['group_name']
186
		);
187
	}
188
	$smcFunc['db_free_result']($result);
189
190
	if (isset($_GET['done']) && $_GET['done'] == 'recountposts')
191
		$context['maintenance_finished'] = $txt['maintain_recountposts'];
192
193
	loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
194
}
195
196
/**
197
 * Supporting function for the topics maintenance area.
198
 */
199
function MaintainTopics()
200
{
201
	global $context, $smcFunc, $txt, $sourcedir;
202
203
	// Let's load up the boards in case they are useful.
204
	$result = $smcFunc['db_query']('order_by_board_order', '
205
		SELECT b.id_board, b.name, b.child_level, c.name AS cat_name, c.id_cat
206
		FROM {db_prefix}boards AS b
207
			LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
208
		WHERE {query_see_board}
209
			AND redirect = {string:blank_redirect}',
210
		array(
211
			'blank_redirect' => '',
212
		)
213
	);
214
	$context['categories'] = array();
215
	while ($row = $smcFunc['db_fetch_assoc']($result))
216
	{
217
		if (!isset($context['categories'][$row['id_cat']]))
218
			$context['categories'][$row['id_cat']] = array(
219
				'name' => $row['cat_name'],
220
				'boards' => array()
221
			);
222
223
		$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
224
			'id' => $row['id_board'],
225
			'name' => $row['name'],
226
			'child_level' => $row['child_level']
227
		);
228
	}
229
	$smcFunc['db_free_result']($result);
230
231
	require_once($sourcedir . '/Subs-Boards.php');
232
	sortCategories($context['categories']);
233
234
	if (isset($_GET['done']) && $_GET['done'] == 'purgeold')
235
		$context['maintenance_finished'] = $txt['maintain_old'];
236
	elseif (isset($_GET['done']) && $_GET['done'] == 'massmove')
237
		$context['maintenance_finished'] = $txt['move_topics_maintenance'];
238
}
239
240
/**
241
 * Find and fix all errors on the forum.
242
 */
243
function MaintainFindFixErrors()
244
{
245
	global $sourcedir;
246
247
	// Honestly, this should be done in the sub function.
248
	validateToken('admin-maint');
249
250
	require_once($sourcedir . '/RepairBoards.php');
251
	RepairBoards();
252
}
253
254
/**
255
 * Wipes the whole cache directory.
256
 * This only applies to SMF's own cache directory, though.
257
 */
258
function MaintainCleanCache()
259
{
260
	global $context, $txt;
261
262
	checkSession();
263
	validateToken('admin-maint');
264
265
	// Just wipe the whole cache directory!
266
	clean_cache();
267
268
	$context['maintenance_finished'] = $txt['maintain_cache'];
269
}
270
271
/**
272
 * Empties all uninmportant logs
273
 */
274
function MaintainEmptyUnimportantLogs()
275
{
276
	global $context, $smcFunc, $txt;
277
278
	checkSession();
279
	validateToken('admin-maint');
280
281
	// No one's online now.... MUHAHAHAHA :P.
282
	$smcFunc['db_query']('', '
283
		DELETE FROM {db_prefix}log_online');
284
285
	// Dump the banning logs.
286
	$smcFunc['db_query']('', '
287
		DELETE FROM {db_prefix}log_banned');
288
289
	// Start id_error back at 0 and dump the error log.
290
	$smcFunc['db_query']('truncate_table', '
291
		TRUNCATE {db_prefix}log_errors');
292
293
	// Clear out the spam log.
294
	$smcFunc['db_query']('', '
295
		DELETE FROM {db_prefix}log_floodcontrol');
296
297
	// Last but not least, the search logs!
298
	$smcFunc['db_query']('truncate_table', '
299
		TRUNCATE {db_prefix}log_search_topics');
300
301
	$smcFunc['db_query']('truncate_table', '
302
		TRUNCATE {db_prefix}log_search_messages');
303
304
	$smcFunc['db_query']('truncate_table', '
305
		TRUNCATE {db_prefix}log_search_results');
306
307
	updateSettings(array('search_pointer' => 0));
308
309
	$context['maintenance_finished'] = $txt['maintain_logs'];
310
}
311
312
/**
313
 * Oh noes! I'd document this but that would give it away
314
 */
315
function Destroy()
316
{
317
	global $context;
318
319
	echo '<!DOCTYPE html>
320
		<html', $context['right_to_left'] ? ' dir="rtl"' : '', '><head><title>', $context['forum_name_html_safe'], ' deleted!</title></head>
321
		<body style="background-color: orange; font-family: arial, sans-serif; text-align: center;">
322
		<div style="margin-top: 8%; font-size: 400%; color: black;">Oh my, you killed ', $context['forum_name_html_safe'], '!</div>
323
		<div style="margin-top: 7%; font-size: 500%; color: red;"><strong>You lazy bum!</strong></div>
324
		</body></html>';
325
	obExit(false);
326
}
327
328
/**
329
 * Convert the column "body" of the table {db_prefix}messages from TEXT to MEDIUMTEXT and vice versa.
330
 * It requires the admin_forum permission.
331
 * This is needed only for MySQL.
332
 * During the conversion from MEDIUMTEXT to TEXT it check if any of the posts exceed the TEXT length and if so it aborts.
333
 * This action is linked from the maintenance screen (if it's applicable).
334
 * Accessed by ?action=admin;area=maintain;sa=database;activity=convertmsgbody.
335
 *
336
 * @uses template_convert_msgbody()
337
 */
338
function ConvertMsgBody()
339
{
340
	global $scripturl, $context, $txt, $db_type;
341
	global $modSettings, $smcFunc;
342
343
	// Show me your badge!
344
	isAllowedTo('admin_forum');
345
346
	if ($db_type != 'mysql')
347
		return;
348
349
	db_extend('packages');
350
351
	$colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
352
	foreach ($colData as $column)
353
		if ($column['name'] == 'body')
354
			$body_type = $column['type'];
355
356
	$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $body_type does not seem to be defined for all execution paths leading up to this point.
Loading history...
357
358
	if ($body_type == 'text' || ($body_type != 'text' && isset($_POST['do_conversion'])))
359
	{
360
		checkSession();
361
		validateToken('admin-maint');
362
363
		// Make it longer so we can do their limit.
364
		if ($body_type == 'text')
365
			$smcFunc['db_change_column']('{db_prefix}messages', 'body', array('type' => 'mediumtext'));
366
		// Shorten the column so we can have a bit (literally per record) less space occupied
367
		else
368
			$smcFunc['db_change_column']('{db_prefix}messages', 'body', array('type' => 'text'));
369
370
		// 3rd party integrations may be interested in knowning about this.
371
		call_integration_hook('integrate_convert_msgbody', array($body_type));
372
373
		$colData = $smcFunc['db_list_columns']('{db_prefix}messages', true);
374
		foreach ($colData as $column)
375
			if ($column['name'] == 'body')
376
				$body_type = $column['type'];
377
378
		$context['maintenance_finished'] = $txt[$context['convert_to'] . '_title'];
379
		$context['convert_to'] = $body_type == 'text' ? 'mediumtext' : 'text';
380
		$context['convert_to_suggest'] = ($body_type != 'text' && !empty($modSettings['max_messageLength']) && $modSettings['max_messageLength'] < 65536);
381
382
		return;
383
	}
384
	elseif ($body_type != 'text' && (!isset($_POST['do_conversion']) || isset($_POST['cont'])))
385
	{
386
		checkSession();
387
		if (empty($_REQUEST['start']))
388
			validateToken('admin-maint');
389
		else
390
			validateToken('admin-convertMsg');
391
392
		$context['page_title'] = $txt['not_done_title'];
393
		$context['continue_post_data'] = '';
394
		$context['continue_countdown'] = 3;
395
		$context['sub_template'] = 'not_done';
396
		$increment = 500;
397
		$id_msg_exceeding = isset($_POST['id_msg_exceeding']) ? explode(',', $_POST['id_msg_exceeding']) : array();
398
399
		$request = $smcFunc['db_query']('', '
400
			SELECT COUNT(*) as count
401
			FROM {db_prefix}messages',
402
			array()
403
		);
404
		list($max_msgs) = $smcFunc['db_fetch_row']($request);
405
		$smcFunc['db_free_result']($request);
406
407
		// Try for as much time as possible.
408
		@set_time_limit(600);
409
410
		while ($_REQUEST['start'] < $max_msgs)
411
		{
412
			$request = $smcFunc['db_query']('', '
413
				SELECT id_msg
414
				FROM {db_prefix}messages
415
				WHERE id_msg BETWEEN {int:start} AND {int:start} + {int:increment}
416
					AND LENGTH(body) > 65535',
417
				array(
418
					'start' => $_REQUEST['start'],
419
					'increment' => $increment - 1,
420
				)
421
			);
422
			while ($row = $smcFunc['db_fetch_assoc']($request))
423
				$id_msg_exceeding[] = $row['id_msg'];
424
			$smcFunc['db_free_result']($request);
425
426
			$_REQUEST['start'] += $increment;
427
428
			if (microtime(true) - TIME_START > 3)
429
			{
430
				createToken('admin-convertMsg');
431
				$context['continue_post_data'] = '
432
					<input type="hidden" name="' . $context['admin-convertMsg_token_var'] . '" value="' . $context['admin-convertMsg_token'] . '">
433
					<input type="hidden" name="' . $context['session_var'] . '" value="' . $context['session_id'] . '">
434
					<input type="hidden" name="id_msg_exceeding" value="' . implode(',', $id_msg_exceeding) . '">';
435
436
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertmsgbody;start=' . $_REQUEST['start'];
437
				$context['continue_percent'] = round(100 * $_REQUEST['start'] / $max_msgs);
438
439
				return;
440
			}
441
		}
442
		createToken('admin-maint');
443
		$context['page_title'] = $txt[$context['convert_to'] . '_title'];
444
		$context['sub_template'] = 'convert_msgbody';
445
446
		if (!empty($id_msg_exceeding))
447
		{
448
			if (count($id_msg_exceeding) > 100)
449
			{
450
				$query_msg = array_slice($id_msg_exceeding, 0, 100);
451
				$context['exceeding_messages_morethan'] = sprintf($txt['exceeding_messages_morethan'], count($id_msg_exceeding));
452
			}
453
			else
454
				$query_msg = $id_msg_exceeding;
455
456
			$context['exceeding_messages'] = array();
457
			$request = $smcFunc['db_query']('', '
458
				SELECT id_msg, id_topic, subject
459
				FROM {db_prefix}messages
460
				WHERE id_msg IN ({array_int:messages})',
461
				array(
462
					'messages' => $query_msg,
463
				)
464
			);
465
			while ($row = $smcFunc['db_fetch_assoc']($request))
466
				$context['exceeding_messages'][] = '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>';
467
			$smcFunc['db_free_result']($request);
468
		}
469
	}
470
}
471
472
/**
473
 * Converts HTML-entities to their UTF-8 character equivalents.
474
 * This requires the admin_forum permission.
475
 * Pre-condition: UTF-8 has been set as database and global character set.
476
 *
477
 * It is divided in steps of 10 seconds.
478
 * This action is linked from the maintenance screen (if applicable).
479
 * It is accessed by ?action=admin;area=maintain;sa=database;activity=convertentities.
480
 *
481
 * @uses template_convert_entities()
482
 */
483
function ConvertEntities()
484
{
485
	global $db_character_set, $modSettings, $context, $smcFunc, $db_type, $db_prefix;
486
487
	isAllowedTo('admin_forum');
488
489
	// Check to see if UTF-8 is currently the default character set.
490
	if ($modSettings['global_character_set'] !== 'UTF-8')
491
		fatal_lang_error('entity_convert_only_utf8');
492
493
	// Some starting values.
494
	$context['table'] = empty($_REQUEST['table']) ? 0 : (int) $_REQUEST['table'];
495
	$context['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
496
497
	$context['start_time'] = time();
498
499
	$context['first_step'] = !isset($_REQUEST[$context['session_var']]);
500
	$context['last_step'] = false;
501
502
	// The first step is just a text screen with some explanation.
503
	if ($context['first_step'])
504
	{
505
		validateToken('admin-maint');
506
		createToken('admin-maint');
507
508
		$context['sub_template'] = 'convert_entities';
509
		return;
510
	}
511
	// Otherwise use the generic "not done" template.
512
	$context['sub_template'] = 'not_done';
513
	$context['continue_post_data'] = '';
514
	$context['continue_countdown'] = 3;
515
516
	// Now we're actually going to convert...
517
	checkSession('request');
518
	validateToken('admin-maint');
519
	createToken('admin-maint');
520
	$context['not_done_token'] = 'admin-maint';
521
522
	// A list of tables ready for conversion.
523
	$tables = array(
524
		'ban_groups',
525
		'ban_items',
526
		'boards',
527
		'calendar',
528
		'calendar_holidays',
529
		'categories',
530
		'log_errors',
531
		'log_search_subjects',
532
		'membergroups',
533
		'members',
534
		'message_icons',
535
		'messages',
536
		'package_servers',
537
		'personal_messages',
538
		'pm_recipients',
539
		'polls',
540
		'poll_choices',
541
		'smileys',
542
		'themes',
543
	);
544
	$context['num_tables'] = count($tables);
545
546
	// Loop through all tables that need converting.
547
	for (; $context['table'] < $context['num_tables']; $context['table']++)
548
	{
549
		$cur_table = $tables[$context['table']];
550
		$primary_key = '';
551
		// Make sure we keep stuff unique!
552
		$primary_keys = array();
553
554
		if (function_exists('apache_reset_timeout'))
555
			@apache_reset_timeout();
556
557
		// Get a list of text columns.
558
		$columns = array();
559
		if ($db_type == 'postgresql')
560
			$request = $smcFunc['db_query']('', '
561
				SELECT column_name "Field", data_type "Type"
562
				FROM information_schema.columns
563
				WHERE table_name = {string:cur_table}
564
					AND (data_type = \'character varying\' or data_type = \'text\')',
565
				array(
566
					'cur_table' => $db_prefix . $cur_table,
567
				)
568
			);
569
		else
570
			$request = $smcFunc['db_query']('', '
571
				SHOW FULL COLUMNS
572
				FROM {db_prefix}{raw:cur_table}',
573
				array(
574
					'cur_table' => $cur_table,
575
				)
576
			);
577
		while ($column_info = $smcFunc['db_fetch_assoc']($request))
578
			if (strpos($column_info['Type'], 'text') !== false || strpos($column_info['Type'], 'char') !== false)
579
				$columns[] = strtolower($column_info['Field']);
580
581
		// Get the column with the (first) primary key.
582
		if ($db_type == 'postgresql')
583
			$request = $smcFunc['db_query']('', '
584
				SELECT a.attname "Column_name", \'PRIMARY\' "Key_name", attnum "Seq_in_index"
585
				FROM   pg_index i
586
				JOIN   pg_attribute a ON a.attrelid = i.indrelid
587
					AND a.attnum = ANY(i.indkey)
588
				WHERE  i.indrelid = {string:cur_table}::regclass
589
					AND    i.indisprimary',
590
				array(
591
					'cur_table' => $db_prefix . $cur_table,
592
				)
593
			);
594
		else
595
			$request = $smcFunc['db_query']('', '
596
				SHOW KEYS
597
				FROM {db_prefix}{raw:cur_table}',
598
				array(
599
					'cur_table' => $cur_table,
600
				)
601
			);
602
		while ($row = $smcFunc['db_fetch_assoc']($request))
603
		{
604
			if ($row['Key_name'] === 'PRIMARY')
605
			{
606
				if ((empty($primary_key) || $row['Seq_in_index'] == 1) && !in_array(strtolower($row['Column_name']), $columns))
607
					$primary_key = $row['Column_name'];
608
609
				$primary_keys[] = $row['Column_name'];
610
			}
611
		}
612
		$smcFunc['db_free_result']($request);
613
614
		// No primary key, no glory.
615
		// Same for columns. Just to be sure we've work to do!
616
		if (empty($primary_key) || empty($columns))
617
			continue;
618
619
		// Get the maximum value for the primary key.
620
		$request = $smcFunc['db_query']('', '
621
			SELECT MAX({identifier:key})
622
			FROM {db_prefix}{raw:cur_table}',
623
			array(
624
				'key' => $primary_key,
625
				'cur_table' => $cur_table,
626
			)
627
		);
628
		list($max_value) = $smcFunc['db_fetch_row']($request);
629
		$smcFunc['db_free_result']($request);
630
631
		if (empty($max_value))
632
			continue;
633
634
		while ($context['start'] <= $max_value)
635
		{
636
			// Retrieve a list of rows that has at least one entity to convert.
637
			$request = $smcFunc['db_query']('', '
638
				SELECT {raw:primary_keys}, {raw:columns}
639
				FROM {db_prefix}{raw:cur_table}
640
				WHERE {raw:primary_key} BETWEEN {int:start} AND {int:start} + 499
641
					AND {raw:like_compare}
642
				LIMIT 500',
643
				array(
644
					'primary_keys' => implode(', ', $primary_keys),
645
					'columns' => implode(', ', $columns),
646
					'cur_table' => $cur_table,
647
					'primary_key' => $primary_key,
648
					'start' => $context['start'],
649
					'like_compare' => '(' . implode(' LIKE \'%&#%\' OR ', $columns) . ' LIKE \'%&#%\')',
650
				)
651
			);
652
			while ($row = $smcFunc['db_fetch_assoc']($request))
653
			{
654
				$insertion_variables = array();
655
				$changes = array();
656
				foreach ($row as $column_name => $column_value)
657
					if ($column_name !== $primary_key && strpos($column_value, '&#') !== false)
658
					{
659
						$changes[] = $column_name . ' = {string:changes_' . $column_name . '}';
660
						$insertion_variables['changes_' . $column_name] = preg_replace_callback('~&#(\d{1,5}|x[0-9a-fA-F]{1,4});~', 'fixchardb__callback', $column_value);
661
					}
662
663
				$where = array();
664
				foreach ($primary_keys as $key)
665
				{
666
					$where[] = $key . ' = {string:where_' . $key . '}';
667
					$insertion_variables['where_' . $key] = $row[$key];
668
				}
669
670
				// Update the row.
671
				if (!empty($changes))
672
					$smcFunc['db_query']('', '
673
						UPDATE {db_prefix}' . $cur_table . '
674
						SET
675
							' . implode(',
676
							', $changes) . '
677
						WHERE ' . implode(' AND ', $where),
678
						$insertion_variables
679
					);
680
			}
681
			$smcFunc['db_free_result']($request);
682
			$context['start'] += 500;
683
684
			// After ten seconds interrupt.
685
			if (time() - $context['start_time'] > 10)
686
			{
687
				// Calculate an approximation of the percentage done.
688
				$context['continue_percent'] = round(100 * ($context['table'] + ($context['start'] / $max_value)) / $context['num_tables'], 1);
689
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=convertentities;table=' . $context['table'] . ';start=' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
690
				return;
691
			}
692
		}
693
		$context['start'] = 0;
694
	}
695
696
	// If we're here, we must be done.
697
	$context['continue_percent'] = 100;
698
	$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;done=convertentities';
699
	$context['last_step'] = true;
700
	$context['continue_countdown'] = 3;
701
}
702
703
/**
704
 * Optimizes all tables in the database and lists how much was saved.
705
 * It requires the admin_forum permission.
706
 * It shows as the maintain_forum admin area.
707
 * It is accessed from ?action=admin;area=maintain;sa=database;activity=optimize.
708
 * It also updates the optimize scheduled task such that the tables are not automatically optimized again too soon.
709
 *
710
 * @uses template_optimize()
711
 */
712
function OptimizeTables()
713
{
714
	global $db_prefix, $txt, $context, $smcFunc;
715
716
	isAllowedTo('admin_forum');
717
718
	checkSession('request');
719
720
	if (!isset($_SESSION['optimized_tables']))
721
		validateToken('admin-maint');
722
	else
723
		validateToken('admin-optimize', 'post', false);
724
725
	ignore_user_abort(true);
726
	db_extend();
727
728
	$context['page_title'] = $txt['database_optimize'];
729
	$context['sub_template'] = 'optimize';
730
	$context['continue_post_data'] = '';
731
	$context['continue_countdown'] = 3;
732
733
	// Only optimize the tables related to this smf install, not all the tables in the db
734
	$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
735
736
	// Get a list of tables, as well as how many there are.
737
	$temp_tables = $smcFunc['db_list_tables'](false, $real_prefix . '%');
738
	$tables = array();
739
	foreach ($temp_tables as $table)
740
		$tables[] = array('table_name' => $table);
741
742
	// If there aren't any tables then I believe that would mean the world has exploded...
743
	$context['num_tables'] = count($tables);
744
	if ($context['num_tables'] == 0)
745
		fatal_error('You appear to be running SMF in a flat file mode... fantastic!', false);
746
747
	$_REQUEST['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
748
749
	// Try for extra time due to large tables.
750
	@set_time_limit(100);
751
752
	// For each table....
753
	$_SESSION['optimized_tables'] = !empty($_SESSION['optimized_tables']) ? $_SESSION['optimized_tables'] : array();
754
	for ($key = $_REQUEST['start']; $context['num_tables'] - 1; $key++)
755
	{
756
		if (empty($tables[$key]))
757
			break;
758
759
		// Continue?
760
		if (microtime(true) - TIME_START > 10)
761
		{
762
			$_REQUEST['start'] = $key;
763
			$context['continue_get_data'] = '?action=admin;area=maintain;sa=database;activity=optimize;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
764
			$context['continue_percent'] = round(100 * $_REQUEST['start'] / $context['num_tables']);
765
			$context['sub_template'] = 'not_done';
766
			$context['page_title'] = $txt['not_done_title'];
767
768
			createToken('admin-optimize');
769
			$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-optimize_token_var'] . '" value="' . $context['admin-optimize_token'] . '">';
770
771
			if (function_exists('apache_reset_timeout'))
772
				apache_reset_timeout();
773
774
			return;
775
		}
776
777
		// Optimize the table!  We use backticks here because it might be a custom table.
778
		$data_freed = $smcFunc['db_optimize_table']($tables[$key]['table_name']);
779
780
		if ($data_freed > 0)
781
			$_SESSION['optimized_tables'][] = array(
782
				'name' => $tables[$key]['table_name'],
783
				'data_freed' => $data_freed,
784
			);
785
	}
786
787
	// Number of tables, etc...
788
	$txt['database_numb_tables'] = sprintf($txt['database_numb_tables'], $context['num_tables']);
789
	$context['num_tables_optimized'] = count($_SESSION['optimized_tables']);
790
	$context['optimized_tables'] = $_SESSION['optimized_tables'];
791
	unset($_SESSION['optimized_tables']);
792
}
793
794
/**
795
 * Recount many forum totals that can be recounted automatically without harm.
796
 * it requires the admin_forum permission.
797
 * It shows the maintain_forum admin area.
798
 *
799
 * Totals recounted:
800
 * - fixes for topics with wrong num_replies.
801
 * - updates for num_posts and num_topics of all boards.
802
 * - recounts instant_messages but not unread_messages.
803
 * - repairs messages pointing to boards with topics pointing to other boards.
804
 * - updates the last message posted in boards and children.
805
 * - updates member count, latest member, topic count, and message count.
806
 *
807
 * The function redirects back to ?action=admin;area=maintain when complete.
808
 * It is accessed via ?action=admin;area=maintain;sa=database;activity=recount.
809
 */
810
function AdminBoardRecount()
811
{
812
	global $txt, $context, $modSettings, $sourcedir, $smcFunc;
813
814
	isAllowedTo('admin_forum');
815
	checkSession('request');
816
817
	// validate the request or the loop
818
	if (!isset($_REQUEST['step']))
819
		validateToken('admin-maint');
820
	else
821
		validateToken('admin-boardrecount');
822
823
	$context['page_title'] = $txt['not_done_title'];
824
	$context['continue_post_data'] = '';
825
	$context['continue_countdown'] = 3;
826
	$context['sub_template'] = 'not_done';
827
828
	// Try for as much time as possible.
829
	@set_time_limit(600);
830
831
	// Step the number of topics at a time so things don't time out...
832
	$request = $smcFunc['db_query']('', '
833
		SELECT MAX(id_topic)
834
		FROM {db_prefix}topics',
835
		array(
836
		)
837
	);
838
	list ($max_topics) = $smcFunc['db_fetch_row']($request);
839
	$smcFunc['db_free_result']($request);
840
841
	$increment = min(max(50, ceil($max_topics / 4)), 2000);
842
	if (empty($_REQUEST['start']))
843
		$_REQUEST['start'] = 0;
844
845
	$total_steps = 8;
846
847
	// Get each topic with a wrong reply count and fix it - let's just do some at a time, though.
848
	if (empty($_REQUEST['step']))
849
	{
850
		$_REQUEST['step'] = 0;
851
852
		while ($_REQUEST['start'] < $max_topics)
853
		{
854
			// Recount approved messages
855
			$request = $smcFunc['db_query']('', '
856
				SELECT t.id_topic, MAX(t.num_replies) AS num_replies,
857
					GREATEST(COUNT(ma.id_msg) - 1, 0) AS real_num_replies
858
				FROM {db_prefix}topics AS t
859
					LEFT JOIN {db_prefix}messages AS ma ON (ma.id_topic = t.id_topic AND ma.approved = {int:is_approved})
860
				WHERE t.id_topic > {int:start}
861
					AND t.id_topic <= {int:max_id}
862
				GROUP BY t.id_topic
863
				HAVING GREATEST(COUNT(ma.id_msg) - 1, 0) != MAX(t.num_replies)',
864
				array(
865
					'is_approved' => 1,
866
					'start' => $_REQUEST['start'],
867
					'max_id' => $_REQUEST['start'] + $increment,
868
				)
869
			);
870
			while ($row = $smcFunc['db_fetch_assoc']($request))
871
				$smcFunc['db_query']('', '
872
					UPDATE {db_prefix}topics
873
					SET num_replies = {int:num_replies}
874
					WHERE id_topic = {int:id_topic}',
875
					array(
876
						'num_replies' => $row['real_num_replies'],
877
						'id_topic' => $row['id_topic'],
878
					)
879
				);
880
			$smcFunc['db_free_result']($request);
881
882
			// Recount unapproved messages
883
			$request = $smcFunc['db_query']('', '
884
				SELECT t.id_topic, MAX(t.unapproved_posts) AS unapproved_posts,
885
					COUNT(mu.id_msg) AS real_unapproved_posts
886
				FROM {db_prefix}topics AS t
887
					LEFT JOIN {db_prefix}messages AS mu ON (mu.id_topic = t.id_topic AND mu.approved = {int:not_approved})
888
				WHERE t.id_topic > {int:start}
889
					AND t.id_topic <= {int:max_id}
890
				GROUP BY t.id_topic
891
				HAVING COUNT(mu.id_msg) != MAX(t.unapproved_posts)',
892
				array(
893
					'not_approved' => 0,
894
					'start' => $_REQUEST['start'],
895
					'max_id' => $_REQUEST['start'] + $increment,
896
				)
897
			);
898
			while ($row = $smcFunc['db_fetch_assoc']($request))
899
				$smcFunc['db_query']('', '
900
					UPDATE {db_prefix}topics
901
					SET unapproved_posts = {int:unapproved_posts}
902
					WHERE id_topic = {int:id_topic}',
903
					array(
904
						'unapproved_posts' => $row['real_unapproved_posts'],
905
						'id_topic' => $row['id_topic'],
906
					)
907
				);
908
			$smcFunc['db_free_result']($request);
909
910
			$_REQUEST['start'] += $increment;
911
912
			if (microtime(true) - TIME_START > 3)
913
			{
914
				createToken('admin-boardrecount');
915
				$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
916
917
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=0;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
918
				$context['continue_percent'] = round((100 * $_REQUEST['start'] / $max_topics) / $total_steps);
919
920
				return;
921
			}
922
		}
923
924
		$_REQUEST['start'] = 0;
925
	}
926
927
	// Update the post count of each board.
928
	if ($_REQUEST['step'] <= 1)
929
	{
930
		if (empty($_REQUEST['start']))
931
			$smcFunc['db_query']('', '
932
				UPDATE {db_prefix}boards
933
				SET num_posts = {int:num_posts}
934
				WHERE redirect = {string:redirect}',
935
				array(
936
					'num_posts' => 0,
937
					'redirect' => '',
938
				)
939
			);
940
941
		while ($_REQUEST['start'] < $max_topics)
942
		{
943
			$request = $smcFunc['db_query']('', '
944
				SELECT m.id_board, COUNT(*) AS real_num_posts
945
				FROM {db_prefix}messages AS m
946
				WHERE m.id_topic > {int:id_topic_min}
947
					AND m.id_topic <= {int:id_topic_max}
948
					AND m.approved = {int:is_approved}
949
				GROUP BY m.id_board',
950
				array(
951
					'id_topic_min' => $_REQUEST['start'],
952
					'id_topic_max' => $_REQUEST['start'] + $increment,
953
					'is_approved' => 1,
954
				)
955
			);
956
			while ($row = $smcFunc['db_fetch_assoc']($request))
957
				$smcFunc['db_query']('', '
958
					UPDATE {db_prefix}boards
959
					SET num_posts = num_posts + {int:real_num_posts}
960
					WHERE id_board = {int:id_board}',
961
					array(
962
						'id_board' => $row['id_board'],
963
						'real_num_posts' => $row['real_num_posts'],
964
					)
965
				);
966
			$smcFunc['db_free_result']($request);
967
968
			$_REQUEST['start'] += $increment;
969
970
			if (microtime(true) - TIME_START > 3)
971
			{
972
				createToken('admin-boardrecount');
973
				$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
974
975
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=1;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
976
				$context['continue_percent'] = round((200 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
977
978
				return;
979
			}
980
		}
981
982
		$_REQUEST['start'] = 0;
983
	}
984
985
	// Update the topic count of each board.
986
	if ($_REQUEST['step'] <= 2)
987
	{
988
		if (empty($_REQUEST['start']))
989
			$smcFunc['db_query']('', '
990
				UPDATE {db_prefix}boards
991
				SET num_topics = {int:num_topics}',
992
				array(
993
					'num_topics' => 0,
994
				)
995
			);
996
997
		while ($_REQUEST['start'] < $max_topics)
998
		{
999
			$request = $smcFunc['db_query']('', '
1000
				SELECT t.id_board, COUNT(*) AS real_num_topics
1001
				FROM {db_prefix}topics AS t
1002
				WHERE t.approved = {int:is_approved}
1003
					AND t.id_topic > {int:id_topic_min}
1004
					AND t.id_topic <= {int:id_topic_max}
1005
				GROUP BY t.id_board',
1006
				array(
1007
					'is_approved' => 1,
1008
					'id_topic_min' => $_REQUEST['start'],
1009
					'id_topic_max' => $_REQUEST['start'] + $increment,
1010
				)
1011
			);
1012
			while ($row = $smcFunc['db_fetch_assoc']($request))
1013
				$smcFunc['db_query']('', '
1014
					UPDATE {db_prefix}boards
1015
					SET num_topics = num_topics + {int:real_num_topics}
1016
					WHERE id_board = {int:id_board}',
1017
					array(
1018
						'id_board' => $row['id_board'],
1019
						'real_num_topics' => $row['real_num_topics'],
1020
					)
1021
				);
1022
			$smcFunc['db_free_result']($request);
1023
1024
			$_REQUEST['start'] += $increment;
1025
1026
			if (microtime(true) - TIME_START > 3)
1027
			{
1028
				createToken('admin-boardrecount');
1029
				$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
1030
1031
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=2;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1032
				$context['continue_percent'] = round((300 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
1033
1034
				return;
1035
			}
1036
		}
1037
1038
		$_REQUEST['start'] = 0;
1039
	}
1040
1041
	// Update the unapproved post count of each board.
1042
	if ($_REQUEST['step'] <= 3)
1043
	{
1044
		if (empty($_REQUEST['start']))
1045
			$smcFunc['db_query']('', '
1046
				UPDATE {db_prefix}boards
1047
				SET unapproved_posts = {int:unapproved_posts}',
1048
				array(
1049
					'unapproved_posts' => 0,
1050
				)
1051
			);
1052
1053
		while ($_REQUEST['start'] < $max_topics)
1054
		{
1055
			$request = $smcFunc['db_query']('', '
1056
				SELECT m.id_board, COUNT(*) AS real_unapproved_posts
1057
				FROM {db_prefix}messages AS m
1058
				WHERE m.id_topic > {int:id_topic_min}
1059
					AND m.id_topic <= {int:id_topic_max}
1060
					AND m.approved = {int:is_approved}
1061
				GROUP BY m.id_board',
1062
				array(
1063
					'id_topic_min' => $_REQUEST['start'],
1064
					'id_topic_max' => $_REQUEST['start'] + $increment,
1065
					'is_approved' => 0,
1066
				)
1067
			);
1068
			while ($row = $smcFunc['db_fetch_assoc']($request))
1069
				$smcFunc['db_query']('', '
1070
					UPDATE {db_prefix}boards
1071
					SET unapproved_posts = unapproved_posts + {int:unapproved_posts}
1072
					WHERE id_board = {int:id_board}',
1073
					array(
1074
						'id_board' => $row['id_board'],
1075
						'unapproved_posts' => $row['real_unapproved_posts'],
1076
					)
1077
				);
1078
			$smcFunc['db_free_result']($request);
1079
1080
			$_REQUEST['start'] += $increment;
1081
1082
			if (microtime(true) - TIME_START > 3)
1083
			{
1084
				createToken('admin-boardrecount');
1085
				$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
1086
1087
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=3;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1088
				$context['continue_percent'] = round((400 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
1089
1090
				return;
1091
			}
1092
		}
1093
1094
		$_REQUEST['start'] = 0;
1095
	}
1096
1097
	// Update the unapproved topic count of each board.
1098
	if ($_REQUEST['step'] <= 4)
1099
	{
1100
		if (empty($_REQUEST['start']))
1101
			$smcFunc['db_query']('', '
1102
				UPDATE {db_prefix}boards
1103
				SET unapproved_topics = {int:unapproved_topics}',
1104
				array(
1105
					'unapproved_topics' => 0,
1106
				)
1107
			);
1108
1109
		while ($_REQUEST['start'] < $max_topics)
1110
		{
1111
			$request = $smcFunc['db_query']('', '
1112
				SELECT t.id_board, COUNT(*) AS real_unapproved_topics
1113
				FROM {db_prefix}topics AS t
1114
				WHERE t.approved = {int:is_approved}
1115
					AND t.id_topic > {int:id_topic_min}
1116
					AND t.id_topic <= {int:id_topic_max}
1117
				GROUP BY t.id_board',
1118
				array(
1119
					'is_approved' => 0,
1120
					'id_topic_min' => $_REQUEST['start'],
1121
					'id_topic_max' => $_REQUEST['start'] + $increment,
1122
				)
1123
			);
1124
			while ($row = $smcFunc['db_fetch_assoc']($request))
1125
				$smcFunc['db_query']('', '
1126
					UPDATE {db_prefix}boards
1127
					SET unapproved_topics = unapproved_topics + {int:real_unapproved_topics}
1128
					WHERE id_board = {int:id_board}',
1129
					array(
1130
						'id_board' => $row['id_board'],
1131
						'real_unapproved_topics' => $row['real_unapproved_topics'],
1132
					)
1133
				);
1134
			$smcFunc['db_free_result']($request);
1135
1136
			$_REQUEST['start'] += $increment;
1137
1138
			if (microtime(true) - TIME_START > 3)
1139
			{
1140
				createToken('admin-boardrecount');
1141
				$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
1142
1143
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=4;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1144
				$context['continue_percent'] = round((500 + 100 * $_REQUEST['start'] / $max_topics) / $total_steps);
1145
1146
				return;
1147
			}
1148
		}
1149
1150
		$_REQUEST['start'] = 0;
1151
	}
1152
1153
	// Get all members with wrong number of personal messages.
1154
	if ($_REQUEST['step'] <= 5)
1155
	{
1156
		$request = $smcFunc['db_query']('', '
1157
			SELECT mem.id_member, COUNT(pmr.id_pm) AS real_num,
1158
				MAX(mem.instant_messages) AS instant_messages
1159
			FROM {db_prefix}members AS mem
1160
				LEFT JOIN {db_prefix}pm_recipients AS pmr ON (mem.id_member = pmr.id_member AND pmr.deleted = {int:is_not_deleted})
1161
			GROUP BY mem.id_member
1162
			HAVING COUNT(pmr.id_pm) != MAX(mem.instant_messages)',
1163
			array(
1164
				'is_not_deleted' => 0,
1165
			)
1166
		);
1167
		while ($row = $smcFunc['db_fetch_assoc']($request))
1168
			updateMemberData($row['id_member'], array('instant_messages' => $row['real_num']));
1169
		$smcFunc['db_free_result']($request);
1170
1171
		$request = $smcFunc['db_query']('', '
1172
			SELECT mem.id_member, COUNT(pmr.id_pm) AS real_num,
1173
				MAX(mem.unread_messages) AS unread_messages
1174
			FROM {db_prefix}members AS mem
1175
				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})
1176
			GROUP BY mem.id_member
1177
			HAVING COUNT(pmr.id_pm) != MAX(mem.unread_messages)',
1178
			array(
1179
				'is_not_deleted' => 0,
1180
				'is_not_read' => 0,
1181
			)
1182
		);
1183
		while ($row = $smcFunc['db_fetch_assoc']($request))
1184
			updateMemberData($row['id_member'], array('unread_messages' => $row['real_num']));
1185
		$smcFunc['db_free_result']($request);
1186
1187
		if (microtime(true) - TIME_START > 3)
1188
		{
1189
			createToken('admin-boardrecount');
1190
			$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
1191
1192
			$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=0;' . $context['session_var'] . '=' . $context['session_id'];
1193
			$context['continue_percent'] = round(700 / $total_steps);
1194
1195
			return;
1196
		}
1197
	}
1198
1199
	// Any messages pointing to the wrong board?
1200
	if ($_REQUEST['step'] <= 6)
1201
	{
1202
		while ($_REQUEST['start'] < $modSettings['maxMsgID'])
1203
		{
1204
			$request = $smcFunc['db_query']('', '
1205
				SELECT t.id_board, m.id_msg
1206
				FROM {db_prefix}messages AS m
1207
					INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic AND t.id_board != m.id_board)
1208
				WHERE m.id_msg > {int:id_msg_min}
1209
					AND m.id_msg <= {int:id_msg_max}',
1210
				array(
1211
					'id_msg_min' => $_REQUEST['start'],
1212
					'id_msg_max' => $_REQUEST['start'] + $increment,
1213
				)
1214
			);
1215
			$boards = array();
1216
			while ($row = $smcFunc['db_fetch_assoc']($request))
1217
				$boards[$row['id_board']][] = $row['id_msg'];
1218
1219
			$smcFunc['db_free_result']($request);
1220
1221
			foreach ($boards as $board_id => $messages)
1222
				$smcFunc['db_query']('', '
1223
					UPDATE {db_prefix}messages
1224
					SET id_board = {int:id_board}
1225
					WHERE id_msg IN ({array_int:id_msg_array})',
1226
					array(
1227
						'id_msg_array' => $messages,
1228
						'id_board' => $board_id,
1229
					)
1230
				);
1231
1232
			$_REQUEST['start'] += $increment;
1233
1234
			if (microtime(true) - TIME_START > 3)
1235
			{
1236
				createToken('admin-boardrecount');
1237
				$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-boardrecount_token_var'] . '" value="' . $context['admin-boardrecount_token'] . '">';
1238
1239
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=routine;activity=recount;step=6;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1240
				$context['continue_percent'] = round((700 + 100 * $_REQUEST['start'] / $modSettings['maxMsgID']) / $total_steps);
1241
1242
				return;
1243
			}
1244
		}
1245
1246
		$_REQUEST['start'] = 0;
1247
	}
1248
1249
	// Update the latest message of each board.
1250
	$request = $smcFunc['db_query']('', '
1251
		SELECT m.id_board, MAX(m.id_msg) AS local_last_msg
1252
		FROM {db_prefix}messages AS m
1253
		WHERE m.approved = {int:is_approved}
1254
		GROUP BY m.id_board',
1255
		array(
1256
			'is_approved' => 1,
1257
		)
1258
	);
1259
	$realBoardCounts = array();
1260
	while ($row = $smcFunc['db_fetch_assoc']($request))
1261
		$realBoardCounts[$row['id_board']] = $row['local_last_msg'];
1262
	$smcFunc['db_free_result']($request);
1263
1264
	$request = $smcFunc['db_query']('', '
1265
		SELECT id_board, id_parent, id_last_msg, child_level, id_msg_updated
1266
		FROM {db_prefix}boards',
1267
		array(
1268
		)
1269
	);
1270
	$resort_me = array();
1271
	while ($row = $smcFunc['db_fetch_assoc']($request))
1272
	{
1273
		$row['local_last_msg'] = isset($realBoardCounts[$row['id_board']]) ? $realBoardCounts[$row['id_board']] : 0;
1274
		$resort_me[$row['child_level']][] = $row;
1275
	}
1276
	$smcFunc['db_free_result']($request);
1277
1278
	krsort($resort_me);
1279
1280
	$lastModifiedMsg = array();
1281
	foreach ($resort_me as $rows)
1282
		foreach ($rows as $row)
1283
		{
1284
			// The latest message is the latest of the current board and its children.
1285
			if (isset($lastModifiedMsg[$row['id_board']]))
1286
				$curLastModifiedMsg = max($row['local_last_msg'], $lastModifiedMsg[$row['id_board']]);
1287
			else
1288
				$curLastModifiedMsg = $row['local_last_msg'];
1289
1290
			// If what is and what should be the latest message differ, an update is necessary.
1291
			if ($row['local_last_msg'] != $row['id_last_msg'] || $curLastModifiedMsg != $row['id_msg_updated'])
1292
				$smcFunc['db_query']('', '
1293
					UPDATE {db_prefix}boards
1294
					SET id_last_msg = {int:id_last_msg}, id_msg_updated = {int:id_msg_updated}
1295
					WHERE id_board = {int:id_board}',
1296
					array(
1297
						'id_last_msg' => $row['local_last_msg'],
1298
						'id_msg_updated' => $curLastModifiedMsg,
1299
						'id_board' => $row['id_board'],
1300
					)
1301
				);
1302
1303
			// Parent boards inherit the latest modified message of their children.
1304
			if (isset($lastModifiedMsg[$row['id_parent']]))
1305
				$lastModifiedMsg[$row['id_parent']] = max($row['local_last_msg'], $lastModifiedMsg[$row['id_parent']]);
1306
			else
1307
				$lastModifiedMsg[$row['id_parent']] = $row['local_last_msg'];
1308
		}
1309
1310
	// Update all the basic statistics.
1311
	updateStats('member');
1312
	updateStats('message');
1313
	updateStats('topic');
1314
1315
	// Finally, update the latest event times.
1316
	require_once($sourcedir . '/ScheduledTasks.php');
1317
	CalculateNextTrigger();
1318
1319
	redirectexit('action=admin;area=maintain;sa=routine;done=recount');
1320
}
1321
1322
/**
1323
 * Perform a detailed version check.  A very good thing ;).
1324
 * The function parses the comment headers in all files for their version information,
1325
 * and outputs that for some javascript to check with simplemachines.org.
1326
 * It does not connect directly with simplemachines.org, but rather expects the client to.
1327
 *
1328
 * It requires the admin_forum permission.
1329
 * Uses the view_versions admin area.
1330
 * Accessed through ?action=admin;area=maintain;sa=routine;activity=version.
1331
 *
1332
 * @uses template_view_versions()
1333
 */
1334
function VersionDetail()
1335
{
1336
	global $txt, $sourcedir, $context;
1337
1338
	isAllowedTo('admin_forum');
1339
1340
	// Call the function that'll get all the version info we need.
1341
	require_once($sourcedir . '/Subs-Admin.php');
1342
	$versionOptions = array(
1343
		'include_ssi' => true,
1344
		'include_subscriptions' => true,
1345
		'include_tasks' => true,
1346
		'sort_results' => true,
1347
	);
1348
	$version_info = getFileVersions($versionOptions);
1349
1350
	// Add the new info to the template context.
1351
	$context += array(
1352
		'file_versions' => $version_info['file_versions'],
1353
		'default_template_versions' => $version_info['default_template_versions'],
1354
		'template_versions' => $version_info['template_versions'],
1355
		'default_language_versions' => $version_info['default_language_versions'],
1356
		'default_known_languages' => array_keys($version_info['default_language_versions']),
1357
		'tasks_versions' => $version_info['tasks_versions'],
1358
	);
1359
1360
	// Make it easier to manage for the template.
1361
	$context['forum_version'] = SMF_FULL_VERSION;
1362
1363
	$context['sub_template'] = 'view_versions';
1364
	$context['page_title'] = $txt['admin_version_check'];
1365
}
1366
1367
/**
1368
 * Re-attribute posts.
1369
 */
1370
function MaintainReattributePosts()
1371
{
1372
	global $sourcedir, $context, $txt;
1373
1374
	checkSession();
1375
1376
	// Find the member.
1377
	require_once($sourcedir . '/Subs-Auth.php');
1378
	$members = findMembers($_POST['to']);
1379
1380
	if (empty($members))
1381
		fatal_lang_error('reattribute_cannot_find_member');
1382
1383
	$memID = array_shift($members);
1384
	$memID = $memID['id'];
1385
1386
	$email = $_POST['type'] == 'email' ? $_POST['from_email'] : '';
1387
	$membername = $_POST['type'] == 'name' ? $_POST['from_name'] : '';
1388
1389
	// Now call the reattribute function.
1390
	require_once($sourcedir . '/Subs-Members.php');
1391
	reattributePosts($memID, $email, $membername, !empty($_POST['posts']));
1392
1393
	$context['maintenance_finished'] = $txt['maintain_reattribute_posts'];
1394
}
1395
1396
/**
1397
 * Removing old members. Done and out!
1398
 *
1399
 * @todo refactor
1400
 */
1401
function MaintainPurgeInactiveMembers()
1402
{
1403
	global $sourcedir, $context, $smcFunc, $txt;
1404
1405
	$_POST['maxdays'] = empty($_POST['maxdays']) ? 0 : (int) $_POST['maxdays'];
1406
	if (!empty($_POST['groups']) && $_POST['maxdays'] > 0)
1407
	{
1408
		checkSession();
1409
		validateToken('admin-maint');
1410
1411
		$groups = array();
1412
		foreach ($_POST['groups'] as $id => $dummy)
1413
			$groups[] = (int) $id;
1414
		$time_limit = (time() - ($_POST['maxdays'] * 24 * 3600));
1415
		$where_vars = array(
1416
			'time_limit' => $time_limit,
1417
		);
1418
		if ($_POST['del_type'] == 'activated')
1419
		{
1420
			$where = 'mem.date_registered < {int:time_limit} AND mem.is_activated = {int:is_activated}';
1421
			$where_vars['is_activated'] = 0;
1422
		}
1423
		else
1424
			$where = 'mem.last_login < {int:time_limit} AND (mem.last_login != 0 OR mem.date_registered < {int:time_limit})';
1425
1426
		// Need to get *all* groups then work out which (if any) we avoid.
1427
		$request = $smcFunc['db_query']('', '
1428
			SELECT id_group, group_name, min_posts
1429
			FROM {db_prefix}membergroups',
1430
			array(
1431
			)
1432
		);
1433
		while ($row = $smcFunc['db_fetch_assoc']($request))
1434
		{
1435
			// Avoid this one?
1436
			if (!in_array($row['id_group'], $groups))
1437
			{
1438
				// Post group?
1439
				if ($row['min_posts'] != -1)
1440
				{
1441
					$where .= ' AND mem.id_post_group != {int:id_post_group_' . $row['id_group'] . '}';
1442
					$where_vars['id_post_group_' . $row['id_group']] = $row['id_group'];
1443
				}
1444
				else
1445
				{
1446
					$where .= ' AND mem.id_group != {int:id_group_' . $row['id_group'] . '} AND FIND_IN_SET({int:id_group_' . $row['id_group'] . '}, mem.additional_groups) = 0';
1447
					$where_vars['id_group_' . $row['id_group']] = $row['id_group'];
1448
				}
1449
			}
1450
		}
1451
		$smcFunc['db_free_result']($request);
1452
1453
		// If we have ungrouped unselected we need to avoid those guys.
1454
		if (!in_array(0, $groups))
1455
		{
1456
			$where .= ' AND (mem.id_group != 0 OR mem.additional_groups != {string:blank_add_groups})';
1457
			$where_vars['blank_add_groups'] = '';
1458
		}
1459
1460
		// Select all the members we're about to murder/remove...
1461
		$request = $smcFunc['db_query']('', '
1462
			SELECT mem.id_member, COALESCE(m.id_member, 0) AS is_mod
1463
			FROM {db_prefix}members AS mem
1464
				LEFT JOIN {db_prefix}moderators AS m ON (m.id_member = mem.id_member)
1465
			WHERE ' . $where,
1466
			$where_vars
1467
		);
1468
		$members = array();
1469
		while ($row = $smcFunc['db_fetch_assoc']($request))
1470
		{
1471
			if (!$row['is_mod'] || !in_array(3, $groups))
1472
				$members[] = $row['id_member'];
1473
		}
1474
		$smcFunc['db_free_result']($request);
1475
1476
		require_once($sourcedir . '/Subs-Members.php');
1477
		deleteMembers($members);
1478
	}
1479
1480
	$context['maintenance_finished'] = $txt['maintain_members'];
1481
	createToken('admin-maint');
1482
}
1483
1484
/**
1485
 * Removing old posts doesn't take much as we really pass through.
1486
 */
1487
function MaintainRemoveOldPosts()
1488
{
1489
	global $sourcedir;
1490
1491
	validateToken('admin-maint');
1492
1493
	// Actually do what we're told!
1494
	require_once($sourcedir . '/RemoveTopic.php');
1495
	RemoveOldTopics2();
1496
}
1497
1498
/**
1499
 * Removing old drafts
1500
 */
1501
function MaintainRemoveOldDrafts()
1502
{
1503
	global $sourcedir, $smcFunc;
1504
1505
	validateToken('admin-maint');
1506
1507
	$drafts = array();
1508
1509
	// Find all of the old drafts
1510
	$request = $smcFunc['db_query']('', '
1511
		SELECT id_draft
1512
		FROM {db_prefix}user_drafts
1513
		WHERE poster_time <= {int:poster_time_old}',
1514
		array(
1515
			'poster_time_old' => time() - (86400 * $_POST['draftdays']),
1516
		)
1517
	);
1518
1519
	while ($row = $smcFunc['db_fetch_row']($request))
1520
		$drafts[] = (int) $row[0];
1521
	$smcFunc['db_free_result']($request);
1522
1523
	// If we have old drafts, remove them
1524
	if (count($drafts) > 0)
1525
	{
1526
		require_once($sourcedir . '/Drafts.php');
1527
		DeleteDraft($drafts, false);
0 ignored issues
show
Bug introduced by
$drafts of type array|integer[] is incompatible with the type integer expected by parameter $id_draft of DeleteDraft(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1527
		DeleteDraft(/** @scrutinizer ignore-type */ $drafts, false);
Loading history...
1528
	}
1529
}
1530
1531
/**
1532
 * Moves topics from one board to another.
1533
 *
1534
 * @uses template_not_done() to pause the process.
1535
 */
1536
function MaintainMassMoveTopics()
1537
{
1538
	global $smcFunc, $sourcedir, $context, $txt;
1539
1540
	// Only admins.
1541
	isAllowedTo('admin_forum');
1542
1543
	checkSession('request');
1544
	validateToken('admin-maint');
1545
1546
	// Set up to the context.
1547
	$context['page_title'] = $txt['not_done_title'];
1548
	$context['continue_countdown'] = 3;
1549
	$context['continue_post_data'] = '';
1550
	$context['continue_get_data'] = '';
1551
	$context['sub_template'] = 'not_done';
1552
	$context['start'] = empty($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
1553
	$context['start_time'] = time();
1554
1555
	// First time we do this?
1556
	$id_board_from = isset($_REQUEST['id_board_from']) ? (int) $_REQUEST['id_board_from'] : 0;
1557
	$id_board_to = isset($_REQUEST['id_board_to']) ? (int) $_REQUEST['id_board_to'] : 0;
1558
	$max_days = isset($_REQUEST['maxdays']) ? (int) $_REQUEST['maxdays'] : 0;
1559
	$locked = isset($_POST['move_type_locked']) || isset($_GET['locked']);
1560
	$sticky = isset($_POST['move_type_sticky']) || isset($_GET['sticky']);
1561
1562
	// No boards then this is your stop.
1563
	if (empty($id_board_from) || empty($id_board_to))
1564
		return;
1565
1566
	// The big WHERE clause
1567
	$conditions = 'WHERE t.id_board = {int:id_board_from}
1568
		AND m.icon != {string:moved}';
1569
1570
	// DB parameters
1571
	$params = array(
1572
		'id_board_from' => $id_board_from,
1573
		'moved' => 'moved',
1574
	);
1575
1576
	// Only moving topics not posted in for x days?
1577
	if (!empty($max_days))
1578
	{
1579
		$conditions .= '
1580
			AND m.poster_time < {int:poster_time}';
1581
		$params['poster_time'] = time() - 3600 * 24 * $max_days;
1582
	}
1583
1584
	// Moving locked topics?
1585
	if ($locked)
1586
	{
1587
		$conditions .= '
1588
			AND t.locked = {int:locked}';
1589
		$params['locked'] = 1;
1590
	}
1591
1592
	// What about sticky topics?
1593
	if ($sticky)
1594
	{
1595
		$conditions .= '
1596
			AND t.is_sticky = {int:sticky}';
1597
		$params['sticky'] = 1;
1598
	}
1599
1600
	// How many topics are we converting?
1601
	if (!isset($_REQUEST['totaltopics']))
1602
	{
1603
		$request = $smcFunc['db_query']('', '
1604
			SELECT COUNT(*)
1605
			FROM {db_prefix}topics AS t
1606
				INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_last_msg)' .
1607
			$conditions,
1608
			$params
1609
		);
1610
		list ($total_topics) = $smcFunc['db_fetch_row']($request);
1611
		$smcFunc['db_free_result']($request);
1612
	}
1613
	else
1614
		$total_topics = (int) $_REQUEST['totaltopics'];
1615
1616
	// Seems like we need this here.
1617
	$context['continue_get_data'] = '?action=admin;area=maintain;sa=topics;activity=massmove;id_board_from=' . $id_board_from . ';id_board_to=' . $id_board_to . ';totaltopics=' . $total_topics . ';max_days=' . $max_days;
1618
1619
	if ($locked)
1620
		$context['continue_get_data'] .= ';locked';
1621
1622
	if ($sticky)
1623
		$context['continue_get_data'] .= ';sticky';
1624
1625
	$context['continue_get_data'] .= ';start=' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1626
1627
	// We have topics to move so start the process.
1628
	if (!empty($total_topics))
1629
	{
1630
		while ($context['start'] <= $total_topics)
1631
		{
1632
			// Lets get the topics.
1633
			$request = $smcFunc['db_query']('', '
1634
				SELECT t.id_topic
1635
				FROM {db_prefix}topics AS t
1636
					INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_last_msg)
1637
				' . $conditions . '
1638
				LIMIT 10',
1639
				$params
1640
			);
1641
1642
			// Get the ids.
1643
			$topics = array();
1644
			while ($row = $smcFunc['db_fetch_assoc']($request))
1645
				$topics[] = $row['id_topic'];
1646
1647
			// Just return if we don't have any topics left to move.
1648
			if (empty($topics))
1649
			{
1650
				cache_put_data('board-' . $id_board_from, null, 120);
1651
				cache_put_data('board-' . $id_board_to, null, 120);
1652
				redirectexit('action=admin;area=maintain;sa=topics;done=massmove');
1653
			}
1654
1655
			// Lets move them.
1656
			require_once($sourcedir . '/MoveTopic.php');
1657
			moveTopics($topics, $id_board_to);
1658
1659
			// We've done at least ten more topics.
1660
			$context['start'] += 10;
1661
1662
			// Lets wait a while.
1663
			if (time() - $context['start_time'] > 3)
1664
			{
1665
				// What's the percent?
1666
				$context['continue_percent'] = round(100 * ($context['start'] / $total_topics), 1);
1667
				$context['continue_get_data'] = '?action=admin;area=maintain;sa=topics;activity=massmove;id_board_from=' . $id_board_from . ';id_board_to=' . $id_board_to . ';totaltopics=' . $total_topics . ';start=' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1668
1669
				// Let the template system do it's thang.
1670
				return;
1671
			}
1672
		}
1673
	}
1674
1675
	// Don't confuse admins by having an out of date cache.
1676
	cache_put_data('board-' . $id_board_from, null, 120);
1677
	cache_put_data('board-' . $id_board_to, null, 120);
1678
1679
	redirectexit('action=admin;area=maintain;sa=topics;done=massmove');
1680
}
1681
1682
/**
1683
 * Recalculate all members post counts
1684
 * it requires the admin_forum permission.
1685
 *
1686
 * - recounts all posts for members found in the message table
1687
 * - updates the members post count record in the members table
1688
 * - honors the boards post count flag
1689
 * - does not count posts in the recycle bin
1690
 * - zeros post counts for all members with no posts in the message table
1691
 * - runs as a delayed loop to avoid server overload
1692
 * - uses the not_done template in Admin.template
1693
 *
1694
 * The function redirects back to action=admin;area=maintain;sa=members when complete.
1695
 * It is accessed via ?action=admin;area=maintain;sa=members;activity=recountposts
1696
 */
1697
function MaintainRecountPosts()
1698
{
1699
	global $txt, $context, $modSettings, $smcFunc;
1700
1701
	// You have to be allowed in here
1702
	isAllowedTo('admin_forum');
1703
	checkSession('request');
1704
1705
	// Set up to the context.
1706
	$context['page_title'] = $txt['not_done_title'];
1707
	$context['continue_countdown'] = 3;
1708
	$context['continue_get_data'] = '';
1709
	$context['sub_template'] = 'not_done';
1710
1711
	// init
1712
	$increment = 200;
1713
	$_REQUEST['start'] = !isset($_REQUEST['start']) ? 0 : (int) $_REQUEST['start'];
1714
1715
	// Ask for some extra time, on big boards this may take a bit
1716
	@set_time_limit(600);
1717
1718
	// Only run this query if we don't have the total number of members that have posted
1719
	if (!isset($_SESSION['total_members']))
1720
	{
1721
		validateToken('admin-maint');
1722
1723
		$request = $smcFunc['db_query']('', '
1724
			SELECT COUNT(DISTINCT m.id_member)
1725
			FROM {db_prefix}messages AS m
1726
			JOIN {db_prefix}boards AS b on m.id_board = b.id_board
1727
			WHERE m.id_member != 0
1728
				AND b.count_posts = 0',
1729
			array(
1730
			)
1731
		);
1732
1733
		// save it so we don't do this again for this task
1734
		list ($_SESSION['total_members']) = $smcFunc['db_fetch_row']($request);
1735
		$smcFunc['db_free_result']($request);
1736
	}
1737
	else
1738
		validateToken('admin-recountposts');
1739
1740
	// Lets get a group of members and determine their post count (from the boards that have post count enabled of course).
1741
	$request = $smcFunc['db_query']('', '
1742
		SELECT m.id_member, COUNT(*) AS posts
1743
		FROM {db_prefix}messages AS m
1744
			INNER JOIN {db_prefix}boards AS b ON m.id_board = b.id_board
1745
		WHERE m.id_member != {int:zero}
1746
			AND b.count_posts = {int:zero}
1747
			' . (!empty($modSettings['recycle_enable']) ? ' AND b.id_board != {int:recycle}' : '') . '
1748
		GROUP BY m.id_member
1749
		LIMIT {int:start}, {int:number}',
1750
		array(
1751
			'start' => $_REQUEST['start'],
1752
			'number' => $increment,
1753
			'recycle' => $modSettings['recycle_board'],
1754
			'zero' => 0,
1755
		)
1756
	);
1757
	$total_rows = $smcFunc['db_num_rows']($request);
1758
1759
	// Update the post count for this group
1760
	while ($row = $smcFunc['db_fetch_assoc']($request))
1761
	{
1762
		$smcFunc['db_query']('', '
1763
			UPDATE {db_prefix}members
1764
			SET posts = {int:posts}
1765
			WHERE id_member = {int:row}',
1766
			array(
1767
				'row' => $row['id_member'],
1768
				'posts' => $row['posts'],
1769
			)
1770
		);
1771
	}
1772
	$smcFunc['db_free_result']($request);
1773
1774
	// Continue?
1775
	if ($total_rows == $increment)
1776
	{
1777
		$_REQUEST['start'] += $increment;
1778
		$context['continue_get_data'] = '?action=admin;area=maintain;sa=members;activity=recountposts;start=' . $_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
1779
		$context['continue_percent'] = round(100 * $_REQUEST['start'] / $_SESSION['total_members']);
1780
1781
		createToken('admin-recountposts');
1782
		$context['continue_post_data'] = '<input type="hidden" name="' . $context['admin-recountposts_token_var'] . '" value="' . $context['admin-recountposts_token'] . '">';
1783
1784
		if (function_exists('apache_reset_timeout'))
1785
			apache_reset_timeout();
1786
		return;
1787
	}
1788
1789
	// final steps ... made more difficult since we don't yet support sub-selects on joins
1790
	// place all members who have posts in the message table in a temp table
1791
	$createTemporary = $smcFunc['db_query']('', '
1792
		CREATE TEMPORARY TABLE {db_prefix}tmp_maint_recountposts (
1793
			id_member mediumint(8) unsigned NOT NULL default {string:string_zero},
1794
			PRIMARY KEY (id_member)
1795
		)
1796
		SELECT m.id_member
1797
		FROM {db_prefix}messages AS m
1798
			INNER JOIN {db_prefix}boards AS b ON m.id_board = b.id_board
1799
		WHERE m.id_member != {int:zero}
1800
			AND b.count_posts = {int:zero}
1801
			' . (!empty($modSettings['recycle_enable']) ? ' AND b.id_board != {int:recycle}' : '') . '
1802
		GROUP BY m.id_member',
1803
		array(
1804
			'zero' => 0,
1805
			'string_zero' => '0',
1806
			'db_error_skip' => true,
1807
			'recycle' => !empty($modSettings['recycle_board']) ? $modSettings['recycle_board'] : 0,
1808
		)
1809
	) !== false;
1810
1811
	if ($createTemporary)
1812
	{
1813
		// outer join the members table on the temporary table finding the members that have a post count but no posts in the message table
1814
		$request = $smcFunc['db_query']('', '
1815
			SELECT mem.id_member, mem.posts
1816
			FROM {db_prefix}members AS mem
1817
				LEFT OUTER JOIN {db_prefix}tmp_maint_recountposts AS res
1818
				ON res.id_member = mem.id_member
1819
			WHERE res.id_member IS null
1820
				AND mem.posts != {int:zero}',
1821
			array(
1822
				'zero' => 0,
1823
			)
1824
		);
1825
1826
		// set the post count to zero for any delinquents we may have found
1827
		while ($row = $smcFunc['db_fetch_assoc']($request))
1828
		{
1829
			$smcFunc['db_query']('', '
1830
				UPDATE {db_prefix}members
1831
				SET posts = {int:zero}
1832
				WHERE id_member = {int:row}',
1833
				array(
1834
					'row' => $row['id_member'],
1835
					'zero' => 0,
1836
				)
1837
			);
1838
		}
1839
		$smcFunc['db_free_result']($request);
1840
	}
1841
1842
	// all done
1843
	unset($_SESSION['total_members']);
1844
	$context['maintenance_finished'] = $txt['maintain_recountposts'];
1845
	redirectexit('action=admin;area=maintain;sa=members;done=recountposts');
1846
}
1847
1848
/**
1849
 * Generates a list of integration hooks for display
1850
 * Accessed through ?action=admin;area=maintain;sa=hooks;
1851
 * Allows for removal or disabling of selected hooks
1852
 */
1853
function list_integration_hooks()
1854
{
1855
	global $boarddir, $sourcedir, $scripturl, $context, $txt;
1856
1857
	$filter_url = '';
1858
	$current_filter = '';
1859
	$hooks = get_integration_hooks();
1860
	$hooks_filters = array();
1861
1862
	if (isset($_GET['filter'], $hooks[$_GET['filter']]))
1863
	{
1864
		$filter_url = ';filter=' . $_GET['filter'];
1865
		$current_filter = $_GET['filter'];
1866
	}
1867
	$filtered_hooks = array_filter(
1868
		$hooks,
1869
		function($hook) use ($current_filter)
1870
		{
1871
			return $current_filter == '' || $current_filter == $hook;
1872
		},
1873
		ARRAY_FILTER_USE_KEY
1874
	);
1875
	ksort($hooks);
1876
1877
	foreach ($hooks as $hook => $functions)
1878
		$hooks_filters[] = '<option' . ($current_filter == $hook ? ' selected ' : '') . ' value="' . $hook . '">' . $hook . '</option>';
1879
1880
	if (!empty($hooks_filters))
1881
		$context['insert_after_template'] .= '
1882
		<script>
1883
			var hook_name_header = document.getElementById(\'header_list_integration_hooks_hook_name\');
1884
			hook_name_header.innerHTML += ' . JavaScriptEscape('<select style="margin-left:15px;" onchange="window.location=(\'' . $scripturl . '?action=admin;area=maintain;sa=hooks\' + (this.value ? \';filter=\' + this.value : \'\'));"><option value="">' . $txt['hooks_reset_filter'] . '</option>' . implode('', $hooks_filters) . '</select>') . ';
1885
		</script>';
1886
1887
	if (!empty($_REQUEST['do']) && isset($_REQUEST['hook']) && isset($_REQUEST['function']))
1888
	{
1889
		checkSession('request');
1890
		validateToken('admin-hook', 'request');
1891
1892
		if ($_REQUEST['do'] == 'remove')
1893
			remove_integration_function($_REQUEST['hook'], urldecode($_REQUEST['function']));
1894
1895
		else
1896
		{
1897
			$function_remove = urldecode($_REQUEST['function']) . (($_REQUEST['do'] == 'disable') ? '' : '!');
1898
			$function_add = urldecode($_REQUEST['function']) . (($_REQUEST['do'] == 'disable') ? '!' : '');
1899
1900
			remove_integration_function($_REQUEST['hook'], $function_remove);
1901
			add_integration_function($_REQUEST['hook'], $function_add);
1902
		}
1903
1904
		redirectexit('action=admin;area=maintain;sa=hooks' . $filter_url);
1905
	}
1906
1907
	createToken('admin-hook', 'request');
1908
1909
	$list_options = array(
1910
		'id' => 'list_integration_hooks',
1911
		'title' => $txt['hooks_title_list'],
1912
		'items_per_page' => 20,
1913
		'base_href' => $scripturl . '?action=admin;area=maintain;sa=hooks' . $filter_url . ';' . $context['session_var'] . '=' . $context['session_id'],
1914
		'default_sort_col' => 'hook_name',
1915
		'get_items' => array(
1916
			'function' => 'get_integration_hooks_data',
1917
			'params' => array(
1918
				$filtered_hooks,
1919
				strtr($boarddir, '\\', '/'),
1920
				strtr($sourcedir, '\\', '/'),
1921
			),
1922
		),
1923
		'get_count' => array(
1924
			'value' => array_reduce(
1925
				$filtered_hooks,
1926
				function($accumulator, $functions)
1927
				{
1928
					return $accumulator + count($functions);
1929
				},
1930
				0
1931
			),
1932
		),
1933
		'no_items_label' => $txt['hooks_no_hooks'],
1934
		'columns' => array(
1935
			'hook_name' => array(
1936
				'header' => array(
1937
					'value' => $txt['hooks_field_hook_name'],
1938
				),
1939
				'data' => array(
1940
					'db' => 'hook_name',
1941
				),
1942
				'sort' => array(
1943
					'default' => 'hook_name',
1944
					'reverse' => 'hook_name DESC',
1945
				),
1946
			),
1947
			'function_name' => array(
1948
				'header' => array(
1949
					'value' => $txt['hooks_field_function_name'],
1950
				),
1951
				'data' => array(
1952
					'function' => function($data) use ($txt)
1953
					{
1954
						// Show a nice icon to indicate this is an instance.
1955
						$instance = (!empty($data['instance']) ? '<span class="main_icons news" title="' . $txt['hooks_field_function_method'] . '"></span> ' : '');
1956
1957
						if (!empty($data['included_file']) && !empty($data['real_function']))
1958
							return $instance . $txt['hooks_field_function'] . ': ' . $data['real_function'] . '<br>' . $txt['hooks_field_included_file'] . ': ' . $data['included_file'];
1959
1960
						else
1961
							return $instance . $data['real_function'];
1962
					},
1963
				),
1964
				'sort' => array(
1965
					'default' => 'function_name',
1966
					'reverse' => 'function_name DESC',
1967
				),
1968
			),
1969
			'file_name' => array(
1970
				'header' => array(
1971
					'value' => $txt['hooks_field_file_name'],
1972
				),
1973
				'data' => array(
1974
					'db' => 'file_name',
1975
				),
1976
				'sort' => array(
1977
					'default' => 'file_name',
1978
					'reverse' => 'file_name DESC',
1979
				),
1980
			),
1981
			'status' => array(
1982
				'header' => array(
1983
					'value' => $txt['hooks_field_hook_exists'],
1984
					'style' => 'width:3%;',
1985
				),
1986
				'data' => array(
1987
					'function' => function($data) use ($txt, $scripturl, $context, $filter_url)
1988
					{
1989
						$change_status = array('before' => '', 'after' => '');
1990
1991
						if ($data['can_disable'])
1992
						{
1993
							$change_status['before'] = '<a href="' . $scripturl . '?action=admin;area=maintain;sa=hooks;do=' . ($data['enabled'] ? 'disable' : 'enable') . ';hook=' . $data['hook_name'] . ';function=' . urlencode($data['real_function']) . $filter_url . ';' . $context['admin-hook_token_var'] . '=' . $context['admin-hook_token'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '" data-confirm="' . $txt['quickmod_confirm'] . '" class="you_sure">';
1994
							$change_status['after'] = '</a>';
1995
						}
1996
1997
						return $change_status['before'] . '<span class="main_icons post_moderation_' . $data['status'] . '" title="' . $data['img_text'] . '"></span>' . $change_status['after'];
1998
					},
1999
					'class' => 'centertext',
2000
				),
2001
				'sort' => array(
2002
					'default' => 'status',
2003
					'reverse' => 'status DESC',
2004
				),
2005
			),
2006
		),
2007
		'additional_rows' => array(
2008
			array(
2009
				'position' => 'after_title',
2010
				'value' => $txt['hooks_disable_instructions'] . '<br>
2011
					' . $txt['hooks_disable_legend'] . ':
2012
				<ul style="list-style: none;">
2013
					<li><span class="main_icons post_moderation_allow"></span> ' . $txt['hooks_disable_legend_exists'] . '</li>
2014
					<li><span class="main_icons post_moderation_moderate"></span> ' . $txt['hooks_disable_legend_disabled'] . '</li>
2015
					<li><span class="main_icons post_moderation_deny"></span> ' . $txt['hooks_disable_legend_missing'] . '</li>
2016
				</ul>'
2017
			),
2018
		),
2019
	);
2020
2021
	$list_options['columns']['remove'] = array(
2022
		'header' => array(
2023
			'value' => $txt['hooks_button_remove'],
2024
			'style' => 'width:3%',
2025
		),
2026
		'data' => array(
2027
			'function' => function($data) use ($txt, $scripturl, $context, $filter_url)
2028
			{
2029
				if (!$data['hook_exists'])
2030
					return '
2031
					<a href="' . $scripturl . '?action=admin;area=maintain;sa=hooks;do=remove;hook=' . $data['hook_name'] . ';function=' . urlencode($data['function_name']) . $filter_url . ';' . $context['admin-hook_token_var'] . '=' . $context['admin-hook_token'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '" data-confirm="' . $txt['quickmod_confirm'] . '" class="you_sure">
2032
						<span class="main_icons delete" title="' . $txt['hooks_button_remove'] . '"></span>
2033
					</a>';
2034
			},
2035
			'class' => 'centertext',
2036
		),
2037
	);
2038
	$list_options['form'] = array(
2039
		'href' => $scripturl . '?action=admin;area=maintain;sa=hooks' . $filter_url . ';' . $context['session_var'] . '=' . $context['session_id'],
2040
		'name' => 'list_integration_hooks',
2041
	);
2042
2043
	require_once($sourcedir . '/Subs-List.php');
2044
	createList($list_options);
2045
2046
	$context['page_title'] = $txt['hooks_title_list'];
2047
	$context['sub_template'] = 'show_list';
2048
	$context['default_list'] = 'list_integration_hooks';
2049
}
2050
2051
/**
2052
 * Gets all of the files in a directory and its children directories
2053
 *
2054
 * @param string $dirname The path to the directory
2055
 * @return array An array containing information about the files found in the specified directory and its children
2056
 */
2057
function get_files_recursive(string $dirname): array
2058
{
2059
	return iterator_to_array(
2060
		new RecursiveIteratorIterator(
2061
			new RecursiveCallbackFilterIterator(
2062
				new RecursiveDirectoryIterator($dirname, FilesystemIterator::UNIX_PATHS),
2063
				function ($fileInfo, $currentFile, $iterator)
0 ignored issues
show
Bug introduced by
function(...) { /* ... */ } of type callable is incompatible with the type string expected by parameter $callback of RecursiveCallbackFilterIterator::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2063
				/** @scrutinizer ignore-type */ function ($fileInfo, $currentFile, $iterator)
Loading history...
2064
				{
2065
					// Allow recursion
2066
					if ($iterator->hasChildren())
2067
						return true;
2068
					return $fileInfo->getExtension() == 'php';
2069
				}
2070
			)
2071
		)
2072
	);
2073
}
2074
2075
/**
2076
 * Callback function for the integration hooks list (list_integration_hooks)
2077
 * Gets all of the hooks in the system and their status
2078
 *
2079
 * @param int $start The item to start with (for pagination purposes)
2080
 * @param int $per_page How many items to display on each page
2081
 * @param string $sort A string indicating how to sort things
2082
 * @return array An array of information about the integration hooks
2083
 */
2084
function get_integration_hooks_data($start, $per_page, $sort, $filtered_hooks, $normalized_boarddir, $normalized_sourcedir)
2085
{
2086
	global $settings, $txt, $context, $scripturl;
2087
2088
	$function_list = $sort_array = $temp_data = array();
2089
	$files = get_files_recursive($normalized_sourcedir);
2090
	foreach ($files as $currentFile => $fileInfo)
2091
		$function_list += get_defined_functions_in_file($currentFile);
2092
2093
	$sort_types = array(
2094
		'hook_name' => array('hook_name', SORT_ASC),
2095
		'hook_name DESC' => array('hook_name', SORT_DESC),
2096
		'function_name' => array('function_name', SORT_ASC),
2097
		'function_name DESC' => array('function_name', SORT_DESC),
2098
		'file_name' => array('file_name', SORT_ASC),
2099
		'file_name DESC' => array('file_name', SORT_DESC),
2100
		'status' => array('status', SORT_ASC),
2101
		'status DESC' => array('status', SORT_DESC),
2102
	);
2103
2104
	foreach ($filtered_hooks as $hook => $functions)
2105
		foreach ($functions as $rawFunc)
2106
		{
2107
			$hookParsedData = parse_integration_hook($hook, $rawFunc);
2108
2109
			// Handle hooks pointing outside the sources directory.
2110
			if ($hookParsedData['absPath'] != '' && !isset($files[$hookParsedData['absPath']]) || file_exists($hookParsedData['absPath']))
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($hookParsedData['absPat...kParsedData['absPath']), Probably Intended Meaning: $hookParsedData['absPath...ParsedData['absPath']))
Loading history...
2111
				$function_list += get_defined_functions_in_file($hookParsedData['absPath']);
2112
2113
			$hook_exists = isset($function_list[$hookParsedData['call']]) || (substr($hook, -8) === '_include' && isset($files[$hookParsedData['absPath']]));
2114
			$temp = array(
2115
				'hook_name' => $hook,
2116
				'function_name' => $hookParsedData['rawData'],
2117
				'real_function' => $hookParsedData['call'],
2118
				'included_file' => $hookParsedData['hookFile'],
2119
				'file_name' => strtr($hookParsedData['absPath'] ?: ($function_list[$hookParsedData['call']] ?? ''), [$normalized_boarddir => '.']),
2120
				'instance' => $hookParsedData['object'],
2121
				'hook_exists' => $hook_exists,
2122
				'status' => $hook_exists ? ($hookParsedData['enabled'] ? 'allow' : 'moderate') : 'deny',
2123
				'img_text' => $txt['hooks_' . ($hook_exists ? ($hookParsedData['enabled'] ? 'active' : 'disabled') : 'missing')],
2124
				'enabled' => $hookParsedData['enabled'],
2125
				'can_disable' => $hookParsedData['call'] != '',
2126
			);
2127
			$sort_array[] = $temp[$sort_types[$sort][0]];
2128
			$temp_data[] = $temp;
2129
		}
2130
2131
	array_multisort($sort_array, $sort_types[$sort][1], $temp_data);
2132
2133
	return array_slice($temp_data, $start, $per_page, true);
2134
}
2135
2136
/**
2137
 * Parses modSettings to create integration hook array
2138
 *
2139
 * @return array An array of information about the integration hooks
2140
 */
2141
function get_integration_hooks()
2142
{
2143
	global $modSettings;
2144
	static $integration_hooks;
2145
2146
	if (!isset($integration_hooks))
2147
	{
2148
		$integration_hooks = array();
2149
		foreach ($modSettings as $key => $value)
2150
		{
2151
			if (!empty($value) && substr($key, 0, 10) === 'integrate_')
2152
				$integration_hooks[$key] = explode(',', $value);
2153
		}
2154
	}
2155
2156
	return $integration_hooks;
2157
}
2158
2159
/**
2160
 * Parses each hook data and returns an array.
2161
 *
2162
 * @param string $hook
2163
 * @param string $rawData A string as it was saved to the DB.
2164
 * @return array everything found in the string itself
2165
 */
2166
function parse_integration_hook(string $hook, string $rawData)
2167
{
2168
	global $boarddir, $settings, $sourcedir;
2169
2170
	// A single string can hold tons of info!
2171
	$hookData = array(
2172
		'object' => false,
2173
		'enabled' => true,
2174
		'absPath' => '',
2175
		'hookFile' => '',
2176
		'pureFunc' => '',
2177
		'method' => '',
2178
		'class' => '',
2179
		'call' => '',
2180
		'rawData' => $rawData,
2181
	);
2182
2183
	// Meh...
2184
	if (empty($rawData))
2185
		return $hookData;
2186
2187
	$modFunc = $rawData;
2188
2189
	// Any files?
2190
	if (substr($hook, -8) === '_include')
2191
		$modFunc = $modFunc . '|';
2192
	if (strpos($modFunc, '|') !== false)
2193
	{
2194
		list ($hookData['hookFile'], $modFunc) = explode('|', $modFunc);
2195
		$hookData['absPath'] = strtr(strtr(trim($hookData['hookFile']), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir, '$themedir' => $settings['theme_dir'] ?? '')), '\\', '/');
2196
	}
2197
2198
	// Hook is an instance.
2199
	if (strpos($modFunc, '#') !== false)
2200
	{
2201
		$modFunc = str_replace('#', '', $modFunc);
2202
		$hookData['object'] = true;
2203
	}
2204
2205
	// Hook is "disabled"
2206
	if (strpos($modFunc, '!') !== false)
2207
	{
2208
		$modFunc = str_replace('!', '', $modFunc);
2209
		$hookData['enabled'] = false;
2210
	}
2211
2212
	// Handling methods?
2213
	if (strpos($modFunc, '::') !== false)
2214
	{
2215
		list ($hookData['class'], $hookData['method']) = explode('::', $modFunc);
2216
		$hookData['pureFunc'] = $hookData['method'];
2217
		$hookData['call'] = $modFunc;
2218
	}
2219
2220
	else
2221
		$hookData['call'] = $hookData['pureFunc'] = $modFunc;
2222
2223
	return $hookData;
2224
}
2225
2226
function get_defined_functions_in_file(string $file): array
2227
{
2228
	$source = file_get_contents($file);
2229
	// token_get_all() is too slow so use a nice little regex instead.
2230
	preg_match_all('/\bnamespace\s++((?P>label)(?:\\\(?P>label))*+)\s*+;|\bclass\s++((?P>label))[\w\s]*+{|\bfunction\s++((?P>label))\s*+\(.*\)[:\|\w\s]*+{(?(DEFINE)(?<label>[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*+))/i', $source, $matches, PREG_SET_ORDER);
2231
2232
	$functions = array();
2233
	$namespace = '';
2234
	$class = '';
2235
2236
	foreach ($matches as $match)
2237
	{
2238
		if (!empty($match[1]))
2239
			$namespace = $match[1] . '\\';
2240
		elseif (!empty($match[2]))
2241
			$class = $namespace . $match[2] . '::';
2242
		elseif (!empty($match[3]))
2243
			$functions[$class . $match[3]] = $file;
2244
	}
2245
2246
	return $functions;
2247
}
2248
2249
/**
2250
 * Converts html entities to utf8 equivalents
2251
 * special db wrapper for mysql based on the limitation of mysql/mb3
2252
 *
2253
 * Callback function for preg_replace_callback
2254
 * Uses capture group 1 in the supplied array
2255
 * Does basic checks to keep characters inside a viewable range.
2256
 *
2257
 * @param array $matches An array of matches (relevant info should be the 2nd item in the array)
2258
 * @return string The fixed string or return the old when limitation of mysql is hit
2259
 */
2260
function fixchardb__callback($matches)
2261
{
2262
	global $smcFunc;
2263
	if (!isset($matches[1]))
2264
		return '';
2265
2266
	$num = $matches[1][0] === 'x' ? hexdec(substr($matches[1], 1)) : (int) $matches[1];
0 ignored issues
show
Bug introduced by
$matches[1] of type array is incompatible with the type string expected by parameter $string of substr(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2266
	$num = $matches[1][0] === 'x' ? hexdec(substr(/** @scrutinizer ignore-type */ $matches[1], 1)) : (int) $matches[1];
Loading history...
2267
2268
	// it's to big for mb3?
2269
	if ($num > 0xFFFF && !$smcFunc['db_mb4'])
2270
		return $matches[0];
2271
	else
2272
		return fixchar__callback($matches);
2273
}
2274
2275
?>