Issues (1061)

Sources/Display.php (1 issue)

1
<?php
2
3
/**
4
 * This is perhaps the most important and probably most accessed file in all
5
 * of SMF.  This file controls topic, message, and attachment display.
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
 * The central part of the board - topic display.
22
 * This function loads the posts in a topic up so they can be displayed.
23
 * It uses the main sub template of the Display template.
24
 * It requires a topic, and can go to the previous or next topic from it.
25
 * It jumps to the correct post depending on a number/time/IS_MSG passed.
26
 * It depends on the messages_per_page, defaultMaxMessages and enableAllMessages settings.
27
 * It is accessed by ?topic=id_topic.START.
28
 *
29
 * @return void
30
 */
31
function Display()
32
{
33
	global $scripturl, $txt, $modSettings, $context, $settings;
34
	global $options, $sourcedir, $user_info, $board_info, $topic, $board;
35
	global $messages_request, $language, $smcFunc;
36
37
	// What are you gonna display if these are empty?!
38
	if (empty($topic))
39
		fatal_lang_error('no_board', false);
40
41
	// Load the proper template.
42
	loadTemplate('Display');
43
44
	// Not only does a prefetch make things slower for the server, but it makes it impossible to know if they read it.
45
	if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
46
	{
47
		ob_end_clean();
48
		send_http_status(403, 'Prefetch Forbidden');
49
		die;
50
	}
51
52
	// How much are we sticking on each page?
53
	$context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
54
55
	// Let's do some work on what to search index.
56
	if (count($_GET) > 2)
57
		foreach ($_GET as $k => $v)
58
		{
59
			if (!in_array($k, array('topic', 'board', 'start', session_name())))
60
				$context['robot_no_index'] = true;
61
		}
62
63
	if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0))
64
		$context['robot_no_index'] = true;
65
66
	// Find the previous or next topic.  Make a fuss if there are no more.
67
	if (isset($_REQUEST['prev_next']) && ($_REQUEST['prev_next'] == 'prev' || $_REQUEST['prev_next'] == 'next'))
68
	{
69
		// No use in calculating the next topic if there's only one.
70
		if ($board_info['num_topics'] > 1)
71
		{
72
			// Just prepare some variables that are used in the query.
73
			$gt_lt = $_REQUEST['prev_next'] == 'prev' ? '>' : '<';
74
			$order = $_REQUEST['prev_next'] == 'prev' ? '' : ' DESC';
75
76
			$request = $smcFunc['db_query']('', '
77
				SELECT t2.id_topic
78
				FROM {db_prefix}topics AS t
79
					INNER JOIN {db_prefix}topics AS t2 ON (
80
					(t2.id_last_msg ' . $gt_lt . ' t.id_last_msg AND t2.is_sticky ' . $gt_lt . '= t.is_sticky) OR t2.is_sticky ' . $gt_lt . ' t.is_sticky)
81
				WHERE t.id_topic = {int:current_topic}
82
					AND t2.id_board = {int:current_board}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
83
					AND (t2.approved = {int:is_approved} OR (t2.id_member_started != {int:id_member_started} AND t2.id_member_started = {int:current_member}))') . '
84
				ORDER BY t2.is_sticky' . $order . ', t2.id_last_msg' . $order . '
85
				LIMIT 1',
86
				array(
87
					'current_board' => $board,
88
					'current_member' => $user_info['id'],
89
					'current_topic' => $topic,
90
					'is_approved' => 1,
91
					'id_member_started' => 0,
92
				)
93
			);
94
95
			// No more left.
96
			if ($smcFunc['db_num_rows']($request) == 0)
97
			{
98
				$smcFunc['db_free_result']($request);
99
100
				// Roll over - if we're going prev, get the last - otherwise the first.
101
				$request = $smcFunc['db_query']('', '
102
					SELECT id_topic
103
					FROM {db_prefix}topics
104
					WHERE id_board = {int:current_board}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
105
						AND (approved = {int:is_approved} OR (id_member_started != {int:id_member_started} AND id_member_started = {int:current_member}))') . '
106
					ORDER BY is_sticky' . $order . ', id_last_msg' . $order . '
107
					LIMIT 1',
108
					array(
109
						'current_board' => $board,
110
						'current_member' => $user_info['id'],
111
						'is_approved' => 1,
112
						'id_member_started' => 0,
113
					)
114
				);
115
			}
116
117
			// Now you can be sure $topic is the id_topic to view.
118
			list ($topic) = $smcFunc['db_fetch_row']($request);
119
			$smcFunc['db_free_result']($request);
120
121
			$context['current_topic'] = $topic;
122
		}
123
124
		// Go to the newest message on this topic.
125
		$_REQUEST['start'] = 'new';
126
	}
127
128
	// Add 1 to the number of views of this topic (except for robots).
129
	if (!$user_info['possibly_robot'] && (empty($_SESSION['last_read_topic']) || $_SESSION['last_read_topic'] != $topic))
130
	{
131
		$smcFunc['db_query']('', '
132
			UPDATE {db_prefix}topics
133
			SET num_views = num_views + 1
134
			WHERE id_topic = {int:current_topic}',
135
			array(
136
				'current_topic' => $topic,
137
			)
138
		);
139
140
		$_SESSION['last_read_topic'] = $topic;
141
	}
142
143
	$topic_parameters = array(
144
		'current_member' => $user_info['id'],
145
		'current_topic' => $topic,
146
		'current_board' => $board,
147
	);
148
	$topic_selects = array();
149
	$topic_tables = array();
150
	$context['topicinfo'] = array();
151
	call_integration_hook('integrate_display_topic', array(&$topic_selects, &$topic_tables, &$topic_parameters));
152
153
	// @todo Why isn't this cached?
154
	// @todo if we get id_board in this query and cache it, we can save a query on posting
155
	// Get all the important topic info.
156
	$request = $smcFunc['db_query']('', '
157
		SELECT
158
			t.num_replies, t.num_views, t.locked, ms.subject, t.is_sticky, t.id_poll,
159
			t.id_member_started, t.id_first_msg, t.id_last_msg, t.approved, t.unapproved_posts, t.id_redirect_topic,
160
			COALESCE(mem.real_name, ms.poster_name) AS topic_started_name, ms.poster_time AS topic_started_time,
161
			' . ($user_info['is_guest'] ? 't.id_last_msg + 1' : 'COALESCE(lt.id_msg, lmr.id_msg, -1) + 1') . ' AS new_from
162
			' . (!empty($board_info['recycle']) ? ', id_previous_board, id_previous_topic' : '') . '
163
			' . (!empty($topic_selects) ? (', ' . implode(', ', $topic_selects)) : '') . '
164
			' . (!$user_info['is_guest'] ? ', COALESCE(lt.unwatched, 0) as unwatched' : '') . '
165
		FROM {db_prefix}topics AS t
166
			INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
167
			LEFT JOIN {db_prefix}members AS mem on (mem.id_member = t.id_member_started)' . ($user_info['is_guest'] ? '' : '
168
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = {int:current_topic} AND lt.id_member = {int:current_member})
169
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})') . '
170
			' . (!empty($topic_tables) ? implode("\n\t", $topic_tables) : '') . '
171
		WHERE t.id_topic = {int:current_topic}
172
		LIMIT 1',
173
		$topic_parameters
174
	);
175
176
	if ($smcFunc['db_num_rows']($request) == 0)
177
		fatal_lang_error('not_a_topic', false, 404);
178
	$context['topicinfo'] = $smcFunc['db_fetch_assoc']($request);
179
	$smcFunc['db_free_result']($request);
180
181
	// Is this a moved or merged topic that we are redirecting to?
182
	if (!empty($context['topicinfo']['id_redirect_topic']))
183
	{
184
		// Mark this as read...
185
		if (!$user_info['is_guest'] && $context['topicinfo']['new_from'] != $context['topicinfo']['id_first_msg'])
186
		{
187
			// Mark this as read first
188
			$smcFunc['db_insert']($context['topicinfo']['new_from'] == 0 ? 'ignore' : 'replace',
189
				'{db_prefix}log_topics',
190
				array(
191
					'id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int',
192
				),
193
				array(
194
					$user_info['id'], $topic, $context['topicinfo']['id_first_msg'], $context['topicinfo']['unwatched'],
195
				),
196
				array('id_member', 'id_topic')
197
			);
198
		}
199
		redirectexit('topic=' . $context['topicinfo']['id_redirect_topic'] . '.0', false, true);
200
	}
201
202
	$can_approve_posts = allowedTo('approve_posts');
203
204
	$context['real_num_replies'] = $context['num_replies'] = $context['topicinfo']['num_replies'];
205
	$context['topic_started_time'] = timeformat($context['topicinfo']['topic_started_time']);
206
	$context['topic_started_timestamp'] = $context['topicinfo']['topic_started_time'];
207
	$context['topic_poster_name'] = $context['topicinfo']['topic_started_name'];
208
	$context['topic_first_message'] = $context['topicinfo']['id_first_msg'];
209
	$context['topic_last_message'] = $context['topicinfo']['id_last_msg'];
210
	$context['topic_unwatched'] = isset($context['topicinfo']['unwatched']) ? $context['topicinfo']['unwatched'] : 0;
211
212
	// Add up unapproved replies to get real number of replies...
213
	if ($modSettings['postmod_active'] && $can_approve_posts)
214
		$context['real_num_replies'] += $context['topicinfo']['unapproved_posts'] - ($context['topicinfo']['approved'] ? 0 : 1);
215
216
	// If this topic has unapproved posts, we need to work out how many posts the user can see, for page indexing.
217
	if ($modSettings['postmod_active'] && $context['topicinfo']['unapproved_posts'] && !$user_info['is_guest'] && !$can_approve_posts)
218
	{
219
		$request = $smcFunc['db_query']('', '
220
			SELECT COUNT(id_member) AS my_unapproved_posts
221
			FROM {db_prefix}messages
222
			WHERE id_topic = {int:current_topic}
223
				AND id_member = {int:current_member}
224
				AND approved = 0',
225
			array(
226
				'current_topic' => $topic,
227
				'current_member' => $user_info['id'],
228
			)
229
		);
230
		list ($myUnapprovedPosts) = $smcFunc['db_fetch_row']($request);
231
		$smcFunc['db_free_result']($request);
232
233
		$context['total_visible_posts'] = $context['num_replies'] + $myUnapprovedPosts + ($context['topicinfo']['approved'] ? 1 : 0);
234
	}
235
	elseif ($user_info['is_guest'])
236
		$context['total_visible_posts'] = $context['num_replies'] + ($context['topicinfo']['approved'] ? 1 : 0);
237
	else
238
		$context['total_visible_posts'] = $context['num_replies'] + $context['topicinfo']['unapproved_posts'] + ($context['topicinfo']['approved'] ? 1 : 0);
239
240
	// The start isn't a number; it's information about what to do, where to go.
241
	if (!is_numeric($_REQUEST['start']))
242
	{
243
		// Redirect to the page and post with new messages, originally by Omar Bazavilvazo.
244
		if ($_REQUEST['start'] == 'new')
245
		{
246
			// Guests automatically go to the last post.
247
			if ($user_info['is_guest'])
248
			{
249
				$context['start_from'] = $context['total_visible_posts'] - 1;
250
				$_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : 0;
251
			}
252
			else
253
			{
254
				// Find the earliest unread message in the topic. (the use of topics here is just for both tables.)
255
				$request = $smcFunc['db_query']('', '
256
					SELECT COALESCE(lt.id_msg, lmr.id_msg, -1) + 1 AS new_from
257
					FROM {db_prefix}topics AS t
258
						LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = {int:current_topic} AND lt.id_member = {int:current_member})
259
						LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})
260
					WHERE t.id_topic = {int:current_topic}
261
					LIMIT 1',
262
					array(
263
						'current_board' => $board,
264
						'current_member' => $user_info['id'],
265
						'current_topic' => $topic,
266
					)
267
				);
