Download()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
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 http://www.simplemachines.org
11
 * @copyright 2019 Simple Machines and individual contributors
12
 * @license http://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;
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...
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
			array(
681
				'current_member' => $user_info['id'],
682
				'id_poll' => $context['topicinfo']['id_poll'],
683
				'not_guest' => 0,
684
			)
685
		);
686
		$pollOptions = array();
687
		$realtotal = 0;
688
		$pollinfo['has_voted'] = false;
689
		while ($row = $smcFunc['db_fetch_assoc']($request))
690
		{
691
			censorText($row['label']);
692
			$pollOptions[$row['id_choice']] = $row;
693
			$realtotal += $row['votes'];
694
			$pollinfo['has_voted'] |= $row['voted_this'] != -1;
695
		}
696
		$smcFunc['db_free_result']($request);
697
698
		// Got we multi choice?
699
		if ($pollinfo['max_votes'] > 1)
700
			$realtotal = $pollinfo['total'];
701
702
		// If this is a guest we need to do our best to work out if they have voted, and what they voted for.
703
		if ($user_info['is_guest'] && $pollinfo['guest_vote'] && allowedTo('poll_vote'))
704
		{
705
			if (!empty($_COOKIE['guest_poll_vote']) && preg_match('~^[0-9,;]+$~', $_COOKIE['guest_poll_vote']) && strpos($_COOKIE['guest_poll_vote'], ';' . $context['topicinfo']['id_poll'] . ',') !== false)
706
			{
707
				// ;id,timestamp,[vote,vote...]; etc
708
				$guestinfo = explode(';', $_COOKIE['guest_poll_vote']);
709
				// Find the poll we're after.
710
				foreach ($guestinfo as $i => $guestvoted)
711
				{
712
					$guestvoted = explode(',', $guestvoted);
713
					if ($guestvoted[0] == $context['topicinfo']['id_poll'])
714
						break;
715
				}
716
				// Has the poll been reset since guest voted?
717
				if ($pollinfo['reset_poll'] > $guestvoted[1])
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $guestvoted seems to be defined by a foreach iteration on line 710. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
718
				{
719
					// Remove the poll info from the cookie to allow guest to vote again
720
					unset($guestinfo[$i]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $i seems to be defined by a foreach iteration on line 710. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
721
					if (!empty($guestinfo))
722
						$_COOKIE['guest_poll_vote'] = ';' . implode(';', $guestinfo);
723
					else
724
						unset($_COOKIE['guest_poll_vote']);
725
				}
726
				else
727
				{
728
					// What did they vote for?
729
					unset($guestvoted[0], $guestvoted[1]);
730
					foreach ($pollOptions as $choice => $details)
731
					{
732
						$pollOptions[$choice]['voted_this'] = in_array($choice, $guestvoted) ? 1 : -1;
733
						$pollinfo['has_voted'] |= $pollOptions[$choice]['voted_this'] != -1;
734
					}
735
					unset($choice, $details, $guestvoted);
736
				}
737
				unset($guestinfo, $guestvoted, $i);
738
			}
739
		}
740
741
		// Set up the basic poll information.
742
		$context['poll'] = array(
743
			'id' => $context['topicinfo']['id_poll'],
744
			'image' => 'normal_' . (empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll'),
745
			'question' => parse_bbc($pollinfo['question']),
746
			'total_votes' => $pollinfo['total'],
747
			'change_vote' => !empty($pollinfo['change_vote']),
748
			'is_locked' => !empty($pollinfo['voting_locked']),
749
			'options' => array(),
750
			'lock' => allowedTo('poll_lock_any') || ($context['user']['started'] && allowedTo('poll_lock_own')),
751
			'edit' => allowedTo('poll_edit_any') || ($context['user']['started'] && allowedTo('poll_edit_own')),
752
			'remove' => allowedTo('poll_remove_any') || ($context['user']['started'] && allowedTo('poll_remove_own')),
753
			'allowed_warning' => $pollinfo['max_votes'] > 1 ? sprintf($txt['poll_options_limit'], min(count($pollOptions), $pollinfo['max_votes'])) : '',
754
			'is_expired' => !empty($pollinfo['expire_time']) && $pollinfo['expire_time'] < time(),
755
			'expire_time' => !empty($pollinfo['expire_time']) ? timeformat($pollinfo['expire_time']) : 0,
756
			'has_voted' => !empty($pollinfo['has_voted']),
757
			'starter' => array(
758
				'id' => $pollinfo['id_member'],
759
				'name' => $row['poster_name'],
760
				'href' => $pollinfo['id_member'] == 0 ? '' : $scripturl . '?action=profile;u=' . $pollinfo['id_member'],
761
				'link' => $pollinfo['id_member'] == 0 ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $pollinfo['id_member'] . '">' . $row['poster_name'] . '</a>'
762
			)
763
		);
764
765
		// Make the lock, edit and remove permissions defined above more directly accessible.
766
		$context['allow_lock_poll'] = $context['poll']['lock'];
767
		$context['allow_edit_poll'] = $context['poll']['edit'];
768
		$context['can_remove_poll'] = $context['poll']['remove'];
769
770
		// You're allowed to vote if:
771
		// 1. the poll did not expire, and
772
		// 2. you're either not a guest OR guest voting is enabled... and
773
		// 3. you're not trying to view the results, and
774
		// 4. the poll is not locked, and
775
		// 5. you have the proper permissions, and
776
		// 6. you haven't already voted before.
777
		$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'];
778
779
		// You're allowed to view the results if:
780
		// 1. you're just a super-nice-guy, or
781
		// 2. anyone can see them (hide_results == 0), or
782
		// 3. you can see them after you voted (hide_results == 1), or
783
		// 4. you've waited long enough for the poll to expire. (whether hide_results is 1 or 2.)
784
		$context['allow_results_view'] = allowedTo('moderate_board') || $pollinfo['hide_results'] == 0 || ($pollinfo['hide_results'] == 1 && $context['poll']['has_voted']) || $context['poll']['is_expired'];
785
786
		// Show the results if:
787
		// 1. You're allowed to see them (see above), and
788
		// 2. $_REQUEST['viewresults'] or $_REQUEST['viewResults'] is set
789
		$context['poll']['show_results'] = $context['allow_results_view'] && (isset($_REQUEST['viewresults']) || isset($_REQUEST['viewResults']));
790
791
		// Show the button if:
792
		// 1. You can vote in the poll (see above), and
793
		// 2. Results are visible to everyone (hidden = 0), and
794
		// 3. You aren't already viewing the results
795
		$context['show_view_results_button'] = $context['allow_vote'] && $context['allow_results_view'] && !$context['poll']['show_results'];
796
797
		// You're allowed to change your vote if:
798
		// 1. the poll did not expire, and
799
		// 2. you're not a guest... and
800
		// 3. the poll is not locked, and
801
		// 4. you have the proper permissions, and
802
		// 5. you have already voted, and
803
		// 6. the poll creator has said you can!
804
		$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'];
805
806
		// You're allowed to return to voting options if:
807
		// 1. you are (still) allowed to vote.
808
		// 2. you are currently seeing the results.
809
		$context['allow_return_vote'] = $context['allow_vote'] && $context['poll']['show_results'];
810
811
		// Calculate the percentages and bar lengths...
812
		$divisor = $realtotal == 0 ? 1 : $realtotal;
813
814
		// Determine if a decimal point is needed in order for the options to add to 100%.
815
		$precision = $realtotal == 100 ? 0 : 1;
816
817
		// Now look through each option, and...
818
		foreach ($pollOptions as $i => $option)
819
		{
820
			// First calculate the percentage, and then the width of the bar...
821
			$bar = round(($option['votes'] * 100) / $divisor, $precision);
822
			$barWide = $bar == 0 ? 1 : floor(($bar * 8) / 3);
823
824
			// Now add it to the poll's contextual theme data.
825
			$context['poll']['options'][$i] = array(
826
				'id' => 'options-' . $i,
827
				'percent' => $bar,
828
				'votes' => $option['votes'],
829
				'voted_this' => $option['voted_this'] != -1,
830
				'bar_ndt' => $bar > 0 ? '<div class="bar" style="width: ' . $bar . '%;"></div>' : '',
831
				'bar_width' => $barWide,
832
				'option' => parse_bbc($option['label']),
833
				'vote_button' => '<input type="' . ($pollinfo['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '">'
834
			);
835
		}
836
837
		// Build the poll moderation button array.
838
		$context['poll_buttons'] = array();
839
840
		if ($context['allow_return_vote'])
841
			$context['poll_buttons']['vote'] = array('text' => 'poll_return_vote', 'image' => 'poll_options.png', 'url' => $scripturl . '?topic=' . $context['current_topic'] . '.' . $context['start']);
842
843
		if ($context['show_view_results_button'])
844
			$context['poll_buttons']['results'] = array('text' => 'poll_results', 'image' => 'poll_results.png', 'url' => $scripturl . '?topic=' . $context['current_topic'] . '.' . $context['start'] . ';viewresults');
845
846
		if ($context['allow_change_vote'])
847
			$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']);
848
849
		if ($context['allow_lock_poll'])
850
			$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']);
851
852
		if ($context['allow_edit_poll'])
853
			$context['poll_buttons']['edit'] = array('text' => 'poll_edit', 'image' => 'poll_edit.png', 'url' => $scripturl . '?action=editpoll;topic=' . $context['current_topic'] . '.' . $context['start']);
854
855
		if ($context['can_remove_poll'])
856
			$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']);
857
858
		// Allow mods to add additional buttons here
859
		call_integration_hook('integrate_poll_buttons');
860
	}
861
862
	$start = $_REQUEST['start'];
863
	$ascending = empty($options['view_newest_first']);
864
865
	// Check if we can use the seek method to speed things up
866
	if (isset($_SESSION['page_topic']) && $_SESSION['page_topic'] == $topic && $_SESSION['page_ascending'] == $ascending)
867
	{
868
		// User moved to the next page
869
		if (isset($_SESSION['page_next_start']) && $_SESSION['page_next_start'] == $start)
870
		{
871
			$start_char = 'M';
872
			$page_id = $_SESSION['page_last_id'];
873
		}
874
		// User moved to the previous page
875
		elseif (isset($_SESSION['page_before_start']) && $_SESSION['page_before_start'] == $start)
876
		{
877
			$start_char = 'L';
878
			$page_id = $_SESSION['page_first_id'];
879
		}
880
		// User refreshed the current page
881
		elseif (isset($_SESSION['page_current_start']) && $_SESSION['page_current_start'] == $start)
882
		{
883
			$start_char = 'C';
884
			$page_id = $_SESSION['page_first_id'];
885
		}
886
	}
887
	// Special case start page
888
	elseif ($start == 0)
889
	{
890
		$start_char = 'C';
891
		$page_id = $ascending ? $context['topicinfo']['id_first_msg'] : $context['topicinfo']['id_last_msg'];
892
	}
893
	else
894
		$start_char = null;
895
896
	$limit = $context['messages_per_page'];
897
898
	$messages = array();
899
	$all_posters = array();
900
	$firstIndex = 0;
901
902
	if (isset($start_char))
903
	{
904
		if ($start_char === 'M' || $start_char === 'C')
905
		{
906
			$DBascending = $ascending;
907
			$page_operator = $ascending ? '>=' : '<=';
908
		}
909
		else
910
		{
911
			$DBascending = !$ascending;
912
			$page_operator = $ascending ? '<=' : '>=';
913
		}
914
915
		if ($start_char === 'C')
916
			$limit_seek = $limit;
917
		else
918
			$limit_seek = $limit + 1;
919
920
		$request = $smcFunc['db_query']('', '
921
			SELECT id_msg, id_member, approved
922
			FROM {db_prefix}messages
923
			WHERE id_topic = {int:current_topic}
924
				AND id_msg ' . $page_operator . ' {int:page_id}' . (!$modSettings['postmod_active'] || $can_approve_posts ? '' : '
925
				AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')') . '
926
			ORDER BY id_msg ' . ($DBascending ? '' : 'DESC') . ($context['messages_per_page'] == -1 ? '' : '
927
			LIMIT {int:limit}'),
928
			array(
929
				'current_member' => $user_info['id'],
930
				'current_topic' => $topic,
931
				'is_approved' => 1,
932
				'blank_id_member' => 0,
933
				'limit' => $limit_seek,
934
				'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...
935
			)
936
		);
937
938
		$found_msg = false;
939
940
		// Fallback
941
		if ($smcFunc['db_num_rows']($request) < 1)
942
			unset($start_char);
943
		else
944
		{
945
			while ($row = $smcFunc['db_fetch_assoc']($request))
946
			{
947
				// Check if the start msg is in our result
948
				if ($row['id_msg'] == $page_id)
949
					$found_msg = true;
950
951
				// Skip the the start msg if we not in mode C
952
				if ($start_char === 'C' || $row['id_msg'] != $page_id)
953
				{
954
					if (!empty($row['id_member']))
955
						$all_posters[$row['id_msg']] = $row['id_member'];
956
957
					$messages[] = $row['id_msg'];
958
				}
959
			}
960
961
			// page_id not found? -> fallback
962
			if (!$found_msg)
963
			{
964
				$messages = array();
965
				$all_posters = array();
966
				unset($start_char);
967
			}
968
		}
969
970
		// Before Page bring in the right order
971
		if (!empty($start_char) && $start_char === 'L')
972
			krsort($messages);
973
	}
974
975
	// Jump to page
976
	if (empty($start_char))
977
	{
978
		// Calculate the fastest way to get the messages!
979
		if ($start >= $context['total_visible_posts'] / 2 && $context['messages_per_page'] != -1)
980
		{
981
			$DBascending = !$ascending;
982
			$limit = $context['total_visible_posts'] <= $start + $limit ? $context['total_visible_posts'] - $start : $limit;
983
			$start = $context['total_visible_posts'] <= $start + $limit ? 0 : $context['total_visible_posts'] - $start - $limit;
984
			$firstIndex = empty($options['view_newest_first']) ? $start - 1 : $limit - 1;
985
		}
986
		else
987
			$DBascending = $ascending;
988
989
		// Get each post and poster in this topic.
990
		$request = $smcFunc['db_query']('', '
991
			SELECT id_msg, id_member, approved
992
			FROM {db_prefix}messages
993
			WHERE id_topic = {int:current_topic}' . (!$modSettings['postmod_active'] || $can_approve_posts ? '' : '
994
				AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')') . '
995
			ORDER BY id_msg ' . ($DBascending ? '' : 'DESC') . ($context['messages_per_page'] == -1 ? '' : '
996
			LIMIT {int:start}, {int:max}'),
997
			array(
998
				'current_member' => $user_info['id'],
999
				'current_topic' => $topic,
1000
				'is_approved' => 1,
1001
				'blank_id_member' => 0,
1002
				'start' => $start,
1003
				'max' => $limit,
1004
			)
1005
		);
1006
1007
		while ($row = $smcFunc['db_fetch_assoc']($request))
1008
		{
1009
			if (!empty($row['id_member']))
1010
				$all_posters[$row['id_msg']] = $row['id_member'];
1011
			$messages[] = $row['id_msg'];
1012
		}
1013
1014
		// Sort the messages into the correct display order
1015
		if (!$DBascending)
1016
			sort($messages);
1017
	}
1018
1019
	// Remember the paging data for next time
1020
	$_SESSION['page_first_id'] = $ascending ? reset($messages) : end($messages);
1021
	$_SESSION['page_before_start'] = $_REQUEST['start'] - $limit;
1022
	$_SESSION['page_last_id'] = $ascending ? end($messages) : reset($messages);
1023
	$_SESSION['page_next_start'] = $_REQUEST['start'] + $limit;
1024
	$_SESSION['page_current_start'] = $_REQUEST['start'];
1025
	$_SESSION['page_topic'] = $topic;
1026
	$_SESSION['page_ascending'] = $ascending;
1027
1028
	$smcFunc['db_free_result']($request);
1029
	$posters = array_unique($all_posters);
1030
1031
	call_integration_hook('integrate_display_message_list', array(&$messages, &$posters));
1032
1033
	// Guests can't mark topics read or for notifications, just can't sorry.
1034
	if (!$user_info['is_guest'] && !empty($messages))
1035
	{
1036
		$mark_at_msg = max($messages);
1037
		if ($mark_at_msg >= $context['topicinfo']['id_last_msg'])
1038
			$mark_at_msg = $modSettings['maxMsgID'];
1039
		if ($mark_at_msg >= $context['topicinfo']['new_from'])
1040
		{
1041
			$smcFunc['db_insert']($context['topicinfo']['new_from'] == 0 ? 'ignore' : 'replace',
1042
				'{db_prefix}log_topics',
1043
				array(
1044
					'id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int', 'unwatched' => 'int',
1045
				),
1046
				array(
1047
					$user_info['id'], $topic, $mark_at_msg, $context['topicinfo']['unwatched'],
1048
				),
1049
				array('id_member', 'id_topic')
1050
			);
1051
		}
1052
1053
		// Check for notifications on this topic OR board.
1054
		$request = $smcFunc['db_query']('', '
1055
			SELECT sent, id_topic
1056
			FROM {db_prefix}log_notify
1057
			WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
1058
				AND id_member = {int:current_member}
1059
			LIMIT 2',
1060
			array(
1061
				'current_board' => $board,
1062
				'current_member' => $user_info['id'],
1063
				'current_topic' => $topic,
1064
			)
1065
		);
1066
		$do_once = true;
1067
		while ($row = $smcFunc['db_fetch_assoc']($request))
1068
		{
1069
			// Find if this topic is marked for notification...
1070
			if (!empty($row['id_topic']))
1071
				$context['is_marked_notify'] = true;
1072
1073
			// Only do this once, but mark the notifications as "not sent yet" for next time.
1074
			if (!empty($row['sent']) && $do_once)
1075
			{
1076
				$smcFunc['db_query']('', '
1077
					UPDATE {db_prefix}log_notify
1078
					SET sent = {int:is_not_sent}
1079
					WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
1080
						AND id_member = {int:current_member}',
1081
					array(
1082
						'current_board' => $board,
1083
						'current_member' => $user_info['id'],
1084
						'current_topic' => $topic,
1085
						'is_not_sent' => 0,
1086
					)
1087
				);
1088
				$do_once = false;
1089
			}
1090
		}
1091
1092
		// Have we recently cached the number of new topics in this board, and it's still a lot?
1093
		if (isset($_REQUEST['topicseen']) && isset($_SESSION['topicseen_cache'][$board]) && $_SESSION['topicseen_cache'][$board] > 5)
1094
			$_SESSION['topicseen_cache'][$board]--;
1095
		// Mark board as seen if this is the only new topic.
1096
		elseif (isset($_REQUEST['topicseen']))
1097
		{
1098
			// Use the mark read tables... and the last visit to figure out if this should be read or not.
1099
			$request = $smcFunc['db_query']('', '
1100
				SELECT COUNT(*)
1101
				FROM {db_prefix}topics AS t
1102
					LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = {int:current_board} AND lb.id_member = {int:current_member})
1103
					LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
1104
				WHERE t.id_board = {int:current_board}
1105
					AND t.id_last_msg > COALESCE(lb.id_msg, 0)
1106
					AND t.id_last_msg > COALESCE(lt.id_msg, 0)' . (empty($_SESSION['id_msg_last_visit']) ? '' : '
1107
					AND t.id_last_msg > {int:id_msg_last_visit}'),
1108
				array(
1109
					'current_board' => $board,
1110
					'current_member' => $user_info['id'],
1111
					'id_msg_last_visit' => (int) $_SESSION['id_msg_last_visit'],
1112
				)
1113
			);
1114
			list ($numNewTopics) = $smcFunc['db_fetch_row']($request);
1115
			$smcFunc['db_free_result']($request);
1116
1117
			// If there're no real new topics in this board, mark the board as seen.
1118
			if (empty($numNewTopics))
1119
				$_REQUEST['boardseen'] = true;
1120
			else
1121
				$_SESSION['topicseen_cache'][$board] = $numNewTopics;
1122
		}
1123
		// Probably one less topic - maybe not, but even if we decrease this too fast it will only make us look more often.
1124
		elseif (isset($_SESSION['topicseen_cache'][$board]))
1125
			$_SESSION['topicseen_cache'][$board]--;
1126
1127
		// Mark board as seen if we came using last post link from BoardIndex. (or other places...)
1128
		if (isset($_REQUEST['boardseen']))
1129
		{
1130
			$smcFunc['db_insert']('replace',
1131
				'{db_prefix}log_boards',
1132
				array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'),
1133
				array($modSettings['maxMsgID'], $user_info['id'], $board),
1134
				array('id_member', 'id_board')
1135
			);
1136
		}
1137
	}
