Failed Conditions
Branch release-2.1 (4e22cf)
by Rick
06:39
created

SSI.php ➔ ssi_logOnline()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Simple Machines Forum (SMF)
5
 *
6
 * @package SMF
7
 * @author Simple Machines http://www.simplemachines.org
8
 * @copyright 2017 Simple Machines and individual contributors
9
 * @license http://www.simplemachines.org/about/smf/license.php BSD
10
 *
11
 * @version 2.1 Beta 4
12
 */
13
14
// Don't do anything if SMF is already loaded.
15
if (defined('SMF'))
16
	return true;
17
18
define('SMF', 'SSI');
19
20
// We're going to want a few globals... these are all set later.
21
global $time_start, $maintenance, $msubject, $mmessage, $mbname, $language;
22
global $boardurl, $boarddir, $sourcedir, $webmaster_email, $cookiename;
23
global $db_type, $db_server, $db_name, $db_user, $db_prefix, $db_persist, $db_error_send, $db_last_error;
24
global $db_connection, $modSettings, $context, $sc, $user_info, $topic, $board, $txt;
25
global $smcFunc, $ssi_db_user, $scripturl, $ssi_db_passwd, $db_passwd, $cachedir;
26
27
// Remember the current configuration so it can be set back.
28
$time_start = microtime();
29
30
// Just being safe...
31
foreach (array('db_character_set', 'cachedir') as $variable)
32
	if (isset($GLOBALS[$variable]))
33
		unset($GLOBALS[$variable]);
34
35
// Get the forum's settings for database and file paths.
36
require_once(dirname(__FILE__) . '/Settings.php');
37
38
// Make absolutely sure the cache directory is defined.
39 View Code Duplication
if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache'))
40
	$cachedir = $boarddir . '/cache';
41
42
$ssi_error_reporting = error_reporting(defined('E_STRICT') ? E_ALL | E_STRICT : E_ALL);
43
/* Set this to one of three values depending on what you want to happen in the case of a fatal error.
44
	false:	Default, will just load the error sub template and die - not putting any theme layers around it.
45
	true:	Will load the error sub template AND put the SMF layers around it (Not useful if on total custom pages).
46
	string:	Name of a callback function to call in the event of an error to allow you to define your own methods. Will die after function returns.
47
*/
48
$ssi_on_error_method = false;
49
50
// Don't do john didley if the forum's been shut down completely.
51
if ($maintenance == 2 && (!isset($ssi_maintenance_off) || $ssi_maintenance_off !== true))
52
	die($mmessage);
53
54
// Fix for using the current directory as a path.
55 View Code Duplication
if (substr($sourcedir, 0, 1) == '.' && substr($sourcedir, 1, 1) != '.')
56
	$sourcedir = dirname(__FILE__) . substr($sourcedir, 1);
57
58
// Load the important includes.
59
require_once($sourcedir . '/QueryString.php');
60
require_once($sourcedir . '/Session.php');
61
require_once($sourcedir . '/Subs.php');
62
require_once($sourcedir . '/Errors.php');
63
require_once($sourcedir . '/Logging.php');
64
require_once($sourcedir . '/Load.php');
65
require_once($sourcedir . '/Security.php');
66
require_once($sourcedir . '/Class-BrowserDetect.php');
67
require_once($sourcedir . '/Subs-Auth.php');
68
69
// Create a variable to store some SMF specific functions in.
70
$smcFunc = array();
71
72
// Initiate the database connection and define some database functions to use.
73
loadDatabase();
74
75
// Load installed 'Mods' settings.
76
reloadSettings();
77
// Clean the request variables.
78
cleanRequest();
79
80
// Seed the random generator?
81
if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69)
82
	smf_seed_generator();
83
84
// Check on any hacking attempts.
85
if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']))
86
	die('No direct access...');
87
elseif (isset($_REQUEST['ssi_theme']) && (int) $_REQUEST['ssi_theme'] == (int) $ssi_theme)
88
	die('No direct access...');
89
elseif (isset($_COOKIE['ssi_theme']) && (int) $_COOKIE['ssi_theme'] == (int) $ssi_theme)
90
	die('No direct access...');
91
elseif (isset($_REQUEST['ssi_layers'], $ssi_layers) && (@get_magic_quotes_gpc() ? stripslashes($_REQUEST['ssi_layers']) : $_REQUEST['ssi_layers']) == $ssi_layers)
92
	die('No direct access...');
93
if (isset($_REQUEST['context']))
94
	die('No direct access...');
95
96
// Gzip output? (because it must be boolean and true, this can't be hacked.)
97
if (isset($ssi_gzip) && $ssi_gzip === true && ini_get('zlib.output_compression') != '1' && ini_get('output_handler') != 'ob_gzhandler' && version_compare(PHP_VERSION, '4.2.0', '>='))
98
	ob_start('ob_gzhandler');
99
else
100
	$modSettings['enableCompressedOutput'] = '0';
101
102
// Primarily, this is to fix the URLs...
103
ob_start('ob_sessrewrite');
104
105
// Start the session... known to scramble SSI includes in cases...
106
if (!headers_sent())
107
	loadSession();
108
else
109
{
110
	if (isset($_COOKIE[session_name()]) || isset($_REQUEST[session_name()]))
111
	{
112
		// Make a stab at it, but ignore the E_WARNINGs generated because we can't send headers.
113
		$temp = error_reporting(error_reporting() & !E_WARNING);
114
		loadSession();
115
		error_reporting($temp);
116
	}
117
118 View Code Duplication
	if (!isset($_SESSION['session_value']))
119
	{
120
		$_SESSION['session_var'] = substr(md5(mt_rand() . session_id() . mt_rand()), 0, rand(7, 12));
121
		$_SESSION['session_value'] = md5(session_id() . mt_rand());
122
	}
123
	$sc = $_SESSION['session_value'];
124
}
125
126
// Get rid of $board and $topic... do stuff loadBoard would do.
127
unset($board, $topic);
128
$user_info['is_mod'] = false;
129
$context['user']['is_mod'] = &$user_info['is_mod'];
130
$context['linktree'] = array();
131
132
// Load the user and their cookie, as well as their settings.
133
loadUserSettings();
134
135
// Load the current user's permissions....
136
loadPermissions();
137
138
// Load the current or SSI theme. (just use $ssi_theme = id_theme;)
139
loadTheme(isset($ssi_theme) ? (int) $ssi_theme : 0);
140
141
// @todo: probably not the best place, but somewhere it should be set...
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
142
if (!headers_sent())
143
	header('Content-Type: text/html; charset=' . (empty($modSettings['global_character_set']) ? (empty($txt['lang_character_set']) ? 'ISO-8859-1' : $txt['lang_character_set']) : $modSettings['global_character_set']));
144
145
// Take care of any banning that needs to be done.
146
if (isset($_REQUEST['ssi_ban']) || (isset($ssi_ban) && $ssi_ban === true))
147
	is_not_banned();
148
149
// Do we allow guests in here?
150
if (empty($ssi_guest_access) && empty($modSettings['allow_guestAccess']) && $user_info['is_guest'] && basename($_SERVER['PHP_SELF']) != 'SSI.php')
151
{
152
	require_once($sourcedir . '/Subs-Auth.php');
153
	KickGuest();
154
	obExit(null, true);
155
}
156
157
// Load the stuff like the menu bar, etc.
158
if (isset($ssi_layers))
159
{
160
	$context['template_layers'] = $ssi_layers;
161
	template_header();
162
}
163
else
164
	setupThemeContext();
165
166
// Make sure they didn't muss around with the settings... but only if it's not cli.
167
if (isset($_SERVER['REMOTE_ADDR']) && !isset($_SERVER['is_cli']) && session_id() == '')
168
	trigger_error($txt['ssi_session_broken'], E_USER_NOTICE);
169
170
// Without visiting the forum this session variable might not be set on submit.
171
if (!isset($_SESSION['USER_AGENT']) && (!isset($_GET['ssi_function']) || $_GET['ssi_function'] !== 'pollVote'))
172
	$_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
173
174
// Have the ability to easily add functions to SSI.
175
call_integration_hook('integrate_SSI');
176
177
// Ignore a call to ssi_* functions if we are not accessing SSI.php directly.
178
if (basename($_SERVER['PHP_SELF']) == 'SSI.php')
179
{
180
	// You shouldn't just access SSI.php directly by URL!!
181
	if (!isset($_GET['ssi_function']))
182
		die(sprintf($txt['ssi_not_direct'], $user_info['is_admin'] ? '\'' . addslashes(__FILE__) . '\'' : '\'SSI.php\''));
183
	// Call a function passed by GET.
184
	if (function_exists('ssi_' . $_GET['ssi_function']) && (!empty($modSettings['allow_guestAccess']) || !$user_info['is_guest']))
185
		call_user_func('ssi_' . $_GET['ssi_function']);
186
	exit;
187
}
188
189
// To avoid side effects later on.
190
unset($_GET['ssi_function']);
191
192
error_reporting($ssi_error_reporting);
193
194
return true;
195
196
/**
197
 * This shuts down the SSI and shows the footer.
198
 * @return void
199
 */
200
function ssi_shutdown()
201
{
202
	if (!isset($_GET['ssi_function']) || $_GET['ssi_function'] != 'shutdown')
203
		template_footer();
204
}
205
206
/**
207
 * Display a welcome message, like: Hey, User, you have 0 messages, 0 are new.
208
 * @param string $output_method The output method. If 'echo', will display everything. Otherwise returns an array of user info.
209
 * @return void|array Displays a welcome message or returns an array of user data depending on output_method.
210
 */
211
function ssi_welcome($output_method = 'echo')
212
{
213
	global $context, $txt, $scripturl;
214
215
	if ($output_method == 'echo')
216
	{
217
		if ($context['user']['is_guest'])
218
			echo sprintf($txt[$context['can_register'] ? 'welcome_guest_register' : 'welcome_guest'], $txt['guest_title'], $context['forum_name_html_safe'], $scripturl . '?action=login', 'return reqOverlayDiv(this.href, ' . JavaScriptEscape($txt['login']) . ');', $scripturl . '?action=signup');
219
		else
220
			echo $txt['hello_member'], ' <strong>', $context['user']['name'], '</strong>', allowedTo('pm_read') ? ', ' . (empty($context['user']['messages']) ? $txt['msg_alert_no_messages'] : (($context['user']['messages'] == 1 ? sprintf($txt['msg_alert_one_message'], $scripturl . '?action=pm') : sprintf($txt['msg_alert_many_message'], $scripturl . '?action=pm', $context['user']['messages'])) . ', ' . ($context['user']['unread_messages'] == 1 ? $txt['msg_alert_one_new'] : sprintf($txt['msg_alert_many_new'], $context['user']['unread_messages'])))) : '';
221
	}
222
	// Don't echo... then do what?!
223
	else
224
		return $context['user'];
225
}
226
227
/**
228
 * Display a menu bar, like is displayed at the top of the forum.
229
 * @param string $output_method The output method. If 'echo', will display the menu, otherwise returns an array of menu data.
230
 * @return void|array Displays the menu or returns an array of menu data depending on output_method.
231
 */
232
function ssi_menubar($output_method = 'echo')
233
{
234
	global $context;
235
236
	if ($output_method == 'echo')
237
		template_menu();
238
	// What else could this do?
239
	else
240
		return $context['menu_buttons'];
241
}
242
243
/**
244
 * Show a logout link.
245
 * @param string $redirect_to A URL to redirect the user to after they log out.
246
 * @param string $output_method The output method. If 'echo', shows a logout link, otherwise returns the HTML for it.
247
 * @return void|string Displays a logout link or returns its HTML depending on output_method.
0 ignored issues
show
Documentation introduced by
Should the return type not be false|null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
248
 */
249
function ssi_logout($redirect_to = '', $output_method = 'echo')
250
{
251
	global $context, $txt, $scripturl;
252
253
	if ($redirect_to != '')
254
		$_SESSION['logout_url'] = $redirect_to;
255
256
	// Guests can't log out.
257
	if ($context['user']['is_guest'])
258
		return false;
259
260
	$link = '<a href="' . $scripturl . '?action=logout;' . $context['session_var'] . '=' . $context['session_id'] . '">' . $txt['logout'] . '</a>';
261
262
	if ($output_method == 'echo')
263
		echo $link;
264
	else
265
		return $link;
266
}
267
268
/**
269
 * Recent post list:   [board] Subject by Poster    Date
270
 * @param int $num_recent How many recent posts to display
271
 * @param null|array $exclude_boards If set, doesn't show posts from the specified boards
272
 * @param null|array $include_boards If set, only includes posts from the specified boards
273
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of information about them.
274
 * @param bool $limit_body Whether or not to only show the first 384 characters of each post
275
 * @return void|array Displays a list of recent posts or returns an array of information about them depending on output_method.
276
 */