268
				list ($new_from) = $smcFunc['db_fetch_row']($request);
269
				$smcFunc['db_free_result']($request);
270
271
				// Fall through to the next if statement.
272
				$_REQUEST['start'] = 'msg' . $new_from;
273
			}
274
		}
275
276
		// Start from a certain time index, not a message.
277
		if (substr($_REQUEST['start'], 0, 4) == 'from')
278
		{
279
			$timestamp = (int) substr($_REQUEST['start'], 4);
280
			if ($timestamp === 0)
281
				$_REQUEST['start'] = 0;
282
			else
283
			{
284
				// Find the number of messages posted before said time...
285
				$request = $smcFunc['db_query']('', '
286
					SELECT COUNT(*)
287
					FROM {db_prefix}messages
288
					WHERE poster_time < {int:timestamp}
289
						AND id_topic = {int:current_topic}' . ($modSettings['postmod_active'] && $context['topicinfo']['unapproved_posts'] && !allowedTo('approve_posts') ? '
290
						AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')' : ''),
291
					array(
292
						'current_topic' => $topic,
293
						'current_member' => $user_info['id'],
294
						'is_approved' => 1,
295
						'timestamp' => $timestamp,
296
					)
297
				);
298
				list ($context['start_from']) = $smcFunc['db_fetch_row']($request);
299
				$smcFunc['db_free_result']($request);
300
301
				// Handle view_newest_first options, and get the correct start value.
302
				$_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : $context['total_visible_posts'] - $context['start_from'] - 1;
303
			}
304
		}
305
306
		// Link to a message...
307
		elseif (substr($_REQUEST['start'], 0, 3) == 'msg')
308
		{
309
			$virtual_msg = (int) substr($_REQUEST['start'], 3);
310
			if (!$context['topicinfo']['unapproved_posts'] && $virtual_msg >= $context['topicinfo']['id_last_msg'])
311
				$context['start_from'] = $context['total_visible_posts'] - 1;
312
			elseif (!$context['topicinfo']['unapproved_posts'] && $virtual_msg <= $context['topicinfo']['id_first_msg'])
313
				$context['start_from'] = 0;
314
			else
315
			{
316
				// Find the start value for that message......
317
				$request = $smcFunc['db_query']('', '
318
					SELECT COUNT(*)
319
					FROM {db_prefix}messages
320
					WHERE id_msg < {int:virtual_msg}
321
						AND id_topic = {int:current_topic}' . ($modSettings['postmod_active'] && $context['topicinfo']['unapproved_posts'] && !allowedTo('approve_posts') ? '
322
						AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')' : ''),
323
					array(
324
						'current_member' => $user_info['id'],
325
						'current_topic' => $topic,
326
						'virtual_msg' => $virtual_msg,
327
						'is_approved' => 1,
328
						'no_member' => 0,
329
					)
330
				);
331
				list ($context['start_from']) = $smcFunc['db_fetch_row']($request);
332
				$smcFunc['db_free_result']($request);
333
			}
334
335
			// We need to reverse the start as well in this case.
336
			$_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : $context['total_visible_posts'] - $context['start_from'] - 1;
337
		}
338
	}
339
340
	// Create a previous next string if the selected theme has it as a selected option.
341
	$context['previous_next'] = $modSettings['enablePreviousNext'] ? '<a href="' . $scripturl . '?topic=' . $topic . '.0;prev_next=prev#new">' . $txt['previous_next_back'] . '</a> - <a href="' . $scripturl . '?topic=' . $topic . '.0;prev_next=next#new">' . $txt['previous_next_forward'] . '</a>' : '';
342
343
	// Check if spellchecking is both enabled and actually working. (for quick reply.)
344
	$context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && (function_exists('pspell_new') || (function_exists('enchant_broker_init') && ($txt['lang_character_set'] == 'UTF-8' || function_exists('iconv'))));
345
346
	// Do we need to show the visual verification image?
347
	$context['require_verification'] = !$user_info['is_mod'] && !$user_info['is_admin'] && !empty($modSettings['posts_require_captcha']) && ($user_info['posts'] < $modSettings['posts_require_captcha'] || ($user_info['is_guest'] && $modSettings['posts_require_captcha'] == -1));
348
	if ($context['require_verification'])
349
	{
350
		require_once($sourcedir . '/Subs-Editor.php');
351
		$verificationOptions = array(
352
			'id' => 'post',
353
		);
354
		$context['require_verification'] = create_control_verification($verificationOptions);
355
		$context['visual_verification_id'] = $verificationOptions['id'];
356
	}
357
358
	// Are we showing signatures - or disabled fields?
359
	$context['signature_enabled'] = substr($modSettings['signature_settings'], 0, 1) == 1;
360
	$context['disabled_fields'] = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
361
362
	// Prevent signature images from going outside the box.
363
	if ($context['signature_enabled'])
364
	{
365
		list ($sig_limits, $sig_bbc) = explode(':', $modSettings['signature_settings']);
366
		$sig_limits = explode(',', $sig_limits);
367
368
		if (!empty($sig_limits[5]) || !empty($sig_limits[6]))
369
			addInlineCss('
370
	.signature img { ' . (!empty($sig_limits[5]) ? 'max-width: ' . (int) $sig_limits[5] . 'px; ' : '') . (!empty($sig_limits[6]) ? 'max-height: ' . (int) $sig_limits[6] . 'px; ' : '') . '}');
371
	}
372
373
	// Censor the title...
374
	censorText($context['topicinfo']['subject']);
375
	$context['page_title'] = $context['topicinfo']['subject'];
376
377
	// Default this topic to not marked for notifications... of course...
378
	$context['is_marked_notify'] = false;
379
380
	// Did we report a post to a moderator just now?
381
	$context['report_sent'] = isset($_GET['reportsent']);
382
383
	// Let's get nosey, who is viewing this topic?
384
	if (!empty($settings['display_who_viewing']))
385
	{
386
		// Start out with no one at all viewing it.
387
		$context['view_members'] = array();
388
		$context['view_members_list'] = array();
389
		$context['view_num_hidden'] = 0;
390
391
		// Search for members who have this topic set in their GET data.
392
		$request = $smcFunc['db_query']('', '
393
			SELECT
394
				lo.id_member, lo.log_time, mem.real_name, mem.member_name, mem.show_online,
395
				mg.online_color, mg.id_group, mg.group_name
396
			FROM {db_prefix}log_online AS lo
397
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lo.id_member)
398
				LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:reg_id_group} THEN mem.id_post_group ELSE mem.id_group END)
399
			WHERE INSTR(lo.url, {string:in_url_string}) > 0 OR lo.session = {string:session}',
400
			array(
401
				'reg_id_group' => 0,
402
				'in_url_string' => '"topic":' . $topic,
403
				'session' => $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id(),
404
			)
405
		);
406
		while ($row = $smcFunc['db_fetch_assoc']($request))
407
		{
408
			if (empty($row['id_member']))
409
				continue;
410
411
			if (!empty($row['online_color']))
412
				$link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" style="color: ' . $row['online_color'] . ';">' . $row['real_name'] . '</a>';
413
			else
414
				$link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>';
415
416
			$is_buddy = in_array($row['id_member'], $user_info['buddies']);
417
			if ($is_buddy)
418
				$link = '<strong>' . $link . '</strong>';
419
420
			// Add them both to the list and to the more detailed list.
421
			if (!empty($row['show_online']) || allowedTo('moderate_forum'))
422
				$context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '<em>' . $link . '</em>' : $link;
423
			$context['view_members'][$row['log_time'] . $row['member_name']] = array(
424
				'id' => $row['id_member'],
425
				'username' => $row['member_name'],
426
				'name' => $row['real_name'],
427
				'group' => $row['id_group'],
428
				'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
429
				'link' => $link,
430
				'is_buddy' => $is_buddy,
431
				'hidden' => empty($row['show_online']),
432
			);
433
434
			if (empty($row['show_online']))
435
				$context['view_num_hidden']++;
436
		}
437
438
		// The number of guests is equal to the rows minus the ones we actually used ;).
439
		$context['view_num_guests'] = $smcFunc['db_num_rows']($request) - count($context['view_members']);
440
		$smcFunc['db_free_result']($request);
441
442
		// Sort the list.
443
		krsort($context['view_members']);
444
		krsort($context['view_members_list']);
445
	}
446
447
	// If all is set, but not allowed... just unset it.
448
	$can_show_all = !empty($modSettings['enableAllMessages']) && $context['total_visible_posts'] > $context['messages_per_page'] && $context['total_visible_posts'] < $modSettings['enableAllMessages'];
449
	if (isset($_REQUEST['all']) && !$can_show_all)
450
		unset($_REQUEST['all']);
451
	// Otherwise, it must be allowed... so pretend start was -1.
452
	elseif (isset($_REQUEST['all']))
453
		$_REQUEST['start'] = -1;
454
455
	// Construct the page index, allowing for the .START method...
456
	$context['page_index'] = constructPageIndex($scripturl . '?topic=' . $topic . '.%1$d', $_REQUEST['start'], $context['total_visible_posts'], $context['messages_per_page'], true);
457
	$context['start'] = $_REQUEST['start'];
458
459
	// This is information about which page is current, and which page we're on - in case you don't like the constructed page index. (again, wireles..)
460
	$context['page_info'] = array(
461
		'current_page' => $_REQUEST['start'] / $context['messages_per_page'] + 1,
462
		'num_pages' => floor(($context['total_visible_posts'] - 1) / $context['messages_per_page']) + 1,
463
	);
464
465
	// Figure out all the link to the next/prev/first/last/etc.
466
	if (!($can_show_all && isset($_REQUEST['all'])))
467
	{
468
		$context['links'] = array(
469
			'first' => $_REQUEST['start'] >= $context['messages_per_page'] ? $scripturl . '?topic=' . $topic . '.0' : '',
470
			'prev' => $_REQUEST['start'] >= $context['messages_per_page'] ? $scripturl . '?topic=' . $topic . '.' . ($_REQUEST['start'] - $context['messages_per_page']) : '',
471
			'next' => $_REQUEST['start'] + $context['messages_per_page'] < $context['total_visible_posts'] ? $scripturl . '?topic=' . $topic . '.' . ($_REQUEST['start'] + $context['messages_per_page']) : '',
472
			'last' => $_REQUEST['start'] + $context['messages_per_page'] < $context['total_visible_posts'] ? $scripturl . '?topic=' . $topic . '.' . (floor($context['total_visible_posts'] / $context['messages_per_page']) * $context['messages_per_page']) : '',
473
			'up' => $scripturl . '?board=' . $board . '.0'
474
		);
475
	}
476
477
	// If they are viewing all the posts, show all the posts, otherwise limit the number.
478
	if ($can_show_all)
479
	{
480
		if (isset($_REQUEST['all']))
481
		{
482
			// No limit! (actually, there is a limit, but...)
483
			$context['messages_per_page'] = -1;
484
			$context['page_index'] .= empty($modSettings['compactTopicPagesEnable']) ? '<strong>' . $txt['all'] . '</strong> ' : '[<strong>' . $txt['all'] . '</strong>] ';
485
486
			// Set start back to 0...
487
			$_REQUEST['start'] = 0;
488
		}
489
		// They aren't using it, but the *option* is there, at least.
490
		else
491
			$context['page_index'] .= '&nbsp;<a href="' . $scripturl . '?topic=' . $topic . '.0;all">' . $txt['all'] . '</a> ';
492
	}
493
494
	// Build the link tree.
495
	$context['linktree'][] = array(
496
		'url' => $scripturl . '?topic=' . $topic . '.0',
497
		'name' => $context['topicinfo']['subject'],
498
	);
499
500
	// Build a list of this board's moderators.
501
	$context['moderators'] = &$board_info['moderators'];
502
	$context['moderator_groups'] = &$board_info['moderator_groups'];
503
	$context['link_moderators'] = array();
504
	if (!empty($board_info['moderators']))