1138
1139
	// Get notification preferences
1140
	$context['topicinfo']['notify_prefs'] = array();
1141
	if (!empty($user_info['id']))
1142
	{
1143
		require_once($sourcedir . '/Subs-Notify.php');
1144
		$prefs = getNotifyPrefs($user_info['id'], array('topic_notify', 'topic_notify_' . $context['current_topic']), true);
1145
		$pref = !empty($prefs[$user_info['id']]) && $context['is_marked_notify'] ? $prefs[$user_info['id']] : array();
1146
		$context['topicinfo']['notify_prefs'] = array(
1147
			'is_custom' => isset($pref['topic_notify_' . $topic]),
1148
			'pref' => isset($pref['topic_notify_' . $context['current_topic']]) ? $pref['topic_notify_' . $context['current_topic']] : (!empty($pref['topic_notify']) ? $pref['topic_notify'] : 0),
1149
		);
1150
	}
1151
1152
	$context['topic_notification'] = !empty($user_info['id']) ? $context['topicinfo']['notify_prefs'] : array();
1153
	// 0 => unwatched, 1 => normal, 2 => receive alerts, 3 => receive emails
1154
	$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;
1155
1156
	$context['loaded_attachments'] = array();
1157
1158
	// If there _are_ messages here... (probably an error otherwise :!)
