Passed
Pull Request — release-2.1 (#6786)
by Jon
05:08
created

fixchardb__callback()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 5
nop 1
dl 0
loc 13
rs 9.6111
c 0
b 0
f 0
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 RC3
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] = smf_entity_decode($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 $sourcedir, $scripturl, $context, $txt;
1856
1857
	$context['filter_url'] = '';
1858
	$context['current_filter'] = '';
1859
	$currentHooks = get_integration_hooks();
1860
	if (isset($_GET['filter']) && in_array($_GET['filter'], array_keys($currentHooks)))
1861
	{
1862
		$context['filter_url'] = ';filter=' . $_GET['filter'];
1863
		$context['current_filter'] = $_GET['filter'];
1864
	}
1865
1866
	if (!empty($_REQUEST['do']) && isset($_REQUEST['hook']) && isset($_REQUEST['function']))
1867
	{
1868
		checkSession('request');
1869
		validateToken('admin-hook', 'request');
1870
1871
		if ($_REQUEST['do'] == 'remove')
1872
			remove_integration_function($_REQUEST['hook'], urldecode($_REQUEST['function']));
1873
1874
		else
1875
		{
1876
			$function_remove = urldecode($_REQUEST['function']) . (($_REQUEST['do'] == 'disable') ? '' : '!');
1877
			$function_add = urldecode($_REQUEST['function']) . (($_REQUEST['do'] == 'disable') ? '!' : '');
1878
1879
			remove_integration_function($_REQUEST['hook'], $function_remove);
1880
			add_integration_function($_REQUEST['hook'], $function_add);
1881
		}
1882
1883
		redirectexit('action=admin;area=maintain;sa=hooks' . $context['filter_url']);
1884
	}
1885
1886
	createToken('admin-hook', 'request');
1887
1888
	$list_options = array(
1889
		'id' => 'list_integration_hooks',
1890
		'title' => $txt['hooks_title_list'],
1891
		'items_per_page' => 20,
1892
		'base_href' => $scripturl . '?action=admin;area=maintain;sa=hooks' . $context['filter_url'] . ';' . $context['session_var'] . '=' . $context['session_id'],
1893
		'default_sort_col' => 'hook_name',
1894
		'get_items' => array(
1895
			'function' => 'get_integration_hooks_data',
1896
		),
1897
		'get_count' => array(
1898
			'function' => 'get_integration_hooks_count',
1899
		),
1900
		'no_items_label' => $txt['hooks_no_hooks'],
1901
		'columns' => array(
1902
			'hook_name' => array(
1903
				'header' => array(
1904
					'value' => $txt['hooks_field_hook_name'],
1905
				),
1906
				'data' => array(
1907
					'db' => 'hook_name',
1908
				),
1909
				'sort' => array(
1910
					'default' => 'hook_name',
1911
					'reverse' => 'hook_name DESC',
1912
				),
1913
			),
1914
			'function_name' => array(
1915
				'header' => array(
1916
					'value' => $txt['hooks_field_function_name'],
1917
				),
1918
				'data' => array(
1919
					'function' => function($data) use ($txt)
1920
					{
1921
						// Show a nice icon to indicate this is an instance.
1922
						$instance = (!empty($data['instance']) ? '<span class="main_icons news" title="' . $txt['hooks_field_function_method'] . '"></span> ' : '');
1923
1924
						if (!empty($data['included_file']))
1925
							return $instance . $txt['hooks_field_function'] . ': ' . $data['real_function'] . '<br>' . $txt['hooks_field_included_file'] . ': ' . $data['included_file'];
1926
1927
						else
1928
							return $instance . $data['real_function'];
1929
					},
1930
				),
1931
				'sort' => array(
1932
					'default' => 'function_name',
1933
					'reverse' => 'function_name DESC',
1934
				),
1935
			),
1936
			'file_name' => array(
1937
				'header' => array(
1938
					'value' => $txt['hooks_field_file_name'],
1939
				),
1940
				'data' => array(
1941
					'db' => 'file_name',
1942
				),
1943
				'sort' => array(
1944
					'default' => 'file_name',
1945
					'reverse' => 'file_name DESC',
1946
				),
1947
			),
1948
			'status' => array(
1949
				'header' => array(
1950
					'value' => $txt['hooks_field_hook_exists'],
1951
					'style' => 'width:3%;',
1952
				),
1953
				'data' => array(
1954
					'function' => function($data) use ($txt, $scripturl, $context)
1955
					{
1956
						$change_status = array('before' => '', 'after' => '');
1957
1958
						$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']) . $context['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">';
1959
						$change_status['after'] = '</a>';
1960
1961
						return $change_status['before'] . '<span class="main_icons post_moderation_' . $data['status'] . '" title="' . $data['img_text'] . '"></span>';
1962
					},
1963
					'class' => 'centertext',
1964
				),
1965
				'sort' => array(
1966
					'default' => 'status',
1967
					'reverse' => 'status DESC',
1968
				),
1969
			),
1970
		),
1971
		'additional_rows' => array(
1972
			array(
1973
				'position' => 'after_title',
1974
				'value' => $txt['hooks_disable_instructions'] . '<br>
1975
					' . $txt['hooks_disable_legend'] . ':
1976
				<ul style="list-style: none;">
1977
					<li><span class="main_icons post_moderation_allow"></span> ' . $txt['hooks_disable_legend_exists'] . '</li>
1978
					<li><span class="main_icons post_moderation_moderate"></span> ' . $txt['hooks_disable_legend_disabled'] . '</li>
1979
					<li><span class="main_icons post_moderation_deny"></span> ' . $txt['hooks_disable_legend_missing'] . '</li>
1980
				</ul>'
1981
			),
1982
		),
1983
	);
1984
1985
	$list_options['columns']['remove'] = array(
1986
		'header' => array(
1987
			'value' => $txt['hooks_button_remove'],
1988
			'style' => 'width:3%',
1989
		),
1990
		'data' => array(
1991
			'function' => function($data) use ($txt, $scripturl, $context)
1992
			{
1993
				if (!$data['hook_exists'])
1994
					return '
1995
					<a href="' . $scripturl . '?action=admin;area=maintain;sa=hooks;do=remove;hook=' . $data['hook_name'] . ';function=' . urlencode($data['function_name']) . $context['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">
1996
						<span class="main_icons delete" title="' . $txt['hooks_button_remove'] . '"></span>
1997
					</a>';
1998
			},
1999
			'class' => 'centertext',
2000
		),
2001
	);
2002
	$list_options['form'] = array(
2003
		'href' => $scripturl . '?action=admin;area=maintain;sa=hooks' . $context['filter_url'] . ';' . $context['session_var'] . '=' . $context['session_id'],
2004
		'name' => 'list_integration_hooks',
2005
	);
2006
2007
	require_once($sourcedir . '/Subs-List.php');
2008
	createList($list_options);
2009
2010
	$context['page_title'] = $txt['hooks_title_list'];
2011
	$context['sub_template'] = 'show_list';
2012
	$context['default_list'] = 'list_integration_hooks';
2013
}
2014
2015
/**
2016
 * Gets all of the files in a directory and its children directories
2017
 *
2018
 * @param string $dir_path The path to the directory
2019
 * @return array An array containing information about the files found in the specified directory and its children
2020
 */