505
	{
506
		// Add a link for each moderator...
507
		foreach ($board_info['moderators'] as $mod)
508
			$context['link_moderators'][] = '<a href="' . $scripturl . '?action=profile;u=' . $mod['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod['name'] . '</a>';
509
	}
510
	if (!empty($board_info['moderator_groups']))
511
	{
512
		// Add a link for each moderator group as well...
513
		foreach ($board_info['moderator_groups'] as $mod_group)
514
			$context['link_moderators'][] = '<a href="' . $scripturl . '?action=groups;sa=viewmemberes;group=' . $mod_group['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod_group['name'] . '</a>';
515
	}
516
517
	if (!empty($context['link_moderators']))
518
	{
519
		// And show it after the board's name.
520
		$context['linktree'][count($context['linktree']) - 2]['extra_after'] = '<span class="board_moderators">(' . (count($context['link_moderators']) == 1 ? $txt['moderator'] : $txt['moderators']) . ': ' . implode(', ', $context['link_moderators']) . ')</span>';
521
	}
522
523
	// Information about the current topic...
524
	$context['is_locked'] = $context['topicinfo']['locked'];
525
	$context['is_sticky'] = $context['topicinfo']['is_sticky'];
526
	$context['is_approved'] = $context['topicinfo']['approved'];
527
	$context['is_poll'] = $context['topicinfo']['id_poll'] > 0 && $modSettings['pollMode'] == '1' && allowedTo('poll_view');
528
529
	// Did this user start the topic or not?
530
	$context['user']['started'] = $user_info['id'] == $context['topicinfo']['id_member_started'] && !$user_info['is_guest'];
531
	$context['topic_starter_id'] = $context['topicinfo']['id_member_started'];
532
533
	// Set the topic's information for the template.
534
	$context['subject'] = $context['topicinfo']['subject'];
535
	$context['num_views'] = comma_format($context['topicinfo']['num_views']);
536
	$context['num_views_text'] = $context['num_views'] == 1 ? $txt['read_one_time'] : sprintf($txt['read_many_times'], $context['num_views']);
537
	$context['mark_unread_time'] = !empty($virtual_msg) ? $virtual_msg : $context['topicinfo']['new_from'];
538
539
	// Set a canonical URL for this page.
540
	$context['canonical_url'] = $scripturl . '?topic=' . $topic . '.' . ($can_show_all ? '0;all' : $context['start']);
541
542
	// For quick reply we need a response prefix in the default forum language.
543
	if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix', 600)))
544
	{
545
		if ($language === $user_info['language'])
546
			$context['response_prefix'] = $txt['response_prefix'];
547
		else
548
		{
549
			loadLanguage('index', $language, false);
550
			$context['response_prefix'] = $txt['response_prefix'];
551
			loadLanguage('index');
552
		}
553
		cache_put_data('response_prefix', $context['response_prefix'], 600);
554
	}
555
556
	// If we want to show event information in the topic, prepare the data.
557
	if (allowedTo('calendar_view') && !empty($modSettings['cal_showInTopic']) && !empty($modSettings['cal_enabled']))
558
	{
559
		require_once($sourcedir . '/Subs-Calendar.php');
560
561
		// Any calendar information for this topic?
562
		$request = $smcFunc['db_query']('', '
563
			SELECT cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, mem.real_name, cal.start_time, cal.end_time, cal.timezone, cal.location
564
			FROM {db_prefix}calendar AS cal
565
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = cal.id_member)
566
			WHERE cal.id_topic = {int:current_topic}
567
			ORDER BY start_date',
568
			array(
569
				'current_topic' => $topic,
570
			)
571
		);
572
		$context['linked_calendar_events'] = array();
573
		while ($row = $smcFunc['db_fetch_assoc']($request))
574
		{
575
			// Get the various time and date properties for this event
576
			list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);
577
578
			// Sanity check
579
			if (!empty($start['error_count']) || !empty($start['warning_count']) || !empty($end['error_count']) || !empty($end['warning_count']))
580
				continue;
581
582
			$linked_calendar_event = array(
583
				'id' => $row['id_event'],
584
				'title' => $row['title'],
585
				'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
586
				'modify_href' => $scripturl . '?action=post;msg=' . $context['topicinfo']['id_first_msg'] . ';topic=' . $topic . '.0;calendar;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
587
				'can_export' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
588
				'export_href' => $scripturl . '?action=calendar;sa=ical;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
589
				'year' => $start['year'],
590
				'month' => $start['month'],
591
				'day' => $start['day'],
592
				'hour' => !$allday ? $start['hour'] : null,
593
				'minute' => !$allday ? $start['minute'] : null,
594
				'second' => !$allday ? $start['second'] : null,
595
				'start_date' => $row['start_date'],
596
				'start_date_local' => $start['date_local'],
597
				'start_date_orig' => $start['date_orig'],
598
				'start_time' => !$allday ? $row['start_time'] : null,
599
				'start_time_local' => !$allday ? $start['time_local'] : null,
600
				'start_time_orig' => !$allday ? $start['time_orig'] : null,
601
				'start_timestamp' => $start['timestamp'],
602
				'start_iso_gmdate' => $start['iso_gmdate'],
603
				'end_year' => $end['year'],
604
				'end_month' => $end['month'],
605
				'end_day' => $end['day'],
606
				'end_hour' => !$allday ? $end['hour'] : null,
607
				'end_minute' => !$allday ? $end['minute'] : null,
608
				'end_second' => !$allday ? $end['second'] : null,
609
				'end_date' => $row['end_date'],
610
				'end_date_local' => $end['date_local'],
611
				'end_date_orig' => $end['date_orig'],
612
				'end_time' => !$allday ? $row['end_time'] : null,
613
				'end_time_local' => !$allday ? $end['time_local'] : null,
614
				'end_time_orig' => !$allday ? $end['time_orig'] : null,
615
				'end_timestamp' => $end['timestamp'],
616
				'end_iso_gmdate' => $end['iso_gmdate'],
617
				'allday' => $allday,
618
				'tz' => !$allday ? $tz : null,
619
				'tz_abbrev' => !$allday ? $tz_abbrev : null,
620
				'span' => $span,
621
				'location' => $row['location'],
622
				'is_last' => false
623
			);
624
625
			$context['linked_calendar_events'][] = $linked_calendar_event;
626
		}
627
		$smcFunc['db_free_result']($request);
628
629
		if (!empty($context['linked_calendar_events']))
630
			$context['linked_calendar_events'][count($context['linked_calendar_events']) - 1]['is_last'] = true;
631
	}
632
633
	// Create the poll info if it exists.
634
	if ($context['is_poll'])
635
	{
636
		// Get the question and if it's locked.
637
		$request = $smcFunc['db_query']('', '
638
			SELECT
639
				p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.change_vote,
640
				p.guest_vote, p.id_member, COALESCE(mem.real_name, p.poster_name) AS poster_name, p.num_guest_voters, p.reset_poll
641
			FROM {db_prefix}polls AS p
642
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = p.id_member)
643
			WHERE p.id_poll = {int:id_poll}
644
			LIMIT 1',
645
			array(
646
				'id_poll' => $context['topicinfo']['id_poll'],
647
			)
648
		);
649
		$pollinfo = $smcFunc['db_fetch_assoc']($request);
650
		$smcFunc['db_free_result']($request);
651
	}
652
653
	// Create the poll info if it exists and is valid.
654
	if ($context['is_poll'] && empty($pollinfo))
655
		$context['is_poll'] = false;
656
	elseif ($context['is_poll'])
657
	{
658
		$request = $smcFunc['db_query']('', '
659
			SELECT COUNT(DISTINCT id_member) AS total
660
			FROM {db_prefix}log_polls
661
			WHERE id_poll = {int:id_poll}
662
				AND id_member != {int:not_guest}',
663
			array(
664
				'id_poll' => $context['topicinfo']['id_poll'],
665
				'not_guest' => 0,
666
			)
667
		);
668
		list ($pollinfo['total']) = $smcFunc['db_fetch_row']($request);
669
		$smcFunc['db_free_result']($request);
670
671
		// Total voters needs to include guest voters
672
		$pollinfo['total'] += $pollinfo['num_guest_voters'];
673
674
		// Get all the options, and calculate the total votes.
675
		$request = $smcFunc['db_query']('', '
676
			SELECT pc.id_choice, pc.label, pc.votes, COALESCE(lp.id_choice, -1) AS voted_this
677
			FROM {db_prefix}poll_choices AS pc
678
				LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_choice = pc.id_choice AND lp.id_poll = {int:id_poll} AND lp.id_member = {int:current_member} AND lp.id_member != {int:not_guest})
679
			WHERE pc.id_poll = {int:id_poll}
680
			ORDER BY pc.id_choice',
681
			array(
682
				'current_member' => $user_info['id'],
683
				'id_poll' => $context['topicinfo']['id_poll'],
684
				'not_guest' => 0,
685
			)
686
		);
687
		$pollOptions = array();
688
		$realtotal = 0;
689
		$pollinfo['has_voted'] = false;
690
		while ($row = $smcFunc['db_fetch_assoc']($request))
691
		{
692
			censorText($row['label']);
693
			$pollOptions[$row['id_choice']] = $row;
694
			$realtotal += $row['votes'];
695
			$pollinfo['has_voted'] |= $row['voted_this'] != -1;
696
		}
697
		$smcFunc['db_free_result']($request);
698
699
		// Got we multi choice?
700
		if ($pollinfo['max_votes'] > 1)
701
			$realtotal = $pollinfo['total'];
702
703
		// If this is a guest we need to do our best to work out if they have voted, and what they voted for.
704
		if ($user_info['is_guest'] && $pollinfo['guest_vote'] && allowedTo('poll_vote'))
705
		{
706
			if (!empty($_COOKIE['guest_poll_vote']) && preg_match('~^[0-9,;]+$~', $_COOKIE['guest_poll_vote']) && strpos($_COOKIE['guest_poll_vote'], ';' . $context['topicinfo']['id_poll'] . ',') !== false)
707
			{
708
				// ;id,timestamp,[vote,vote...]; etc
709
				$guestinfo = explode(';', $_COOKIE['guest_poll_vote']);
710
				// Find the poll we're after.
711
				foreach ($guestinfo as $i => $guestvoted)
712
				{
713
					$guestvoted = explode(',', $guestvoted);
714
					if ($guestvoted[0] == $context['topicinfo']['id_poll'])
715
						break;
716
				}
717
				// Has the poll been reset since guest voted?
718
				if ($pollinfo['reset_poll'] > $guestvoted[1])
719
				{
720
					// Remove the poll info from the cookie to allow guest to vote again
721
					unset($guestinfo[$i]);
722
					if (!empty($guestinfo))
723
						$_COOKIE['guest_poll_vote'] = ';' . implode(';', $guestinfo);
724
					else
725
						unset($_COOKIE['guest_poll_vote']);
726
				}
727
				else
728
				{
729
					// What did they vote for?
730
					unset($guestvoted[0], $guestvoted[1]);
731
					foreach ($pollOptions as $choice => $details)
732
					{
733
						$pollOptions[$choice]['voted_this'] = in_array($choice, $guestvoted) ? 1 : -1;
734
						$pollinfo['has_voted'] |= $pollOptions[$choice]['voted_this'] != -1;
735
					}
736
					unset($choice, $details, $guestvoted);
737
				}
738
				unset($guestinfo, $guestvoted, $i);
739
			}
740
		}
741
742
		// Set up the basic poll information.