1159
	if (!empty($messages))
1160
	{
1161
		// Fetch attachments.
1162
		if (!empty($modSettings['attachmentEnable']) && allowedTo('view_attachments'))
1163
		{
1164
			require_once($sourcedir . '/Subs-Attachments.php');
1165
			prepareAttachsByMsg($messages);
1166
		}
1167
1168
		$msg_parameters = array(
1169
			'message_list' => $messages,
1170
			'new_from' => $context['topicinfo']['new_from'],
1171
		);
1172
		$msg_selects = array();
1173
		$msg_tables = array();
1174
		call_integration_hook('integrate_query_message', array(&$msg_selects, &$msg_tables, &$msg_parameters));
1175
1176
		// What?  It's not like it *couldn't* be only guests in this topic...
1177
		loadMemberData($posters);
1178
		$messages_request = $smcFunc['db_query']('', '
1179
			SELECT
1180
				id_msg, icon, subject, poster_time, poster_ip, id_member, modified_time, modified_name, modified_reason, body,
1181
				smileys_enabled, poster_name, poster_email, approved, likes,
1182
				id_msg_modified < {int:new_from} AS is_read
1183
				' . (!empty($msg_selects) ? (', ' . implode(', ', $msg_selects)) : '') . '
1184
			FROM {db_prefix}messages
1185
				' . (!empty($msg_tables) ? implode("\n\t", $msg_tables) : '') . '
1186
			WHERE id_msg IN ({array_int:message_list})
1187
			ORDER BY id_msg' . (empty($options['view_newest_first']) ? '' : ' DESC'),
1188
			$msg_parameters
1189
		);
1190
1191
		// And the likes
1192
		if (!empty($modSettings['enable_likes']))
1193
			$context['my_likes'] = $context['user']['is_guest'] ? array() : prepareLikesContext($topic);
1194
1195
		// Go to the last message if the given time is beyond the time of the last message.
1196
		if (isset($context['start_from']) && $context['start_from'] >= $context['topicinfo']['num_replies'])
1197
			$context['start_from'] = $context['topicinfo']['num_replies'];
1198
1199
		// Since the anchor information is needed on the top of the page we load these variables beforehand.
1200
		$context['first_message'] = isset($messages[$firstIndex]) ? $messages[$firstIndex] : $messages[0];
1201
		if (empty($options['view_newest_first']))
1202
			$context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $context['start_from'];
1203
		else
1204
			$context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $context['topicinfo']['num_replies'] - $context['start_from'];
1205
	}