2021
function get_files_recursive($dir_path)
2022
{
2023
	$files = array();
2024
2025
	if ($dh = opendir($dir_path))
2026
	{
2027
		while (($file = readdir($dh)) !== false)
2028
		{
2029
			if ($file != '.' && $file != '..')
2030
			{
2031
				if (is_dir($dir_path . '/' . $file))
2032
					$files = array_merge($files, get_files_recursive($dir_path . '/' . $file));
2033
				else
2034
					$files[] = array('dir' => $dir_path, 'name' => $file);
2035
			}
2036
		}
2037
	}
2038
	closedir($dh);
2039
2040
	return $files;
2041
}
2042
2043
/**
2044
 * Callback function for the integration hooks list (list_integration_hooks)
2045
 * Gets all of the hooks in the system and their status
2046
 *
2047
 * @param int $start The item to start with (for pagination purposes)
2048
 * @param int $per_page How many items to display on each page
2049
 * @param string $sort A string indicating how to sort things
2050
 * @return array An array of information about the integration hooks
2051
 */
2052
function get_integration_hooks_data($start, $per_page, $sort)
2053
{
2054
	global $boarddir, $sourcedir, $settings, $txt, $context, $scripturl;
2055
2056
	$hooks = $temp_hooks = get_integration_hooks();
2057
	$hooks_data = $temp_data = $hook_status = array();
2058
2059
	$files = get_files_recursive($sourcedir);
2060
	if (!empty($files))
2061
	{
2062
		foreach ($files as $file)
2063
		{
2064
			if (is_file($file['dir'] . '/' . $file['name']) && substr($file['name'], -4) === '.php')
2065
			{
2066
				$fp = fopen($file['dir'] . '/' . $file['name'], 'rb');
2067
				$fc = fread($fp, filesize($file['dir'] . '/' . $file['name']));
2068
				fclose($fp);
2069
2070
				foreach ($temp_hooks as $hook => $allFunctions)
2071
				{
2072
					foreach ($allFunctions as $rawFunc)
2073
					{
2074
						// Get the hook info.
2075
						$hookParsedData = get_hook_info_from_raw($rawFunc);
2076
2077
						if (substr($hook, -8) === '_include')
2078
						{
2079
							$hook_status[$hook][$hookParsedData['class']][$hookParsedData['pureFunc']]['exists'] = file_exists(strtr(trim($rawFunc), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir, '$themedir' => $settings['theme_dir'])));
2080
							// I need to know if there is at least one function called in this file.
2081
							$temp_data['include'][$hookParsedData['pureFunc']] = array('hook' => $hook, 'function' => $hookParsedData['pureFunc']);
2082
							unset($temp_hooks[$hook][$rawFunc]);
2083
						}
2084
						elseif (strpos(str_replace(' (', '(', $fc), 'function ' . trim($hookParsedData['pureFunc']) . '(') !== false)
2085
						{
2086
							$hook_status[$hook][$hookParsedData['class']][$hookParsedData['pureFunc']] = $hookParsedData;
2087
							$hook_status[$hook][$hookParsedData['class']][$hookParsedData['pureFunc']]['exists'] = true;
2088
							$hook_status[$hook][$hookParsedData['class']][$hookParsedData['pureFunc']]['in_file'] = (!empty($hookParsedData['hookFile']) ? $hookParsedData['hookFile'] : (!empty($file['name']) ? $file['name'] : ''));
2089
2090
							// Does the hook has its own file?
2091
							if (!empty($hookParsedData['hookFile']))
2092
								$temp_data['include'][$hookParsedData['pureFunc']] = array('hook' => $hook, 'function' => $hookParsedData['pureFunc']);
2093
2094
							// I want to remember all the functions called within this file (to check later if they are enabled or disabled and decide if the integrare_*_include of that file can be disabled too)
2095
							$temp_data['function'][$file['name']][$hookParsedData['pureFunc']] = $hookParsedData['enabled'];
2096
							unset($temp_hooks[$hook][$rawFunc]);
2097
						}
2098
					}
2099
				}
2100
			}
2101
		}
2102
	}