743
		$context['poll'] = array(
744
			'id' => $context['topicinfo']['id_poll'],
745
			'image' => 'normal_' . (empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll'),
746
			'question' => parse_bbc($pollinfo['question']),
747
			'total_votes' => $pollinfo['total'],
748
			'change_vote' => !empty($pollinfo['change_vote']),
749
			'is_locked' => !empty($pollinfo['voting_locked']),
750
			'options' => array(),
751
			'lock' => allowedTo('poll_lock_any') || ($context['user']['started'] && allowedTo('poll_lock_own')),
752
			'edit' => allowedTo('poll_edit_any') || ($context['user']['started'] && allowedTo('poll_edit_own')),
753
			'remove' => allowedTo('poll_remove_any') || ($context['user']['started'] && allowedTo('poll_remove_own')),
754
			'allowed_warning' => $pollinfo['max_votes'] > 1 ? sprintf($txt['poll_options_limit'], min(count($pollOptions), $pollinfo['max_votes'])) : '',
755
			'is_expired' => !empty($pollinfo['expire_time']) && $pollinfo['expire_time'] < time(),
756
			'expire_time' => !empty($pollinfo['expire_time']) ? timeformat($pollinfo['expire_time']) : 0,
757
			'has_voted' => !empty($pollinfo['has_voted']),
758
			'starter' => array(
759
				'id' => $pollinfo['id_member'],
760
				'name' => $row['poster_name'],
761
				'href' => $pollinfo['id_member'] == 0 ? '' : $scripturl . '?action=profile;u=' . $pollinfo['id_member'],
762
				'link' => $pollinfo['id_member'] == 0 ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $pollinfo['id_member'] . '">' . $row['poster_name'] . '</a>'
763
			)
764
		);
765
766
		// Make the lock, edit and remove permissions defined above more directly accessible.
767
		$context['allow_lock_poll'] = $context['poll']['lock'];
768
		$context['allow_edit_poll'] = $context['poll']['edit'];
769
		$context['can_remove_poll'] = $context['poll']['remove'];
770
771
		// You're allowed to vote if:
772
		// 1. the poll did not expire, and
773
		// 2. you're either not a guest OR guest voting is enabled... and
774
		// 3. you're not trying to view the results, and
775
		// 4. the poll is not locked, and
776
		// 5. you have the proper permissions, and
777
		// 6. you haven't already voted before.
778
		$context['allow_vote'] = !$context['poll']['is_expired'] && (!$user_info['is_guest'] || ($pollinfo['guest_vote'] && allowedTo('poll_vote'))) && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && !$context['poll']['has_voted'];
779
780
		// You're allowed to view the results if:
781
		// 1. you're just a super-nice-guy, or
782
		// 2. anyone can see them (hide_results == 0), or
783
		// 3. you can see them after you voted (hide_results == 1), or
784
		// 4. you've waited long enough for the poll to expire. (whether hide_results is 1 or 2.)
785
		$context['allow_results_view'] = allowedTo('moderate_board') || $pollinfo['hide_results'] == 0 || ($pollinfo['hide_results'] == 1 && $context['poll']['has_voted']) || $context['poll']['is_expired'];
786
787
		// Show the results if:
788
		// 1. You're allowed to see them (see above), and
789
		// 2. $_REQUEST['viewresults'] or $_REQUEST['viewResults'] is set
790
		$context['poll']['show_results'] = $context['allow_results_view'] && (isset($_REQUEST['viewresults']) || isset($_REQUEST['viewResults']));
791
792
		// Show the button if:
793
		// 1. You can vote in the poll (see above), and
794
		// 2. Results are visible to everyone (hidden = 0), and
795
		// 3. You aren't already viewing the results
796
		$context['show_view_results_button'] = $context['allow_vote'] && $context['allow_results_view'] && !$context['poll']['show_results'];
797
798
		// You're allowed to change your vote if:
799
		// 1. the poll did not expire, and
800
		// 2. you're not a guest... and
801
		// 3. the poll is not locked, and
802
		// 4. you have the proper permissions, and
803
		// 5. you have already voted, and
804
		// 6. the poll creator has said you can!
805
		$context['allow_change_vote'] = !$context['poll']['is_expired'] && !$user_info['is_guest'] && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && $context['poll']['has_voted'] && $context['poll']['change_vote'];
806
807
		// You're allowed to return to voting options if:
808
		// 1. you are (still) allowed to vote.
809
		// 2. you are currently seeing the results.
810
		$context['allow_return_vote'] = $context['allow_vote'] && $context['poll']['show_results'];
811
812
		// Calculate the percentages and bar lengths...
813
		$divisor = $realtotal == 0 ? 1 : $realtotal;
814
815
		// Determine if a decimal point is needed in order for the options to add to 100%.
816
		$precision = $realtotal == 100 ? 0 : 1;
817
818
		// Now look through each option, and...
819
		foreach ($pollOptions as $i => $option)
820
		{
821
			// First calculate the percentage, and then the width of the bar...
822
			$bar = round(($option['votes'] * 100) / $divisor, $precision);
823
			$barWide = $bar == 0 ? 1 : floor(($bar * 8) / 3);
824
825
			// Now add it to the poll's contextual theme data.
826
			$context['poll']['options'][$i] = array(
827
				'id' => 'options-' . $i,
828
				'percent' => $bar,
829
				'votes' => $option['votes'],
830
				'voted_this' => $option['voted_this'] != -1,
831
				'bar_ndt' => $bar > 0 ? '<div class="bar" style="width: ' . $bar . '%;"></div>' : '',
832
				'bar_width' => $barWide,
833
				'option' => parse_bbc($option['label']),
834
				'vote_button' => '<input type="' . ($pollinfo['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '">'
835
			);
836
		}
837
838
		// Build the poll moderation button array.
839
		$context['poll_buttons'] = array();
840
841
		if ($context['allow_return_vote'])
842
			$context['poll_buttons']['vote'] = array('text' => 'poll_return_vote', 'image' => 'poll_options.png', 'url' => $scripturl . '?topic=' . $context['current_topic'] . '.' . $context['start']);
843
844
		if ($context['show_view_results_button'])
845
			$context['poll_buttons']['results'] = array('text' => 'poll_results', 'image' => 'poll_results.png', 'url' => $scripturl . '?topic=' . $context['current_topic'] . '.' . $context['start'] . ';viewresults');
846
847
		if ($context['allow_change_vote'])
848
			$context['poll_buttons']['change_vote'] = array('text' => 'poll_change_vote', 'image' => 'poll_change_vote.png', 'url' => $scripturl . '?action=vote;topic=' . $context['current_topic'] . '.' . $context['start'] . ';poll=' . $context['poll']['id'] . ';' . $context['session_var'] . '=' . $context['session_id']);
849
850
		if ($context['allow_lock_poll'])
851
			$context['poll_buttons']['lock'] = array('text' => (!$context['poll']['is_locked'] ? 'poll_lock' : 'poll_unlock'), 'image' => 'poll_lock.png', 'url' => $scripturl . '?action=lockvoting;topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']);
852
853
		if ($context['allow_edit_poll'])
854
			$context['poll_buttons']['edit'] = array('text' => 'poll_edit', 'image' => 'poll_edit.png', 'url' => $scripturl . '?action=editpoll;topic=' . $context['current_topic'] . '.' . $context['start']);
855
856
		if ($context['can_remove_poll'])
857
			$context['poll_buttons']['remove_poll'] = array('text' => 'poll_remove', 'image' => 'admin_remove_poll.png', 'custom' => 'data-confirm="' . $txt['poll_remove_warn'] . '"', 'class' => 'you_sure', 'url' => $scripturl . '?action=removepoll;topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']);
858
859
		// Allow mods to add additional buttons here
860
		call_integration_hook('integrate_poll_buttons');
861
	}
862
863
	$start = $_REQUEST['start'];
864
	$ascending = empty($options['view_newest_first']);
865
866
	// Check if we can use the seek method to speed things up
867
	if (isset($_SESSION['page_topic']) && $_SESSION['page_topic'] == $topic && $_SESSION['page_ascending'] == $ascending)
868
	{
869
		// User moved to the next page
870
		if (isset($_SESSION['page_next_start']) && $_SESSION['page_next_start'] == $start)
871
		{
872
			$start_char = 'M';
873
			$page_id = $_SESSION['page_last_id'];
874
		}
875
		// User moved to the previous page
876
		elseif (isset($_SESSION['page_before_start']) && $_SESSION['page_before_start'] == $start)
877
		{
878
			$start_char = 'L';
879
			$page_id = $_SESSION['page_first_id'];
880
		}
881
		// User refreshed the current page
882
		elseif (isset($_SESSION['page_current_start']) && $_SESSION['page_current_start'] == $start)
883
		{
884
			$start_char = 'C';
885
			$page_id = $_SESSION['page_first_id'];
886
		}
887
	}
888
	// Special case start page
889
	elseif ($start == 0)
890
	{
891
		$start_char = 'C';
892
		$page_id = $ascending ? $context['topicinfo']['id_first_msg'] : $context['topicinfo']['id_last_msg'];
893
	}
894
	else
895
		$start_char = null;
896
897
	$limit = $context['messages_per_page'];
898
899
	$messages = array();
900
	$all_posters = array();
901
	$firstIndex = 0;
902
903
	if (isset($start_char))
904
	{
905
		if ($start_char === 'M' || $start_char === 'C')
906
		{
907
			$DBascending = $ascending;
908
			$page_operator = $ascending ? '>=' : '<=';
909
		}
910
		else
911
		{
912
			$DBascending = !$ascending;
913
			$page_operator = $ascending ? '<=' : '>=';
914
		}
915
916
		if ($start_char === 'C')
917
			$limit_seek = $limit;
918
		else
919
			$limit_seek = $limit + 1;
920
921
		$request = $smcFunc['db_query']('', '
922
			SELECT id_msg, id_member, approved
923
			FROM {db_prefix}messages
924
			WHERE id_topic = {int:current_topic}
925
				AND id_msg ' . $page_operator . ' {int:page_id}' . (!$modSettings['postmod_active'] || $can_approve_posts ? '' : '
926
				AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')') . '
927
			ORDER BY id_msg ' . ($DBascending ? '' : 'DESC') . ($context['messages_per_page'] == -1 ? '' : '
928
			LIMIT {int:limit}'),
929
			array(
930
				'current_member' => $user_info['id'],
931
				'current_topic' => $topic,
932
				'is_approved' => 1,
933
				'blank_id_member' => 0,
934
				'limit' => $limit_seek,
935
				'page_id' => $page_id,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $page_id does not seem to be defined for all execution paths leading up to this point.
Loading history...
936
			)
937
		);
938
939
		$found_msg = false;
940
941
		// Fallback
942
		if ($smcFunc['db_num_rows']($request) < 1)
943
			unset($start_char);
944
		else
945
		{
946
			while ($row = $smcFunc['db_fetch_assoc']($request))
947
			{
948
				// Check if the start msg is in our result
949
				if ($row['id_msg'] == $page_id)
950
					$found_msg = true;
951
952
				// Skip the the start msg if we not in mode C
953
				if ($start_char === 'C' || $row['id_msg'] != $page_id)
954
				{
955
					if (!empty($row['id_member']))
956
						$all_posters[$row['id_msg']] = $row['id_member'];
957
958
					$messages[] = $row['id_msg'];
959
				}
960
			}
961
962
			// page_id not found? -> fallback
963
			if (!$found_msg)
964
			{
965
				$messages = array();
966
				$all_posters = array();
967
				unset($start_char);
968
			}
969
		}
970
971
		// Before Page bring in the right order
972
		if (!empty($start_char) && $start_char === 'L')
973
			krsort($messages);
974
	}
975
976
	// Jump to page
977
	if (empty($start_char))