1206
	else
1207
	{
1208
		$messages_request = false;
1209
		$context['first_message'] = 0;
1210
		$context['first_new_message'] = false;
1211
1212
		$context['likes'] = array();
1213
	}
1214
1215
	$context['jump_to'] = array(
1216
		'label' => addslashes(un_htmlspecialchars($txt['jump_to'])),
1217
		'board_name' => $smcFunc['htmlspecialchars'](strtr(strip_tags($board_info['name']), array('&amp;' => '&'))),
1218
		'child_level' => $board_info['child_level'],
1219
	);
1220
1221
	// Set the callback.  (do you REALIZE how much memory all the messages would take?!?)
1222
	// This will be called from the template.
1223
	$context['get_message'] = 'prepareDisplayContext';
1224
1225
	// Now set all the wonderful, wonderful permissions... like moderation ones...
1226
	$common_permissions = array(
1227
		'can_approve' => 'approve_posts',
1228
		'can_ban' => 'manage_bans',
1229
		'can_sticky' => 'make_sticky',
1230
		'can_merge' => 'merge_any',
1231
		'can_split' => 'split_any',
1232
		'calendar_post' => 'calendar_post',
1233
		'can_send_pm' => 'pm_send',
1234
		'can_report_moderator' => 'report_any',
1235
		'can_moderate_forum' => 'moderate_forum',
1236
		'can_issue_warning' => 'issue_warning',
1237
		'can_restore_topic' => 'move_any',
1238
		'can_restore_msg' => 'move_any',
1239
		'can_like' => 'likes_like',
1240
	);
1241
	foreach ($common_permissions as $contextual => $perm)
1242
		$context[$contextual] = allowedTo($perm);
1243
1244
	// Permissions with _any/_own versions.  $context[YYY] => ZZZ_any/_own.
1245
	$anyown_permissions = array(
1246
		'can_move' => 'move',
1247
		'can_lock' => 'lock',
1248
		'can_delete' => 'remove',
1249
		'can_add_poll' => 'poll_add',
1250
		'can_remove_poll' => 'poll_remove',
1251
		'can_reply' => 'post_reply',
1252
		'can_reply_unapproved' => 'post_unapproved_replies',
1253
		'can_view_warning' => 'profile_warning',
1254
	);
1255
	foreach ($anyown_permissions as $contextual => $perm)
1256
		$context[$contextual] = allowedTo($perm . '_any') || ($context['user']['started'] && allowedTo($perm . '_own'));
1257
1258
	if (!$user_info['is_admin'] && $context['can_move'] && !$modSettings['topic_move_any'])
1259
	{
1260
		// We'll use this in a minute
1261
		$boards_allowed = array_diff(boardsAllowedTo('post_new'), array($board));
1262
1263
		/* You can't move this unless you have permission
1264
			to start new topics on at least one other board */
1265
		$context['can_move'] = count($boards_allowed) > 1;
1266
	}
1267
1268
	// If a topic is locked, you can't remove it unless it's yours and you locked it or you can lock_any
1269
	if ($context['topicinfo']['locked'])
1270
	{
1271
		$context['can_delete'] &= (($context['topicinfo']['locked'] == 1 && $context['user']['started']) || allowedTo('lock_any'));
1272
	}
1273
1274
	// Cleanup all the permissions with extra stuff...
1275
	$context['can_mark_notify'] = !$context['user']['is_guest'];
1276
	$context['calendar_post'] &= !empty($modSettings['cal_enabled']);
1277
	$context['can_add_poll'] &= $modSettings['pollMode'] == '1' && $context['topicinfo']['id_poll'] <= 0;
1278
	$context['can_remove_poll'] &= $modSettings['pollMode'] == '1' && $context['topicinfo']['id_poll'] > 0;
1279
	$context['can_reply'] &= empty($context['topicinfo']['locked']) || allowedTo('moderate_board');
1280
	$context['can_reply_unapproved'] &= $modSettings['postmod_active'] && (empty($context['topicinfo']['locked']) || allowedTo('moderate_board'));
1281
	$context['can_issue_warning'] &= $modSettings['warning_settings'][0] == 1;
1282
	// Handle approval flags...
1283
	$context['can_reply_approved'] = $context['can_reply'];
1284
	$context['can_reply'] |= $context['can_reply_unapproved'];
1285
	$context['can_quote'] = $context['can_reply'] && (empty($modSettings['disabledBBC']) || !in_array('quote', explode(',', $modSettings['disabledBBC'])));
1286
	$context['can_mark_unread'] = !$user_info['is_guest'];
1287
	$context['can_unwatch'] = !$user_info['is_guest'];
1288
	$context['can_set_notify'] = !$user_info['is_guest'];
