Issues (1061)

Sources/MessageIndex.php (6 issues)

1
<?php
2
3
/**
4
 * This file is what shows the listing of topics in a board.
5
 * It's just one or two functions, but don't under estimate it ;).
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines https://www.simplemachines.org
11
 * @copyright 2020 Simple Machines and individual contributors
12
 * @license https://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 RC2
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * Show the list of topics in this board, along with any child boards.
22
 */
23
function MessageIndex()
24
{
25
	global $txt, $scripturl, $board, $modSettings, $context;
26
	global $options, $settings, $board_info, $user_info, $smcFunc, $sourcedir;
27
28
	// If this is a redirection board head off.
29
	if ($board_info['redirect'])
30
	{
31
		$smcFunc['db_query']('', '
32
			UPDATE {db_prefix}boards
33
			SET num_posts = num_posts + 1
34
			WHERE id_board = {int:current_board}',
35
			array(
36
				'current_board' => $board,
37
			)
38
		);
39
40
		redirectexit($board_info['redirect']);
41
	}
42
43
	loadTemplate('MessageIndex');
44
45
	if (!$user_info['is_guest'])
46
	{
47
		// We can't know they read it if we allow prefetches.
48
		// But we'll actually mark it read later after we've done everything else.
49
		if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
50
		{
51
			ob_end_clean();
52
			send_http_status(403, 'Prefetch Forbidden');
53
			die;
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
54
		}
55
	}
56
57
	$context['name'] = $board_info['name'];
58
	$context['description'] = $board_info['description'];
59
	if (!empty($board_info['description']))
60
		$context['meta_description'] = strip_tags($board_info['description']);
61
62
	// How many topics do we have in total?
63
	$board_info['total_topics'] = allowedTo('approve_posts') ? $board_info['num_topics'] + $board_info['unapproved_topics'] : $board_info['num_topics'] + $board_info['unapproved_user_topics'];
64
65
	// View all the topics, or just a few?
66
	$context['topics_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['topics_per_page']) ? $options['topics_per_page'] : $modSettings['defaultMaxTopics'];
67
	$context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
68
	$context['maxindex'] = isset($_REQUEST['all']) && !empty($modSettings['enableAllMessages']) ? $board_info['total_topics'] : $context['topics_per_page'];
69
70
	// Right, let's only index normal stuff!
71
	if (count($_GET) > 1)
72
	{
73
		$session_name = session_name();
74
		foreach ($_GET as $k => $v)
75
		{
76
			if (!in_array($k, array('board', 'start', $session_name)))
77
				$context['robot_no_index'] = true;
78
		}
79
	}
80
	if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0))
81
		$context['robot_no_index'] = true;
82
83
	// If we can view unapproved messages and there are some build up a list.
84
	if (allowedTo('approve_posts') && ($board_info['unapproved_topics'] || $board_info['unapproved_posts']))
85
	{
86
		$untopics = $board_info['unapproved_topics'] ? '<a href="' . $scripturl . '?action=moderate;area=postmod;sa=topics;brd=' . $board . '">' . $board_info['unapproved_topics'] . '</a>' : 0;
87
		$unposts = $board_info['unapproved_posts'] ? '<a href="' . $scripturl . '?action=moderate;area=postmod;sa=posts;brd=' . $board . '">' . ($board_info['unapproved_posts'] - $board_info['unapproved_topics']) . '</a>' : 0;
88
		$context['unapproved_posts_message'] = sprintf($txt['there_are_unapproved_topics'], $untopics, $unposts, $scripturl . '?action=moderate;area=postmod;sa=' . ($board_info['unapproved_topics'] ? 'topics' : 'posts') . ';brd=' . $board);
89
	}
90
91
	// Default sort methods.
92
	$sort_methods = array(
93
		'subject' => 'mf.subject',
94
		'starter' => 'COALESCE(memf.real_name, mf.poster_name)',
95
		'last_poster' => 'COALESCE(meml.real_name, ml.poster_name)',
96
		'replies' => 't.num_replies',
97
		'views' => 't.num_views',
98
		'first_post' => 't.id_topic',
99
		'last_post' => 't.id_last_msg'
100
	);
101
102
	// Default sort methods tables.
103
	$sort_methods_table = array(
104
		'subject' => 'JOIN {db_prefix}messages mf ON (mf.id_msg = t.id_first_msg)',
105
		'starter' => 'JOIN {db_prefix}messages mf ON (mf.id_msg = t.id_first_msg)
106
			LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = mf.id_member)',
107
		'last_poster' => 'JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
108
			LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)',
109
		'replies' => '',
110
		'views' => '',
111
		'first_post' => '',
112
		'last_post' => ''
113
	);
114
115
	// Bring in any changes we want to make before the query.
116
	call_integration_hook('integrate_pre_messageindex', array(&$sort_methods, &$sort_methods_table));
117
118
	// We only know these.
119
	if (isset($_REQUEST['sort']) && !in_array($_REQUEST['sort'], array_keys($sort_methods)))
120
		$_REQUEST['sort'] = 'last_post';
121
122
	// Make sure the starting place makes sense and construct the page index.
123
	if (isset($_REQUEST['sort']))
124
		$context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d;sort=' . $_REQUEST['sort'] . (isset($_REQUEST['desc']) ? ';desc' : ''), $_REQUEST['start'], $board_info['total_topics'], $context['maxindex'], true);
125
	else
126
		$context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d', $_REQUEST['start'], $board_info['total_topics'], $context['maxindex'], true);
127
	$context['start'] = &$_REQUEST['start'];
128
129
	// Set a canonical URL for this page.
130
	$context['canonical_url'] = $scripturl . '?board=' . $board . '.' . $context['start'];
131
132
	$can_show_all = !empty($modSettings['enableAllMessages']) && $context['maxindex'] > $modSettings['enableAllMessages'];
133
134
	if (!($can_show_all && isset($_REQUEST['all'])))
135
	{
136
		$context['links'] = array(
137
			'first' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?board=' . $board . '.0' : '',
138
			'prev' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?board=' . $board . '.' . ($_REQUEST['start'] - $context['topics_per_page']) : '',
139
			'next' => $_REQUEST['start'] + $context['topics_per_page'] < $board_info['total_topics'] ? $scripturl . '?board=' . $board . '.' . ($_REQUEST['start'] + $context['topics_per_page']) : '',
140
			'last' => $_REQUEST['start'] + $context['topics_per_page'] < $board_info['total_topics'] ? $scripturl . '?board=' . $board . '.' . (floor(($board_info['total_topics'] - 1) / $context['topics_per_page']) * $context['topics_per_page']) : '',
141
			'up' => $board_info['parent'] == 0 ? $scripturl . '?' : $scripturl . '?board=' . $board_info['parent'] . '.0'
142
		);
143
	}
144
145
	$context['page_info'] = array(
146
		'current_page' => $_REQUEST['start'] / $context['topics_per_page'] + 1,
147
		'num_pages' => floor(($board_info['total_topics'] - 1) / $context['topics_per_page']) + 1
148
	);
149
150
	if (isset($_REQUEST['all']) && $can_show_all)
151
	{
152
		$context['maxindex'] = $modSettings['enableAllMessages'];
153
		$_REQUEST['start'] = 0;
154
	}
155
156
	// Build a list of the board's moderators.
157
	$context['moderators'] = &$board_info['moderators'];
158
	$context['moderator_groups'] = &$board_info['moderator_groups'];
159
	$context['link_moderators'] = array();
160
	if (!empty($board_info['moderators']))