277
function ssi_recentPosts($num_recent = 8, $exclude_boards = null, $include_boards = null, $output_method = 'echo', $limit_body = true)
278
{
279
	global $modSettings, $context;
280
281
	// Excluding certain boards...
282 View Code Duplication
	if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0)
283
		$exclude_boards = array($modSettings['recycle_board']);
284
	else
285
		$exclude_boards = empty($exclude_boards) ? array() : (is_array($exclude_boards) ? $exclude_boards : array($exclude_boards));
286
287
	// What about including certain boards - note we do some protection here as pre-2.0 didn't have this parameter.
288 View Code Duplication
	if (is_array($include_boards) || (int) $include_boards === $include_boards)
289
	{
290
		$include_boards = is_array($include_boards) ? $include_boards : array($include_boards);
291
	}
292
	elseif ($include_boards != null)
293
	{
294
		$include_boards = array();
295
	}
296
297
	// Let's restrict the query boys (and girls)
298
	$query_where = '
299
		m.id_msg >= {int:min_message_id}
300
		' . (empty($exclude_boards) ? '' : '
301
		AND b.id_board NOT IN ({array_int:exclude_boards})') . '
302
		' . ($include_boards === null ? '' : '
303
		AND b.id_board IN ({array_int:include_boards})') . '
304
		AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
305
		AND m.approved = {int:is_approved}' : '');
306
307
	$query_where_params = array(
308
		'is_approved' => 1,
309
		'include_boards' => $include_boards === null ? '' : $include_boards,
310
		'exclude_boards' => empty($exclude_boards) ? '' : $exclude_boards,
311
		'min_message_id' => $modSettings['maxMsgID'] - (!empty($context['min_message_posts']) ? $context['min_message_posts'] : 25) * min($num_recent, 5),
312
	);
313
314
	// Past to this simpleton of a function...
315
	return ssi_queryPosts($query_where, $query_where_params, $num_recent, 'm.id_msg DESC', $output_method, $limit_body);
316
}
317
318
/**
319
 * Fetches one or more posts by ID.
320
 * @param array $post_ids An array containing the IDs of the posts to show
321
 * @param bool $override_permissions Whether to ignore permissions. If true, will show posts even if the user doesn't have permission to see them.
322
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of info about them
323
 * @return void|array Displays the specified posts or returns an array of info about them, depending on output_method.
324
 */
325
function ssi_fetchPosts($post_ids = array(), $override_permissions = false, $output_method = 'echo')
326
{
327
	global $modSettings;
328
329
	if (empty($post_ids))
330
		return;
331
332
	// Allow the user to request more than one - why not?
333
	$post_ids = is_array($post_ids) ? $post_ids : array($post_ids);
334
335
	// Restrict the posts required...
336
	$query_where = '
337
		m.id_msg IN ({array_int:message_list})' . ($override_permissions ? '' : '
338
			AND {query_wanna_see_board}') . ($modSettings['postmod_active'] ? '
339
			AND m.approved = {int:is_approved}' : '');
340
	$query_where_params = array(
341
		'message_list' => $post_ids,
342
		'is_approved' => 1,
343
	);
344
345
	// Then make the query and dump the data.
346
	return ssi_queryPosts($query_where, $query_where_params, '', 'm.id_msg DESC', $output_method, false, $override_permissions);
347
}
348
349
/**
350
 * This handles actually pulling post info. Called from other functions to eliminate duplication.
351
 * @param string $query_where The WHERE clause for the query
352
 * @param array $query_where_params An array of parameters for the WHERE clause
353
 * @param int $query_limit The maximum number of rows to return
354
 * @param string $query_order The ORDER BY clause for the query
355
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of info about them.
356
 * @param bool $limit_body If true, will only show the first 384 characters of the post rather than all of it
357
 * @param bool|false $override_permissions Whether or not to ignore permissions. If true, will show all posts regardless of whether the user can actually see them
358
 * @return void|array Displays the posts or returns an array of info about them, depending on output_method
359
 */
360
function ssi_queryPosts($query_where = '', $query_where_params = array(), $query_limit = 10, $query_order = 'm.id_msg DESC', $output_method = 'echo', $limit_body = false, $override_permissions = false)
361
{
362
	global $scripturl, $txt, $user_info;
363
	global $modSettings, $smcFunc, $context;
364
365
	if (!empty($modSettings['enable_likes']))
366
		$context['can_like'] = allowedTo('likes_like');
367
368
	// Find all the posts. Newer ones will have higher IDs.
369
	$request = $smcFunc['db_query']('substring', '
370
		SELECT
371
			m.poster_time, m.subject, m.id_topic, m.id_member, m.id_msg, m.id_board, m.likes, b.name AS board_name,
372
			IFNULL(mem.real_name, m.poster_name) AS poster_name, ' . ($user_info['is_guest'] ? '1 AS is_read, 0 AS new_from' : '
373
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) >= m.id_msg_modified AS is_read,
374
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from') . ', ' . ($limit_body ? 'SUBSTRING(m.body, 1, 384) AS body' : 'm.body') . ', m.smileys_enabled
375
		FROM {db_prefix}messages AS m
376
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
377
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (!$user_info['is_guest'] ? '
378
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = m.id_topic AND lt.id_member = {int:current_member})
379
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = m.id_board AND lmr.id_member = {int:current_member})' : '') . '
380
		WHERE 1=1 ' . ($override_permissions ? '' : '
381
			AND {query_wanna_see_board}') . ($modSettings['postmod_active'] ? '
382
			AND m.approved = {int:is_approved}' : '') . '
383
		' . (empty($query_where) ? '' : 'AND ' . $query_where) . '
384
		ORDER BY ' . $query_order . '
385
		' . ($query_limit == '' ? '' : 'LIMIT ' . $query_limit),
386
		array_merge($query_where_params, array(
387
			'current_member' => $user_info['id'],
388
			'is_approved' => 1,
389
		))
390
	);
391
	$posts = array();
392
	while ($row = $smcFunc['db_fetch_assoc']($request))
393
	{
394
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
395
396
		// Censor it!
397
		censorText($row['subject']);
398
		censorText($row['body']);
399
400
		$preview = strip_tags(strtr($row['body'], array('<br>' => '&#10;')));
401
402
		// Build the array.
403
		$posts[$row['id_msg']] = array(
404
			'id' => $row['id_msg'],
405
			'board' => array(
406
				'id' => $row['id_board'],
407
				'name' => $row['board_name'],
408
				'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
409
				'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['board_name'] . '</a>'
410
			),
411
			'topic' => $row['id_topic'],
412
			'poster' => array(
413
				'id' => $row['id_member'],
414
				'name' => $row['poster_name'],
415
				'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
416
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
417
			),
418
			'subject' => $row['subject'],
419
			'short_subject' => shorten_subject($row['subject'], 25),
420
			'preview' => $smcFunc['strlen']($preview) > 128 ? $smcFunc['substr']($preview, 0, 128) . '...' : $preview,
421
			'body' => $row['body'],
422
			'time' => timeformat($row['poster_time']),
423
			'timestamp' => forum_time(true, $row['poster_time']),
424
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
425
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '" rel="nofollow">' . $row['subject'] . '</a>',
426
			'new' => !empty($row['is_read']),
427
			'is_new' => empty($row['is_read']),
428
			'new_from' => $row['new_from'],
429
		);
430
431
		// Get the likes for each message.
432 View Code Duplication
		if (!empty($modSettings['enable_likes']))
433
			$posts[$row['id_msg']]['likes'] = array(
434
				'count' => $row['likes'],
435
				'you' => in_array($row['id_msg'], prepareLikesContext($row['id_topic'])),
436
				'can_like' => !$context['user']['is_guest'] && $row['id_member'] != $context['user']['id'] && !empty($context['can_like']),
437
			);
438
	}
439
	$smcFunc['db_free_result']($request);
440
441
	// If mods want to do somthing with this list of posts, let them do that now.
442
	call_integration_hook('integrate_ssi_queryPosts', array(&$posts));
443
444
	// Just return it.
445
	if ($output_method != 'echo' || empty($posts))
446
		return $posts;
447
448
	echo '
449
		<table style="border: none" class="ssi_table">';
450 View Code Duplication
	foreach ($posts as $post)
451
		echo '
452
			<tr>
453
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
454
					[', $post['board']['link'], ']
455
				</td>
456
				<td style="vertical-align: top">
457
					<a href="', $post['href'], '">', $post['subject'], '</a>
458
					', $txt['by'], ' ', $post['poster']['link'], '
459
					', $post['is_new'] ? '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow"><span class="new_posts">' . $txt['new'] . '</span></a>' : '', '
460
				</td>
461
				<td style="text-align: right; white-space: nowrap">
462
					', $post['time'], '
463
				</td>
464
			</tr>';
465
	echo '
466
		</table>';
467
}
468
469
/**
470
 * Recent topic list:   [board] Subject by Poster   Date
471
 * @param int $num_recent How many recent topics to show
472
 * @param null|array $exclude_boards If set, exclude topics from the specified board(s)
473
 * @param null|array $include_boards If set, only include topics from the specified board(s)
474
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
475
 * @return void|array Either displays a list of topics or returns an array of info about them, depending on output_method.
476
 */
477
function ssi_recentTopics($num_recent = 8, $exclude_boards = null, $include_boards = null, $output_method = 'echo')
478
{
479
	global $settings, $scripturl, $txt, $user_info;
480
	global $modSettings, $smcFunc, $context;
481
482 View Code Duplication
	if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0)
483
		$exclude_boards = array($modSettings['recycle_board']);
484
	else
485
		$exclude_boards = empty($exclude_boards) ? array() : (is_array($exclude_boards) ? $exclude_boards : array($exclude_boards));
486
487
	// Only some boards?.
488 View Code Duplication
	if (is_array($include_boards) || (int) $include_boards === $include_boards)
489
	{
490
		$include_boards = is_array($include_boards) ? $include_boards : array($include_boards);
491
	}
492
	elseif ($include_boards != null)
493
	{
494
		$output_method = $include_boards;
495
		$include_boards = array();
496
	}
497
498
	$icon_sources = array();
499
	foreach ($context['stable_icons'] as $icon)
500
		$icon_sources[$icon] = 'images_url';
501
502
	// Find all the posts in distinct topics.  Newer ones will have higher IDs.
503
	$request = $smcFunc['db_query']('substring', '
504
		SELECT
505
			t.id_topic, b.id_board, b.name AS board_name
506
		FROM {db_prefix}topics AS t
507
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
508
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
509
		WHERE t.id_last_msg >= {int:min_message_id}' . (empty($exclude_boards) ? '' : '
510
			AND b.id_board NOT IN ({array_int:exclude_boards})') . '' . (empty($include_boards) ? '' : '
511
			AND b.id_board IN ({array_int:include_boards})') . '
512
			AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
513
			AND t.approved = {int:is_approved}
514
			AND ml.approved = {int:is_approved}' : '') . '
515
		ORDER BY t.id_last_msg DESC
516
		LIMIT ' . $num_recent,
517
		array(
518
			'include_boards' => empty($include_boards) ? '' : $include_boards,
519
			'exclude_boards' => empty($exclude_boards) ? '' : $exclude_boards,
520
			'min_message_id' => $modSettings['maxMsgID'] - (!empty($context['min_message_topics']) ? $context['min_message_topics'] : 35) * min($num_recent, 5),
521
			'is_approved' => 1,
522
		)
523
	);
524
	$topics = array();
525
	while ($row = $smcFunc['db_fetch_assoc']($request))
526
		$topics[$row['id_topic']] = $row;
527
	$smcFunc['db_free_result']($request);
528
529
	// Did we find anything? If not, bail.
530
	if (empty($topics))
531
		return array();
532
533
	$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
534
535
	// Find all the posts in distinct topics.  Newer ones will have higher IDs.
536
	$request = $smcFunc['db_query']('substring', '
537
		SELECT
538
			mf.poster_time, mf.subject, ml.id_topic, mf.id_member, ml.id_msg, t.num_replies, t.num_views, mg.online_color,
539
			IFNULL(mem.real_name, mf.poster_name) AS poster_name, ' . ($user_info['is_guest'] ? '1 AS is_read, 0 AS new_from' : '
540
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) >= ml.id_msg_modified AS is_read,
541
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from') . ', SUBSTRING(mf.body, 1, 384) AS body, mf.smileys_enabled, mf.icon
542
		FROM {db_prefix}topics AS t