1289
1290
	$context['can_print'] = empty($modSettings['disable_print_topic']);
1291
1292
	// Start this off for quick moderation - it will be or'd for each post.
1293
	$context['can_remove_post'] = allowedTo('delete_any') || (allowedTo('delete_replies') && $context['user']['started']);
1294
1295
	// Can restore topic?  That's if the topic is in the recycle board and has a previous restore state.
1296
	$context['can_restore_topic'] &= !empty($board_info['recycle']) && !empty($context['topicinfo']['id_previous_board']);
1297
	$context['can_restore_msg'] &= !empty($board_info['recycle']) && !empty($context['topicinfo']['id_previous_topic']);
1298
1299
	// Check if the draft functions are enabled and that they have permission to use them (for quick reply.)
1300
	$context['drafts_save'] = !empty($modSettings['drafts_post_enabled']) && allowedTo('post_draft') && $context['can_reply'];
1301
	$context['drafts_autosave'] = !empty($context['drafts_save']) && !empty($modSettings['drafts_autosave_enabled']);
1302
	if (!empty($context['drafts_save']))
1303
		loadLanguage('Drafts');
1304
1305
	// When was the last time this topic was replied to?  Should we warn them about it?
1306
	if (!empty($modSettings['oldTopicDays']) && ($context['can_reply'] || $context['can_reply_unapproved']) && empty($context['topicinfo']['is_sticky']))
1307
	{
1308
		$request = $smcFunc['db_query']('', '
1309
			SELECT poster_time
1310
			FROM {db_prefix}messages
1311
			WHERE id_msg = {int:id_last_msg}
1312
			LIMIT 1',
1313
			array(
1314
				'id_last_msg' => $context['topicinfo']['id_last_msg'],
1315
			)
1316
		);
1317
1318
		list ($lastPostTime) = $smcFunc['db_fetch_row']($request);
1319
		$smcFunc['db_free_result']($request);
1320
1321
		$context['oldTopicError'] = $lastPostTime + $modSettings['oldTopicDays'] * 86400 < time();
1322
	}
1323
1324
	// You can't link an existing topic to the calendar unless you can modify the first post...
1325
	$context['calendar_post'] &= allowedTo('modify_any') || (allowedTo('modify_own') && $context['user']['started']);
1326
1327
	// Load up the "double post" sequencing magic.
1328
	checkSubmitOnce('register');
1329
	$context['name'] = isset($_SESSION['guest_name']) ? $_SESSION['guest_name'] : '';
1330
	$context['email'] = isset($_SESSION['guest_email']) ? $_SESSION['guest_email'] : '';
1331
	// Needed for the editor and message icons.
1332
	require_once($sourcedir . '/Subs-Editor.php');
1333
1334
	// Now create the editor.
1335
	$editorOptions = array(
1336
		'id' => 'quickReply',
1337
		'value' => '',
1338
		'disable_smiley_box' => empty($options['use_editor_quick_reply']),
1339
		'labels' => array(
1340
			'post_button' => $txt['post'],
1341
		),
1342
		// add height and width for the editor
1343
		'height' => '250px',
1344
		'width' => '100%',
1345
		// We do HTML preview here.
1346
		'preview_type' => 1,
1347
		// This is required
1348
		'required' => true,
1349
	);
1350
	create_control_richedit($editorOptions);
1351
1352
	// Store the ID.
1353
	$context['post_box_name'] = $editorOptions['id'];
1354
1355
	// Set a flag so the sub template knows what to do...
1356
	$context['show_bbc'] = !empty($options['use_editor_quick_reply']);
1357
	$modSettings['disable_wysiwyg'] = !empty($options['use_editor_quick_reply']);
1358
	$context['attached'] = '';
1359
	$context['make_poll'] = isset($_REQUEST['poll']);
1360
1361
	// Message icons - customized icons are off?
1362
	$context['icons'] = getMessageIcons($board);
1363
1364
	if (!empty($context['icons']))
1365
		$context['icons'][count($context['icons']) - 1]['is_last'] = true;
1366
1367
	// Build the normal button array.
1368
	$context['normal_buttons'] = array();
1369
1370
	if ($context['can_reply'])
1371
		$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);
1372
1373
	if ($context['can_add_poll'])
1374
		$context['normal_buttons']['add_poll'] = array('text' => 'add_poll', 'url' => $scripturl . '?action=editpoll;add;topic=' . $context['current_topic'] . '.' . $context['start']);
1375
1376
	if ($context['can_mark_unread'])
1377
		$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']);
1378
1379
	if ($context['can_print'])
1380
		$context['normal_buttons']['print'] = array('text' => 'print', 'custom' => 'rel="nofollow"', 'url' => $scripturl . '?action=printpage;topic=' . $context['current_topic'] . '.0');
1381
1382
	if ($context['can_set_notify'])
1383
		$context['normal_buttons']['notify'] = array(
1384
			'text' => 'notify_topic_' . $context['topic_notification_mode'],
1385
			'sub_buttons' => array(
1386
				array(
1387
					'test' => 'can_unwatch',
1388
					'text' => 'notify_topic_0',
1389
					'url' => $scripturl . '?action=notifytopic;topic=' . $context['current_topic'] . ';mode=0;' . $context['session_var'] . '=' . $context['session_id'],
1390
				),
1391
				array(
1392
					'text' => 'notify_topic_1',
1393
					'url' => $scripturl . '?action=notifytopic;topic=' . $context['current_topic'] . ';mode=1;' . $context['session_var'] . '=' . $context['session_id'],
1394
				),
1395
				array(
1396
					'text' => 'notify_topic_2',
1397
					'url' => $scripturl . '?action=notifytopic;topic=' . $context['current_topic'] . ';mode=2;' . $context['session_var'] . '=' . $context['session_id'],
1398
				),
1399
				array(
1400
					'text' => 'notify_topic_3',
1401
					'url' => $scripturl . '?action=notifytopic;topic=' . $context['current_topic'] . ';mode=3;' . $context['session_var'] . '=' . $context['session_id'],
1402
				),
1403
			),
1404
		);
1405
1406
	// Build the mod button array
1407
	$context['mod_buttons'] = array();
1408
1409
	if ($context['can_move'])
1410
		$context['mod_buttons']['move'] = array('text' => 'move_topic', 'url' => $scripturl . '?action=movetopic;current_board=' . $context['current_board'] . ';topic=' . $context['current_topic'] . '.0');
1411
1412
	if ($context['can_delete'])
1413
		$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']);
1414
1415
	if ($context['can_lock'])
1416
		$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']);
1417
1418
	if ($context['can_sticky'])
1419
		$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']);
1420
1421
	if ($context['can_merge'])
1422
		$context['mod_buttons']['merge'] = array('text' => 'merge', 'url' => $scripturl . '?action=mergetopics;board=' . $context['current_board'] . '.0;from=' . $context['current_topic']);
1423
1424
	if ($context['calendar_post'])
1425
		$context['mod_buttons']['calendar'] = array('text' => 'calendar_link', 'url' => $scripturl . '?action=post;calendar;msg=' . $context['topic_first_message'] . ';topic=' . $context['current_topic'] . '.0');
1426
1427
	// Restore topic. eh?  No monkey business.
1428
	if ($context['can_restore_topic'])