978
	{
979
		// Calculate the fastest way to get the messages!
980
		if ($start >= $context['total_visible_posts'] / 2 && $context['messages_per_page'] != -1)
981
		{
982
			$DBascending = !$ascending;
983
			$limit = $context['total_visible_posts'] <= $start + $limit ? $context['total_visible_posts'] - $start : $limit;
984
			$start = $context['total_visible_posts'] <= $start + $limit ? 0 : $context['total_visible_posts'] - $start - $limit;
985
			$firstIndex = empty($options['view_newest_first']) ? $start - 1 : $limit - 1;
986
		}
987
		else
988
			$DBascending = $ascending;
989
990
		// Get each post and poster in this topic.
991
		$request = $smcFunc['db_query']('', '
992
			SELECT id_msg, id_member, approved
993
			FROM {db_prefix}messages
994
			WHERE id_topic = {int:current_topic}' . (!$modSettings['postmod_active'] || $can_approve_posts ? '' : '
995
				AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')') . '
996
			ORDER BY id_msg ' . ($DBascending ? '' : 'DESC') . ($context['messages_per_page'] == -1 ? '' : '
997
			LIMIT {int:start}, {int:max}'),
998
			array(
999
				'current_member' => $user_info['id'],
1000
				'current_topic' => $topic,
1001
				'is_approved' => 1,
1002
				'blank_id_member' => 0,
1003
				'start' => $start,
1004
				'max' => $limit,
1005
			)
1006
		);
1007
1008
		while ($row = $smcFunc['db_fetch_assoc']($request))
1009
		{
1010
			if (!empty($row['id_member']))
1011
				$all_posters[$row['id_msg']] = $row['id_member'];
1012
			$messages[] = $row['id_msg'];
1013
		}
1014
1015
		// Sort the messages into the correct display order
1016
		if (!$DBascending)
1017
			sort($messages);
1018
	}
1019
1020
	// Remember the paging data for next time
1021
	$_SESSION['page_first_id'] = $ascending ? reset($messages) : end($messages);
1022
	$_SESSION['page_before_start'] = $_REQUEST['start'] - $limit;
1023
	$_SESSION['page_last_id'] = $ascending ? end($messages) : reset($messages);
1024
	$_SESSION['page_next_start'] = $_REQUEST['start'] + $limit;
1025
	$_SESSION['page_current_start'] = $_REQUEST['start'];
1026
	$_SESSION['page_topic'] = $topic;
1027
	$_SESSION['page_ascending'] = $ascending;
1028
1029
	$smcFunc['db_free_result']($request);
1030
	$posters = array_unique($all_posters);
1031
1032
	call_integration_hook('integrate_display_message_list', array(&$messages, &$posters));
1033
1034
	// Guests can't mark topics read or for notifications, just can't sorry.
1035
	if (!$user_info['is_guest'] && !empty($messages))
1036
	{
1037
		$mark_at_msg = max($messages);
1038
		if ($mark_at_msg >= $context['topicinfo']['id_last_msg'])
1039
			$mark_at_msg = $modSettings['maxMsgID'];
1040
		if ($mark_at_msg >= $context['topicinfo']['new_from'])
1041
		{
1042
			$smcFunc['db_insert']($context['topicinfo']['new_from'] == 0 ? 'ignore' : 'replace',
1043
				'{db_prefix}log_topics',
1044
				array(
1045
					'id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int',
1046
				),
1047
				array(
1048
					$user_info['id'], $topic, $mark_at_msg, $context['topicinfo']['unwatched'],
1049
				),
1050
				array('id_member', 'id_topic')
1051
			);
1052
		}
1053
1054
		// Check for notifications on this topic OR board.
1055
		$request = $smcFunc['db_query']('', '
1056
			SELECT sent, id_topic
1057
			FROM {db_prefix}log_notify
1058
			WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
1059
				AND id_member = {int:current_member}
1060
			LIMIT 2',
1061
			array(
1062
				'current_board' => $board,
1063
				'current_member' => $user_info['id'],
1064
				'current_topic' => $topic,
1065
			)
1066
		);
1067
		$do_once = true;
1068
		while ($row = $smcFunc['db_fetch_assoc']($request))
1069
		{
1070
			// Find if this topic is marked for notification...
1071
			if (!empty($row['id_topic']))
1072
				$context['is_marked_notify'] = true;
1073
1074
			// Only do this once, but mark the notifications as "not sent yet" for next time.
1075
			if (!empty($row['sent']) && $do_once)
1076
			{
1077
				$smcFunc['db_query']('', '
1078
					UPDATE {db_prefix}log_notify
1079
					SET sent = {int:is_not_sent}
1080
					WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
1081
						AND id_member = {int:current_member}',
1082
					array(
1083
						'current_board' => $board,
1084
						'current_member' => $user_info['id'],
1085
						'current_topic' => $topic,
1086
						'is_not_sent' => 0,
1087
					)
1088
				);
1089
				$do_once = false;
1090
			}
1091
		}
1092
1093
		// Have we recently cached the number of new topics in this board, and it's still a lot?
1094
		if (isset($_REQUEST['topicseen']) && isset($_SESSION['topicseen_cache'][$board]) && $_SESSION['topicseen_cache'][$board] > 5)
1095
			$_SESSION['topicseen_cache'][$board]--;
1096
		// Mark board as seen if this is the only new topic.
1097
		elseif (isset($_REQUEST['topicseen']))
1098
		{
1099
			// Use the mark read tables... and the last visit to figure out if this should be read or not.
1100
			$request = $smcFunc['db_query']('', '
1101
				SELECT COUNT(*)
1102
				FROM {db_prefix}topics AS t
1103
					LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = {int:current_board} AND lb.id_member = {int:current_member})
1104
					LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
1105
				WHERE t.id_board = {int:current_board}
1106
					AND t.id_last_msg > COALESCE(lb.id_msg, 0)
1107
					AND t.id_last_msg > COALESCE(lt.id_msg, 0)' . (empty($_SESSION['id_msg_last_visit']) ? '' : '
1108
					AND t.id_last_msg > {int:id_msg_last_visit}'),
1109
				array(
1110
					'current_board' => $board,
1111
					'current_member' => $user_info['id'],
1112
					'id_msg_last_visit' => (int) $_SESSION['id_msg_last_visit'],
1113
				)
1114
			);
1115
			list ($numNewTopics) = $smcFunc['db_fetch_row']($request);
1116
			$smcFunc['db_free_result']($request);
1117
1118
			// If there're no real new topics in this board, mark the board as seen.
1119
			if (empty($numNewTopics))
1120
				$_REQUEST['boardseen'] = true;
1121
			else
1122
				$_SESSION['topicseen_cache'][$board] = $numNewTopics;
1123
		}
1124
		// Probably one less topic - maybe not, but even if we decrease this too fast it will only make us look more often.
1125
		elseif (isset($_SESSION['topicseen_cache'][$board]))
1126
			$_SESSION['topicseen_cache'][$board]--;
1127
1128
		// Mark board as seen if we came using last post link from BoardIndex. (or other places...)
1129
		if (isset($_REQUEST['boardseen']))
1130
		{
1131
			$smcFunc['db_insert']('replace',
1132
				'{db_prefix}log_boards',
1133
				array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
1134
				array($modSettings['maxMsgID'], $user_info['id'], $board),
1135
				array('id_member', 'id_board')
1136
			);
1137
		}
1138
1139
		// Mark any alerts about this topic or the posts on this page as read.
1140
		if (!empty($user_info['alerts']))
1141
		{
1142
			$smcFunc['db_query']('', '
1143
				UPDATE {db_prefix}user_alerts
1144
				SET is_read = {int:now}
1145
				WHERE is_read = 0 AND id_member = {int:current_member}
1146
					AND
1147
					(
1148
						(content_id IN ({array_int:messages}) AND content_type = {string:msg})
1149
						OR
1150
						(content_id = {int:current_topic} AND (content_type = {string:topic} OR (content_type = {string:board} AND content_action = {string:topic})))
1151
					)',
1152
				array(
1153
					'topic' => 'topic',
1154
					'board' => 'board',
1155
					'msg' => 'msg',
1156
					'current_member' => $user_info['id'],
1157
					'current_topic' => $topic,
1158
					'messages' => $messages,
1159
					'now' => time(),
1160
				)
1161
			);
1162
			$user_info['alerts'] = $user_info['alerts'] - max(0, $smcFunc['db_affected_rows']());
1163
			updateMemberData($user_info['id'], array('alerts' => $user_info['alerts']));
1164
		}
1165
	}
1166
1167
	// Get notification preferences
1168
	$context['topicinfo']['notify_prefs'] = array();
1169
	if (!empty($user_info['id']))
1170
	{
1171
		require_once($sourcedir . '/Subs-Notify.php');
1172
		$prefs = getNotifyPrefs($user_info['id'], array('topic_notify', 'topic_notify_' . $context['current_topic']), true);
1173
		$pref = !empty($prefs[$user_info['id']]) && $context['is_marked_notify'] ? $prefs[$user_info['id']] : array();
1174
		$context['topicinfo']['notify_prefs'] = array(
1175
			'is_custom' => isset($pref['topic_notify_' . $topic]),
1176
			'pref' => isset($pref['topic_notify_' . $context['current_topic']]) ? $pref['topic_notify_' . $context['current_topic']] : (!empty($pref['topic_notify']) ? $pref['topic_notify'] : 0),
1177
		);
1178
	}
1179
1180
	$context['topic_notification'] = !empty($user_info['id']) ? $context['topicinfo']['notify_prefs'] : array();
1181
	// 0 => unwatched, 1 => normal, 2 => receive alerts, 3 => receive emails
1182
	$context['topic_notification_mode'] = !$user_info['is_guest'] ? ($context['topic_unwatched'] ? 0 : ($context['topicinfo']['notify_prefs']['pref'] & 0x02 ? 3 : ($context['topicinfo']['notify_prefs']['pref'] & 0x01 ? 2 : 1))) : 0;
1183
1184
	$context['loaded_attachments'] = array();
1185
1186
	// If there _are_ messages here... (probably an error otherwise :!)
1187
	if (!empty($messages))
1188
	{
1189
		// Fetch attachments.
1190
		if (!empty($modSettings['attachmentEnable']) && allowedTo('view_attachments'))
1191
		{
1192
			require_once($sourcedir . '/Subs-Attachments.php');
1193
			prepareAttachsByMsg($messages);
1194
		}
1195
1196
		$msg_parameters = array(
1197
			'message_list' => $messages,
1198
			'new_from' => $context['topicinfo']['new_from'],
1199
		);
1200
		$msg_selects = array();
1201
		$msg_tables = array();
1202
		call_integration_hook('integrate_query_message', array(&$msg_selects, &$msg_tables, &$msg_parameters));
1203
1204
		// What?  It's not like it *couldn't* be only guests in this topic...
1205
		loadMemberData($posters);
1206
		$messages_request = $smcFunc['db_query']('', '
1207
			SELECT
1208
				id_msg, icon, subject, poster_time, poster_ip, id_member, modified_time, modified_name, modified_reason, body,
1209
				smileys_enabled, poster_name, poster_email, approved, likes,
1210
				id_msg_modified < {int:new_from} AS is_read
1211
				' . (!empty($msg_selects) ? (', ' . implode(', ', $msg_selects)) : '') . '
1212
			FROM {db_prefix}messages
1213
				' . (!empty($msg_tables) ? implode("\n\t", $msg_tables) : '') . '
1214
			WHERE id_msg IN ({array_int:message_list})
1215
			ORDER BY id_msg' . (empty($options['view_newest_first']) ? '' : ' DESC'),
1216
			$msg_parameters
1217
		);
1218
1219
		// And the likes
1220
		if (!empty($modSettings['enable_likes']))
1221
			$context['my_likes'] = $context['user']['is_guest'] ? array() : prepareLikesContext($topic);
1222
1223
		// Go to the last message if the given time is beyond the time of the last message.
1224
		if (isset($context['start_from']) && $context['start_from'] >= $context['topicinfo']['num_replies'])
1225
			$context['start_from'] = $context['topicinfo']['num_replies'];
1226
1227
		// Since the anchor information is needed on the top of the page we load these variables beforehand.
1228
		$context['first_message'] = isset($messages[$firstIndex]) ? $messages[$firstIndex] : $messages[0];
1229
		if (empty($options['view_newest_first']))
1230
			$context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $context['start_from'];
1231
		else
1232
			$context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $context['topicinfo']['num_replies'] - $context['start_from'];
1233
	}
1234
	else