2103
2104
	$sort_types = array(
2105
		'hook_name' => array('hook', SORT_ASC),
2106
		'hook_name DESC' => array('hook', SORT_DESC),
2107
		'function_name' => array('function', SORT_ASC),
2108
		'function_name DESC' => array('function', SORT_DESC),
2109
		'file_name' => array('file_name', SORT_ASC),
2110
		'file_name DESC' => array('file_name', SORT_DESC),
2111
		'status' => array('status', SORT_ASC),
2112
		'status DESC' => array('status', SORT_DESC),
2113
	);
2114
2115
	$sort_options = $sort_types[$sort];
2116
	$sort = array();
2117
	$hooks_filters = array();
2118
2119
	foreach ($hooks as $hook => $functions)
2120
		$hooks_filters[] = '<option' . ($context['current_filter'] == $hook ? ' selected ' : '') . ' value="' . $hook . '">' . $hook . '</option>';
2121
2122
	if (!empty($hooks_filters))
2123
		$context['insert_after_template'] .= '
2124
		<script>
2125
			var hook_name_header = document.getElementById(\'header_list_integration_hooks_hook_name\');
2126
			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>') . ';
2127
		</script>';
2128
2129
	$temp_data = array();
2130
	$id = 0;
2131
2132
	foreach ($hooks as $hook => $functions)
2133
	{
2134
		if (empty($context['filter']) || (!empty($context['filter']) && $context['filter'] == $hook))
2135
		{
2136
			foreach ($functions as $rawFunc)
2137
			{
2138
				// Get the hook info.
2139
				$hookParsedData = get_hook_info_from_raw($rawFunc);
2140
2141
				$hook_exists = !empty($hook_status[$hook][$hookParsedData['class']][$hookParsedData['pureFunc']]['exists']);
2142
				$sort[] = $sort_options[0];
2143
2144
				$temp_data[] = array(
2145
					'id' => 'hookid_' . $id++,
2146
					'hook_name' => $hook,
2147
					'function_name' => $hookParsedData['rawData'],
2148
					'real_function' => $hookParsedData['pureFunc'],
2149
					'included_file' => !empty($hookParsedData['absPath']) ? $hookParsedData['absPath'] : '',
2150
					'file_name' => (isset($hook_status[$hook][$hookParsedData['class']][$hookParsedData['pureFunc']]['in_file']) ? $hook_status[$hook][$hookParsedData['class']][$hookParsedData['pureFunc']]['in_file'] : (!empty($hookParsedData['hookFile']) ? $hookParsedData['hookFile'] : '')),
2151
					'instance' => $hookParsedData['object'],
2152
					'hook_exists' => $hook_exists,
2153
					'status' => $hook_exists ? ($hookParsedData['enabled'] ? 'allow' : 'moderate') : 'deny',
2154
					'img_text' => $txt['hooks_' . ($hook_exists ? ($hookParsedData['enabled'] ? 'active' : 'disabled') : 'missing')],
2155
					'enabled' => $hookParsedData['enabled'],
2156
					'can_be_disabled' => !isset($hook_status[$hook][$hookParsedData['class']][$hookParsedData['pureFunc']]['enabled']),
2157
				);
2158
			}
2159
		}
2160
	}
2161
2162
	array_multisort($sort, $sort_options[1], $temp_data);
2163
2164
	$counter = 0;
2165
	$start++;
2166
2167
	foreach ($temp_data as $data)
2168
	{
2169
		if (++$counter < $start)
2170
			continue;
2171
		elseif ($counter == $start + $per_page)
2172
			break;
2173
2174
		$hooks_data[] = $data;
2175
	}
2176
2177
	return $hooks_data;
2178
}
2179
2180
/**
2181
 * Simply returns the total count of integration hooks
2182
 * Used by the integration hooks list function (list_integration_hooks)
2183
 *
2184
 * @return int The number of hooks currently in use
2185
 */