543
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
544
			INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_last_msg)
545
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mf.id_member)' . (!$user_info['is_guest'] ? '
546
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
547
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})' : '') . '
548
			LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)
549
		WHERE t.id_topic IN ({array_int:topic_list})',
550
		array(
551
			'current_member' => $user_info['id'],
552
			'topic_list' => array_keys($topics),
553
		)
554
	);
555
	$posts = array();
556
	while ($row = $smcFunc['db_fetch_assoc']($request))
557
	{
558
		$row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']), array('<br>' => '&#10;')));
559 View Code Duplication
		if ($smcFunc['strlen']($row['body']) > 128)
560
			$row['body'] = $smcFunc['substr']($row['body'], 0, 128) . '...';
561
562
		// Censor the subject.
563
		censorText($row['subject']);
564
		censorText($row['body']);
565
566
		// Recycled icon
567
		if (!empty($recycle_board) && $topics[$row['id_topic']]['id_board'])
568
			$row['icon'] = 'recycled';
569
570 View Code Duplication
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
571
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
572
573
		// Build the array.
574
		$posts[] = array(
575
			'board' => array(
576
				'id' => $topics[$row['id_topic']]['id_board'],
577
				'name' => $topics[$row['id_topic']]['board_name'],
578
				'href' => $scripturl . '?board=' . $topics[$row['id_topic']]['id_board'] . '.0',
579
				'link' => '<a href="' . $scripturl . '?board=' . $topics[$row['id_topic']]['id_board'] . '.0">' . $topics[$row['id_topic']]['board_name'] . '</a>',
580
			),
581
			'topic' => $row['id_topic'],
582
			'poster' => array(
583
				'id' => $row['id_member'],
584
				'name' => $row['poster_name'],
585
				'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
586
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
587
			),
588
			'subject' => $row['subject'],
589
			'replies' => $row['num_replies'],
590
			'views' => $row['num_views'],
591
			'short_subject' => shorten_subject($row['subject'], 25),
592
			'preview' => $row['body'],
593
			'time' => timeformat($row['poster_time']),
594
			'timestamp' => forum_time(true, $row['poster_time']),
595
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
596
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#new" rel="nofollow">' . $row['subject'] . '</a>',
597
			// Retained for compatibility - is technically incorrect!
598
			'new' => !empty($row['is_read']),
599
			'is_new' => empty($row['is_read']),
600
			'new_from' => $row['new_from'],
601
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" style="vertical-align:middle;" alt="' . $row['icon'] . '">',
602
		);
603
	}
604
	$smcFunc['db_free_result']($request);
605
606
	// If mods want to do somthing with this list of topics, let them do that now.
607
	call_integration_hook('integrate_ssi_recentTopics', array(&$posts));
608
609
	// Just return it.
610
	if ($output_method != 'echo' || empty($posts))
611
		return $posts;
612
613
	echo '
614
		<table style="border: none" class="ssi_table">';
615 View Code Duplication
	foreach ($posts as $post)
616
		echo '
617
			<tr>
618
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
619
					[', $post['board']['link'], ']
620
				</td>
621
				<td style="vertical-align: top">
622
					<a href="', $post['href'], '">', $post['subject'], '</a>
623
					', $txt['by'], ' ', $post['poster']['link'], '
624
					', !$post['is_new'] ? '' : '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow"><span class="new_posts">' . $txt['new'] . '</span></a>', '
625
				</td>
626
				<td style="text-align: right; white-space: nowrap">
627
					', $post['time'], '
628
				</td>
629
			</tr>';
630
	echo '
631
		</table>';
632
}
633
634
/**
635
 * Shows a list of top posters
636
 * @param int $topNumber How many top posters to list
637
 * @param string $output_method The output method. If 'echo', will display a list of users, otherwise returns an array of info about them.
638
 * @return void|array Either displays a list of users or returns an array of info about them, depending on output_method.
639
 */
640
function ssi_topPoster($topNumber = 1, $output_method = 'echo')
641
{
642
	global $scripturl, $smcFunc;
643
644
	// Find the latest poster.
645
	$request = $smcFunc['db_query']('', '
646
		SELECT id_member, real_name, posts
647
		FROM {db_prefix}members
648
		ORDER BY posts DESC
649
		LIMIT ' . $topNumber,
650
		array(
651
		)
652
	);
653
	$return = array();
654
	while ($row = $smcFunc['db_fetch_assoc']($request))
655
		$return[] = array(
656
			'id' => $row['id_member'],
657
			'name' => $row['real_name'],
658
			'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
659
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>',
660
			'posts' => $row['posts']
661
		);
662
	$smcFunc['db_free_result']($request);
663
664
	// If mods want to do somthing with this list of members, let them do that now.
665
	call_integration_hook('integrate_ssi_topPoster', array(&$return));
666
667
	// Just return all the top posters.
668
	if ($output_method != 'echo')
669
		return $return;
670
671
	// Make a quick array to list the links in.
672
	$temp_array = array();
673
	foreach ($return as $member)
674
		$temp_array[] = $member['link'];
675
676
	echo implode(', ', $temp_array);
677
}
678
679
/**
680
 * Shows a list of top boards based on activity
681
 * @param int $num_top How many boards to display
682
 * @param string $output_method The output method. If 'echo', displays a list of boards, otherwise returns an array of info about them.
683
 * @return void|array Displays a list of the top boards or returns an array of info about them, depending on output_method.
684
 */