161
	{
162
		foreach ($board_info['moderators'] as $mod)
163
			$context['link_moderators'][] = '<a href="' . $scripturl . '?action=profile;u=' . $mod['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod['name'] . '</a>';
164
	}
165
	if (!empty($board_info['moderator_groups']))
166
	{
167
		// By default just tack the moderator groups onto the end of the members
168
		foreach ($board_info['moderator_groups'] as $mod_group)
169
			$context['link_moderators'][] = '<a href="' . $scripturl . '?action=groups;sa=members;group=' . $mod_group['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod_group['name'] . '</a>';
170
	}
171
172
	// Now we tack the info onto the end of the linktree
173
	if (!empty($context['link_moderators']))
174
	{
175
		$context['linktree'][count($context['linktree']) - 1]['extra_after'] = '<span class="board_moderators">(' . (count($context['link_moderators']) == 1 ? $txt['moderator'] : $txt['moderators']) . ': ' . implode(', ', $context['link_moderators']) . ')</span>';
176
	}
177
178
	// 'Print' the header and board info.
179
	$context['page_title'] = strip_tags($board_info['name']);
180
181
	// Set the variables up for the template.
182
	$context['can_mark_notify'] = !$user_info['is_guest'];
183
	$context['can_post_new'] = allowedTo('post_new') || ($modSettings['postmod_active'] && allowedTo('post_unapproved_topics'));
184
	$context['can_post_poll'] = $modSettings['pollMode'] == '1' && allowedTo('poll_post') && $context['can_post_new'];
185
	$context['can_moderate_forum'] = allowedTo('moderate_forum');
186
	$context['can_approve_posts'] = allowedTo('approve_posts');
187
188
	require_once($sourcedir . '/Subs-BoardIndex.php');
189
	$boardIndexOptions = array(
190
		'include_categories' => false,
191
		'base_level' => $board_info['child_level'] + 1,
192
		'parent_id' => $board_info['id'],
193
		'set_latest_post' => false,
194
		'countChildPosts' => !empty($modSettings['countChildPosts']),
195
	);
196
	$context['boards'] = getBoardIndex($boardIndexOptions);
197
198
	// Nosey, nosey - who's viewing this topic?
199
	if (!empty($settings['display_who_viewing']))
200
	{
201
		$context['view_members'] = array();
202
		$context['view_members_list'] = array();
203
		$context['view_num_hidden'] = 0;
204
205
		$request = $smcFunc['db_query']('', '
206
			SELECT
207
				lo.id_member, lo.log_time, mem.real_name, mem.member_name, mem.show_online,
208
				mg.online_color, mg.id_group, mg.group_name
209
			FROM {db_prefix}log_online AS lo
210
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lo.id_member)
211
				LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:reg_member_group} THEN mem.id_post_group ELSE mem.id_group END)
212
			WHERE INSTR(lo.url, {string:in_url_string}) > 0 OR lo.session = {string:session}',
213
			array(
214
				'reg_member_group' => 0,
215
				'in_url_string' => '"board":' . $board,
216
				'session' => $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id(),
217
			)
218
		);
219
		while ($row = $smcFunc['db_fetch_assoc']($request))
220
		{
221
			if (empty($row['id_member']))
222
				continue;
223
224
			if (!empty($row['online_color']))
225
				$link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" style="color: ' . $row['online_color'] . ';">' . $row['real_name'] . '</a>';
226
			else
227
				$link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>';
228
229
			$is_buddy = in_array($row['id_member'], $user_info['buddies']);
230
			if ($is_buddy)
231
				$link = '<strong>' . $link . '</strong>';
232
233
			if (!empty($row['show_online']) || allowedTo('moderate_forum'))
234
				$context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '<em>' . $link . '</em>' : $link;
235
			// @todo why are we filling this array of data that are just counted (twice) and discarded? ???
236
			$context['view_members'][$row['log_time'] . $row['member_name']] = array(
237
				'id' => $row['id_member'],
238
				'username' => $row['member_name'],
239
				'name' => $row['real_name'],
240
				'group' => $row['id_group'],
241
				'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
242
				'link' => $link,
243
				'is_buddy' => $is_buddy,
244
				'hidden' => empty($row['show_online']),
245
			);
246
247
			if (empty($row['show_online']))
248
				$context['view_num_hidden']++;
249
		}
250
		$context['view_num_guests'] = $smcFunc['db_num_rows']($request) - count($context['view_members']);
251
		$smcFunc['db_free_result']($request);
252
253
		// Put them in "last clicked" order.
254
		krsort($context['view_members_list']);
255
		krsort($context['view_members']);
256
	}
257
258
	// They didn't pick one, default to by last post descending.
259
	if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']]))
260
	{
261
		$context['sort_by'] = 'last_post';
262
		$_REQUEST['sort'] = 'id_last_msg';
263
		$ascending = isset($_REQUEST['asc']);
264
	}
265
	// Otherwise default to ascending.
266
	else
267
	{
268
		$context['sort_by'] = $_REQUEST['sort'];
269
		$_REQUEST['sort'] = $sort_methods[$_REQUEST['sort']];
270
		$ascending = !isset($_REQUEST['desc']);
271
	}
272
273
	$context['sort_direction'] = $ascending ? 'up' : 'down';
274
	$txt['starter'] = $txt['started_by'];
275
276
	foreach ($sort_methods as $key => $val)
277
		$context['topics_headers'][$key] = '<a href="' . $scripturl . '?board=' . $context['current_board'] . '.' . $context['start'] . ';sort=' . $key . ($context['sort_by'] == $key && $context['sort_direction'] == 'up' ? ';desc' : '') . '">' . $txt[$key] . ($context['sort_by'] == $key ? '<span class="main_icons sort_' . $context['sort_direction'] . '"></span>' : '') . '</a>';
278
279
	// Calculate the fastest way to get the topics.
280
	$start = (int) $_REQUEST['start'];
281
	if ($start > ($board_info['total_topics'] - 1) / 2)
282
	{
283
		$ascending = !$ascending;
284
		$fake_ascending = true;
285
		$context['maxindex'] = $board_info['total_topics'] < $start + $context['maxindex'] + 1 ? $board_info['total_topics'] - $start : $context['maxindex'];
286
		$start = $board_info['total_topics'] < $start + $context['maxindex'] + 1 ? 0 : $board_info['total_topics'] - $start - $context['maxindex'];
287
	}
288
	else
289
		$fake_ascending = false;
290
291
	// Setup the default topic icons...
292
	$context['icon_sources'] = array();
293
	foreach ($context['stable_icons'] as $icon)
294
		$context['icon_sources'][$icon] = 'images_url';
295
296
	$topic_ids = array();
297
	$context['topics'] = array();
298
299
	// Grab the appropriate topic information...
300
	// For search engine effectiveness we'll link guests differently.