1235
	{
1236
		$messages_request = false;
1237
		$context['first_message'] = 0;
1238
		$context['first_new_message'] = false;
1239
1240
		$context['likes'] = array();
1241
	}
1242
1243
	$context['jump_to'] = array(
1244
		'label' => addslashes(un_htmlspecialchars($txt['jump_to'])),
1245
		'board_name' => $smcFunc['htmlspecialchars'](strtr(strip_tags($board_info['name']), array('&amp;' => '&'))),
1246
		'child_level' => $board_info['child_level'],
1247
	);
1248
1249
	// Set the callback.  (do you REALIZE how much memory all the messages would take?!?)
1250
	// This will be called from the template.
1251
	$context['get_message'] = 'prepareDisplayContext';
1252
1253
	// Now set all the wonderful, wonderful permissions... like moderation ones...
1254
	$common_permissions = array(
1255
		'can_approve' => 'approve_posts',
1256
		'can_ban' => 'manage_bans',
1257
		'can_sticky' => 'make_sticky',
1258
		'can_merge' => 'merge_any',
1259
		'can_split' => 'split_any',
1260
		'calendar_post' => 'calendar_post',
1261
		'can_send_pm' => 'pm_send',
1262
		'can_report_moderator' => 'report_any',
1263
		'can_moderate_forum' => 'moderate_forum',
1264
		'can_issue_warning' => 'issue_warning',
1265
		'can_restore_topic' => 'move_any',
1266
		'can_restore_msg' => 'move_any',
1267
		'can_like' => 'likes_like',
1268
	);
1269
	foreach ($common_permissions as $contextual => $perm)
1270
		$context[$contextual] = allowedTo($perm);
1271
1272
	// Permissions with _any/_own versions.  $context[YYY] => ZZZ_any/_own.
1273
	$anyown_permissions = array(
1274
		'can_move' => 'move',
1275
		'can_lock' => 'lock',
1276
		'can_delete' => 'remove',
1277
		'can_add_poll' => 'poll_add',
1278
		'can_remove_poll' => 'poll_remove',
1279
		'can_reply' => 'post_reply',
1280
		'can_reply_unapproved' => 'post_unapproved_replies',
1281
		'can_view_warning' => 'profile_warning',
1282
	);
1283
	foreach ($anyown_permissions as $contextual => $perm)
1284
		$context[$contextual] = allowedTo($perm . '_any') || ($context['user']['started'] && allowedTo($perm . '_own'));
1285
1286
	if (!$user_info['is_admin'] && $context['can_move'] && !$modSettings['topic_move_any'])
1287
	{
1288
		// We'll use this in a minute
1289
		$boards_allowed = array_diff(boardsAllowedTo('post_new'), array($board));
1290
1291
		/* You can't move this unless you have permission
1292
			to start new topics on at least one other board */
1293
		$context['can_move'] = count($boards_allowed) > 1;
1294
	}
1295
1296
	// If a topic is locked, you can't remove it unless it's yours and you locked it or you can lock_any
1297
	if ($context['topicinfo']['locked'])
1298
	{
1299
		$context['can_delete'] &= (($context['topicinfo']['locked'] == 1 && $context['user']['started']) || allowedTo('lock_any'));
1300
	}
1301
1302
	// Cleanup all the permissions with extra stuff...
1303
	$context['can_mark_notify'] = !$context['user']['is_guest'];
1304
	$context['calendar_post'] &= !empty($modSettings['cal_enabled']);
1305
	$context['can_add_poll'] &= $modSettings['pollMode'] == '1' && $context['topicinfo']['id_poll'] <= 0;
1306
	$context['can_remove_poll'] &= $modSettings['pollMode'] == '1' && $context['topicinfo']['id_poll'] > 0;
1307
	$context['can_reply'] &= empty($context['topicinfo']['locked']) || allowedTo('moderate_board');
1308
	$context['can_reply_unapproved'] &= $modSettings['postmod_active'] && (empty($context['topicinfo']['locked']) || allowedTo('moderate_board'));
1309
	$context['can_issue_warning'] &= $modSettings['warning_settings'][0] == 1;
1310
	// Handle approval flags...
1311
	$context['can_reply_approved'] = $context['can_reply'];
1312
	$context['can_reply'] |= $context['can_reply_unapproved'];
1313
	$context['can_quote'] = $context['can_reply'] && (empty($modSettings['disabledBBC']) || !in_array('quote', explode(',', $modSettings['disabledBBC'])));
1314
	$context['can_mark_unread'] = !$user_info['is_guest'];
1315
	$context['can_unwatch'] = !$user_info['is_guest'];
1316
	$context['can_set_notify'] = !$user_info['is_guest'];
1317
1318
	$context['can_print'] = empty($modSettings['disable_print_topic']);
1319
1320
	// Start this off for quick moderation - it will be or'd for each post.
1321
	$context['can_remove_post'] = allowedTo('delete_any') || (allowedTo('delete_replies') && $context['user']['started']);
1322
1323
	// Can restore topic?  That's if the topic is in the recycle board and has a previous restore state.
1324
	$context['can_restore_topic'] &= !empty($board_info['recycle']) && !empty($context['topicinfo']['id_previous_board']);
1325
	$context['can_restore_msg'] &= !empty($board_info['recycle']) && !empty($context['topicinfo']['id_previous_topic']);
1326
1327
	// Check if the draft functions are enabled and that they have permission to use them (for quick reply.)
1328
	$context['drafts_save'] = !empty($modSettings['drafts_post_enabled']) && allowedTo('post_draft') && $context['can_reply'];
1329
	$context['drafts_autosave'] = !empty($context['drafts_save']) && !empty($modSettings['drafts_autosave_enabled']);
1330
	if (!empty($context['drafts_save']))
1331
		loadLanguage('Drafts');
1332
1333
	// When was the last time this topic was replied to?  Should we warn them about it?
1334
	if (!empty($modSettings['oldTopicDays']) && ($context['can_reply'] || $context['can_reply_unapproved']) && empty($context['topicinfo']['is_sticky']))
1335
	{
1336
		$request = $smcFunc['db_query']('', '
1337
			SELECT poster_time
1338
			FROM {db_prefix}messages
1339
			WHERE id_msg = {int:id_last_msg}
1340
			LIMIT 1',
1341
			array(
1342
				'id_last_msg' => $context['topicinfo']['id_last_msg'],
1343
			)
1344
		);
1345
1346
		list ($lastPostTime) = $smcFunc['db_fetch_row']($request);
1347
		$smcFunc['db_free_result']($request);
1348
1349
		$context['oldTopicError'] = $lastPostTime + $modSettings['oldTopicDays'] * 86400 < time();
1350
	}
1351
1352
	// You can't link an existing topic to the calendar unless you can modify the first post...
1353
	$context['calendar_post'] &= allowedTo('modify_any') || (allowedTo('modify_own') && $context['user']['started']);
1354
1355
	// Load up the "double post" sequencing magic.
1356
	checkSubmitOnce('register');
1357
	$context['name'] = isset($_SESSION['guest_name']) ? $_SESSION['guest_name'] : '';
1358
	$context['email'] = isset($_SESSION['guest_email']) ? $_SESSION['guest_email'] : '';
1359
	// Needed for the editor and message icons.
1360
	require_once($sourcedir . '/Subs-Editor.php');
1361
1362
	// Now create the editor.
1363
	$editorOptions = array(
1364
		'id' => 'quickReply',
1365
		'value' => '',
1366
		'labels' => array(
1367
			'post_button' => $txt['post'],
1368
		),
1369
		// add height and width for the editor
1370
		'height' => '150px',
1371
		'width' => '100%',
1372
		// We do HTML preview here.
1373
		'preview_type' => 1,
1374
		// This is required
1375
		'required' => true,
1376
	);
1377
	create_control_richedit($editorOptions);
1378
1379
	// Store the ID.
1380
	$context['post_box_name'] = $editorOptions['id'];
1381
1382
	$context['attached'] = '';
1383
	$context['make_poll'] = isset($_REQUEST['poll']);
1384
1385
	// Message icons - customized icons are off?
1386
	$context['icons'] = getMessageIcons($board);
1387
1388
	if (!empty($context['icons']))
1389
		$context['icons'][count($context['icons']) - 1]['is_last'] = true;
1390
1391
	// Build the normal button array.
1392
	$context['normal_buttons'] = array();
1393
1394
	if ($context['can_reply'])
1395
		$context['normal_buttons']['reply'] = array('text' => 'reply', 'url' => $scripturl . '?action=post;topic=' . $context['current_topic'] . '.' . $context['start'] . ';last_msg=' . $context['topic_last_message'], 'active' => true);
1396
1397
	if ($context['can_add_poll'])
1398
		$context['normal_buttons']['add_poll'] = array('text' => 'add_poll', 'url' => $scripturl . '?action=editpoll;add;topic=' . $context['current_topic'] . '.' . $context['start']);
1399
1400
	if ($context['can_mark_unread'])