1429
		$context['mod_buttons']['restore_topic'] = array('text' => 'restore_topic', 'url' => $scripturl . '?action=restoretopic;topics=' . $context['current_topic'] . ';' . $context['session_var'] . '=' . $context['session_id']);
1430
1431
	// Show a message in case a recently posted message became unapproved.
1432
	$context['becomesUnapproved'] = !empty($_SESSION['becomesUnapproved']);
1433
	unset($_SESSION['becomesUnapproved']);
1434
1435
	// Allow adding new mod buttons easily.
1436
	// Note: $context['normal_buttons'] and $context['mod_buttons'] are added for backward compatibility with 2.0, but are deprecated and should not be used
1437
	call_integration_hook('integrate_display_buttons', array(&$context['normal_buttons']));
1438
	// Note: integrate_mod_buttons is no more necessary and deprecated, but is kept for backward compatibility with 2.0
1439
	call_integration_hook('integrate_mod_buttons', array(&$context['mod_buttons']));
1440
1441
	// Load the drafts js file
1442
	if ($context['drafts_autosave'])
1443
		loadJavaScriptFile('drafts.js', array('defer' => false, 'minimize' => true), 'smf_drafts');
1444
1445
	// Spellcheck
1446
	if ($context['show_spellchecking'])
1447
		loadJavaScriptFile('spellcheck.js', array('defer' => false, 'minimize' => true), 'smf_spellcheck');
1448
1449
	// topic.js
1450
	loadJavaScriptFile('topic.js', array('defer' => false, 'minimize' => true), 'smf_topic');
1451
1452
	// quotedText.js
1453
	loadJavaScriptFile('quotedText.js', array('defer' => true, 'minimize' => true), 'smf_quotedText');
1454
1455
	// Mentions
1456
	if (!empty($modSettings['enable_mentions']) && allowedTo('mention'))
1457
	{
1458
		loadJavaScriptFile('jquery.atwho.min.js', array('defer' => true), 'smf_atwho');
1459
		loadJavaScriptFile('jquery.caret.min.js', array('defer' => true), 'smf_caret');
1460
		loadJavaScriptFile('mentions.js', array('defer' => true, 'minimize' => true), 'smf_mentions');
1461
	}
1462
}
1463
1464
/**
1465
 * Callback for the message display.
1466
 * It actually gets and prepares the message context.
1467
 * This function will start over from the beginning if reset is set to true, which is
1468
 * useful for showing an index before or after the posts.
1469
 *
1470
 * @param bool $reset Whether or not to reset the db seek pointer
1471
 * @return array A large array of contextual data for the posts
1472
 */