685
function ssi_topBoards($num_top = 10, $output_method = 'echo')
686
{
687
	global $txt, $scripturl, $user_info, $modSettings, $smcFunc;
688
689
	// Find boards with lots of posts.
690
	$request = $smcFunc['db_query']('', '
691
		SELECT
692
			b.name, b.num_topics, b.num_posts, b.id_board,' . (!$user_info['is_guest'] ? ' 1 AS is_read' : '
693
			(IFNULL(lb.id_msg, 0) >= b.id_last_msg) AS is_read') . '
694
		FROM {db_prefix}boards AS b
695
			LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
696
		WHERE {query_wanna_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
697
			AND b.id_board != {int:recycle_board}' : '') . '
698
		ORDER BY b.num_posts DESC
699
		LIMIT ' . $num_top,
700
		array(
701
			'current_member' => $user_info['id'],
702
			'recycle_board' => (int) $modSettings['recycle_board'],
703
		)
704
	);
705
	$boards = array();
706
	while ($row = $smcFunc['db_fetch_assoc']($request))
707
		$boards[] = array(
708
			'id' => $row['id_board'],
709
			'num_posts' => $row['num_posts'],
710
			'num_topics' => $row['num_topics'],
711
			'name' => $row['name'],
712
			'new' => empty($row['is_read']),
713
			'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
714
			'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>'
715
		);
716
	$smcFunc['db_free_result']($request);
717
718
	// If mods want to do somthing with this list of boards, let them do that now.
719
	call_integration_hook('integrate_ssi_topBoards', array(&$boards));
720
721
	// If we shouldn't output or have nothing to output, just jump out.
722
	if ($output_method != 'echo' || empty($boards))
723
		return $boards;
724
725
	echo '
726
		<table class="ssi_table">
727
			<tr>
728
				<th style="text-align: left">', $txt['board'], '</th>
729
				<th style="text-align: left">', $txt['board_topics'], '</th>
730
				<th style="text-align: left">', $txt['posts'], '</th>
731
			</tr>';
732
	foreach ($boards as $sBoard)
733
		echo '
734
			<tr>
735
				<td>', $sBoard['link'], $sBoard['new'] ? ' <a href="' . $sBoard['href'] . '"><span class="new_posts">' . $txt['new'] . '</span></a>' : '', '</td>
736
				<td style="text-align: right">', comma_format($sBoard['num_topics']), '</td>
737
				<td style="text-align: right">', comma_format($sBoard['num_posts']), '</td>
738
			</tr>';
739
	echo '
740
		</table>';
741
}
742
743
// Shows the top topics.
744
/**
745
 * Shows a list of top topics based on views or replies
746
 * @param string $type Can be either replies or views
747
 * @param int $num_topics How many topics to display
748
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them.
749
 * @return void|array Either displays a list of topics or returns an array of info about them, depending on output_method.
750
 */
751
function ssi_topTopics($type = 'replies', $num_topics = 10, $output_method = 'echo')
752
{
753
	global $txt, $scripturl, $modSettings, $smcFunc;
754
755
	if ($modSettings['totalMessages'] > 100000)
756
	{
757
		// @todo Why don't we use {query(_wanna)_see_board}?
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
758
		$request = $smcFunc['db_query']('', '
759
			SELECT id_topic
760
			FROM {db_prefix}topics
761
			WHERE num_' . ($type != 'replies' ? 'views' : 'replies') . ' != 0' . ($modSettings['postmod_active'] ? '
762
				AND approved = {int:is_approved}' : '') . '
763
			ORDER BY num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
764
			LIMIT {int:limit}',
765
			array(
766
				'is_approved' => 1,
767
				'limit' => $num_topics > 100 ? ($num_topics + ($num_topics / 2)) : 100,
768
			)
769
		);
770
		$topic_ids = array();
771
		while ($row = $smcFunc['db_fetch_assoc']($request))
772
			$topic_ids[] = $row['id_topic'];
773
		$smcFunc['db_free_result']($request);
774
	}
775
	else
776
		$topic_ids = array();
777
778
	$request = $smcFunc['db_query']('', '
779
		SELECT m.subject, m.id_topic, t.num_views, t.num_replies
780
		FROM {db_prefix}topics AS t
781
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
782
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
783
		WHERE {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
784
			AND t.approved = {int:is_approved}' : '') . (!empty($topic_ids) ? '
785
			AND t.id_topic IN ({array_int:topic_list})' : '') . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
786
			AND b.id_board != {int:recycle_enable}' : '') . '
787
		ORDER BY t.num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
788
		LIMIT {int:limit}',
789
		array(
790
			'topic_list' => $topic_ids,
791
			'is_approved' => 1,
792
			'recycle_enable' => $modSettings['recycle_board'],
793
			'limit' => $num_topics,
794
		)
795
	);
796
	$topics = array();
797
	while ($row = $smcFunc['db_fetch_assoc']($request))
798
	{
799
		censorText($row['subject']);
800
801
		$topics[] = array(
802
			'id' => $row['id_topic'],
803
			'subject' => $row['subject'],
804
			'num_replies' => $row['num_replies'],
805
			'num_views' => $row['num_views'],
806
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
807
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
808
		);
809
	}
810
	$smcFunc['db_free_result']($request);
811
812
	// If mods want to do somthing with this list of topics, let them do that now.
813
	call_integration_hook('integrate_ssi_topTopics', array(&$topics, $type));
814
815
	if ($output_method != 'echo' || empty($topics))
816
		return $topics;
817
818
	echo '
819
		<table class="ssi_table">
820
			<tr>
821
				<th style="text-align: left"></th>
822
				<th style="text-align: left">', $txt['views'], '</th>
823
				<th style="text-align: left">', $txt['replies'], '</th>
824
			</tr>';
825
	foreach ($topics as $sTopic)
826
		echo '
827
			<tr>
828
				<td style="text-align: left">
829
					', $sTopic['link'], '
830
				</td>
831
				<td style="text-align: right">', comma_format($sTopic['num_views']), '</td>
832
				<td style="text-align: right">', comma_format($sTopic['num_replies']), '</td>
833
			</tr>';
834
	echo '
835
		</table>';
836
}
837
838
/**
839
 * Top topics based on replies
840
 * @param int $num_topics How many topics to show
841
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
842
 * @return void|array Either displays a list of top topics or returns an array of info about them, depending on output_method.
843
 */
844
function ssi_topTopicsReplies($num_topics = 10, $output_method = 'echo')
845
{
846
	return ssi_topTopics('replies', $num_topics, $output_method);
847
}
848
849
/**
850
 * Top topics based on views
851
 * @param int $num_topics How many topics to show
852
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
853
 * @return void|array Either displays a list of top topics or returns an array of info about them, depending on output_method.
854
 */
855
function ssi_topTopicsViews($num_topics = 10, $output_method = 'echo')
856
{
857
	return ssi_topTopics('views', $num_topics, $output_method);
858
}
859
860
/**
861
 * Show a link to the latest member: Please welcome, Someone, our latest member.
862
 * @param string $output_method The output method. If 'echo', returns a string with a link to the latest member's profile, otherwise returns an array of info about them.
863
 * @return void|array Displays a "welcome" message for the latest member or returns an array of info about them, depending on output_method.
864
 */
865
function ssi_latestMember($output_method = 'echo')
866
{
867
	global $txt, $context;
868
869
	if ($output_method == 'echo')
870
		echo '
871
	', sprintf($txt['welcome_newest_member'], $context['common_stats']['latest_member']['link']), '<br>';
872
	else
873
		return $context['common_stats']['latest_member'];
874
}
875
876
/**
877
 * Fetches a random member.
878
 * @param string $random_type If 'day', only fetches a new random member once a day.
879
 * @param string $output_method The output method. If 'echo', displays a link to the member's profile, otherwise returns an array of info about them.
880
 * @return void|array Displays a link to a random member's profile or returns an array of info about them depending on output_method.
881
 */
882
function ssi_randomMember($random_type = '', $output_method = 'echo')
883
{
884
	global $modSettings;
885
886
	// If we're looking for something to stay the same each day then seed the generator.
887
	if ($random_type == 'day')
888
	{
889
		// Set the seed to change only once per day.
890
		mt_srand(floor(time() / 86400));
891
	}
892
893
	// Get the lowest ID we're interested in.
894
	$member_id = mt_rand(1, $modSettings['latestMember']);
895
896
	$where_query = '
897
		id_member >= {int:selected_member}
898
		AND is_activated = {int:is_activated}';
899
900
	$query_where_params = array(
901
		'selected_member' => $member_id,
902
		'is_activated' => 1,
903
	);
904
905
	$result = ssi_queryMembers($where_query, $query_where_params, 1, 'id_member ASC', $output_method);
906
907
	// If we got nothing do the reverse - in case of unactivated members.
908
	if (empty($result))
909
	{
910
		$where_query = '
911
			id_member <= {int:selected_member}
912
			AND is_activated = {int:is_activated}';
913
914
		$query_where_params = array(
915
			'selected_member' => $member_id,
916
			'is_activated' => 1,
917
		);
918
919
		$result = ssi_queryMembers($where_query, $query_where_params, 1, 'id_member DESC', $output_method);
920
	}
921
922
	// Just to be sure put the random generator back to something... random.
923
	if ($random_type != '')
924
		mt_srand(time());
925
926
	return $result;
927
}
928
929
/**
930
 * Fetch specific members
931
 * @param array $member_ids The IDs of the members to fetch
932
 * @param string $output_method The output method. If 'echo', displays a list of links to the members' profiles, otherwise returns an array of info about them.
933
 * @return void|array Displays links to the specified members' profiles or returns an array of info about them, depending on output_method.
934
 */
935
function ssi_fetchMember($member_ids = array(), $output_method = 'echo')
936
{
937
	if (empty($member_ids))
938
		return;
939
940
	// Can have more than one member if you really want...
941
	$member_ids = is_array($member_ids) ? $member_ids : array($member_ids);
942
943
	// Restrict it right!
944
	$query_where = '
945
		id_member IN ({array_int:member_list})';
946
947
	$query_where_params = array(
948
		'member_list' => $member_ids,
949
	);
950
951
	// Then make the query and dump the data.
952
	return ssi_queryMembers($query_where, $query_where_params, '', 'id_member', $output_method);
953
}
954
955
/**
956
 * Get al members in the specified group
957
 * @param int $group_id The ID of the group to get members from
0 ignored issues
show
Documentation introduced by
Should the type for parameter $group_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
958
 * @param string $output_method The output method. If 'echo', returns a list of group members, otherwise returns an array of info about them.
959
 * @return void|array Displays a list of group members or returns an array of info about them, depending on output_method.
960
 */
961
function ssi_fetchGroupMembers($group_id = null, $output_method = 'echo')
962
{
963
	if ($group_id === null)
964
		return;
965
966
	$query_where = '
967
		id_group = {int:id_group}
968
		OR id_post_group = {int:id_group}
969
		OR FIND_IN_SET({int:id_group}, additional_groups) != 0';
970
971
	$query_where_params = array(
972
		'id_group' => $group_id,
973
	);
974
975
	return ssi_queryMembers($query_where, $query_where_params, '', 'real_name', $output_method);
976
}
977
978
/**
979
 * Pulls info about members based on the specified parameters. Used by other functions to eliminate duplication.
980
 * @param string $query_where The info for the WHERE clause of the query
0 ignored issues
show
Documentation introduced by
Should the type for parameter $query_where not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
981
 * @param array $query_where_params The parameters for the WHERE clause
982
 * @param string|int $query_limit The number of rows to return or an empty string to return all
983
 * @param string $query_order The info for the ORDER BY clause of the query
984
 * @param string $output_method The output method. If 'echo', displays a list of members, otherwise returns an array of info about them
985
 * @return void|array Displays a list of members or returns an array of info about them, depending on output_method.
986
 */
987
function ssi_queryMembers($query_where = null, $query_where_params = array(), $query_limit = '', $query_order = 'id_member DESC', $output_method = 'echo')
988
{
989
	global $smcFunc, $memberContext;
990
991
	if ($query_where === null)
992
		return;
993
994
	// Fetch the members in question.
995
	$request = $smcFunc['db_query']('', '
996
		SELECT id_member
997
		FROM {db_prefix}members
998
		WHERE ' . $query_where . '
999
		ORDER BY ' . $query_order . '
1000
		' . ($query_limit == '' ? '' : 'LIMIT ' . $query_limit),
1001
		array_merge($query_where_params, array(
1002
		))
1003
	);
1004
	$members = array();
1005
	while ($row = $smcFunc['db_fetch_assoc']($request))
1006
		$members[] = $row['id_member'];
1007
	$smcFunc['db_free_result']($request);
1008
1009
	if (empty($members))
1010
		return array();
1011
1012
	// If mods want to do somthing with this list of members, let them do that now.
1013
	call_integration_hook('integrate_ssi_queryMembers', array(&$members));
1014
1015
	// Load the members.
1016
	loadMemberData($members);
1017
1018
	// Draw the table!
1019
	if ($output_method == 'echo')
1020
		echo '
1021
		<table style="border: none" class="ssi_table">';
1022
1023
	$query_members = array();
1024
	foreach ($members as $member)
1025
	{
1026
		// Load their context data.
1027
		if (!loadMemberContext($member))
1028
			continue;
1029
1030
		// Store this member's information.
1031
		$query_members[$member] = $memberContext[$member];
1032
1033
		// Only do something if we're echo'ing.
1034
		if ($output_method == 'echo')
1035
			echo '
1036
			<tr>
1037
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
1038
					', $query_members[$member]['link'], '
1039
					<br>', $query_members[$member]['blurb'], '
1040
					<br>', $query_members[$member]['avatar']['image'], '
1041
				</td>
1042
			</tr>';
1043
	}
1044
1045
	// End the table if appropriate.
1046
	if ($output_method == 'echo')
1047
		echo '
1048
		</table>';
1049
1050
	// Send back the data.
1051
	return $query_members;
1052
}
1053
1054
/**
1055
 * Show some basic stats:   Total This: XXXX, etc.
1056
 * @param string $output_method The output method. If 'echo', displays the stats, otherwise returns an array of info about them
1057
 * @return void|array Doesn't return anything if the user can't view stats. Otherwise either displays the stats or returns an array of info about them, depending on output_method.
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use null|array.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
1058
 */
1059
function ssi_boardStats($output_method = 'echo')
1060
{
1061
	global $txt, $scripturl, $modSettings, $smcFunc;
1062
1063
	if (!allowedTo('view_stats'))
1064
		return;
1065
1066
	$totals = array(
1067
		'members' => $modSettings['totalMembers'],
1068
		'posts' => $modSettings['totalMessages'],
1069
		'topics' => $modSettings['totalTopics']
1070
	);
1071
1072
	$result = $smcFunc['db_query']('', '
1073
		SELECT COUNT(*)
1074
		FROM {db_prefix}boards',
1075
		array(
1076
		)
1077
	);
1078
	list ($totals['boards']) = $smcFunc['db_fetch_row']($result);
1079
	$smcFunc['db_free_result']($result);
1080
1081
	$result = $smcFunc['db_query']('', '
1082
		SELECT COUNT(*)
1083
		FROM {db_prefix}categories',
1084
		array(
1085
		)
1086
	);
1087
	list ($totals['categories']) = $smcFunc['db_fetch_row']($result);
1088
	$smcFunc['db_free_result']($result);
1089
1090
	// If mods want to do somthing with the board stats, let them do that now.
1091
	call_integration_hook('integrate_ssi_boardStats', array(&$totals));
1092
1093
	if ($output_method != 'echo')
1094
		return $totals;
1095
1096
	echo '
1097
		', $txt['total_members'], ': <a href="', $scripturl . '?action=mlist">', comma_format($totals['members']), '</a><br>
1098
		', $txt['total_posts'], ': ', comma_format($totals['posts']), '<br>
1099
		', $txt['total_topics'], ': ', comma_format($totals['topics']), ' <br>
1100
		', $txt['total_cats'], ': ', comma_format($totals['categories']), '<br>
1101
		', $txt['total_boards'], ': ', comma_format($totals['boards']);
1102
}
1103
1104
/**
1105
 * Shows a list of online users:  YY Guests, ZZ Users and then a list...
1106
 * @param string $output_method The output method. If 'echo', displays a list, otherwise returns an array of info about the online users.
1107
 * @return void|array Either displays a list of online users or returns an array of info about them, depending on output_method.
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array|null.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
1108
 */
1109
function ssi_whosOnline($output_method = 'echo')
1110
{
1111
	global $user_info, $txt, $sourcedir, $settings;
1112
1113
	require_once($sourcedir . '/Subs-MembersOnline.php');
1114
	$membersOnlineOptions = array(
1115
		'show_hidden' => allowedTo('moderate_forum'),
1116
	);
1117
	$return = getMembersOnlineStats($membersOnlineOptions);
1118
1119
	// If mods want to do somthing with the list of who is online, let them do that now.
1120
	call_integration_hook('integrate_ssi_whosOnline', array(&$return));
1121
1122
	// Add some redundancy for backwards compatibility reasons.
1123
	if ($output_method != 'echo')
1124
		return $return + array(
1125
			'users' => $return['users_online'],
1126
			'guests' => $return['num_guests'],
1127
			'hidden' => $return['num_users_hidden'],
1128
			'buddies' => $return['num_buddies'],
1129
			'num_users' => $return['num_users_online'],
1130
			'total_users' => $return['num_users_online'] + $return['num_guests'],
1131
		);
1132
1133
	echo '
1134
		', comma_format($return['num_guests']), ' ', $return['num_guests'] == 1 ? $txt['guest'] : $txt['guests'], ', ', comma_format($return['num_users_online']), ' ', $return['num_users_online'] == 1 ? $txt['user'] : $txt['users'];
1135
1136
	$bracketList = array();
1137 View Code Duplication
	if (!empty($user_info['buddies']))
1138
		$bracketList[] = comma_format($return['num_buddies']) . ' ' . ($return['num_buddies'] == 1 ? $txt['buddy'] : $txt['buddies']);
1139 View Code Duplication
	if (!empty($return['num_spiders']))
1140
		$bracketList[] = comma_format($return['num_spiders']) . ' ' . ($return['num_spiders'] == 1 ? $txt['spider'] : $txt['spiders']);
0 ignored issues
show
Documentation introduced by
$return['num_spiders'] is of type array|integer, but the function expects a double.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1141
	if (!empty($return['num_users_hidden']))
1142
		$bracketList[] = comma_format($return['num_users_hidden']) . ' ' . $txt['hidden'];
0 ignored issues
show
Documentation introduced by
$return['num_users_hidden'] is of type array|integer, but the function expects a double.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1143
1144
	if (!empty($bracketList))
1145
		echo ' (' . implode(', ', $bracketList) . ')';
1146
1147
	echo '<br>
1148
			', implode(', ', $return['list_users_online']);
1149
1150
	// Showing membergroups?
1151 View Code Duplication
	if (!empty($settings['show_group_key']) && !empty($return['membergroups']))
1152
		echo '<br>
1153
			[' . implode(']&nbsp;&nbsp;[', $return['membergroups']) . ']';
1154
}
1155
1156
/**
1157
 * Just like whosOnline except it also logs the online presence.
1158
 * @param string $output_method The output method. If 'echo', displays a list, otherwise returns an array of info about the online users.
1159
 * @return void|array Either displays a list of online users or returns an aray of info about them, depending on output_method.
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array|null.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
1160
 */
1161
function ssi_logOnline($output_method = 'echo')
1162
{
1163
	writeLog();
1164
1165
	if ($output_method != 'echo')
1166
		return ssi_whosOnline($output_method);
1167
	else
1168
		ssi_whosOnline($output_method);
1169
}
1170
1171
// Shows a login box.
1172
/**
1173
 * Shows a login box
1174
 * @param string $redirect_to The URL to redirect the user to after they login
1175
 * @param string $output_method The output method. If 'echo' and the user is a guest, displays a login box, otherwise returns whether the user is a guest
1176
 * @return void|bool Either displays a login box or returns whether the user is a guest, depending on whether the user is logged in and output_method.
1177
 */
1178
function ssi_login($redirect_to = '', $output_method = 'echo')
1179
{
1180
	global $scripturl, $txt, $user_info, $context;
1181
1182
	if ($redirect_to != '')
1183
		$_SESSION['login_url'] = $redirect_to;
1184
1185
	if ($output_method != 'echo' || !$user_info['is_guest'])
1186
		return $user_info['is_guest'];
1187
1188
	// Create a login token
1189
	createToken('login');
1190
1191
	echo '
1192
		<form action="', $scripturl, '?action=login2" method="post" accept-charset="', $context['character_set'], '">
1193
			<table style="border: none" class="ssi_table">
1194
				<tr>
1195
					<td style="text-align: right; border-spacing: 1"><label for="user">', $txt['username'], ':</label>&nbsp;</td>
1196
					<td><input type="text" id="user" name="user" size="9" value="', $user_info['username'], '" class="input_text"></td>
1197
				</tr><tr>
1198
					<td style="text-align: right; border-spacing: 1"><label for="passwrd">', $txt['password'], ':</label>&nbsp;</td>
1199
					<td><input type="password" name="passwrd" id="passwrd" size="9" class="input_password"></td>
1200
				</tr>
1201
				<tr>
1202
					<td>
1203
						<input type="hidden" name="cookielength" value="-1">
1204
						<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
1205
						<input type="hidden" name="', $context['login_token_var'], '" value="', $context['login_token'], '">
1206
					</td>
1207
					<td><input type="submit" value="', $txt['login'], '" class="button_submit"></td>
1208
				</tr>
1209
			</table>
1210
		</form>';
1211
1212
}
1213
1214
/**
1215
 * Show the top poll based on votes
1216
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it
1217
 * @return void|array Either shows the top poll or returns an array of info about it, depending on output_method.
1218
 */
1219
function ssi_topPoll($output_method = 'echo')
1220
{
1221
	// Just use recentPoll, no need to duplicate code...
1222
	return ssi_recentPoll(true, $output_method);
1223
}
1224
1225
// Show the most recently posted poll.
1226
/**
1227
 * Shows the most recent poll
1228
 * @param bool $topPollInstead Whether to show the top poll (based on votes) instead of the most recent one
1229
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it.
1230
 * @return void|array Either shows the poll or returns an array of info about it, depending on output_method.
1231
 */
1232
function ssi_recentPoll($topPollInstead = false, $output_method = 'echo')
1233
{
1234
	global $txt, $boardurl, $user_info, $context, $smcFunc, $modSettings;
1235
1236
	$boardsAllowed = array_intersect(boardsAllowedTo('poll_view'), boardsAllowedTo('poll_vote'));
1237
1238
	if (empty($boardsAllowed))
1239
		return array();
1240
1241
	$request = $smcFunc['db_query']('', '
1242
		SELECT p.id_poll, p.question, t.id_topic, p.max_votes, p.guest_vote, p.hide_results, p.expire_time
1243
		FROM {db_prefix}polls AS p
1244
			INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
1245
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)' . ($topPollInstead ? '
1246
			INNER JOIN {db_prefix}poll_choices AS pc ON (pc.id_poll = p.id_poll)' : '') . '
1247
			LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_poll = p.id_poll AND lp.id_member > {int:no_member} AND lp.id_member = {int:current_member})
1248
		WHERE p.voting_locked = {int:voting_opened}
1249
			AND (p.expire_time = {int:no_expiration} OR {int:current_time} < p.expire_time)
1250
			AND ' . ($user_info['is_guest'] ? 'p.guest_vote = {int:guest_vote_allowed}' : 'lp.id_choice IS NULL') . '
1251
			AND {query_wanna_see_board}' . (!in_array(0, $boardsAllowed) ? '
1252
			AND b.id_board IN ({array_int:boards_allowed_list})' : '') . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
1253
			AND b.id_board != {int:recycle_enable}' : '') . '
1254
		ORDER BY ' . ($topPollInstead ? 'pc.votes' : 'p.id_poll') . ' DESC
1255
		LIMIT 1',
1256
		array(
1257
			'current_member' => $user_info['id'],
1258
			'boards_allowed_list' => $boardsAllowed,
1259
			'is_approved' => 1,
1260
			'guest_vote_allowed' => 1,
1261
			'no_member' => 0,
1262
			'voting_opened' => 0,
1263
			'no_expiration' => 0,
1264
			'current_time' => time(),
1265
			'recycle_enable' => $modSettings['recycle_board'],
1266
		)
1267
	);
1268
	$row = $smcFunc['db_fetch_assoc']($request);
1269
	$smcFunc['db_free_result']($request);
1270
1271
	// This user has voted on all the polls.
1272
	if (empty($row) || !is_array($row))
1273
		return array();
1274
1275
	// If this is a guest who's voted we'll through ourselves to show poll to show the results.
1276
	if ($user_info['is_guest'] && (!$row['guest_vote'] || (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))))