2186
function get_integration_hooks_count()
2187
{
2188
	global $context;
2189
2190
	$hooks = get_integration_hooks();
2191
	$hooks_count = 0;
2192
2193
	$context['filter'] = false;
2194
	if (isset($_GET['filter']))
2195
		$context['filter'] = $_GET['filter'];
2196
2197
	foreach ($hooks as $hook => $functions)
2198
	{
2199
		if (empty($context['filter']) || (!empty($context['filter']) && $context['filter'] == $hook))
2200
			$hooks_count += count($functions);
2201
	}
2202
2203
	return $hooks_count;
2204
}
2205
2206
/**
2207
 * Parses modSettings to create integration hook array
2208
 *
2209
 * @return array An array of information about the integration hooks
2210
 */
2211
function get_integration_hooks()
2212
{
2213
	global $modSettings;
2214
	static $integration_hooks;
2215
2216
	if (!isset($integration_hooks))
2217
	{
2218
		$integration_hooks = array();
2219
		foreach ($modSettings as $key => $value)
2220
		{
2221
			if (!empty($value) && substr($key, 0, 10) === 'integrate_')
2222
				$integration_hooks[$key] = explode(',', $value);
2223
		}
2224
	}
2225
2226
	return $integration_hooks;
2227
}
2228
2229
/**
2230
 * Parses each hook data and returns an array.
2231
 *
2232
 * @param string $rawData A string as it was saved to the DB.
2233
 * @return array everything found in the string itself
2234
 */
2235
function get_hook_info_from_raw($rawData)
2236
{
2237
	global $boarddir, $settings, $sourcedir;
2238
2239
	// A single string can hold tons of info!
2240
	$hookData = array(
2241
		'object' => false,
2242
		'enabled' => true,
2243
		'fileExists' => false,
2244
		'absPath' => '',
2245
		'hookFile' => '',
2246
		'pureFunc' => '',
2247
		'method' => '',
2248
		'class' => '',
2249
		'rawData' => $rawData,
2250
	);
2251
2252
	// Meh...
2253
	if (empty($rawData))
2254
		return $hookData;
2255
2256
	// For convenience purposes only!
2257
	$modFunc = $rawData;
2258
2259
	// Any files?
2260
	if (strpos($modFunc, '|') !== false)
2261
	{
2262
		list ($hookData['hookFile'], $modFunc) = explode('|', $modFunc);
2263
2264
		// Does the file exists? who knows!
2265
		if (empty($settings['theme_dir']))
2266
			$hookData['absPath'] = strtr(trim($hookData['hookFile']), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir));
2267
2268
		else
2269
			$hookData['absPath'] = strtr(trim($hookData['hookFile']), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir, '$themedir' => $settings['theme_dir']));
2270
2271
		$hookData['fileExists'] = file_exists($hookData['absPath']);
2272
		$hookData['hookFile'] = basename($hookData['hookFile']);
2273
	}
2274
2275
	// Hook is an instance.
2276
	if (strpos($modFunc, '#') !== false)
2277
	{
2278
		$modFunc = str_replace('#', '', $modFunc);
2279
		$hookData['object'] = true;
2280
	}
2281
2282
	// Hook is "disabled"
2283
	if (strpos($modFunc, '!') !== false)
2284
	{
2285
		$modFunc = str_replace('!', '', $modFunc);
2286
		$hookData['enabled'] = false;
2287
	}
2288
2289
	// Handling methods?
2290
	if (strpos($modFunc, '::') !== false)
2291
	{
2292
		list ($hookData['class'], $hookData['method']) = explode('::', $modFunc);
2293
		$hookData['pureFunc'] = $hookData['method'];
2294
	}
2295
2296
	else
2297
		$hookData['pureFunc'] = $modFunc;
2298
2299
	return $hookData;
2300
}
2301
2302
?>