1473
function prepareDisplayContext($reset = false)
1474
{
1475
	global $settings, $txt, $modSettings, $scripturl, $options, $user_info, $smcFunc;
1476
	global $memberContext, $context, $messages_request, $topic, $board_info, $sourcedir;
1477
1478
	static $counter = null;
1479
1480
	// If the query returned false, bail.
1481
	if ($messages_request == false)
1482
		return false;
1483
1484
	// Remember which message this is.  (ie. reply #83)
1485
	if ($counter === null || $reset)
1486
		$counter = empty($options['view_newest_first']) ? $context['start'] : $context['total_visible_posts'] - $context['start'];
1487
1488
	// Start from the beginning...
1489
	if ($reset)
1490
		return @$smcFunc['db_data_seek']($messages_request, 0);
1491
1492
	// Attempt to get the next message.
1493
	$message = $smcFunc['db_fetch_assoc']($messages_request);
1494
	if (!$message)
1495
	{
1496
		$smcFunc['db_free_result']($messages_request);
1497
		return false;
1498
	}
1499
1500
	// $context['icon_sources'] says where each icon should come from - here we set up the ones which will always exist!
1501
	if (empty($context['icon_sources']))
1502
	{
1503
		$context['icon_sources'] = array();
1504
		foreach ($context['stable_icons'] as $icon)
1505
			$context['icon_sources'][$icon] = 'images_url';
1506
	}
1507
1508
	// Message Icon Management... check the images exist.
1509
	if (empty($modSettings['messageIconChecks_disable']))
1510
	{
1511
		// If the current icon isn't known, then we need to do something...
1512
		if (!isset($context['icon_sources'][$message['icon']]))
1513
			$context['icon_sources'][$message['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['icon'] . '.png') ? 'images_url' : 'default_images_url';
1514
	}
1515
	elseif (!isset($context['icon_sources'][$message['icon']]))
1516
		$context['icon_sources'][$message['icon']] = 'images_url';
1517
1518
	// If you're a lazy bum, you probably didn't give a subject...
1519
	$message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
1520
1521
	// Are you allowed to remove at least a single reply?
1522
	$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'];
1523
1524
	// If the topic is locked, you might not be able to delete the post...
1525
	if ($context['is_locked'])
1526
	{
1527
		$context['can_remove_post'] &= ($context['user']['started'] && $context['is_locked'] == 1) || allowedTo('lock_any');
1528
	}
1529
1530
	// If it couldn't load, or the user was a guest.... someday may be done with a guest table.
1531
	if (!loadMemberContext($message['id_member'], true))
1532
	{
1533
		// Notice this information isn't used anywhere else....
1534
		$memberContext[$message['id_member']]['name'] = $message['poster_name'];
1535
		$memberContext[$message['id_member']]['id'] = 0;
1536
		$memberContext[$message['id_member']]['group'] = $txt['guest_title'];
1537
		$memberContext[$message['id_member']]['link'] = $message['poster_name'];
1538
		$memberContext[$message['id_member']]['email'] = $message['poster_email'];
1539
		$memberContext[$message['id_member']]['show_email'] = allowedTo('moderate_forum');
1540
		$memberContext[$message['id_member']]['is_guest'] = true;
1541
	}
1542
	else
1543
	{
1544
		// Define this here to make things a bit more readable
1545
		$can_view_warning = allowedTo('moderate_forum') || allowedTo('view_warning_any') || ($message['id_member'] == $user_info['id'] && allowedTo('view_warning_own'));
1546
1547
		$memberContext[$message['id_member']]['can_view_profile'] = allowedTo('profile_view') || ($message['id_member'] == $user_info['id'] && !$user_info['is_guest']);
1548
		$memberContext[$message['id_member']]['is_topic_starter'] = $message['id_member'] == $context['topic_starter_id'];
1549
		$memberContext[$message['id_member']]['can_see_warning'] = !isset($context['disabled_fields']['warning_status']) && $memberContext[$message['id_member']]['warning_status'] && $can_view_warning;
1550
		// Show the email if it's your post...
1551
		$memberContext[$message['id_member']]['show_email'] |= ($message['id_member'] == $user_info['id']);
1552
	}
1553
1554
	$memberContext[$message['id_member']]['ip'] = inet_dtop($message['poster_ip']);
1555
	$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']);
1556
1557
	// Do the censor thang.
1558
	censorText($message['body']);
1559
	censorText($message['subject']);
1560
1561
	// Run BBC interpreter on the message.
1562
	$message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
1563
1564
	// If it's in the recycle bin we need to override whatever icon we did have.
1565
	if (!empty($board_info['recycle']))
1566
		$message['icon'] = 'recycled';
1567
1568
	require_once($sourcedir . '/Subs-Attachments.php');
1569
1570
	// Compose the memory eat- I mean message array.
1571
	$output = array(
1572
		'attachment' => loadAttachmentContext($message['id_msg'], $context['loaded_attachments']),
1573
		'id' => $message['id_msg'],
1574
		'href' => $scripturl . '?msg=' . $message['id_msg'],
1575
		'link' => '<a href="' . $scripturl . '?msg=' . $message['id_msg'] . '" rel="nofollow">' . $message['subject'] . '</a>',
1576
		'member' => &$memberContext[$message['id_member']],
1577
		'icon' => $message['icon'],
1578
		'icon_url' => $settings[$context['icon_sources'][$message['icon']]] . '/post/' . $message['icon'] . '.png',
1579
		'subject' => $message['subject'],
1580
		'time' => timeformat($message['poster_time']),
1581
		'timestamp' => forum_time(true, $message['poster_time']),
1582
		'counter' => $counter,
1583
		'modified' => array(
1584
			'time' => timeformat($message['modified_time']),
1585
			'timestamp' => forum_time(true, $message['modified_time']),
1586
			'name' => $message['modified_name'],
1587
			'reason' => $message['modified_reason']
1588
		),
1589
		'body' => $message['body'],
1590
		'new' => empty($message['is_read']),
1591
		'approved' => $message['approved'],
1592
		'first_new' => isset($context['start_from']) && $context['start_from'] == $counter,
1593
		'is_ignored' => !empty($modSettings['enable_buddylist']) && !empty($options['posts_apply_ignore_list']) && in_array($message['id_member'], $context['user']['ignoreusers']),
1594
		'can_approve' => !$message['approved'] && $context['can_approve'],
1595
		'can_unapprove' => !empty($modSettings['postmod_active']) && $context['can_approve'] && $message['approved'],
1596
		'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()))),
1597
		'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())),
1598
		'can_see_ip' => allowedTo('moderate_forum') || ($message['id_member'] == $user_info['id'] && !empty($user_info['id'])),
1599
		'css_class' => $message['approved'] ? 'windowbg' : 'approvebg',
1600
	);
1601
1602
	// Does the file contains any attachments? if so, change the icon.
1603
	if (!empty($output['attachment']))
1604
	{
1605
		$output['icon'] = 'clip';
1606
		$output['icon_url'] = $settings[$context['icon_sources'][$output['icon']]] . '/post/' . $output['icon'] . '.png';
1607
	}
1608
1609
	// Are likes enable?
1610
	if (!empty($modSettings['enable_likes']))
1611
		$output['likes'] = array(
1612
			'count' => $message['likes'],
1613
			'you' => in_array($message['id_msg'], $context['my_likes']),
1614
			'can_like' => !$context['user']['is_guest'] && $message['id_member'] != $context['user']['id'] && !empty($context['can_like']),
1615
		);
1616
1617
	// Is this user the message author?
1618
	$output['is_message_author'] = $message['id_member'] == $user_info['id'];
1619
	if (!empty($output['modified']['name']))
1620
		$output['modified']['last_edit_text'] = sprintf($txt['last_edit_by'], $output['modified']['time'], $output['modified']['name']);
1621
1622
	// Did they give a reason for editing?
1623
	if (!empty($output['modified']['name']) && !empty($output['modified']['reason']))
1624
		$output['modified']['last_edit_text'] .= '&nbsp;' . sprintf($txt['last_edit_reason'], $output['modified']['reason']);
1625
1626
	// Any custom profile fields?
1627
	if (!empty($memberContext[$message['id_member']]['custom_fields']))
1628
		foreach ($memberContext[$message['id_member']]['custom_fields'] as $custom)
1629
			$output['custom_fields'][$context['cust_profile_fields_placement'][$custom['placement']]][] = $custom;
1630
1631
	$output['quickbuttons'] = array(
1632
		'quote' => array(
1633
			'label' => $txt['quote_action'],
1634
			'href' => $scripturl.'?action=post;quote='.$output['id'].';topic='.$context['current_topic'], '.'.$context['start'].';last_msg='.$context['topic_last_message'],
1635
			'javascript' => 'onclick="return oQuickReply.quote('.$output['id'].');"',
1636
			'icon' => 'quote',
1637
			'show' => $context['can_quote']
1638
		),
1639
		'quote_selected' => array(
1640
			'label' => $txt['quote_selected_action'],
1641
			'id' => 'quoteSelected_'. $output['id'],
1642
			'href' => 'javascript:void(0)',
1643
			'custom' => 'style="display:none"',
1644
			'icon' => 'quote_selected',
1645
			'show' => $context['can_quote']
1646
		),
1647
		'quick_edit' => array(
1648
			'label' => $txt['quick_edit'],
1649
			'class' => 'quick_edit',
1650
			'id' =>' modify_button_'. $output['id'],
1651
			'custom' => 'onclick="oQuickModify.modifyMsg(\''.$output['id'].'\', \''.!empty($modSettings['toggle_subject']).'\')"',
1652
			'icon' => 'quick_edit_button',
1653
			'show' => $output['can_modify']
1654
		),
1655
		'more' => array(
1656
			'modify' => array(
1657
				'label' => $txt['modify'],
1658
				'href' => $scripturl.'?action=post;msg='.$output['id'].';topic='.$context['current_topic'].'.'.$context['start'],
1659
				'icon' => 'modify_button',
1660
				'show' => $output['can_modify']
1661
			),
1662
			'remove_topic' => array(
1663
				'label' => $txt['remove_topic'],
1664
				'href' => $scripturl.'?action=removetopic2;topic='.$context['current_topic'].'.'.$context['start'].';'.$context['session_var'].'='.$context['session_id'],
1665
				'javascript' => 'data-confirm="'.$txt['are_sure_remove_topic'].'" class="you_sure"',
1666
				'icon' => 'remove_button',
1667
				'show' => $context['can_delete'] && ($context['topic_first_message'] == $output['id'])
1668
			),
1669
			'remove' => array(
1670
				'label' => $txt['remove'],
1671
				'href' => $scripturl.'?action=deletemsg;topic='.$context['current_topic'].'.'.$context['start'].';msg='.$output['id'].';'.$context['session_var'].'='.$context['session_id'],
1672
				'javascript' => 'data-confirm="'.$txt['remove_message_question'].'" class="you_sure"',
1673
				'icon' => 'remove_button',
1674
				'show' => $output['can_remove'] && ($context['topic_first_message'] != $output['id'])
1675
			),
1676
			'split' => array(
1677
				'label' => $txt['split'],
1678
				'href' => $scripturl.'?action=splittopics;topic='.$context['current_topic'].'.0;at='.$output['id'],
1679
				'icon' => 'split_button',
1680
				'show' => $context['can_split'] && !empty($context['real_num_replies'])
1681
			),
1682
			'report' => array(
1683
				'label' => $txt['report_to_mod'],
1684
				'href' => $scripturl.'?action=reporttm;topic='.$context['current_topic'].'.'.$output['counter'].';msg='.$output['id'],
1685
				'icon' => 'error',
1686
				'show' => $context['can_report_moderator']
1687
			),
1688
			'warn' => array(
1689
				'label' => $txt['issue_warning'],
1690
				'href' => $scripturl.'?action=profile;area=issuewarning;u='.$output['member']['id'].';msg='.$output['id'],
1691
				'icon' => 'warn_button',
1692
				'show' => $context['can_issue_warning'] && !$output['is_message_author'] && !$output['member']['is_guest']
1693
			),
1694
			'restore' => array(
1695
				'label' => $txt['restore_message'],
1696
				'href' => $scripturl.'?action=restoretopic;msgs='.$output['id'].';'.$context['session_var'].'='.$context['session_id'],
1697
				'icon' => 'restore_button',
1698
				'show' => $context['can_restore_msg']
1699
			),
1700
			'approve' => array(
1701
				'label' => $txt['approve'],
1702
				'href' => $scripturl.'?action=moderate;area=postmod;sa=approve;topic='.$context['current_topic'].'.'.$context['start'].';msg='.$output['id'].';'.$context['session_var'].'='.$context['session_id'],
1703
				'icon' => 'approve_button',
1704
				'show' => $output['can_approve']
1705
			),
1706
			'unapprove' => array(
1707
				'label' => $txt['unapprove'],
1708
				'href' => $scripturl.'?action=moderate;area=postmod;sa=approve;topic='.$context['current_topic'].'.'.$context['start'].';msg='.$output['id'].';'.$context['session_var'].'='.$context['session_id'],
1709
				'icon' => 'unapprove_button',
1710
				'show' => $output['can_unapprove']
1711
			),
1712
		),
1713
		'quickmod' => array(
1714
			'id' => 'in_topic_mod_check_'. $output['id'],
1715
			'custom' => 'style="display: none;"',
1716
			'content' => '',
1717
			'show' => !empty($options['display_quick_mod']) && $options['display_quick_mod'] == 1 && $output['can_remove'],
1718
		)
1719
	);
1720
1721
	if (empty($options['view_newest_first']))
1722
		$counter++;
1723
1724
	else
1725
		$counter--;
1726
1727
	call_integration_hook('integrate_prepare_display_context', array(&$output, &$message, $counter));
1728
1729
	return $output;
1730
}
1731
1732
/**
1733
 * Once upon a time, this function handled downloading attachments.
1734
 * Now it's just an alias retained for the sake of backwards compatibility.
1735
 */
1736
function Download()
1737
{
1738
	global $sourcedir;
1739
	require_once($sourcedir . '/ShowAttachments.php');
1740
	showAttachment();
1741
}
1742
1743
/**
1744
 * In-topic quick moderation.
1745
 */
1746
function QuickInTopicModeration()
1747
{
1748
	global $sourcedir, $topic, $board, $user_info, $smcFunc, $modSettings, $context;
1749
1750
	// Check the session = get or post.
1751
	checkSession('request');
1752
1753
	require_once($sourcedir . '/RemoveTopic.php');
1754
1755
	if (empty($_REQUEST['msgs']))
1756
		redirectexit('topic=' . $topic . '.' . $_REQUEST['start']);
1757
1758
	$messages = array();
1759
	foreach ($_REQUEST['msgs'] as $dummy)
1760
		$messages[] = (int) $dummy;
1761
1762
	// We are restoring messages. We handle this in another place.
1763
	if (isset($_REQUEST['restore_selected']))
1764
		redirectexit('action=restoretopic;msgs=' . implode(',', $messages) . ';' . $context['session_var'] . '=' . $context['session_id']);
1765
	if (isset($_REQUEST['split_selection']))
1766
	{
1767
		$request = $smcFunc['db_query']('', '
1768
			SELECT subject
1769
			FROM {db_prefix}messages
1770
			WHERE id_msg = {int:message}
1771
			LIMIT 1',
1772
			array(
1773
				'message' => min($messages),
1774
			)
1775
		);
1776
		list($subname) = $smcFunc['db_fetch_row']($request);
1777
		$smcFunc['db_free_result']($request);
1778
		$_SESSION['split_selection'][$topic] = $messages;
1779
		redirectexit('action=splittopics;sa=selectTopics;topic=' . $topic . '.0;subname_enc=' . urlencode($subname) . ';' . $context['session_var'] . '=' . $context['session_id']);
1780
	}
1781
1782
	// Allowed to delete any message?
1783
	if (allowedTo('delete_any'))
1784
		$allowed_all = true;
1785
	// Allowed to delete replies to their messages?
1786
	elseif (allowedTo('delete_replies'))
1787
	{
1788
		$request = $smcFunc['db_query']('', '
1789
			SELECT id_member_started
1790
			FROM {db_prefix}topics
1791
			WHERE id_topic = {int:current_topic}
1792
			LIMIT 1',
1793
			array(
1794
				'current_topic' => $topic,
1795
			)
1796
		);
1797
		list ($starter) = $smcFunc['db_fetch_row']($request);
1798
		$smcFunc['db_free_result']($request);
1799
1800
		$allowed_all = $starter == $user_info['id'];
1801
	}
1802
	else
1803
		$allowed_all = false;
1804
1805
	// Make sure they're allowed to delete their own messages, if not any.
1806
	if (!$allowed_all)
1807
		isAllowedTo('delete_own');
1808
1809
	// Allowed to remove which messages?
1810
	$request = $smcFunc['db_query']('', '
1811
		SELECT id_msg, subject, id_member, poster_time
1812
		FROM {db_prefix}messages
1813
		WHERE id_msg IN ({array_int:message_list})
1814
			AND id_topic = {int:current_topic}' . (!$allowed_all ? '
1815
			AND id_member = {int:current_member}' : '') . '
1816
		LIMIT {int:limit}',
1817
		array(
1818
			'current_member' => $user_info['id'],
1819
			'current_topic' => $topic,
1820
			'message_list' => $messages,
1821
			'limit' => count($messages),
1822
		)
1823
	);
1824
	$messages = array();
1825
	while ($row = $smcFunc['db_fetch_assoc']($request))
1826
	{
1827
		if (!$allowed_all && !empty($modSettings['edit_disable_time']) && $row['poster_time'] + $modSettings['edit_disable_time'] * 60 < time())
1828
			continue;
1829
1830
		$messages[$row['id_msg']] = array($row['subject'], $row['id_member']);
1831
	}
1832
	$smcFunc['db_free_result']($request);
1833
1834
	// Get the first message in the topic - because you can't delete that!
1835
	$request = $smcFunc['db_query']('', '
1836
		SELECT id_first_msg, id_last_msg
1837
		FROM {db_prefix}topics
1838
		WHERE id_topic = {int:current_topic}
1839
		LIMIT 1',
1840
		array(
1841
			'current_topic' => $topic,
1842
		)
1843
	);
1844
	list ($first_message, $last_message) = $smcFunc['db_fetch_row']($request);
1845
	$smcFunc['db_free_result']($request);
1846
1847
	// Delete all the messages we know they can delete. ($messages)
1848
	foreach ($messages as $message => $info)
1849
	{
1850
		// Just skip the first message - if it's not the last.
1851
		if ($message == $first_message && $message != $last_message)
1852
			continue;
1853
		// If the first message is going then don't bother going back to the topic as we're effectively deleting it.
1854
		elseif ($message == $first_message)
1855
			$topicGone = true;
1856
1857
		removeMessage($message);
1858
1859
		// Log this moderation action ;).
1860
		if (allowedTo('delete_any') && (!allowedTo('delete_own') || $info[1] != $user_info['id']))
1861
			logAction('delete', array('topic' => $topic, 'subject' => $info[0], 'member' => $info[1], 'board' => $board));
1862
	}
1863
1864
	redirectexit(!empty($topicGone) ? 'board=' . $board : 'topic=' . $topic . '.' . $_REQUEST['start']);
1865
}
1866
1867
?>