Issues (1065)

Sources/Display.php (2 issues)

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