301
	$context['pageindex_multiplier'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
302
303
	$message_index_parameters = array(
304
		'current_board' => $board,
305
		'current_member' => $user_info['id'],
306
		'topic_list' => $topic_ids,
307
		'is_approved' => 1,
308
		'find_set_topics' => implode(',', $topic_ids),
309
		'start' => $start,
310
		'maxindex' => $context['maxindex'],
311
	);
312
313
	$message_index_selects = array();
314
	$message_index_tables = array();
315
	$message_index_wheres = array();
316
	$message_index_topic_wheres = array();
317
318
	call_integration_hook('integrate_message_index', array(&$message_index_selects, &$message_index_tables, &$message_index_parameters, &$message_index_wheres, &$topic_ids, &$message_index_topic_wheres));
319
320
	if (!empty($modSettings['enableParticipation']) && !$user_info['is_guest'])
321
		$enableParticipation = true;
322
	else
323
		$enableParticipation = false;
324
325
	$sort_table = '
326
		SELECT t.id_topic, t.id_first_msg, t.id_last_msg' . (!empty($message_index_selects) ? (', ' . implode(', ', $message_index_selects)) : '') . '
327
		FROM {db_prefix}topics t
328
		' . (empty($sort_methods_table[$context['sort_by']]) ? '' : $sort_methods_table[$context['sort_by']]) . '
329
		' . (!empty($message_index_tables) ? implode("\n\t\t\t\t", $message_index_tables) : '') . '
330
		WHERE t.id_board = {int:current_board} '
331
			. (!$modSettings['postmod_active'] || $context['can_approve_posts'] ? '' : '
332
			AND (t.approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR t.id_member_started = {int:current_member}') . ')') . (!empty($message_index_topic_wheres) ? ' 
333
			AND ' . implode("\n\t\t\t\tAND ", $message_index_topic_wheres) : ''). '
334
		ORDER BY is_sticky' . ($fake_ascending ? '' : ' DESC') . ', ' . $_REQUEST['sort'] . ($ascending ? '' : ' DESC') . '
335
		LIMIT {int:maxindex}
336
			OFFSET {int:start} ';
337
338
	$result = $smcFunc['db_query']('substring', '
339
		SELECT
340
			t.id_topic, t.num_replies, t.locked, t.num_views, t.is_sticky, t.id_poll, t.id_previous_board,
341
			' . ($user_info['is_guest'] ? '0' : 'COALESCE(lt.id_msg, COALESCE(lmr.id_msg, -1)) + 1') . ' AS new_from,
342
			' . ($enableParticipation ? ' COALESCE(( SELECT 1 FROM {db_prefix}messages AS parti WHERE t.id_topic = parti.id_topic and parti.id_member = {int:current_member} LIMIT 1) , 0) as is_posted_in,
343
			' : '') . '
344
			t.id_last_msg, t.approved, t.unapproved_posts, ml.poster_time AS last_poster_time, t.id_redirect_topic,
345
			ml.id_msg_modified, ml.subject AS last_subject, ml.icon AS last_icon,
346
			ml.poster_name AS last_member_name, ml.id_member AS last_id_member,' . (!empty($settings['avatars_on_indexes']) ? ' meml.avatar, meml.email_address, memf.avatar AS first_member_avatar, memf.email_address AS first_member_mail, COALESCE(af.id_attach, 0) AS first_member_id_attach, af.filename AS first_member_filename, af.attachment_type AS first_member_attach_type, COALESCE(al.id_attach, 0) AS last_member_id_attach, al.filename AS last_member_filename, al.attachment_type AS last_member_attach_type,' : '') . '
347
			COALESCE(meml.real_name, ml.poster_name) AS last_display_name, t.id_first_msg,
348
			mf.poster_time AS first_poster_time, mf.subject AS first_subject, mf.icon AS first_icon,
349
			mf.poster_name AS first_member_name, mf.id_member AS first_id_member,
350
			COALESCE(memf.real_name, mf.poster_name) AS first_display_name, ' . (!empty($modSettings['preview_characters']) ? '
351
			SUBSTRING(ml.body, 1, ' . ($modSettings['preview_characters'] + 256) . ') AS last_body,
352
			SUBSTRING(mf.body, 1, ' . ($modSettings['preview_characters'] + 256) . ') AS first_body,' : '') . 'ml.smileys_enabled AS last_smileys, mf.smileys_enabled AS first_smileys
353
			' . (!empty($message_index_selects) ? (', ' . implode(', ', $message_index_selects)) : '') . '
354
		FROM (' . $sort_table . ') as st
355
			JOIN {db_prefix}topics AS t ON (st.id_topic = t.id_topic)
356
			JOIN {db_prefix}messages AS ml ON (ml.id_msg = st.id_last_msg)
357
			JOIN {db_prefix}messages AS mf ON (mf.id_msg = st.id_first_msg)
358
			LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)
359
			LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = mf.id_member)' . (!empty($settings['avatars_on_indexes']) ? '
360
			LEFT JOIN {db_prefix}attachments AS af ON (af.id_member = memf.id_member)
361
			LEFT JOIN {db_prefix}attachments AS al ON (al.id_member = meml.id_member)' : '') . '' . ($user_info['is_guest'] ? '' : '
362
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
363
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})') . '
364
			' . (!empty($message_index_tables) ? implode("\n\t\t\t\t", $message_index_tables) : '') . '
365
			' . (!empty($message_index_wheres) ? ' WHERE ' . implode("\n\t\t\t\tAND ", $message_index_wheres) : '') . '
366
		ORDER BY is_sticky' . ($fake_ascending ? '' : ' DESC') . ', ' . $_REQUEST['sort'] . ($ascending ? '' : ' DESC'),
367
		$message_index_parameters
368
	);
369
370
	// Begin 'printing' the message index for current board.
371
	while ($row = $smcFunc['db_fetch_assoc']($result))