1277
		return ssi_showPoll($row['id_topic'], $output_method);
1278
1279
	$request = $smcFunc['db_query']('', '
1280
		SELECT COUNT(DISTINCT id_member)
1281
		FROM {db_prefix}log_polls
1282
		WHERE id_poll = {int:current_poll}',
1283
		array(
1284
			'current_poll' => $row['id_poll'],
1285
		)
1286
	);
1287
	list ($total) = $smcFunc['db_fetch_row']($request);
1288
	$smcFunc['db_free_result']($request);
1289
1290
	$request = $smcFunc['db_query']('', '
1291
		SELECT id_choice, label, votes
1292
		FROM {db_prefix}poll_choices
1293
		WHERE id_poll = {int:current_poll}',
1294
		array(
1295
			'current_poll' => $row['id_poll'],
1296
		)
1297
	);
1298
	$sOptions = array();
1299 View Code Duplication
	while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
1300
	{
1301
		censorText($rowChoice['label']);
1302
1303
		$sOptions[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
1304
	}
1305
	$smcFunc['db_free_result']($request);
1306
1307
	// Can they view it?
1308
	$is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
1309
	$allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || $is_expired;
1310
1311
	$return = array(
1312
		'id' => $row['id_poll'],
1313
		'image' => 'poll',
1314
		'question' => $row['question'],
1315
		'total_votes' => $total,
1316
		'is_locked' => false,
1317
		'topic' => $row['id_topic'],
1318
		'allow_view_results' => $allow_view_results,
1319
		'options' => array()
1320
	);
1321
1322
	// Calculate the percentages and bar lengths...
1323
	$divisor = $return['total_votes'] == 0 ? 1 : $return['total_votes'];
1324
	foreach ($sOptions as $i => $option)
1325
	{
1326
		$bar = floor(($option[1] * 100) / $divisor);
1327
		$return['options'][$i] = array(
1328
			'id' => 'options-' . ($topPollInstead ? 'top-' : 'recent-') . $i,
1329
			'percent' => $bar,
1330
			'votes' => $option[1],
1331
			'option' => parse_bbc($option[0]),
1332
			'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . ($topPollInstead ? 'top-' : 'recent-') . $i . '" value="' . $i . '" class="input_' . ($row['max_votes'] > 1 ? 'check' : 'radio') . '">'
1333
		);
1334
	}
1335
1336
	$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options6'], min(count($sOptions), $row['max_votes'])) : '';
1337
1338
	// If mods want to do somthing with this list of polls, let them do that now.
1339
	call_integration_hook('integrate_ssi_recentPoll', array(&$return, $topPollInstead));
1340
1341
	if ($output_method != 'echo')
1342
		return $return;
1343
1344
	if ($allow_view_results)
1345
	{
1346
		echo '
1347
		<form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
1348
			<strong>', $return['question'], '</strong><br>
1349
			', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br>' : '';
1350
1351 View Code Duplication
		foreach ($return['options'] as $option)
1352
			echo '
1353
			<label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br>';
1354
1355
		echo '
1356
			<input type="submit" value="', $txt['poll_vote'], '" class="button_submit">
1357
			<input type="hidden" name="poll" value="', $return['id'], '">
1358
			<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
1359
		</form>';
1360
	}
1361
	else
1362
		echo $txt['poll_cannot_see'];
1363
}
1364
1365
/**
1366
 * Shows the poll from the specified topic
1367
 * @param null|int $topic The topic to show the poll from. If null, $_REQUEST['ssi_topic'] will be used instead.
1368
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it.
1369
 * @return void|array Either displays the poll or returns an array of info about it, depending on output_method.
1370
 */
