MessageIndex()   F
last analyzed

Complexity

Conditions 195

Size

Total Lines 726
Code Lines 431

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 195
eloc 431
nop 0
dl 0
loc 726
rs 3.3333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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