Passed
Pull Request — release-2.1 (#5574)
by John
04:35
created

approved_attach_sort()   A

Complexity

Conditions 3

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 3
c 0
b 0
f 0
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
/**
4
 * This is perhaps the most important and probably most accessed file in all
5
 * of SMF.  This file controls topic, message, and attachment display.
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines http://www.simplemachines.org
11
 * @copyright 2019 Simple Machines and individual contributors
12
 * @license http://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 RC2
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * The central part of the board - topic display.
22
 * This function loads the posts in a topic up so they can be displayed.
23
 * It uses the main sub template of the Display template.
24
 * It requires a topic, and can go to the previous or next topic from it.
25
 * It jumps to the correct post depending on a number/time/IS_MSG passed.
26
 * It depends on the messages_per_page, defaultMaxMessages and enableAllMessages settings.
27
 * It is accessed by ?topic=id_topic.START.
28
 *
29
 * @return void
30
 */
31
function Display()
32
{
33
	global $scripturl, $txt, $modSettings, $context, $settings;
34
	global $options, $sourcedir, $user_info, $board_info, $topic, $board;
35
	global $messages_request, $language, $smcFunc;
36
37
	// What are you gonna display if these are empty?!
38
	if (empty($topic))
39
		fatal_lang_error('no_board', false);
40
41
	// Load the proper template.
42
	loadTemplate('Display');
43
44
	// Not only does a prefetch make things slower for the server, but it makes it impossible to know if they read it.
45
	if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
46
	{
47
		ob_end_clean();
48
		send_http_status(403, 'Prefetch Forbidden');
49
		die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

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