1371
function ssi_showPoll($topic = null, $output_method = 'echo')
1372
{
1373
	global $txt, $boardurl, $user_info, $context, $smcFunc, $modSettings;
1374
1375
	$boardsAllowed = boardsAllowedTo('poll_view');
1376
1377
	if (empty($boardsAllowed))
1378
		return array();
1379
1380
	if ($topic === null && isset($_REQUEST['ssi_topic']))
1381
		$topic = (int) $_REQUEST['ssi_topic'];
1382
	else
1383
		$topic = (int) $topic;
1384
1385
	$request = $smcFunc['db_query']('', '
1386
		SELECT
1387
			p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.guest_vote, b.id_board
1388
		FROM {db_prefix}topics AS t
1389
			INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
1390
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1391
		WHERE t.id_topic = {int:current_topic}
1392
			AND {query_see_board}' . (!in_array(0, $boardsAllowed) ? '
1393
			AND b.id_board IN ({array_int:boards_allowed_see})' : '') . ($modSettings['postmod_active'] ? '
1394
			AND t.approved = {int:is_approved}' : '') . '
1395
		LIMIT 1',
1396
		array(
1397
			'current_topic' => $topic,
1398
			'boards_allowed_see' => $boardsAllowed,
1399
			'is_approved' => 1,
1400
		)
1401
	);
1402
1403
	// Either this topic has no poll, or the user cannot view it.
1404
	if ($smcFunc['db_num_rows']($request) == 0)
1405
		return array();
1406
1407
	$row = $smcFunc['db_fetch_assoc']($request);
1408
	$smcFunc['db_free_result']($request);
1409
1410
	// Check if they can vote.
1411
	$already_voted = false;
1412
	if (!empty($row['expire_time']) && $row['expire_time'] < time())
1413
		$allow_vote = false;
1414
	elseif ($user_info['is_guest'])
1415
	{
1416
		// There's a difference between "allowed to vote" and "already voted"...
1417
		$allow_vote = $row['guest_vote'];
1418
1419
		// Did you already vote?
1420
		if (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1421
		{
1422
			$already_voted = true;
1423
		}
1424
	}
1425
	elseif (!empty($row['voting_locked']) || !allowedTo('poll_vote', $row['id_board']))
1426
		$allow_vote = false;
1427
	else
1428
	{
1429
		$request = $smcFunc['db_query']('', '
1430
			SELECT id_member
1431
			FROM {db_prefix}log_polls
1432
			WHERE id_poll = {int:current_poll}
1433
				AND id_member = {int:current_member}
1434
			LIMIT 1',
1435
			array(
1436
				'current_member' => $user_info['id'],
1437
				'current_poll' => $row['id_poll'],
1438
			)
1439
		);
1440
		$allow_vote = $smcFunc['db_num_rows']($request) == 0;
1441
		$already_voted = $allow_vote;
1442
		$smcFunc['db_free_result']($request);
1443
	}
1444
1445
	// Can they view?
1446
	$is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
1447
	$allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || ($row['hide_results'] == 1 && $already_voted) || $is_expired;
1448
1449
	$request = $smcFunc['db_query']('', '
1450
		SELECT COUNT(DISTINCT id_member)
1451
		FROM {db_prefix}log_polls
1452
		WHERE id_poll = {int:current_poll}',
1453
		array(
1454
			'current_poll' => $row['id_poll'],
1455
		)
1456
	);
1457
	list ($total) = $smcFunc['db_fetch_row']($request);
1458
	$smcFunc['db_free_result']($request);
1459
1460
	$request = $smcFunc['db_query']('', '
1461
		SELECT id_choice, label, votes
1462
		FROM {db_prefix}poll_choices
1463
		WHERE id_poll = {int:current_poll}',
1464
		array(
1465
			'current_poll' => $row['id_poll'],
1466
		)
1467
	);
1468
	$sOptions = array();
1469
	$total_votes = 0;
1470 View Code Duplication
	while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
1471
	{
1472
		censorText($rowChoice['label']);
1473
1474
		$sOptions[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
1475
		$total_votes += $rowChoice['votes'];
1476
	}
1477
	$smcFunc['db_free_result']($request);
1478
1479
	$return = array(
1480
		'id' => $row['id_poll'],
1481
		'image' => empty($row['voting_locked']) ? 'poll' : 'locked_poll',
1482
		'question' => $row['question'],
1483
		'total_votes' => $total,
1484
		'is_locked' => !empty($row['voting_locked']),
1485
		'allow_vote' => $allow_vote,
1486
		'allow_view_results' => $allow_view_results,
1487
		'topic' => $topic
1488
	);
1489
1490
	// Calculate the percentages and bar lengths...
1491
	$divisor = $total_votes == 0 ? 1 : $total_votes;
1492
	foreach ($sOptions as $i => $option)
1493
	{
1494
		$bar = floor(($option[1] * 100) / $divisor);
1495
		$return['options'][$i] = array(
1496
			'id' => 'options-' . $i,
1497
			'percent' => $bar,
1498
			'votes' => $option[1],
1499
			'option' => parse_bbc($option[0]),
1500
			'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="input_' . ($row['max_votes'] > 1 ? 'check' : 'radio') . '">'
1501
		);
1502
	}
1503
1504
	$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options6'], min(count($sOptions), $row['max_votes'])) : '';
1505
1506
	// If mods want to do somthing with this poll, let them do that now.
1507
	call_integration_hook('integrate_ssi_showPoll', array(&$return));
1508
1509
	if ($output_method != 'echo')
1510
		return $return;
1511
1512
	if ($return['allow_vote'])
1513
	{
1514
		echo '
1515
			<form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
1516
				<strong>', $return['question'], '</strong><br>
1517
				', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br>' : '';
1518
1519 View Code Duplication
		foreach ($return['options'] as $option)
1520
			echo '
1521
				<label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br>';
1522
1523
		echo '
1524
				<input type="submit" value="', $txt['poll_vote'], '" class="button_submit">
1525
				<input type="hidden" name="poll" value="', $return['id'], '">
1526
				<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
1527
			</form>';
1528
	}
1529
	else
1530
	{
1531
		echo '
1532
			<div class="ssi_poll">
1533
				<strong>', $return['question'], '</strong>
1534
				<dl>';
1535
1536
		foreach ($return['options'] as $option)
1537
		{
1538
			echo '
1539
					<dt>', $option['option'], '</dt>
1540
					<dd>';
1541
1542
			if ($return['allow_view_results'])
1543
			{
1544
				echo '
1545
						<div class="ssi_poll_bar" style="border: 1px solid #666; height: 1em">
1546
							<div class="ssi_poll_bar_fill" style="background: #ccf; height: 1em; width: ', $option['percent'], '%;">
1547
							</div>
1548
						</div>
1549
						', $option['votes'], ' (', $option['percent'], '%)';
1550
			}
1551
1552
			echo '
1553
					</dd>';
1554
		}
1555
1556
		echo '
1557
				</dl>', ($return['allow_view_results'] ? '
1558
				<strong>'. $txt['poll_total_voters'] . ': ' . $return['total_votes'] . '</strong>' : ''), '
1559
			</div>';
1560
	}
1561
}
1562
1563
/**
1564
 * Handles voting in a poll (done automatically)
1565
 */
1566
function ssi_pollVote()
1567
{
1568
	global $context, $db_prefix, $user_info, $sc, $smcFunc, $sourcedir, $modSettings;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $sc. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
1569
1570
	if (!isset($_POST[$context['session_var']]) || $_POST[$context['session_var']] != $sc || empty($_POST['options']) || !isset($_POST['poll']))
1571
	{
1572
		echo '<!DOCTYPE html>
1573
<html>
1574
<head>
1575
	<script>
1576
		history.go(-1);
1577
	</script>
1578
</head>
1579
<body>&laquo;</body>
1580
</html>';
1581
		return;
1582
	}
1583
1584
	// This can cause weird errors! (ie. copyright missing.)
1585
	checkSession();
1586
1587
	$_POST['poll'] = (int) $_POST['poll'];
1588
1589
	// Check if they have already voted, or voting is locked.
1590
	$request = $smcFunc['db_query']('', '
1591
		SELECT
1592
			p.id_poll, p.voting_locked, p.expire_time, p.max_votes, p.guest_vote,
1593
			t.id_topic,
1594
			IFNULL(lp.id_choice, -1) AS selected
1595
		FROM {db_prefix}polls AS p
1596
			INNER JOIN {db_prefix}topics AS t ON (t.id_poll = {int:current_poll})
1597
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1598
			LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_poll = p.id_poll AND lp.id_member = {int:current_member})
1599
		WHERE p.id_poll = {int:current_poll}
1600
			AND {query_see_board}' . ($modSettings['postmod_active'] ? '
1601
			AND t.approved = {int:is_approved}' : '') . '
1602
		LIMIT 1',
1603
		array(
1604
			'current_member' => $user_info['id'],
1605
			'current_poll' => $_POST['poll'],
1606
			'is_approved' => 1,
1607
		)
1608
	);
1609
	if ($smcFunc['db_num_rows']($request) == 0)
1610
		die;
1611
	$row = $smcFunc['db_fetch_assoc']($request);
1612
	$smcFunc['db_free_result']($request);
1613
1614
	if (!empty($row['voting_locked']) || ($row['selected'] != -1 && !$user_info['is_guest']) || (!empty($row['expire_time']) && time() > $row['expire_time']))
1615
		redirectexit('topic=' . $row['id_topic'] . '.0');
1616
1617
	// Too many options checked?
1618
	if (count($_REQUEST['options']) > $row['max_votes'])
1619
		redirectexit('topic=' . $row['id_topic'] . '.0');
1620
1621
	// It's a guest who has already voted?
1622
	if ($user_info['is_guest'])
1623
	{
1624
		// Guest voting disabled?
1625
		if (!$row['guest_vote'])
1626
			redirectexit('topic=' . $row['id_topic'] . '.0');
1627
		// Already voted?
1628
		elseif (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1629
			redirectexit('topic=' . $row['id_topic'] . '.0');
1630
	}
1631
1632
	$sOptions = array();
1633
	$inserts = array();
1634 View Code Duplication
	foreach ($_REQUEST['options'] as $id)
1635
	{
1636
		$id = (int) $id;
1637
1638
		$sOptions[] = $id;
1639
		$inserts[] = array($_POST['poll'], $user_info['id'], $id);
1640
	}
1641
1642
	// Add their vote in to the tally.
1643
	$smcFunc['db_insert']('insert',
1644
		$db_prefix . 'log_polls',
1645
		array('id_poll' => 'int', 'id_member' => 'int', 'id_choice' => 'int'),
1646
		$inserts,
1647
		array('id_poll', 'id_member', 'id_choice')
1648
	);
1649
	$smcFunc['db_query']('', '
1650
		UPDATE {db_prefix}poll_choices
1651
		SET votes = votes + 1
1652
		WHERE id_poll = {int:current_poll}
1653
			AND id_choice IN ({array_int:option_list})',
1654
		array(
1655
			'option_list' => $sOptions,
1656
			'current_poll' => $_POST['poll'],
1657
		)
1658
	);
1659
1660
	// Track the vote if a guest.
1661
	if ($user_info['is_guest'])
1662
	{
1663
		$_COOKIE['guest_poll_vote'] = !empty($_COOKIE['guest_poll_vote']) ? ($_COOKIE['guest_poll_vote'] . ',' . $row['id_poll']) : $row['id_poll'];
1664
1665
		require_once($sourcedir . '/Subs-Auth.php');
1666
		$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
1667
		smf_setcookie('guest_poll_vote', $_COOKIE['guest_poll_vote'], time() + 2500000, $cookie_url[1], $cookie_url[0], false, false);
1668
	}
1669
1670
	redirectexit('topic=' . $row['id_topic'] . '.0');
1671
}
1672
1673
// Show a search box.
1674
/**
1675
 * Shows a search box
1676
 * @param string $output_method The output method. If 'echo', displays a search box, otherwise returns the URL of the search page.
1677
 * @return void|string Displays a search box or returns the URL to the search page depending on output_method. If you don't have permission to search, the function won't return anything.
1678
 */
1679
function ssi_quickSearch($output_method = 'echo')
1680
{
1681
	global $scripturl, $txt, $context;
1682
1683
	if (!allowedTo('search_posts'))
1684
		return;
1685
1686
	if ($output_method != 'echo')
1687
		return $scripturl . '?action=search';
1688
1689
	echo '
1690
		<form action="', $scripturl, '?action=search2" method="post" accept-charset="', $context['character_set'], '">
1691
			<input type="hidden" name="advanced" value="0"><input type="text" name="ssi_search" size="30" class="input_text"> <input type="submit" value="', $txt['search'], '" class="button_submit">
1692
		</form>';
1693
}
1694
1695
/**
1696
 * Show a random forum news item
1697
 * @param string $output_method The output method. If 'echo', shows the news item, otherwise returns it.
1698
 * @return void|string Shows or returns a random forum news item, depending on output_method.
1699
 */
1700
function ssi_news($output_method = 'echo')
1701
{
1702
	global $context;
1703
1704
	$context['random_news_line'] = !empty($context['news_lines']) ? $context['news_lines'][mt_rand(0, count($context['news_lines']) - 1)] : '';
1705
1706
	// If mods want to do somthing with the news, let them do that now. Don't need to pass the news line itself, since it is already in $context.
1707
	call_integration_hook('integrate_ssi_news');
1708
1709
	if ($output_method != 'echo')
1710
		return $context['random_news_line'];
1711
1712
	echo $context['random_news_line'];
1713
}
1714
1715
/**
1716
 * Show today's birthdays.
1717
 * @param string $output_method The output method. If 'echo', displays a list of users, otherwise returns an array of info about them.
1718
 * @return void|array Displays a list of users or returns an array of info about them depending on output_method.
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1719
 */
1720
function ssi_todaysBirthdays($output_method = 'echo')
1721
{
1722
	global $scripturl, $modSettings, $user_info;
1723
1724
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view') || !allowedTo('profile_view'))
1725
		return;
1726
1727
	$eventOptions = array(
1728
		'include_birthdays' => true,
1729
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1730
	);
1731
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1732
1733
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1734
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1735
1736
	if ($output_method != 'echo')
1737
		return $return['calendar_birthdays'];
1738
1739
	foreach ($return['calendar_birthdays'] as $member)
0 ignored issues
show
Bug introduced by
The expression $return['calendar_birthdays'] of type string is not traversable.
Loading history...
1740
		echo '
1741
			<a href="', $scripturl, '?action=profile;u=', $member['id'], '"><span class="fix_rtl_names">' . $member['name'] . '</span>' . (isset($member['age']) ? ' (' . $member['age'] . ')' : '') . '</a>' . (!$member['is_last'] ? ', ' : '');
1742
}
1743
1744
/**
1745
 * Shows today's holidays.
1746
 * @param string $output_method The output method. If 'echo', displays a list of holidays, otherwise returns an array of info about them.
1747
 * @return void|array Displays a list of holidays or returns an array of info about them depending on output_method
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1748
 */
1749
function ssi_todaysHolidays($output_method = 'echo')
1750
{
1751
	global $modSettings, $user_info;
1752
1753
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1754
		return;
1755
1756
	$eventOptions = array(
1757
		'include_holidays' => true,
1758
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1759
	);
1760
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1761
1762
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1763
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1764
1765
	if ($output_method != 'echo')
1766
		return $return['calendar_holidays'];
1767
1768
	echo '
1769
		', implode(', ', $return['calendar_holidays']);
1770
}
1771
1772
/**
1773
 * @param string $output_method The output method. If 'echo', displays a list of events, otherwise returns an array of info about them.
1774
 * @return void|array Displays a list of events or returns an array of info about them depending on output_method
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1775
 */
1776
function ssi_todaysEvents($output_method = 'echo')
1777
{
1778
	global $modSettings, $user_info;
1779
1780
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1781
		return;
1782
1783
	$eventOptions = array(
1784
		'include_events' => true,
1785
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1786
	);
1787
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1788
1789
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1790
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1791
1792
	if ($output_method != 'echo')
1793
		return $return['calendar_events'];
1794
1795 View Code Duplication
	foreach ($return['calendar_events'] as $event)
0 ignored issues
show
Bug introduced by
The expression $return['calendar_events'] of type string is not traversable.
Loading history...
1796
	{
1797
		if ($event['can_edit'])
1798
			echo '
1799
	<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
1800
		echo '
1801
	' . $event['link'] . (!$event['is_last'] ? ', ' : '');
1802
	}
1803
}
1804
1805
/**
1806
 * Shows today's calendar items (events, birthdays and holidays)
1807
 * @param string $output_method The output method. If 'echo', displays a list of calendar items, otherwise returns an array of info about them.
1808
 * @return void|array Displays a list of calendar items or returns an array of info about them depending on output_method
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1809
 */
1810
function ssi_todaysCalendar($output_method = 'echo')
1811
{
1812
	global $modSettings, $txt, $scripturl, $user_info;
1813
1814
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1815
		return;
1816
1817
	$eventOptions = array(
1818
		'include_birthdays' => allowedTo('profile_view'),
1819
		'include_holidays' => true,
1820
		'include_events' => true,
1821
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1822
	);
1823
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1824
1825
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1826
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1827
1828
	if ($output_method != 'echo')
1829
		return $return;
1830
1831
	if (!empty($return['calendar_holidays']))
1832
		echo '
1833
			<span class="holiday">' . $txt['calendar_prompt'] . ' ' . implode(', ', $return['calendar_holidays']) . '<br></span>';
1834
	if (!empty($return['calendar_birthdays']))
1835
	{
1836
		echo '
1837
			<span class="birthday">' . $txt['birthdays_upcoming'] . '</span> ';
1838 View Code Duplication
		foreach ($return['calendar_birthdays'] as $member)
0 ignored issues
show
Bug introduced by
The expression $return['calendar_birthdays'] of type string is not traversable.
Loading history...
1839
			echo '
1840
			<a href="', $scripturl, '?action=profile;u=', $member['id'], '"><span class="fix_rtl_names">', $member['name'], '</span>', isset($member['age']) ? ' (' . $member['age'] . ')' : '', '</a>', !$member['is_last'] ? ', ' : '';
1841
		echo '
1842
			<br>';
1843
	}
1844
	if (!empty($return['calendar_events']))
1845
	{
1846
		echo '
1847
			<span class="event">' . $txt['events_upcoming'] . '</span> ';
1848 View Code Duplication
		foreach ($return['calendar_events'] as $event)
0 ignored issues
show
Bug introduced by
The expression $return['calendar_events'] of type string is not traversable.
Loading history...
1849
		{
1850
			if ($event['can_edit'])
1851
				echo '
1852
			<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
1853
			echo '
1854
			' . $event['link'] . (!$event['is_last'] ? ', ' : '');
1855
		}
1856
	}
1857
}
1858
1859
/**
1860
 * Show the latest news, with a template... by board.
1861
 * @param null|int $board The ID of the board to get the info from. Defaults to $board or $_GET['board'] if not set.
1862
 * @param null|int $limit How many items to show. Defaults to $_GET['limit'] or 5 if not set.
1863
 * @param null|int $start Start with the specified item. Defaults to $_GET['start'] or 0 if not set.
1864
 * @param null|int $length How many characters to show from each post. Defaults to $_GET['length'] or 0 (no limit) if not set.
1865
 * @param string $output_method The output method. If 'echo', displays the news items, otherwise returns an array of info about them.
1866
 * @return void|array Displays the news items or returns an array of info about them, depending on output_method.
1867
 */
1868
function ssi_boardNews($board = null, $limit = null, $start = null, $length = null, $output_method = 'echo')
1869
{
1870
	global $scripturl, $txt, $settings, $modSettings, $context;
1871
	global $smcFunc;
1872
1873
	loadLanguage('Stats');
1874
1875
	// Must be integers....
1876
	if ($limit === null)
1877
		$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 5;
1878
	else
1879
		$limit = (int) $limit;
1880
1881
	if ($start === null)
1882
		$start = isset($_GET['start']) ? (int) $_GET['start'] : 0;
1883
	else
1884
		$start = (int) $start;
1885
1886
	if ($board !== null)
1887
		$board = (int) $board;
1888
	elseif (isset($_GET['board']))
1889
		$board = (int) $_GET['board'];
1890
1891
	if ($length === null)
1892
		$length = isset($_GET['length']) ? (int) $_GET['length'] : 0;
1893
	else
1894
		$length = (int) $length;
1895
1896
	$limit = max(0, $limit);
1897
	$start = max(0, $start);
1898
1899
	// Make sure guests can see this board.
1900
	$request = $smcFunc['db_query']('', '
1901
		SELECT id_board
1902
		FROM {db_prefix}boards
1903
		WHERE ' . ($board === null ? '' : 'id_board = {int:current_board}
1904
			AND ') . 'FIND_IN_SET(-1, member_groups) != 0
1905
		LIMIT 1',
1906
		array(
1907
			'current_board' => $board,
1908
		)
1909
	);
1910
	if ($smcFunc['db_num_rows']($request) == 0)
1911
	{
1912
		if ($output_method == 'echo')
1913
			die($txt['ssi_no_guests']);
1914
		else
1915
			return array();
1916
	}
1917
	list ($board) = $smcFunc['db_fetch_row']($request);
1918
	$smcFunc['db_free_result']($request);
1919
1920
	$icon_sources = array();
1921
	foreach ($context['stable_icons'] as $icon)
1922
		$icon_sources[$icon] = 'images_url';
1923
1924
	if (!empty($modSettings['enable_likes']))
1925
	{
1926
		$context['can_like'] = allowedTo('likes_like');
1927
		$context['can_see_likes'] = allowedTo('likes_view');
1928
	}
1929
1930
	// Find the post ids.
1931
	$request = $smcFunc['db_query']('', '
1932
		SELECT t.id_first_msg
1933
		FROM {db_prefix}topics as t
1934
		LEFT JOIN {db_prefix}boards as b ON (b.id_board = t.id_board)
1935
		WHERE t.id_board = {int:current_board}' . ($modSettings['postmod_active'] ? '
1936
			AND t.approved = {int:is_approved}' : '') . '
1937
			AND {query_see_board}
1938
		ORDER BY t.id_first_msg DESC
1939
		LIMIT ' . $start . ', ' . $limit,
1940
		array(
1941
			'current_board' => $board,
1942
			'is_approved' => 1,
1943
		)
1944
	);
1945
	$posts = array();
1946
	while ($row = $smcFunc['db_fetch_assoc']($request))
1947
		$posts[] = $row['id_first_msg'];
1948
	$smcFunc['db_free_result']($request);
1949
1950
	if (empty($posts))
1951
		return array();
1952
1953
	// Find the posts.
1954
	$request = $smcFunc['db_query']('', '
1955
		SELECT
1956
			m.icon, m.subject, m.body, IFNULL(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.likes,
1957
			t.num_replies, t.id_topic, m.id_member, m.smileys_enabled, m.id_msg, t.locked, t.id_last_msg, m.id_board
1958
		FROM {db_prefix}topics AS t
1959
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
1960
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
1961
		WHERE t.id_first_msg IN ({array_int:post_list})
1962
		ORDER BY t.id_first_msg DESC
1963
		LIMIT ' . count($posts),
1964
		array(
1965
			'post_list' => $posts,
1966
		)
1967
	);
1968
	$return = array();
1969
	$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
1970
	while ($row = $smcFunc['db_fetch_assoc']($request))
1971
	{
1972
		// If we want to limit the length of the post.
1973
		if (!empty($length) && $smcFunc['strlen']($row['body']) > $length)
1974
		{
1975
			$row['body'] = $smcFunc['substr']($row['body'], 0, $length);
1976
			$cutoff = false;
1977
1978
			$last_space = strrpos($row['body'], ' ');
1979
			$last_open = strrpos($row['body'], '<');
1980
			$last_close = strrpos($row['body'], '>');
1981
			if (empty($last_space) || ($last_space == $last_open + 3 && (empty($last_close) || (!empty($last_close) && $last_close < $last_open))) || $last_space < $last_open || $last_open == $length - 6)
1982
				$cutoff = $last_open;
1983
			elseif (empty($last_close) || $last_close < $last_open)
1984
				$cutoff = $last_space;
1985
1986
			if ($cutoff !== false)
1987
				$row['body'] = $smcFunc['substr']($row['body'], 0, $cutoff);
1988
			$row['body'] .= '...';
1989
		}
1990
1991
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
1992
1993
		if (!empty($recycle_board) && $row['id_board'] == $recycle_board)
1994
			$row['icon'] = 'recycled';
1995
1996
		// Check that this message icon is there...
1997 View Code Duplication
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
1998
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
1999
2000
		censorText($row['subject']);
2001
		censorText($row['body']);
2002
2003
		$return[] = array(
2004
			'id' => $row['id_topic'],
2005
			'message_id' => $row['id_msg'],
2006
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" alt="' . $row['icon'] . '">',
2007
			'subject' => $row['subject'],
2008
			'time' => timeformat($row['poster_time']),
2009
			'timestamp' => forum_time(true, $row['poster_time']),
2010
			'body' => $row['body'],
2011
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
2012
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['num_replies'] . ' ' . ($row['num_replies'] == 1 ? $txt['ssi_comment'] : $txt['ssi_comments']) . '</a>',
2013
			'replies' => $row['num_replies'],
2014
			'comment_href' => !empty($row['locked']) ? '' : $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . ';last_msg=' . $row['id_last_msg'],
2015
			'comment_link' => !empty($row['locked']) ? '' : '<a href="' . $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . ';last_msg=' . $row['id_last_msg'] . '">' . $txt['ssi_write_comment'] . '</a>',
2016
			'new_comment' => !empty($row['locked']) ? '' : '<a href="' . $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . '">' . $txt['ssi_write_comment'] . '</a>',
2017
			'poster' => array(
2018
				'id' => $row['id_member'],
2019
				'name' => $row['poster_name'],
2020
				'href' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
2021
				'link' => !empty($row['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>' : $row['poster_name']
2022
			),
2023
			'locked' => !empty($row['locked']),
2024
			'is_last' => false,
2025
			// Nasty ternary for likes not messing around the "is_last" check.
2026
			'likes' => !empty($modSettings['enable_likes']) ? array(
2027
				'count' => $row['likes'],
2028
				'you' => in_array($row['id_msg'], prepareLikesContext((int) $row['id_topic'])),
2029
				'can_like' => !$context['user']['is_guest'] && $row['id_member'] != $context['user']['id'] && !empty($context['can_like']),
2030
			) : array(),
2031
		);
2032
	}
2033
	$smcFunc['db_free_result']($request);
2034
2035
	if (empty($return))
2036
		return $return;
2037
2038
	$return[count($return) - 1]['is_last'] = true;
2039
2040
	// If mods want to do somthing with this list of posts, let them do that now.
2041
	call_integration_hook('integrate_ssi_boardNews', array(&$return));
2042
2043
	if ($output_method != 'echo')
2044
		return $return;
2045
2046
	foreach ($return as $news)
2047
	{
2048
		echo '
2049
			<div class="news_item">
2050
				<h3 class="news_header">
2051
					', $news['icon'], '
2052
					<a href="', $news['href'], '">', $news['subject'], '</a>
2053
				</h3>
2054
				<div class="news_timestamp">', $news['time'], ' ', $txt['by'], ' ', $news['poster']['link'], '</div>
2055
				<div class="news_body" style="padding: 2ex 0;">', $news['body'], '</div>
2056
				', $news['link'], $news['locked'] ? '' : ' | ' . $news['comment_link'], '';
2057
2058
2059
		// Is there any likes to show?
2060
		if (!empty($modSettings['enable_likes']))
2061
		{
2062
			echo '
2063
					<ul>';
2064
2065
			if (!empty($news['likes']['can_like']))
2066
			{
2067
				echo '
2068
						<li class="like_button" id="msg_', $news['message_id'], '_likes"><a href="', $scripturl, '?action=likes;ltype=msg;sa=like;like=', $news['message_id'], ';', $context['session_var'], '=', $context['session_id'], '" class="msg_like"><span class="', $news['likes']['you'] ? 'unlike' : 'like', '"></span>', $news['likes']['you'] ? $txt['unlike'] : $txt['like'], '</a></li>';
2069
			}
2070
2071 View Code Duplication
			if (!empty($news['likes']['count']) && !empty($context['can_see_likes']))
2072
			{
2073
				$context['some_likes'] = true;
2074
				$count = $news['likes']['count'];
2075
				$base = 'likes_';
2076
				if ($news['likes']['you'])
2077
				{
2078
					$base = 'you_' . $base;
2079
					$count--;
2080
				}
2081
				$base .= (isset($txt[$base . $count])) ? $count : 'n';
2082
2083
				echo '
2084
						<li class="like_count smalltext">', sprintf($txt[$base], $scripturl . '?action=likes;sa=view;ltype=msg;like=' . $news['message_id'] . ';' . $context['session_var'] . '=' . $context['session_id'], comma_format($count)), '</li>';
2085
			}
2086
2087
			echo '
2088
					</ul>';
2089
		}
2090
2091
2092
		// Close the main div.
2093
		echo '
2094
			</div>';
2095
2096
		if (!$news['is_last'])
2097
			echo '
2098
			<hr>';
2099
	}
2100
}
2101
2102
/**
2103
 * Show the most recent events
2104
 * @param int $max_events The maximum number of events to show
2105
 * @param string $output_method The output method. If 'echo', displays the events, otherwise returns an array of info about them.
2106
 * @return void|array Displays the events or returns an array of info about them, depending on output_method.
2107
 */
2108
function ssi_recentEvents($max_events = 7, $output_method = 'echo')
2109
{
2110
	global $user_info, $scripturl, $modSettings, $txt, $context, $smcFunc;
2111
2112
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
2113
		return;
2114
2115
	// Find all events which are happening in the near future that the member can see.
2116
	$request = $smcFunc['db_query']('', '
2117
		SELECT
2118
			cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
2119
			cal.start_time, cal.end_time, cal.timezone, cal.location,
2120
			cal.id_board, t.id_first_msg, t.approved
2121
		FROM {db_prefix}calendar AS cal
2122
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
2123
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
2124
		WHERE cal.start_date <= {date:current_date}
2125
			AND cal.end_date >= {date:current_date}
2126
			AND (cal.id_board = {int:no_board} OR {query_wanna_see_board})
2127
		ORDER BY cal.start_date DESC
2128
		LIMIT ' . $max_events,
2129
		array(
2130
			'current_date' => strftime('%Y-%m-%d', forum_time(false)),
2131
			'no_board' => 0,
2132
		)
2133
	);
2134
	$return = array();
2135
	$duplicates = array();
2136
	while ($row = $smcFunc['db_fetch_assoc']($request))
2137
	{
2138
		// Check if we've already come by an event linked to this same topic with the same title... and don't display it if we have.
2139
		if (!empty($duplicates[$row['title'] . $row['id_topic']]))
2140
			continue;
2141
2142
		// Censor the title.
2143
		censorText($row['title']);
2144
2145
		if ($row['start_date'] < strftime('%Y-%m-%d', forum_time(false)))
2146
			$date = strftime('%Y-%m-%d', forum_time(false));
2147
		else
2148
			$date = $row['start_date'];
2149
2150
		// If the topic it is attached to is not approved then don't link it.
2151
		if (!empty($row['id_first_msg']) && !$row['approved'])
2152
			$row['id_board'] = $row['id_topic'] = $row['id_first_msg'] = 0;
2153
2154
		$allday = (empty($row['start_time']) || empty($row['end_time']) || empty($row['timezone']) || !in_array($row['timezone'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC))) ? true : false;
2155
2156
		$return[$date][] = array(
2157
			'id' => $row['id_event'],
2158
			'title' => $row['title'],
2159
			'location' => $row['location'],
2160
			'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
2161
			'modify_href' => $scripturl . '?action=' . ($row['id_board'] == 0 ? 'calendar;sa=post;' : 'post;msg=' . $row['id_first_msg'] . ';topic=' . $row['id_topic'] . '.0;calendar;') . 'eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
2162
			'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
2163
			'link' => $row['id_board'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
2164
			'start_date' => $row['start_date'],
2165
			'end_date' => $row['end_date'],
2166
			'start_time' => !$allday ? $row['start_time'] : null,
2167
			'end_time' => !$allday ? $row['end_time'] : null,
2168
			'tz' => !$allday ? $row['timezone'] : null,
2169
			'allday' => $allday,
2170
			'is_last' => false
2171
		);
2172
2173
		// Let's not show this one again, huh?
2174
		$duplicates[$row['title'] . $row['id_topic']] = true;
2175
	}
2176
	$smcFunc['db_free_result']($request);
2177
2178
	foreach ($return as $mday => $array)
2179
		$return[$mday][count($array) - 1]['is_last'] = true;
2180
2181
	// If mods want to do somthing with this list of events, let them do that now.
2182
	call_integration_hook('integrate_ssi_recentEvents', array(&$return));
2183
2184
	if ($output_method != 'echo' || empty($return))
2185
		return $return;
2186
2187
	// Well the output method is echo.
2188
	echo '
2189
			<span class="event">' . $txt['events'] . '</span> ';
2190
	foreach ($return as $mday => $array)
2191
		foreach ($array as $event)
2192
		{
2193
			if ($event['can_edit'])
2194
				echo '
2195
				<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
2196
2197
			echo '
2198
				' . $event['link'] . (!$event['is_last'] ? ', ' : '');
2199
		}
2200
}
2201
2202
/**
2203
 * Checks whether the specified password is correct for the specified user.
2204
 * @param int|string $id The ID or username of a user
0 ignored issues
show
Documentation introduced by
Should the type for parameter $id not be integer|string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
2205
 * @param string $password The password to check
0 ignored issues
show
Documentation introduced by
Should the type for parameter $password not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
2206
 * @param bool $is_username If true, treats $id as a username rather than a user ID
2207
 * @return bool Whether or not the password is correct.
0 ignored issues
show
Documentation introduced by
Should the return type not be null|boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
2208
 */
2209
function ssi_checkPassword($id = null, $password = null, $is_username = false)
2210
{
2211
	global $smcFunc;
2212
2213
	// If $id is null, this was most likely called from a query string and should do nothing.
2214
	if ($id === null)
2215
		return;
2216
2217
	$request = $smcFunc['db_query']('', '
2218
		SELECT passwd, member_name, is_activated
2219
		FROM {db_prefix}members
2220
		WHERE ' . ($is_username ? 'member_name' : 'id_member') . ' = {string:id}
2221
		LIMIT 1',
2222
		array(
2223
			'id' => $id,
2224
		)
2225
	);
2226
	list ($pass, $user, $active) = $smcFunc['db_fetch_row']($request);
2227
	$smcFunc['db_free_result']($request);
2228
2229
	return hash_verify_password($user, $password, $pass) && $active == 1;
2230
}
2231
2232
/**
2233
 * Shows the most recent attachments that the user can see
2234
 * @param int $num_attachments How many to show
2235
 * @param array $attachment_ext Only shows attachments with the specified extensions ('jpg', 'gif', etc.) if set
2236
 * @param string $output_method The output method. If 'echo', displays a table with links/info, otherwise returns an array with information about the attachments
2237
 * @return void|array Displays a table of attachment info or returns an array containing info about the attachments, depending on output_method.
2238
 */
2239
function ssi_recentAttachments($num_attachments = 10, $attachment_ext = array(), $output_method = 'echo')
2240
{
2241
	global $smcFunc, $modSettings, $scripturl, $txt, $settings;
2242
2243
	// We want to make sure that we only get attachments for boards that we can see *if* any.
2244
	$attachments_boards = boardsAllowedTo('view_attachments');
2245
2246
	// No boards?  Adios amigo.
2247
	if (empty($attachments_boards))
2248
		return array();
2249
2250
	// Is it an array?
2251
	$attachment_ext = (array) $attachment_ext;
2252
2253
	// Lets build the query.
2254
	$request = $smcFunc['db_query']('', '
2255
		SELECT
2256
			att.id_attach, att.id_msg, att.filename, IFNULL(att.size, 0) AS filesize, att.downloads, mem.id_member,
2257
			IFNULL(mem.real_name, m.poster_name) AS poster_name, m.id_topic, m.subject, t.id_board, m.poster_time,
2258
			att.width, att.height' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ', IFNULL(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
2259
		FROM {db_prefix}attachments AS att
2260
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = att.id_msg)
2261
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
2262
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
2263
			LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = att.id_thumb)') . '
2264
		WHERE att.attachment_type = 0' . ($attachments_boards === array(0) ? '' : '
2265
			AND m.id_board IN ({array_int:boards_can_see})') . (!empty($attachment_ext) ? '
2266
			AND att.fileext IN ({array_string:attachment_ext})' : '') .
2267
			(!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
2268
			AND t.approved = {int:is_approved}
2269
			AND m.approved = {int:is_approved}
2270
			AND att.approved = {int:is_approved}') . '
2271
		ORDER BY att.id_attach DESC
2272
		LIMIT {int:num_attachments}',
2273
		array(
2274
			'boards_can_see' => $attachments_boards,
2275
			'attachment_ext' => $attachment_ext,
2276
			'num_attachments' => $num_attachments,
2277
			'is_approved' => 1,
2278
		)
2279
	);
2280
2281
	// We have something.
2282
	$attachments = array();
2283
	while ($row = $smcFunc['db_fetch_assoc']($request))
2284
	{
2285
		$filename = preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($row['filename']));
2286
2287
		// Is it an image?
2288
		$attachments[$row['id_attach']] = array(
2289
			'member' => array(
2290
				'id' => $row['id_member'],
2291
				'name' => $row['poster_name'],
2292
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>',
2293
			),
2294
			'file' => array(
2295
				'filename' => $filename,
2296
				'filesize' => round($row['filesize'] / 1024, 2) . $txt['kilobyte'],
2297
				'downloads' => $row['downloads'],
2298
				'href' => $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'],
2299
				'link' => '<img src="' . $settings['images_url'] . '/icons/clip.png" alt=""> <a href="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . '">' . $filename . '</a>',
2300
				'is_image' => !empty($row['width']) && !empty($row['height']) && !empty($modSettings['attachmentShowImages']),
2301
			),
2302
			'topic' => array(
2303
				'id' => $row['id_topic'],
2304
				'subject' => $row['subject'],
2305
				'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
2306
				'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>',
2307
				'time' => timeformat($row['poster_time']),
2308
			),
2309
		);
2310
2311
		// Images.
2312
		if ($attachments[$row['id_attach']]['file']['is_image'])
2313
		{
2314
			$id_thumb = empty($row['id_thumb']) ? $row['id_attach'] : $row['id_thumb'];
2315
			$attachments[$row['id_attach']]['file']['image'] = array(
2316
				'id' => $id_thumb,
2317
				'width' => $row['width'],
2318
				'height' => $row['height'],
2319
				'img' => '<img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . ';image" alt="' . $filename . '">',
2320
				'thumb' => '<img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image" alt="' . $filename . '">',
2321
				'href' => $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image',
2322
				'link' => '<a href="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . ';image"><img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image" alt="' . $filename . '"></a>',
2323
			);
2324
		}
2325
	}
2326
	$smcFunc['db_free_result']($request);
2327
2328
	// If mods want to do somthing with this list of attachments, let them do that now.
2329
	call_integration_hook('integrate_ssi_recentAttachments', array(&$attachments));
2330
2331
	// So you just want an array?  Here you can have it.
2332
	if ($output_method == 'array' || empty($attachments))
2333
		return $attachments;
2334
2335
	// Give them the default.
2336
	echo '
2337
		<table class="ssi_downloads">
2338
			<tr>
2339
				<th style="text-align: left; padding: 2">', $txt['file'], '</th>
2340
				<th style="text-align: left; padding: 2">', $txt['posted_by'], '</th>
2341
				<th style="text-align: left; padding: 2">', $txt['downloads'], '</th>
2342
				<th style="text-align: left; padding: 2">', $txt['filesize'], '</th>
2343
			</tr>';
2344
	foreach ($attachments as $attach)
2345
		echo '
2346
			<tr>
2347
				<td>', $attach['file']['link'], '</td>
2348
				<td>', $attach['member']['link'], '</td>
2349
				<td style="text-align: center">', $attach['file']['downloads'], '</td>
2350
				<td>', $attach['file']['filesize'], '</td>
2351
			</tr>';
2352
	echo '
2353
		</table>';
2354
}
2355
2356
?>