372
	{
373
		if ($row['id_poll'] > 0 && $modSettings['pollMode'] == '0')
374
			continue;
375
376
		$topic_ids[] = $row['id_topic'];
377
378
		// Reference the main color class.
379
		$colorClass = 'windowbg';
380
381
		// Does the theme support message previews?
382
		if (!empty($modSettings['preview_characters']))
383
		{
384
			// Limit them to $modSettings['preview_characters'] characters
385
			$row['first_body'] = strip_tags(strtr(parse_bbc($row['first_body'], $row['first_smileys'], $row['id_first_msg']), array('<br>' => '&#10;')));
386
			if ($smcFunc['strlen']($row['first_body']) > $modSettings['preview_characters'])
387
				$row['first_body'] = $smcFunc['substr']($row['first_body'], 0, $modSettings['preview_characters']) . '...';
388
389
			// Censor the subject and message preview.
390
			censorText($row['first_subject']);
391
			censorText($row['first_body']);
392
393
			// Don't censor them twice!
394
			if ($row['id_first_msg'] == $row['id_last_msg'])
395
			{
396
				$row['last_subject'] = $row['first_subject'];
397
				$row['last_body'] = $row['first_body'];
398
			}
399
			else
400
			{
401
				$row['last_body'] = strip_tags(strtr(parse_bbc($row['last_body'], $row['last_smileys'], $row['id_last_msg']), array('<br>' => '&#10;')));
402
				if ($smcFunc['strlen']($row['last_body']) > $modSettings['preview_characters'])
403
					$row['last_body'] = $smcFunc['substr']($row['last_body'], 0, $modSettings['preview_characters']) . '...';
404
405
				censorText($row['last_subject']);
406
				censorText($row['last_body']);
407
			}
408
		}
409
		else
410
		{
411
			$row['first_body'] = '';
412
			$row['last_body'] = '';
413
			censorText($row['first_subject']);
414
415
			if ($row['id_first_msg'] == $row['id_last_msg'])
416
				$row['last_subject'] = $row['first_subject'];
417
			else
418
				censorText($row['last_subject']);
419
		}
420
421
		// Decide how many pages the topic should have.
422
		if ($row['num_replies'] + 1 > $context['messages_per_page'])
423
		{
424
			// We can't pass start by reference.
425
			$start = -1;
426
			$pages = constructPageIndex($scripturl . '?topic=' . $row['id_topic'] . '.%1$d', $start, $row['num_replies'] + 1, $context['messages_per_page'], true, false);
427
428
			// If we can use all, show all.
429
			if (!empty($modSettings['enableAllMessages']) && $row['num_replies'] + 1 < $modSettings['enableAllMessages'])
430
				$pages .= ' &nbsp;<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0;all">' . $txt['all'] . '</a>';
431
		}
432
		else
433
			$pages = '';
434
435
		// We need to check the topic icons exist...
436
		if (!empty($modSettings['messageIconChecks_enable']))
437
		{
438
			if (!isset($context['icon_sources'][$row['first_icon']]))
439
				$context['icon_sources'][$row['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
440
			if (!isset($context['icon_sources'][$row['last_icon']]))
441
				$context['icon_sources'][$row['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
442
		}
443
		else
444
		{
445
			if (!isset($context['icon_sources'][$row['first_icon']]))
446
				$context['icon_sources'][$row['first_icon']] = 'images_url';
447
			if (!isset($context['icon_sources'][$row['last_icon']]))
448
				$context['icon_sources'][$row['last_icon']] = 'images_url';
449
		}
450
451
		if (!empty($board_info['recycle']))
452
			$row['first_icon'] = 'recycled';
453
454
		// Is this topic pending approval, or does it have any posts pending approval?
455
		if ($context['can_approve_posts'] && $row['unapproved_posts'])
456
			$colorClass .= (!$row['approved'] ? ' approvetopic' : ' approvepost');
457
458
		// Sticky topics should get a different color, too.
459
		if ($row['is_sticky'])
460
			$colorClass .= ' sticky';
461
462
		// Locked topics get special treatment as well.
463
		if ($row['locked'])
464
			$colorClass .= ' locked';
465
466
		// 'Print' the topic info.
467
		$context['topics'][$row['id_topic']] = array_merge($row, array(
468
			'id' => $row['id_topic'],
469
			'first_post' => array(
470
				'id' => $row['id_first_msg'],
471
				'member' => array(
472
					'username' => $row['first_member_name'],
473
					'name' => $row['first_display_name'],
474
					'id' => $row['first_id_member'],
475
					'href' => !empty($row['first_id_member']) ? $scripturl . '?action=profile;u=' . $row['first_id_member'] : '',
476
					'link' => !empty($row['first_id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['first_id_member'] . '" title="' . $txt['profile_of'] . ' ' . $row['first_display_name'] . '" class="preview">' . $row['first_display_name'] . '</a>' : $row['first_display_name']
477
				),
478
				'time' => timeformat($row['first_poster_time']),
479
				'timestamp' => forum_time(true, $row['first_poster_time']),
480
				'subject' => $row['first_subject'],
481
				'preview' => $row['first_body'],
482
				'icon' => $row['first_icon'],
483
				'icon_url' => $settings[$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png',
484
				'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
485
				'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['first_subject'] . '</a>',
486
			),
487
			'last_post' => array(
488
				'id' => $row['id_last_msg'],
489
				'member' => array(
490
					'username' => $row['last_member_name'],
491
					'name' => $row['last_display_name'],
492
					'id' => $row['last_id_member'],
493
					'href' => !empty($row['last_id_member']) ? $scripturl . '?action=profile;u=' . $row['last_id_member'] : '',
494
					'link' => !empty($row['last_id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['last_id_member'] . '">' . $row['last_display_name'] . '</a>' : $row['last_display_name']
495
				),
496
				'time' => timeformat($row['last_poster_time']),
497
				'timestamp' => forum_time(true, $row['last_poster_time']),
498
				'subject' => $row['last_subject'],
499
				'preview' => $row['last_body'],
500
				'icon' => $row['last_icon'],
501
				'icon_url' => $settings[$context['icon_sources'][$row['last_icon']]] . '/post/' . $row['last_icon'] . '.png',
502
				'href' => $scripturl . '?topic=' . $row['id_topic'] . ($user_info['is_guest'] ? ('.' . (!empty($options['view_newest_first']) ? 0 : ((int) (($row['num_replies']) / $context['pageindex_multiplier'])) * $context['pageindex_multiplier']) . '#msg' . $row['id_last_msg']) : (($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . '#new')),
503
				'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . ($user_info['is_guest'] ? ('.' . (!empty($options['view_newest_first']) ? 0 : ((int) (($row['num_replies']) / $context['pageindex_multiplier'])) * $context['pageindex_multiplier']) . '#msg' . $row['id_last_msg']) : (($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . '#new')) . '" ' . ($row['num_replies'] == 0 ? '' : 'rel="nofollow"') . '>' . $row['last_subject'] . '</a>'
504
			),
505
			'is_sticky' => !empty($row['is_sticky']),
506
			'is_locked' => !empty($row['locked']),
507
			'is_redirect' => !empty($row['id_redirect_topic']),
508
			'is_poll' => $modSettings['pollMode'] == '1' && $row['id_poll'] > 0,
509
			'is_posted_in' => ($enableParticipation ? $row['is_posted_in'] : false),
510
			'is_watched' => false,
511
			'icon' => $row['first_icon'],
512
			'icon_url' => $settings[$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png',
513
			'subject' => $row['first_subject'],
514
			'new' => $row['new_from'] <= $row['id_msg_modified'],
515
			'new_from' => $row['new_from'],
516
			'newtime' => $row['new_from'],
517
			'new_href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['new_from'] . '#new',
518
			'pages' => $pages,
519
			'replies' => comma_format($row['num_replies']),
520
			'views' => comma_format($row['num_views']),
521
			'approved' => $row['approved'],
522
			'unapproved_posts' => $row['unapproved_posts'],
523
			'css_class' => $colorClass,
524
		));
525
		if (!empty($settings['avatars_on_indexes']))
526
		{
527
			// Last post member avatar
528
			$context['topics'][$row['id_topic']]['last_post']['member']['avatar'] = set_avatar_data(array(
529
				'avatar' => $row['avatar'],
530
				'email' => $row['email_address'],
531
				'filename' => !empty($row['last_member_filename']) ? $row['last_member_filename'] : '',
532
			));
533
534
			// First post member avatar
535
			$context['topics'][$row['id_topic']]['first_post']['member']['avatar'] = set_avatar_data(array(
536
				'avatar' => $row['first_member_avatar'],
537
				'email' => $row['first_member_mail'],
538
				'filename' => !empty($row['first_member_filename']) ? $row['first_member_filename'] : '',
539
			));
540
		}
541
	}
542
	$smcFunc['db_free_result']($result);
543
544
	// Fix the sequence of topics if they were retrieved in the wrong order. (for speed reasons...)
545
	if ($fake_ascending)
546
		$context['topics'] = array_reverse($context['topics'], true);
547
548
	$context['jump_to'] = array(
549
		'label' => addslashes(un_htmlspecialchars($txt['jump_to'])),
550
		'board_name' => $smcFunc['htmlspecialchars'](strtr(strip_tags($board_info['name']), array('&amp;' => '&'))),
551
		'child_level' => $board_info['child_level'],
552
	);
553
554
	// Is Quick Moderation active/needed?
555
	if (!empty($options['display_quick_mod']) && !empty($context['topics']))
556
	{
557
		$context['can_markread'] = $context['user']['is_logged'];
558
		$context['can_lock'] = allowedTo('lock_any');
559
		$context['can_sticky'] = allowedTo('make_sticky');
560
		$context['can_move'] = allowedTo('move_any');
561
		$context['can_remove'] = allowedTo('remove_any');
562
		$context['can_merge'] = allowedTo('merge_any');
563
		// Ignore approving own topics as it's unlikely to come up...
564
		$context['can_approve'] = $modSettings['postmod_active'] && allowedTo('approve_posts') && !empty($board_info['unapproved_topics']);
565
		// Can we restore topics?
566
		$context['can_restore'] = allowedTo('move_any') && !empty($board_info['recycle']);
567
568
		if ($user_info['is_admin'] || $modSettings['topic_move_any'])
569
			$context['can_move_any'] = true;
570
		else
571
		{
572
			// We'll use this in a minute
573
			$boards_allowed = boardsAllowedTo('post_new');
574
575
			// How many boards can you do this on besides this one?
576
			$context['can_move_any'] = count($boards_allowed) > 1;
577
		}
578
579
		// Set permissions for all the topics.
580
		foreach ($context['topics'] as $t => $topic)
581
		{
582
			$started = $topic['first_post']['member']['id'] == $user_info['id'];
583
			$context['topics'][$t]['quick_mod'] = array(
584
				'lock' => allowedTo('lock_any') || ($started && allowedTo('lock_own')),
585
				'sticky' => allowedTo('make_sticky'),
586
				'move' => (allowedTo('move_any') || ($started && allowedTo('move_own')) && $context['can_move_any']),
587
				'modify' => allowedTo('modify_any') || ($started && allowedTo('modify_own')),
588
				'remove' => allowedTo('remove_any') || ($started && allowedTo('remove_own')),
589
				'approve' => $context['can_approve'] && $topic['unapproved_posts']
590
			);
591
			$context['can_lock'] |= ($started && allowedTo('lock_own'));
592
			$context['can_move'] |= ($started && allowedTo('move_own') && $context['can_move_any']);
593
			$context['can_remove'] |= ($started && allowedTo('remove_own'));
594
		}
595
596
		// Can we use quick moderation checkboxes?
597
		if ($options['display_quick_mod'] == 1)
598
			$context['can_quick_mod'] = $context['user']['is_logged'] || $context['can_approve'] || $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'] || $context['can_merge'] || $context['can_restore'];
599
		// Or the icons?
600
		else
601
			$context['can_quick_mod'] = $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'];
602
	}
603
604
	if (!empty($context['can_quick_mod']) && $options['display_quick_mod'] == 1)
605
	{
606
		$context['qmod_actions'] = array('approve', 'remove', 'lock', 'sticky', 'move', 'merge', 'restore', 'markread');
607
		call_integration_hook('integrate_quick_mod_actions');
608
	}
609
610
	// Mark current and parent boards as seen.
611
	if (!$user_info['is_guest'])
612
	{
613
		$smcFunc['db_insert']('replace',
614
			'{db_prefix}log_boards',
615
			array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
616
			array($modSettings['maxMsgID'], $user_info['id'], $board),
617
			array('id_member', 'id_board')
618
		);
619
620
		if (!empty($board_info['parent_boards']))
621
		{
622
			$smcFunc['db_query']('', '
623
				UPDATE {db_prefix}log_boards
624
				SET id_msg = {int:id_msg}
625
				WHERE id_member = {int:current_member}
626
					AND id_board IN ({array_int:board_list})',
627
				array(
628
					'current_member' => $user_info['id'],
629
					'board_list' => array_keys($board_info['parent_boards']),
630
					'id_msg' => $modSettings['maxMsgID'],
631
				)
632
			);
633
634
			// We've seen all these boards now!
635
			foreach ($board_info['parent_boards'] as $k => $dummy)
636
				if (isset($_SESSION['topicseen_cache'][$k]))
637
					unset($_SESSION['topicseen_cache'][$k]);
638
		}
639
640
		if (isset($_SESSION['topicseen_cache'][$board]))
641
			unset($_SESSION['topicseen_cache'][$board]);
642
643
		$request = $smcFunc['db_query']('', '
644
			SELECT id_topic, id_board, sent
645
			FROM {db_prefix}log_notify
646
			WHERE id_member = {int:current_member}
647
				AND (' . (!empty($context['topics']) ? 'id_topic IN ({array_int:topics}) OR ' : '') . 'id_board = {int:current_board})',
648
			array(
649
				'current_board' => $board,
650
				'topics' => !empty($context['topics']) ? array_keys($context['topics']) : array(),
651
				'current_member' => $user_info['id'],
652
			)
653
		);
654
		$context['is_marked_notify'] = false; // this is for the *board* only
655
		while ($row = $smcFunc['db_fetch_assoc']($request))
656
		{
657
			if (!empty($row['id_board']))
658
			{
659
				$context['is_marked_notify'] = true;
660
				$board_sent = $row['sent'];
661
			}
662
			if (!empty($row['id_topic']))
663
				$context['topics'][$row['id_topic']]['is_watched'] = true;
664
		}
665
		$smcFunc['db_free_result']($request);
666
667
		if ($context['is_marked_notify'] && !empty($board_sent))
668
		{
669
			$smcFunc['db_query']('', '
670
				UPDATE {db_prefix}log_notify
671
				SET sent = {int:is_sent}
672
				WHERE id_member = {int:current_member}
673
					AND id_board = {int:current_board}',
674
				array(
675
					'current_board' => $board,
676
					'current_member' => $user_info['id'],
677
					'is_sent' => 0,
678
				)
679
			);
680
		}
681
682
		require_once($sourcedir . '/Subs-Notify.php');
683
		$pref = getNotifyPrefs($user_info['id'], array('board_notify', 'board_notify_' . $board), true);
684
		$pref = !empty($pref[$user_info['id']]) ? $pref[$user_info['id']] : array();
685
		$pref = isset($pref['board_notify_' . $board]) ? $pref['board_notify_' . $board] : (!empty($pref['board_notify']) ? $pref['board_notify'] : 0);
686
		$context['board_notification_mode'] = !$context['is_marked_notify'] ? 1 : ($pref & 0x02 ? 3 : ($pref & 0x01 ? 2 : 1));
687
	}
688
	else
689
	{
690
		$context['is_marked_notify'] = false;
691
		$context['board_notification_mode'] = 1;
692
	}
693
694
	// If there are children, but no topics and no ability to post topics...
695
	$context['no_topic_listing'] = !empty($context['boards']) && empty($context['topics']) && !$context['can_post_new'];
696
697
	// Show a message in case a recently posted message became unapproved.
698
	$context['becomesUnapproved'] = !empty($_SESSION['becomesUnapproved']);
699
	unset($_SESSION['becomesUnapproved']);
700
701
	// Build the message index button array.
702
	$context['normal_buttons'] = array();
703
704
	if ($context['can_post_new'])
705
		$context['normal_buttons']['new_topic'] = array('text' => 'new_topic', 'image' => 'new_topic.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0', 'active' => true);
706
707
	if ($context['can_post_poll'])
708
		$context['normal_buttons']['post_poll'] = array('text' => 'new_poll', 'image' => 'new_poll.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0;poll');
709
710
	if ($context['user']['is_logged'])
711
		$context['normal_buttons']['markread'] = array('text' => 'mark_read_short', 'image' => 'markread.png', 'lang' => true, 'custom' => 'data-confirm="' . $txt['are_sure_mark_read'] . '"', 'class' => 'you_sure', 'url' => $scripturl . '?action=markasread;sa=board;board=' . $context['current_board'] . '.0;' . $context['session_var'] . '=' . $context['session_id']);
712
713
	if ($context['can_mark_notify'])
714
		$context['normal_buttons']['notify'] = array(
715
			'lang' => true,
716
			'text' => 'notify_board_' . $context['board_notification_mode'],
717
			'sub_buttons' => array(
718
				array(
719
					'text' => 'notify_board_1',
720
					'url' => $scripturl . '?action=notifyboard;board=' . $board . ';mode=1;' . $context['session_var'] . '=' . $context['session_id'],
721
				),
722
				array(
723
					'text' => 'notify_board_2',
724
					'url' => $scripturl . '?action=notifyboard;board=' . $board . ';mode=2;' . $context['session_var'] . '=' . $context['session_id'],
725
				),
726
				array(
727
					'text' => 'notify_board_3',
728
					'url' => $scripturl . '?action=notifyboard;board=' . $board . ';mode=3;' . $context['session_var'] . '=' . $context['session_id'],
729
				),
730
			),
731
		);
732
733
	// Javascript for inline editing.
734
	loadJavaScriptFile('topic.js', array('defer' => false, 'minimize' => true), 'smf_topic');
735
736
	// Allow adding new buttons easily.
737
	// Note: $context['normal_buttons'] is added for backward compatibility with 2.0, but is deprecated and should not be used
738
	call_integration_hook('integrate_messageindex_buttons', array(&$context['normal_buttons']));
739
}
740
741
/**
742
 * Handles moderation from the message index.
743
 *
744
 * @todo refactor this...
745
 */
746
function QuickModeration()
747
{
748
	global $sourcedir, $board, $user_info, $modSettings, $smcFunc, $context;
749
750
	// Check the session = get or post.
751
	checkSession('request');
752
753
	// Lets go straight to the restore area.
754
	if (isset($_REQUEST['qaction']) && $_REQUEST['qaction'] == 'restore' && !empty($_REQUEST['topics']))
755
		redirectexit('action=restoretopic;topics=' . implode(',', $_REQUEST['topics']) . ';' . $context['session_var'] . '=' . $context['session_id']);
756
757
	if (isset($_SESSION['topicseen_cache']))
758
		$_SESSION['topicseen_cache'] = array();
759
760
	// This is going to be needed to send off the notifications and for updateLastMessages().
761
	require_once($sourcedir . '/Subs-Post.php');
762
763
	// Remember the last board they moved things to.
764
	if (isset($_REQUEST['move_to']))
765
		$_SESSION['move_to_topic'] = $_REQUEST['move_to'];
766
767
	// Only a few possible actions.
768
	$possibleActions = array();
769
770
	if (!empty($board))
771
	{
772
		$boards_can = array(
773
			'make_sticky' => allowedTo('make_sticky') ? array($board) : array(),
774
			'move_any' => allowedTo('move_any') ? array($board) : array(),
775
			'move_own' => allowedTo('move_own') ? array($board) : array(),
776
			'remove_any' => allowedTo('remove_any') ? array($board) : array(),
777
			'remove_own' => allowedTo('remove_own') ? array($board) : array(),
778
			'lock_any' => allowedTo('lock_any') ? array($board) : array(),
779
			'lock_own' => allowedTo('lock_own') ? array($board) : array(),
780
			'merge_any' => allowedTo('merge_any') ? array($board) : array(),
781
			'approve_posts' => allowedTo('approve_posts') ? array($board) : array(),
782
		);
783
784
		$redirect_url = 'board=' . $board . '.' . $_REQUEST['start'];
785
	}
786
	else
787
	{
788
		$boards_can = boardsAllowedTo(array('make_sticky', 'move_any', 'move_own', 'remove_any', 'remove_own', 'lock_any', 'lock_own', 'merge_any', 'approve_posts'), true, false);
789
790
		$redirect_url = isset($_POST['redirect_url']) ? $_POST['redirect_url'] : (isset($_SESSION['old_url']) ? $_SESSION['old_url'] : '');
791
	}
792
793
	// Are we enforcing the "no moving topics to boards where you can't post new ones" rule?
794
	if (!$user_info['is_admin'] && !$modSettings['topic_move_any'])
795
	{
796
		// Don't count this board, if it's specified
797
		if (!empty($board))
798
		{
799
			$boards_can['post_new'] = array_diff(boardsAllowedTo('post_new'), array($board));
800
		}
801
		else
802
		{
803
			$boards_can['post_new'] = boardsAllowedTo('post_new');
804
		}
805
806
		if (empty($boards_can['post_new']))
807
		{
808
			$boards_can['move_any'] = $boards_can['move_own'] = array();
809
		}
810
	}
811
812
	if (!$user_info['is_guest'])
813
		$possibleActions[] = 'markread';
814
815
	if (!empty($boards_can['make_sticky']))
816
		$possibleActions[] = 'sticky';
817
818
	if (!empty($boards_can['move_any']) || !empty($boards_can['move_own']))
819
		$possibleActions[] = 'move';
820
821
	if (!empty($boards_can['remove_any']) || !empty($boards_can['remove_own']))
822
		$possibleActions[] = 'remove';
823
824
	if (!empty($boards_can['lock_any']) || !empty($boards_can['lock_own']))
825
		$possibleActions[] = 'lock';
826
827
	if (!empty($boards_can['merge_any']))
828
		$possibleActions[] = 'merge';
829
830
	if (!empty($boards_can['approve_posts']))
831
		$possibleActions[] = 'approve';
832
833
	// Two methods: $_REQUEST['actions'] (id_topic => action), and $_REQUEST['topics'] and $_REQUEST['qaction'].
834
	// (if action is 'move', $_REQUEST['move_to'] or $_REQUEST['move_tos'][$topic] is used.)
835
	if (!empty($_REQUEST['topics']))
836
	{
837
		// If the action isn't valid, just quit now.
838
		if (empty($_REQUEST['qaction']) || !in_array($_REQUEST['qaction'], $possibleActions))
839
			redirectexit($redirect_url);
840
841
		// Merge requires all topics as one parameter and can be done at once.
842
		if ($_REQUEST['qaction'] == 'merge')
843
		{
844
			// Merge requires at least two topics.
845
			if (empty($_REQUEST['topics']) || count($_REQUEST['topics']) < 2)
846
				redirectexit($redirect_url);
847
848
			require_once($sourcedir . '/SplitTopics.php');
849
			return MergeExecute($_REQUEST['topics']);
850
		}
851
852
		// Just convert to the other method, to make it easier.
853
		foreach ($_REQUEST['topics'] as $topic)
854
			$_REQUEST['actions'][(int) $topic] = $_REQUEST['qaction'];
855
	}
856
857
	// Weird... how'd you get here?
858
	if (empty($_REQUEST['actions']))
859
		redirectexit($redirect_url);
860
861
	// Validate each action.
862
	$temp = array();
863
	foreach ($_REQUEST['actions'] as $topic => $action)
864
	{
865
		if (in_array($action, $possibleActions))
866
			$temp[(int) $topic] = $action;
867
	}
868
	$_REQUEST['actions'] = $temp;
869
870
	if (!empty($_REQUEST['actions']))
871
	{
872
		// Find all topics...
873
		$request = $smcFunc['db_query']('', '
874
			SELECT id_topic, id_member_started, id_board, locked, approved, unapproved_posts
875
			FROM {db_prefix}topics
876
			WHERE id_topic IN ({array_int:action_topic_ids})
877
			LIMIT {int:limit}',
878
			array(
879
				'action_topic_ids' => array_keys($_REQUEST['actions']),
880
				'limit' => count($_REQUEST['actions']),
881
			)
882
		);
883
		while ($row = $smcFunc['db_fetch_assoc']($request))
884
		{
885
			if (!empty($board))
886
			{
887
				if ($row['id_board'] != $board || ($modSettings['postmod_active'] && !$row['approved'] && !allowedTo('approve_posts')))
888
					unset($_REQUEST['actions'][$row['id_topic']]);
889
			}
890
			else
891
			{
892
				// Don't allow them to act on unapproved posts they can't see...
893
				if ($modSettings['postmod_active'] && !$row['approved'] && !in_array(0, $boards_can['approve_posts']) && !in_array($row['id_board'], $boards_can['approve_posts']))
894
					unset($_REQUEST['actions'][$row['id_topic']]);
895
				// Goodness, this is fun.  We need to validate the action.
896
				elseif ($_REQUEST['actions'][$row['id_topic']] == 'sticky' && !in_array(0, $boards_can['make_sticky']) && !in_array($row['id_board'], $boards_can['make_sticky']))
897
					unset($_REQUEST['actions'][$row['id_topic']]);
898
				elseif ($_REQUEST['actions'][$row['id_topic']] == 'move' && !in_array(0, $boards_can['move_any']) && !in_array($row['id_board'], $boards_can['move_any']) && ($row['id_member_started'] != $user_info['id'] || (!in_array(0, $boards_can['move_own']) && !in_array($row['id_board'], $boards_can['move_own']))))
899
					unset($_REQUEST['actions'][$row['id_topic']]);
900
				elseif ($_REQUEST['actions'][$row['id_topic']] == 'remove' && !in_array(0, $boards_can['remove_any']) && !in_array($row['id_board'], $boards_can['remove_any']) && ($row['id_member_started'] != $user_info['id'] || (!in_array(0, $boards_can['remove_own']) && !in_array($row['id_board'], $boards_can['remove_own']))))
901
					unset($_REQUEST['actions'][$row['id_topic']]);
902
				// @todo $locked is not set, what are you trying to do? (taking the change it is supposed to be $row['locked'])
903
				elseif ($_REQUEST['actions'][$row['id_topic']] == 'lock' && !in_array(0, $boards_can['lock_any']) && !in_array($row['id_board'], $boards_can['lock_any']) && ($row['id_member_started'] != $user_info['id'] || $row['locked'] == 1 || (!in_array(0, $boards_can['lock_own']) && !in_array($row['id_board'], $boards_can['lock_own']))))
904
					unset($_REQUEST['actions'][$row['id_topic']]);
905
				// If the topic is approved then you need permission to approve the posts within.
906
				elseif ($_REQUEST['actions'][$row['id_topic']] == 'approve' && (!$row['unapproved_posts'] || (!in_array(0, $boards_can['approve_posts']) && !in_array($row['id_board'], $boards_can['approve_posts']))))
907
					unset($_REQUEST['actions'][$row['id_topic']]);
908
			}
909
		}
910
		$smcFunc['db_free_result']($request);
911
	}
912
913
	$stickyCache = array();
914
	$moveCache = array(0 => array(), 1 => array());
915
	$removeCache = array();
916
	$lockCache = array();
917
	$markCache = array();
918
	$approveCache = array();
919
920
	// Separate the actions.
921
	foreach ($_REQUEST['actions'] as $topic => $action)
0 ignored issues
show
Comprehensibility Bug introduced by
$topic is overwriting a variable from outer foreach loop.
Loading history...
Comprehensibility Bug introduced by
$action is overwriting a variable from outer foreach loop.
Loading history...
922
	{
923
		$topic = (int) $topic;
924
925
		if ($action == 'markread')
926
			$markCache[] = $topic;
927
		elseif ($action == 'sticky')
928
			$stickyCache[] = $topic;
929
		elseif ($action == 'move')
930
		{
931
			require_once($sourcedir . '/MoveTopic.php');
932
			moveTopicConcurrence();
933
934
			// $moveCache[0] is the topic, $moveCache[1] is the board to move to.
935
			$moveCache[1][$topic] = (int) (isset($_REQUEST['move_tos'][$topic]) ? $_REQUEST['move_tos'][$topic] : $_REQUEST['move_to']);
936
937
			if (empty($moveCache[1][$topic]))
938
				continue;
939
940
			$moveCache[0][] = $topic;
941
		}
942
		elseif ($action == 'remove')
943
			$removeCache[] = $topic;
944
		elseif ($action == 'lock')
945
			$lockCache[] = $topic;
946
		elseif ($action == 'approve')
947
			$approveCache[] = $topic;
948
	}
949
950
	if (empty($board))
951
		$affectedBoards = array();
952
	else
953
		$affectedBoards = array($board => array(0, 0));
954
955
	// Do all the stickies...
956
	if (!empty($stickyCache))
957
	{
958
		$smcFunc['db_query']('', '
959
			UPDATE {db_prefix}topics
960
			SET is_sticky = CASE WHEN is_sticky = {int:is_sticky} THEN 0 ELSE 1 END
961
			WHERE id_topic IN ({array_int:sticky_topic_ids})',
962
			array(
963
				'sticky_topic_ids' => $stickyCache,
964
				'is_sticky' => 1,
965
			)
966
		);
967
968
		// Get the board IDs and Sticky status
969
		$request = $smcFunc['db_query']('', '
970
			SELECT id_topic, id_board, is_sticky
971
			FROM {db_prefix}topics
972
			WHERE id_topic IN ({array_int:sticky_topic_ids})
973
			LIMIT {int:limit}',
974
			array(
975
				'sticky_topic_ids' => $stickyCache,
976
				'limit' => count($stickyCache),
977
			)
978
		);
979
		$stickyCacheBoards = array();
980
		$stickyCacheStatus = array();
981
		while ($row = $smcFunc['db_fetch_assoc']($request))
982
		{
983
			$stickyCacheBoards[$row['id_topic']] = $row['id_board'];
984
			$stickyCacheStatus[$row['id_topic']] = empty($row['is_sticky']);
985
		}
986
		$smcFunc['db_free_result']($request);
987
	}
988
989
	// Move sucka! (this is, by the by, probably the most complicated part....)
990
	if (!empty($moveCache[0]))
991
	{
992
		// I know - I just KNOW you're trying to beat the system.  Too bad for you... we CHECK :P.
993
		$request = $smcFunc['db_query']('', '
994
			SELECT t.id_topic, t.id_board, b.count_posts
995
			FROM {db_prefix}topics AS t
996
				LEFT JOIN {db_prefix}boards AS b ON (t.id_board = b.id_board)
997
			WHERE t.id_topic IN ({array_int:move_topic_ids})' . (!empty($board) && !allowedTo('move_any') ? '
998
				AND t.id_member_started = {int:current_member}' : '') . '
999
			LIMIT {int:limit}',
1000
			array(
1001
				'current_member' => $user_info['id'],
1002
				'move_topic_ids' => $moveCache[0],
1003
				'limit' => count($moveCache[0])
1004
			)
1005
		);
1006
		$moveTos = array();
1007
		$moveCache2 = array();
1008
		$countPosts = array();
1009
		while ($row = $smcFunc['db_fetch_assoc']($request))
1010
		{
1011
			$to = $moveCache[1][$row['id_topic']];
1012
1013
			if (empty($to))
1014
				continue;
1015
1016
			// Does this topic's board count the posts or not?
1017
			$countPosts[$row['id_topic']] = empty($row['count_posts']);
1018
1019
			if (!isset($moveTos[$to]))
1020
				$moveTos[$to] = array();
1021
1022
			$moveTos[$to][] = $row['id_topic'];
1023
1024
			// For reporting...
1025
			$moveCache2[] = array($row['id_topic'], $row['id_board'], $to);
1026
		}
1027
		$smcFunc['db_free_result']($request);
1028
1029
		$moveCache = $moveCache2;
1030
1031
		require_once($sourcedir . '/MoveTopic.php');
1032
1033
		// Do the actual moves...
1034
		foreach ($moveTos as $to => $topics)
1035
			moveTopics($topics, $to);
1036
1037
		// Does the post counts need to be updated?
1038
		if (!empty($moveTos))
1039
		{
1040
			$topicRecounts = array();
1041
			$request = $smcFunc['db_query']('', '
1042
				SELECT id_board, count_posts
1043
				FROM {db_prefix}boards
1044
				WHERE id_board IN ({array_int:move_boards})',
1045
				array(
1046
					'move_boards' => array_keys($moveTos),
1047
				)
1048
			);
1049
1050
			while ($row = $smcFunc['db_fetch_assoc']($request))
1051
			{
1052
				$cp = empty($row['count_posts']);
1053
1054
				// Go through all the topics that are being moved to this board.
1055
				foreach ($moveTos[$row['id_board']] as $topic)
1056
				{
1057
					// If both boards have the same value for post counting then no adjustment needs to be made.
1058
					if ($countPosts[$topic] != $cp)
1059
					{
1060
						// If the board being moved to does count the posts then the other one doesn't so add to their post count.
1061
						$topicRecounts[$topic] = $cp ? '+' : '-';
1062
					}
1063
				}
1064
			}
1065
1066
			$smcFunc['db_free_result']($request);
1067
1068
			if (!empty($topicRecounts))
1069
			{
1070
				$members = array();
1071
1072
				// Get all the members who have posted in the moved topics.
1073
				$request = $smcFunc['db_query']('', '
1074
					SELECT id_member, id_topic
1075
					FROM {db_prefix}messages
1076
					WHERE id_topic IN ({array_int:moved_topic_ids})',
1077
					array(
1078
						'moved_topic_ids' => array_keys($topicRecounts),
1079
					)
1080
				);
1081
1082
				while ($row = $smcFunc['db_fetch_assoc']($request))
1083
				{
1084
					if (!isset($members[$row['id_member']]))
1085
						$members[$row['id_member']] = 0;
1086
1087
					if ($topicRecounts[$row['id_topic']] === '+')
1088
						$members[$row['id_member']] += 1;
1089
					else
1090
						$members[$row['id_member']] -= 1;
1091
				}
1092
1093
				$smcFunc['db_free_result']($request);
1094
1095
				// And now update them member's post counts
1096
				foreach ($members as $id_member => $post_adj)
1097
					updateMemberData($id_member, array('posts' => 'posts + ' . $post_adj));
1098
			}
1099
		}
1100
	}
1101
1102
	// Now delete the topics...
1103
	if (!empty($removeCache))
1104
	{
1105
		// They can only delete their own topics. (we wouldn't be here if they couldn't do that..)
1106
		$result = $smcFunc['db_query']('', '
1107
			SELECT id_topic, id_board
1108
			FROM {db_prefix}topics
1109
			WHERE id_topic IN ({array_int:removed_topic_ids})' . (!empty($board) && !allowedTo('remove_any') ? '
1110
				AND id_member_started = {int:current_member}' : '') . '
1111
			LIMIT {int:limit}',
1112
			array(
1113
				'current_member' => $user_info['id'],
1114
				'removed_topic_ids' => $removeCache,
1115
				'limit' => count($removeCache),
1116
			)
1117
		);
1118
1119
		$removeCache = array();
1120
		$removeCacheBoards = array();
1121
		while ($row = $smcFunc['db_fetch_assoc']($result))
1122
		{
1123
			$removeCache[] = $row['id_topic'];
1124
			$removeCacheBoards[$row['id_topic']] = $row['id_board'];
1125
		}
1126
		$smcFunc['db_free_result']($result);
1127
1128
		// Maybe *none* were their own topics.
1129
		if (!empty($removeCache))
1130
		{
1131
			// Gotta send the notifications *first*!
1132
			foreach ($removeCache as $topic)
1133
			{
1134
				// Only log the topic ID if it's not in the recycle board.
1135
				logAction('remove', array((empty($modSettings['recycle_enable']) || $modSettings['recycle_board'] != $removeCacheBoards[$topic] ? 'topic' : 'old_topic_id') => $topic, 'board' => $removeCacheBoards[$topic]));
1136
				sendNotifications($topic, 'remove');
1137
			}
1138
1139
			require_once($sourcedir . '/RemoveTopic.php');
1140
			removeTopics($removeCache);
1141
		}
1142
	}
1143
1144
	// Approve the topics...
1145
	if (!empty($approveCache))
1146
	{
1147
		// We need unapproved topic ids and their authors!
1148
		$request = $smcFunc['db_query']('', '
1149
			SELECT id_topic, id_member_started
1150
			FROM {db_prefix}topics
1151
			WHERE id_topic IN ({array_int:approve_topic_ids})
1152
				AND approved = {int:not_approved}
1153
			LIMIT {int:limit}',
1154
			array(
1155
				'approve_topic_ids' => $approveCache,
1156
				'not_approved' => 0,
1157
				'limit' => count($approveCache),
1158
			)
1159
		);
1160
		$approveCache = array();
1161
		$approveCacheMembers = array();
1162
		while ($row = $smcFunc['db_fetch_assoc']($request))
1163
		{
1164
			$approveCache[] = $row['id_topic'];
1165
			$approveCacheMembers[$row['id_topic']] = $row['id_member_started'];
1166
		}
1167
		$smcFunc['db_free_result']($request);
1168
1169
		// Any topics to approve?
1170
		if (!empty($approveCache))
1171
		{
1172
			// Handle the approval part...
1173
			approveTopics($approveCache);
1174
1175
			// Time for some logging!
1176
			foreach ($approveCache as $topic)
1177
				logAction('approve_topic', array('topic' => $topic, 'member' => $approveCacheMembers[$topic]));
1178
		}
1179
	}
1180
1181
	// And (almost) lastly, lock the topics...
1182
	if (!empty($lockCache))
1183
	{
1184
		$lockStatus = array();
1185
1186
		// Gotta make sure they CAN lock/unlock these topics...
1187
		if (!empty($board) && !allowedTo('lock_any'))
1188
		{
1189
			// Make sure they started the topic AND it isn't already locked by someone with higher priv's.
1190
			$result = $smcFunc['db_query']('', '
1191
				SELECT id_topic, locked, id_board
1192
				FROM {db_prefix}topics
1193
				WHERE id_topic IN ({array_int:locked_topic_ids})
1194
					AND id_member_started = {int:current_member}
1195
					AND locked IN (2, 0)
1196
				LIMIT {int:limit}',
1197
				array(
1198
					'current_member' => $user_info['id'],
1199
					'locked_topic_ids' => $lockCache,
1200
					'limit' => count($lockCache),
1201
				)
1202
			);
1203
			$lockCache = array();
1204
			$lockCacheBoards = array();
1205
			while ($row = $smcFunc['db_fetch_assoc']($result))
1206
			{
1207
				$lockCache[] = $row['id_topic'];
1208
				$lockCacheBoards[$row['id_topic']] = $row['id_board'];
1209
				$lockStatus[$row['id_topic']] = empty($row['locked']);
1210
			}
1211
			$smcFunc['db_free_result']($result);
1212
		}
1213
		else
1214
		{
1215
			$result = $smcFunc['db_query']('', '
1216
				SELECT id_topic, locked, id_board
1217
				FROM {db_prefix}topics
1218
				WHERE id_topic IN ({array_int:locked_topic_ids})
1219
				LIMIT {int:limit}',
1220
				array(
1221
					'locked_topic_ids' => $lockCache,
1222
					'limit' => count($lockCache)
1223
				)
1224
			);
1225
			$lockCacheBoards = array();
1226
			while ($row = $smcFunc['db_fetch_assoc']($result))
1227
			{
1228
				$lockStatus[$row['id_topic']] = empty($row['locked']);
1229
				$lockCacheBoards[$row['id_topic']] = $row['id_board'];
1230
			}
1231
			$smcFunc['db_free_result']($result);
1232
		}
1233
1234
		// It could just be that *none* were their own topics...
1235
		if (!empty($lockCache))
1236
		{
1237
			// Alternate the locked value.
1238
			$smcFunc['db_query']('', '
1239
				UPDATE {db_prefix}topics
1240
				SET locked = CASE WHEN locked = {int:is_locked} THEN ' . (allowedTo('lock_any') ? '1' : '2') . ' ELSE 0 END
1241
				WHERE id_topic IN ({array_int:locked_topic_ids})',
1242
				array(
1243
					'locked_topic_ids' => $lockCache,
1244
					'is_locked' => 0,
1245
				)
1246
			);
1247
		}
1248
	}
1249
1250
	if (!empty($markCache))
1251
	{
1252
		$request = $smcFunc['db_query']('', '
1253
			SELECT id_topic, unwatched
1254
			FROM {db_prefix}log_topics
1255
			WHERE id_topic IN ({array_int:selected_topics})
1256
				AND id_member = {int:current_user}',
1257
			array(
1258
				'selected_topics' => $markCache,
1259
				'current_user' => $user_info['id'],
1260
			)
1261
		);
1262
		$logged_topics = array();
1263
		while ($row = $smcFunc['db_fetch_assoc']($request))
1264
			$logged_topics[$row['id_topic']] = $row['unwatched'];
1265
1266
		$smcFunc['db_free_result']($request);
1267
1268
		$markArray = array();
1269
		foreach ($markCache as $topic)
1270
			$markArray[] = array($modSettings['maxMsgID'], $user_info['id'], $topic, (isset($logged_topics[$topic]) ? $logged_topics[$topic] : 0));
1271
1272
		$smcFunc['db_insert']('replace',
1273
			'{db_prefix}log_topics',
1274
			array('id_msg' => 'int', 'id_member' => 'int', 'id_topic' => 'int', 'unwatched' => 'int'),
1275
			$markArray,
1276
			array('id_member', 'id_topic')
1277
		);
1278
	}
1279
1280
	foreach ($moveCache as $topic)
0 ignored issues
show
Comprehensibility Bug introduced by
$topic is overwriting a variable from outer foreach loop.
Loading history...
1281
	{
1282
		// Didn't actually move anything!
1283
		if (!isset($topic[0]))
1284
			break;
1285
1286
		logAction('move', array('topic' => $topic[0], 'board_from' => $topic[1], 'board_to' => $topic[2]));
1287
		sendNotifications($topic[0], 'move');
1288
	}
1289
	foreach ($lockCache as $topic)
0 ignored issues
show
Comprehensibility Bug introduced by
$topic is overwriting a variable from outer foreach loop.
Loading history...
1290
	{
1291
		logAction($lockStatus[$topic] ? 'lock' : 'unlock', array('topic' => $topic, 'board' => $lockCacheBoards[$topic]));
1292
		sendNotifications($topic, $lockStatus[$topic] ? 'lock' : 'unlock');
1293
	}
1294
	foreach ($stickyCache as $topic)
0 ignored issues
show
Comprehensibility Bug introduced by
$topic is overwriting a variable from outer foreach loop.
Loading history...
1295
	{
1296
		logAction($stickyCacheStatus[$topic] ? 'unsticky' : 'sticky', array('topic' => $topic, 'board' => $stickyCacheBoards[$topic]));
1297
		sendNotifications($topic, 'sticky');
1298
	}
1299
1300
	updateStats('topic');
1301
	updateStats('message');
1302
	updateSettings(array(
1303
		'calendar_updated' => time(),
1304
	));
1305
1306
	if (!empty($affectedBoards))
1307
		updateLastMessages(array_keys($affectedBoards));
1308
1309
	redirectexit($redirect_url);
1310
}
1311
1312
?>