prepareDisplayContext()   F
last analyzed

Complexity

Conditions 76

Size

Total Lines 260
Code Lines 175

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 76
eloc 175
nop 1
dl 0
loc 260
rs 3.3333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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