1401
		$context['normal_buttons']['mark_unread'] = array('text' => 'mark_unread', 'url' => $scripturl . '?action=markasread;sa=topic;t=' . $context['mark_unread_time'] . ';topic=' . $context['current_topic'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']);
1402
1403
	if ($context['can_print'])
1404
		$context['normal_buttons']['print'] = array('text' => 'print', 'custom' => 'rel="nofollow"', 'url' => $scripturl . '?action=printpage;topic=' . $context['current_topic'] . '.0');
1405
1406
	if ($context['can_set_notify'])
1407
		$context['normal_buttons']['notify'] = array(
1408
			'text' => 'notify_topic_' . $context['topic_notification_mode'],
1409
			'sub_buttons' => array(
1410
				array(
1411
					'test' => 'can_unwatch',
1412
					'text' => 'notify_topic_0',
1413
					'url' => $scripturl . '?action=notifytopic;topic=' . $context['current_topic'] . ';mode=0;' . $context['session_var'] . '=' . $context['session_id'],
1414
				),
1415
				array(
1416
					'text' => 'notify_topic_1',
1417
					'url' => $scripturl . '?action=notifytopic;topic=' . $context['current_topic'] . ';mode=1;' . $context['session_var'] . '=' . $context['session_id'],
1418
				),
1419
				array(
1420
					'text' => 'notify_topic_2',
1421
					'url' => $scripturl . '?action=notifytopic;topic=' . $context['current_topic'] . ';mode=2;' . $context['session_var'] . '=' . $context['session_id'],
1422
				),
1423
				array(
1424
					'text' => 'notify_topic_3',
1425
					'url' => $scripturl . '?action=notifytopic;topic=' . $context['current_topic'] . ';mode=3;' . $context['session_var'] . '=' . $context['session_id'],
1426
				),
1427
			),
1428
		);
1429
1430
	// Build the mod button array
1431
	$context['mod_buttons'] = array();
1432
1433
	if ($context['can_move'])
1434
		$context['mod_buttons']['move'] = array('text' => 'move_topic', 'url' => $scripturl . '?action=movetopic;current_board=' . $context['current_board'] . ';topic=' . $context['current_topic'] . '.0');
1435
1436
	if ($context['can_delete'])
1437
		$context['mod_buttons']['delete'] = array('text' => 'remove_topic', 'custom' => 'data-confirm="' . $txt['are_sure_remove_topic'] . '"', 'class' => 'you_sure', 'url' => $scripturl . '?action=removetopic2;topic=' . $context['current_topic'] . '.0;' . $context['session_var'] . '=' . $context['session_id']);
1438
1439
	if ($context['can_lock'])
1440
		$context['mod_buttons']['lock'] = array('text' => empty($context['is_locked']) ? 'set_lock' : 'set_unlock', 'url' => $scripturl . '?action=lock;topic=' . $context['current_topic'] . '.' . $context['start'] . ';sa=' . ($context['is_locked'] ? 'unlock' : 'lock') . ';' . $context['session_var'] . '=' . $context['session_id']);
1441
1442
	if ($context['can_sticky'])
1443
		$context['mod_buttons']['sticky'] = array('text' => empty($context['is_sticky']) ? 'set_sticky' : 'set_nonsticky', 'url' => $scripturl . '?action=sticky;topic=' . $context['current_topic'] . '.' . $context['start'] . ';sa=' . ($context['is_sticky'] ? 'nonsticky' : 'sticky') . ';' . $context['session_var'] . '=' . $context['session_id']);
1444
1445
	if ($context['can_merge'])
1446
		$context['mod_buttons']['merge'] = array('text' => 'merge', 'url' => $scripturl . '?action=mergetopics;board=' . $context['current_board'] . '.0;from=' . $context['current_topic']);
1447
1448
	if ($context['calendar_post'])
1449
		$context['mod_buttons']['calendar'] = array('text' => 'calendar_link', 'url' => $scripturl . '?action=post;calendar;msg=' . $context['topic_first_message'] . ';topic=' . $context['current_topic'] . '.0');
1450
1451
	// Restore topic. eh?  No monkey business.
1452
	if ($context['can_restore_topic'])
1453
		$context['mod_buttons']['restore_topic'] = array('text' => 'restore_topic', 'url' => $scripturl . '?action=restoretopic;topics=' . $context['current_topic'] . ';' . $context['session_var'] . '=' . $context['session_id']);
1454
1455
	// Show a message in case a recently posted message became unapproved.
1456
	$context['becomesUnapproved'] = !empty($_SESSION['becomesUnapproved']);
1457
	unset($_SESSION['becomesUnapproved']);
1458
1459
	// Allow adding new mod buttons easily.
1460
	// Note: $context['normal_buttons'] and $context['mod_buttons'] are added for backward compatibility with 2.0, but are deprecated and should not be used
1461
	call_integration_hook('integrate_display_buttons', array(&$context['normal_buttons']));
1462
	// Note: integrate_mod_buttons is no more necessary and deprecated, but is kept for backward compatibility with 2.0
1463
	call_integration_hook('integrate_mod_buttons', array(&$context['mod_buttons']));
1464
1465
	// Load the drafts js file
1466
	if ($context['drafts_autosave'])
1467
		loadJavaScriptFile('drafts.js', array('defer' => false, 'minimize' => true), 'smf_drafts');
1468
1469
	// Spellcheck
1470
	if ($context['show_spellchecking'])
1471
		loadJavaScriptFile('spellcheck.js', array('defer' => false, 'minimize' => true), 'smf_spellcheck');
1472
1473
	// topic.js
1474
	loadJavaScriptFile('topic.js', array('defer' => false, 'minimize' => true), 'smf_topic');
1475
1476
	// quotedText.js
1477
	loadJavaScriptFile('quotedText.js', array('defer' => true, 'minimize' => true), 'smf_quotedText');
1478
1479
	// Mentions
1480
	if (!empty($modSettings['enable_mentions']) && allowedTo('mention'))
1481
	{
1482
		loadJavaScriptFile('jquery.atwho.min.js', array('defer' => true), 'smf_atwho');
1483
		loadJavaScriptFile('jquery.caret.min.js', array('defer' => true), 'smf_caret');
1484
		loadJavaScriptFile('mentions.js', array('defer' => true, 'minimize' => true), 'smf_mentions');
1485
	}
1486
}
1487
1488
/**
1489
 * Callback for the message display.
1490
 * It actually gets and prepares the message context.
1491
 * This function will start over from the beginning if reset is set to true, which is
1492
 * useful for showing an index before or after the posts.
1493
 *
1494
 * @param bool $reset Whether or not to reset the db seek pointer
1495
 * @return array A large array of contextual data for the posts
1496
 */
1497
function prepareDisplayContext($reset = false)
1498
{
1499
	global $settings, $txt, $modSettings, $scripturl, $options, $user_info, $smcFunc;
1500
	global $memberContext, $context, $messages_request, $topic, $board_info, $sourcedir;
1501
1502
	static $counter = null;
1503
1504
	// If the query returned false, bail.
1505
	if ($messages_request == false)
1506
		return false;
1507
1508
	// Remember which message this is.  (ie. reply #83)
1509
	if ($counter === null || $reset)
1510
		$counter = empty($options['view_newest_first']) ? $context['start'] : $context['total_visible_posts'] - $context['start'];
1511
1512
	// Start from the beginning...
1513
	if ($reset)
1514
		return @$smcFunc['db_data_seek']($messages_request, 0);
1515
1516
	// Attempt to get the next message.
1517
	$message = $smcFunc['db_fetch_assoc']($messages_request);
1518
	if (!$message)
1519
	{
1520
		$smcFunc['db_free_result']($messages_request);
1521
		return false;
1522
	}
1523
1524
	// $context['icon_sources'] says where each icon should come from - here we set up the ones which will always exist!
1525
	if (empty($context['icon_sources']))
1526
	{
1527
		$context['icon_sources'] = array();
1528
		foreach ($context['stable_icons'] as $icon)
1529
			$context['icon_sources'][$icon] = 'images_url';
1530
	}
1531
1532
	// Message Icon Management... check the images exist.
1533
	if (!empty($modSettings['messageIconChecks_enable']))
1534
	{
1535
		// If the current icon isn't known, then we need to do something...
1536
		if (!isset($context['icon_sources'][$message['icon']]))
1537
			$context['icon_sources'][$message['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['icon'] . '.png') ? 'images_url' : 'default_images_url';
1538
	}
1539
	elseif (!isset($context['icon_sources'][$message['icon']]))
1540
		$context['icon_sources'][$message['icon']] = 'images_url';
1541
1542
	// If you're a lazy bum, you probably didn't give a subject...
1543
	$message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
1544
1545
	// Are you allowed to remove at least a single reply?
1546
	$context['can_remove_post'] |= allowedTo('delete_own') && (empty($modSettings['edit_disable_time']) || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 >= time()) && $message['id_member'] == $user_info['id'];
1547
1548
	// If the topic is locked, you might not be able to delete the post...
1549
	if ($context['is_locked'])
1550
	{
1551
		$context['can_remove_post'] &= ($context['user']['started'] && $context['is_locked'] == 1) || allowedTo('lock_any');
1552
	}
1553
1554
	// If it couldn't load, or the user was a guest.... someday may be done with a guest table.
1555
	if (!loadMemberContext($message['id_member'], true))
1556
	{
1557
		// Notice this information isn't used anywhere else....
1558
		$memberContext[$message['id_member']]['name'] = $message['poster_name'];
1559
		$memberContext[$message['id_member']]['id'] = 0;
1560
		$memberContext[$message['id_member']]['group'] = $txt['guest_title'];
1561
		$memberContext[$message['id_member']]['link'] = $message['poster_name'];
1562
		$memberContext[$message['id_member']]['email'] = $message['poster_email'];
1563
		$memberContext[$message['id_member']]['show_email'] = allowedTo('moderate_forum');
1564
		$memberContext[$message['id_member']]['is_guest'] = true;
1565
	}
1566
	else
1567
	{
1568
		// Define this here to make things a bit more readable
1569
		$can_view_warning = allowedTo('moderate_forum') || allowedTo('view_warning_any') || ($message['id_member'] == $user_info['id'] && allowedTo('view_warning_own'));
1570
1571
		$memberContext[$message['id_member']]['can_view_profile'] = allowedTo('profile_view') || ($message['id_member'] == $user_info['id'] && !$user_info['is_guest']);
1572
		$memberContext[$message['id_member']]['is_topic_starter'] = $message['id_member'] == $context['topic_starter_id'];
1573
		$memberContext[$message['id_member']]['can_see_warning'] = !isset($context['disabled_fields']['warning_status']) && $memberContext[$message['id_member']]['warning_status'] && $can_view_warning;
1574
		// Show the email if it's your post...
1575
		$memberContext[$message['id_member']]['show_email'] |= ($message['id_member'] == $user_info['id']);
1576
	}
1577
1578
	$memberContext[$message['id_member']]['ip'] = inet_dtop($message['poster_ip']);
1579
	$memberContext[$message['id_member']]['show_profile_buttons'] = !empty($modSettings['show_profile_buttons']) && (!empty($memberContext[$message['id_member']]['can_view_profile']) || (!empty($memberContext[$message['id_member']]['website']['url']) && !isset($context['disabled_fields']['website'])) || $memberContext[$message['id_member']]['show_email'] || $context['can_send_pm']);
1580
1581
	// Do the censor thang.
1582
	censorText($message['body']);
1583
	censorText($message['subject']);
1584
1585
	// Run BBC interpreter on the message.
1586
	$message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
1587
1588
	// If it's in the recycle bin we need to override whatever icon we did have.
1589
	if (!empty($board_info['recycle']))
1590
		$message['icon'] = 'recycled';
1591
1592
	require_once($sourcedir . '/Subs-Attachments.php');
1593
1594
	// Compose the memory eat- I mean message array.
1595
	$output = array(
1596
		'attachment' => loadAttachmentContext($message['id_msg'], $context['loaded_attachments']),
1597
		'id' => $message['id_msg'],
1598
		'href' => $scripturl . '?msg=' . $message['id_msg'],
1599
		'link' => '<a href="' . $scripturl . '?msg=' . $message['id_msg'] . '" rel="nofollow">' . $message['subject'] . '</a>',
1600
		'member' => &$memberContext[$message['id_member']],
1601
		'icon' => $message['icon'],
1602
		'icon_url' => $settings[$context['icon_sources'][$message['icon']]] . '/post/' . $message['icon'] . '.png',
1603
		'subject' => $message['subject'],
1604
		'time' => timeformat($message['poster_time']),
1605
		'timestamp' => forum_time(true, $message['poster_time']),
1606
		'counter' => $counter,
1607
		'modified' => array(
1608
			'time' => timeformat($message['modified_time']),
1609
			'timestamp' => forum_time(true, $message['modified_time']),
1610
			'name' => $message['modified_name'],
1611
			'reason' => $message['modified_reason']
1612
		),
1613
		'body' => $message['body'],
1614
		'new' => empty($message['is_read']),
1615
		'approved' => $message['approved'],
1616
		'first_new' => isset($context['start_from']) && $context['start_from'] == $counter,
1617
		'is_ignored' => !empty($modSettings['enable_buddylist']) && !empty($options['posts_apply_ignore_list']) && in_array($message['id_member'], $context['user']['ignoreusers']),
1618
		'can_approve' => !$message['approved'] && $context['can_approve'],
1619
		'can_unapprove' => !empty($modSettings['postmod_active']) && $context['can_approve'] && $message['approved'],
1620
		'can_modify' => (!$context['is_locked'] || allowedTo('moderate_board')) && (allowedTo('modify_any') || (allowedTo('modify_replies') && $context['user']['started']) || (allowedTo('modify_own') && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || !$message['approved'] || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 > time()))),
1621
		'can_remove' => allowedTo('delete_any') || (allowedTo('delete_replies') && $context['user']['started']) || (allowedTo('delete_own') && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 > time())),
1622
		'can_see_ip' => allowedTo('moderate_forum') || ($message['id_member'] == $user_info['id'] && !empty($user_info['id'])),
1623
		'css_class' => $message['approved'] ? 'windowbg' : 'approvebg',
1624
	);
1625
1626
	// Does the file contains any attachments? if so, change the icon.
1627
	if (!empty($output['attachment']))
1628
	{
1629
		$output['icon'] = 'clip';
1630
		$output['icon_url'] = $settings[$context['icon_sources'][$output['icon']]] . '/post/' . $output['icon'] . '.png';
1631
	}
1632
1633
	// Are likes enable?
1634
	if (!empty($modSettings['enable_likes']))
1635
		$output['likes'] = array(
1636
			'count' => $message['likes'],
1637
			'you' => in_array($message['id_msg'], $context['my_likes']),
1638
			'can_like' => !$context['user']['is_guest'] && $message['id_member'] != $context['user']['id'] && !empty($context['can_like']),
1639
		);
1640
1641
	// Is this user the message author?
1642
	$output['is_message_author'] = $message['id_member'] == $user_info['id'];
1643
	if (!empty($output['modified']['name']))
1644
		$output['modified']['last_edit_text'] = sprintf($txt['last_edit_by'], $output['modified']['time'], $output['modified']['name']);
1645
1646
	// Did they give a reason for editing?
1647
	if (!empty($output['modified']['name']) && !empty($output['modified']['reason']))
1648
		$output['modified']['last_edit_text'] .= '&nbsp;' . sprintf($txt['last_edit_reason'], $output['modified']['reason']);
1649
1650
	// Any custom profile fields?
1651
	if (!empty($memberContext[$message['id_member']]['custom_fields']))
1652
		foreach ($memberContext[$message['id_member']]['custom_fields'] as $custom)
1653
			$output['custom_fields'][$context['cust_profile_fields_placement'][$custom['placement']]][] = $custom;
1654
1655
	$output['quickbuttons'] = array(
1656
		'quote' => array(
1657
			'label' => $txt['quote_action'],
1658
			'href' => $scripturl.'?action=post;quote='.$output['id'].';topic='.$context['current_topic'], '.'.$context['start'].';last_msg='.$context['topic_last_message'],
1659
			'javascript' => 'onclick="return oQuickReply.quote('.$output['id'].');"',
1660
			'icon' => 'quote',
1661
			'show' => $context['can_quote']
1662
		),
1663
		'quote_selected' => array(
1664
			'label' => $txt['quote_selected_action'],
1665
			'id' => 'quoteSelected_'. $output['id'],
1666
			'href' => 'javascript:void(0)',
1667
			'custom' => 'style="display:none"',
1668
			'icon' => 'quote_selected',
1669
			'show' => $context['can_quote']
1670
		),
1671
		'quick_edit' => array(
1672
			'label' => $txt['quick_edit'],
1673
			'class' => 'quick_edit',
1674
			'id' =>' modify_button_'. $output['id'],
1675
			'custom' => 'onclick="oQuickModify.modifyMsg(\''.$output['id'].'\', \''.!empty($modSettings['toggle_subject']).'\')"',
1676
			'icon' => 'quick_edit_button',
1677
			'show' => $output['can_modify']
1678
		),
1679
		'more' => array(
1680
			'modify' => array(
1681
				'label' => $txt['modify'],
1682
				'href' => $scripturl.'?action=post;msg='.$output['id'].';topic='.$context['current_topic'].'.'.$context['start'],
1683
				'icon' => 'modify_button',
1684
				'show' => $output['can_modify']
1685
			),
1686
			'remove_topic' => array(
1687
				'label' => $txt['remove_topic'],
1688
				'href' => $scripturl.'?action=removetopic2;topic='.$context['current_topic'].'.'.$context['start'].';'.$context['session_var'].'='.$context['session_id'],
1689
				'javascript' => 'data-confirm="'.$txt['are_sure_remove_topic'].'"',
1690
				'class' => 'you_sure',
1691
				'icon' => 'remove_button',
1692
				'show' => $context['can_delete'] && ($context['topic_first_message'] == $output['id'])
1693
			),
1694
			'remove' => array(
1695
				'label' => $txt['remove'],
1696
				'href' => $scripturl.'?action=deletemsg;topic='.$context['current_topic'].'.'.$context['start'].';msg='.$output['id'].';'.$context['session_var'].'='.$context['session_id'],
1697
				'javascript' => 'data-confirm="'.$txt['remove_message_question'].'"',
1698
				'class' => 'you_sure',
1699
				'icon' => 'remove_button',
1700
				'show' => $output['can_remove'] && ($context['topic_first_message'] != $output['id'])
1701
			),
1702
			'split' => array(
1703
				'label' => $txt['split'],
1704
				'href' => $scripturl.'?action=splittopics;topic='.$context['current_topic'].'.0;at='.$output['id'],
1705
				'icon' => 'split_button',
1706
				'show' => $context['can_split'] && !empty($context['real_num_replies'])
1707
			),
1708
			'report' => array(
1709
				'label' => $txt['report_to_mod'],
1710
				'href' => $scripturl.'?action=reporttm;topic='.$context['current_topic'].'.'.$output['counter'].';msg='.$output['id'],
1711
				'icon' => 'error',
1712
				'show' => $context['can_report_moderator']
1713
			),
1714
			'warn' => array(
1715
				'label' => $txt['issue_warning'],
1716
				'href' => $scripturl.'?action=profile;area=issuewarning;u='.$output['member']['id'].';msg='.$output['id'],
1717
				'icon' => 'warn_button',
1718
				'show' => $context['can_issue_warning'] && !$output['is_message_author'] && !$output['member']['is_guest']
1719
			),
1720
			'restore' => array(
1721
				'label' => $txt['restore_message'],
1722
				'href' => $scripturl.'?action=restoretopic;msgs='.$output['id'].';'.$context['session_var'].'='.$context['session_id'],
1723
				'icon' => 'restore_button',
1724
				'show' => $context['can_restore_msg']
1725
			),
1726
			'approve' => array(
1727
				'label' => $txt['approve'],
1728
				'href' => $scripturl.'?action=moderate;area=postmod;sa=approve;topic='.$context['current_topic'].'.'.$context['start'].';msg='.$output['id'].';'.$context['session_var'].'='.$context['session_id'],
1729
				'icon' => 'approve_button',
1730
				'show' => $output['can_approve']
1731
			),
1732
			'unapprove' => array(
1733
				'label' => $txt['unapprove'],
1734
				'href' => $scripturl.'?action=moderate;area=postmod;sa=approve;topic='.$context['current_topic'].'.'.$context['start'].';msg='.$output['id'].';'.$context['session_var'].'='.$context['session_id'],
1735
				'icon' => 'unapprove_button',
1736
				'show' => $output['can_unapprove']
1737
			),
1738
		),
1739
		'quickmod' => array(
1740
			'id' => 'in_topic_mod_check_'. $output['id'],
1741
			'custom' => 'style="display: none;"',
1742
			'content' => '',
1743
			'show' => !empty($options['display_quick_mod']) && $options['display_quick_mod'] == 1 && $output['can_remove'],
1744
		)
1745
	);
1746
1747
	if (empty($options['view_newest_first']))
1748
		$counter++;
1749
1750
	else
1751
		$counter--;
1752
1753
	call_integration_hook('integrate_prepare_display_context', array(&$output, &$message, $counter));
1754
1755
	return $output;
1756
}
1757
1758
/**
1759
 * Once upon a time, this function handled downloading attachments.
1760
 * Now it's just an alias retained for the sake of backwards compatibility.
1761
 */
1762
function Download()
1763
{
1764
	global $sourcedir;
1765
	require_once($sourcedir . '/ShowAttachments.php');
1766
	showAttachment();
1767
}
1768
1769
/**
1770
 * In-topic quick moderation.
1771
 */
1772
function QuickInTopicModeration()
1773
{
1774
	global $sourcedir, $topic, $board, $user_info, $smcFunc, $modSettings, $context;
1775
1776
	// Check the session = get or post.
1777
	checkSession('request');
1778
1779
	require_once($sourcedir . '/RemoveTopic.php');
1780
1781
	if (empty($_REQUEST['msgs']))
1782
		redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
1783
1784
	$messages = array();
1785
	foreach ($_REQUEST['msgs'] as $dummy)
1786
		$messages[] = (int) $dummy;
1787
1788
	// We are restoring messages. We handle this in another place.
1789
	if (isset($_REQUEST['restore_selected']))
1790
		redirectexit('action=restoretopic;msgs=' . implode(',', $messages) . ';' . $context['session_var'] . '=' . $context['session_id']);
1791
	if (isset($_REQUEST['split_selection']))
1792
	{
1793
		$request = $smcFunc['db_query']('', '
1794
			SELECT subject
1795
			FROM {db_prefix}messages
1796
			WHERE id_msg = {int:message}
1797
			LIMIT 1',
1798
			array(
1799
				'message' => min($messages),
1800
			)
1801
		);
1802
		list($subname) = $smcFunc['db_fetch_row']($request);
1803
		$smcFunc['db_free_result']($request);
1804
		$_SESSION['split_selection'][$topic] = $messages;
1805
		redirectexit('action=splittopics;sa=selectTopics;topic=' . $topic . '.0;subname_enc=' . urlencode($subname) . ';' . $context['session_var'] . '=' . $context['session_id']);
1806
	}
1807
1808
	// Allowed to delete any message?
1809
	if (allowedTo('delete_any'))
1810
		$allowed_all = true;
1811
	// Allowed to delete replies to their messages?
1812
	elseif (allowedTo('delete_replies'))
1813
	{
1814
		$request = $smcFunc['db_query']('', '
1815
			SELECT id_member_started
1816
			FROM {db_prefix}topics
1817
			WHERE id_topic = {int:current_topic}
1818
			LIMIT 1',
1819
			array(
1820
				'current_topic' => $topic,
1821
			)
1822
		);
1823
		list ($starter) = $smcFunc['db_fetch_row']($request);
1824
		$smcFunc['db_free_result']($request);
1825
1826
		$allowed_all = $starter == $user_info['id'];
1827
	}
1828
	else
1829
		$allowed_all = false;
1830
1831
	// Make sure they're allowed to delete their own messages, if not any.
1832
	if (!$allowed_all)
1833
		isAllowedTo('delete_own');
1834
1835
	// Allowed to remove which messages?
1836
	$request = $smcFunc['db_query']('', '
1837
		SELECT id_msg, subject, id_member, poster_time
1838
		FROM {db_prefix}messages
1839
		WHERE id_msg IN ({array_int:message_list})
1840
			AND id_topic = {int:current_topic}' . (!$allowed_all ? '
1841
			AND id_member = {int:current_member}' : '') . '
1842
		LIMIT {int:limit}',
1843
		array(
1844
			'current_member' => $user_info['id'],
1845
			'current_topic' => $topic,
1846
			'message_list' => $messages,
1847
			'limit' => count($messages),
1848
		)
1849
	);
1850
	$messages = array();
1851
	while ($row = $smcFunc['db_fetch_assoc']($request))
1852
	{
1853
		if (!$allowed_all && !empty($modSettings['edit_disable_time']) && $row['poster_time'] + $modSettings['edit_disable_time'] * 60 < time())
1854
			continue;
1855
1856
		$messages[$row['id_msg']] = array($row['subject'], $row['id_member']);
1857
	}
1858
	$smcFunc['db_free_result']($request);
1859
1860
	// Get the first message in the topic - because you can't delete that!
1861
	$request = $smcFunc['db_query']('', '
1862
		SELECT id_first_msg, id_last_msg
1863
		FROM {db_prefix}topics
1864
		WHERE id_topic = {int:current_topic}
1865
		LIMIT 1',
1866
		array(
1867
			'current_topic' => $topic,
1868
		)
1869
	);
1870
	list ($first_message, $last_message) = $smcFunc['db_fetch_row']($request);
1871
	$smcFunc['db_free_result']($request);
1872
1873
	// Delete all the messages we know they can delete. ($messages)
1874
	foreach ($messages as $message => $info)
1875
	{
1876
		// Just skip the first message - if it's not the last.
1877
		if ($message == $first_message && $message != $last_message)
1878
			continue;
1879
		// If the first message is going then don't bother going back to the topic as we're effectively deleting it.
1880
		elseif ($message == $first_message)
1881
			$topicGone = true;
1882
1883
		removeMessage($message);
1884
1885
		// Log this moderation action ;).
1886
		if (allowedTo('delete_any') && (!allowedTo('delete_own') || $info[1] != $user_info['id']))
1887
			logAction('delete', array('topic' => $topic, 'subject' => $info[0], 'member' => $info[1], 'board' => $board));
1888
	}
1889
1890
	redirectexit(!empty($topicGone) ? 'board=' . $board : 'topic=' . $topic . '.' . $_REQUEST['start']);
1891
}
1892
1893
?>