Issues (1014)

1
<?php
2
3
/**
4
 * Simple Machines Forum (SMF)
5
 *
6
 * @package SMF
7
 * @author Simple Machines https://www.simplemachines.org
8
 * @copyright 2022 Simple Machines and individual contributors
9
 * @license https://www.simplemachines.org/about/smf/license.php BSD
10
 *
11
 * @version 2.1.2
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
define('SMF_VERSION', '2.1.2');
20
define('SMF_FULL_VERSION', 'SMF ' . SMF_VERSION);
21
define('SMF_SOFTWARE_YEAR', '2022');
22
define('JQUERY_VERSION', '3.6.0');
23
define('POSTGRE_TITLE', 'PostgreSQL');
24
define('MYSQL_TITLE', 'MySQL');
25
define('SMF_USER_AGENT', 'Mozilla/5.0 (' . php_uname('s') . ' ' . php_uname('m') . ') AppleWebKit/605.1.15 (KHTML, like Gecko)  SMF/' . strtr(SMF_VERSION, ' ', '.'));
26
27
// Just being safe...  Do this before defining globals as otherwise it unsets the global.
28
foreach (array('db_character_set', 'cachedir') as $variable)
29
	unset($GLOBALS[$variable]);
30
31
// We're going to want a few globals... these are all set later.
32
global $maintenance, $msubject, $mmessage, $mbname, $language;
33
global $boardurl, $boarddir, $sourcedir, $webmaster_email, $cookiename, $db_character_set;
34
global $db_type, $db_server, $db_name, $db_user, $db_prefix, $db_persist, $db_error_send, $db_last_error, $db_show_debug;
35
global $db_connection, $db_port, $modSettings, $context, $sc, $user_info, $topic, $board, $txt;
36
global $smcFunc, $ssi_db_user, $scripturl, $ssi_db_passwd, $db_passwd, $cache_enable, $cachedir;
37
global $auth_secret;
38
39
if (!defined('TIME_START'))
40
	define('TIME_START', microtime(true));
41
42
// Get the forum's settings for database and file paths.
43
require_once(dirname(__FILE__) . '/Settings.php');
44
45
// Make absolutely sure the cache directory is defined and writable.
46
if (empty($cachedir) || !is_dir($cachedir) || !is_writable($cachedir))
47
{
48
	if (is_dir($boarddir . '/cache') && is_writable($boarddir . '/cache'))
49
		$cachedir = $boarddir . '/cache';
50
	else
51
	{
52
		$cachedir = sys_get_temp_dir() . '/smf_cache_' . md5($boarddir);
53
		@mkdir($cachedir, 0750);
54
	}
55
}
56
57
$ssi_error_reporting = error_reporting(!empty($db_show_debug) ? E_ALL : E_ALL & ~E_DEPRECATED);
58
/* Set this to one of three values depending on what you want to happen in the case of a fatal error.
59
	false:	Default, will just load the error sub template and die - not putting any theme layers around it.
60
	true:	Will load the error sub template AND put the SMF layers around it (Not useful if on total custom pages).
61
	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.
62
*/
63
$ssi_on_error_method = false;
64
65
// Don't do john didley if the forum's been shut down completely.
66
if ($maintenance == 2 && (!isset($ssi_maintenance_off) || $ssi_maintenance_off !== true))
67
	die($mmessage);
68
69
// Fix for using the current directory as a path.
70
if (substr($sourcedir, 0, 1) == '.' && substr($sourcedir, 1, 1) != '.')
71
	$sourcedir = dirname(__FILE__) . substr($sourcedir, 1);
72
73
// Load the important includes.
74
require_once($sourcedir . '/QueryString.php');
75
require_once($sourcedir . '/Session.php');
76
require_once($sourcedir . '/Subs.php');
77
require_once($sourcedir . '/Errors.php');
78
require_once($sourcedir . '/Logging.php');
79
require_once($sourcedir . '/Load.php');
80
require_once($sourcedir . '/Security.php');
81
require_once($sourcedir . '/Class-BrowserDetect.php');
82
require_once($sourcedir . '/Subs-Auth.php');
83
84
// Ensure we don't trip over disabled internal functions
85
if (version_compare(PHP_VERSION, '8.0.0', '>='))
86
	require_once($sourcedir . '/Subs-Compat.php');
87
88
// Create a variable to store some SMF specific functions in.
89
$smcFunc = array();
90
91
// Initiate the database connection and define some database functions to use.
92
loadDatabase();
93
94
/**
95
 * An autoloader for certain classes.
96
 *
97
 * @param string $class The fully-qualified class name.
98
 */
99
spl_autoload_register(function($class) use ($sourcedir)
100
{
101
	$classMap = array(
102
		'ReCaptcha\\' => 'ReCaptcha/',
103
		'MatthiasMullie\\Minify\\' => 'minify/src/',
104
		'MatthiasMullie\\PathConverter\\' => 'minify/path-converter/src/',
105
		'SMF\\Cache\\' => 'Cache/',
106
	);
107
108
	// Do any third-party scripts want in on the fun?
109
	call_integration_hook('integrate_autoload', array(&$classMap));
110
111
	foreach ($classMap as $prefix => $dirName)
112
	{
113
		// does the class use the namespace prefix?
114
		$len = strlen($prefix);
115
		if (strncmp($prefix, $class, $len) !== 0)
116
		{
117
			continue;
118
		}
119
120
		// get the relative class name
121
		$relativeClass = substr($class, $len);
122
123
		// replace the namespace prefix with the base directory, replace namespace
124
		// separators with directory separators in the relative class name, append
125
		// with .php
126
		$fileName = $dirName . strtr($relativeClass, '\\', '/') . '.php';
127
128
		// if the file exists, require it
129
		if (file_exists($fileName = $sourcedir . '/' . $fileName))
130
		{
131
			require_once $fileName;
132
133
			return;
134
		}
135
	}
136
});
137
138
// Load installed 'Mods' settings.
139
reloadSettings();
140
// Clean the request variables.
141
cleanRequest();
142
143
// Seed the random generator?
144
if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69)
145
	smf_seed_generator();
146
147
// Check on any hacking attempts.
148
if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']))
149
	die('No direct access...');
150
elseif (isset($_REQUEST['ssi_theme']) && (int) $_REQUEST['ssi_theme'] == (int) $ssi_theme)
151
	die('No direct access...');
152
elseif (isset($_COOKIE['ssi_theme']) && (int) $_COOKIE['ssi_theme'] == (int) $ssi_theme)
153
	die('No direct access...');
154
elseif (isset($_REQUEST['ssi_layers'], $ssi_layers) && (@get_magic_quotes_gpc() ? stripslashes($_REQUEST['ssi_layers']) : $_REQUEST['ssi_layers']) == $ssi_layers)
155
	die('No direct access...');
156
if (isset($_REQUEST['context']))
157
	die('No direct access...');
158
159
// Gzip output? (because it must be boolean and true, this can't be hacked.)
160
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', '>='))
161
	ob_start('ob_gzhandler');
162
else
163
	$modSettings['enableCompressedOutput'] = '0';
164
165
// Primarily, this is to fix the URLs...
166
ob_start('ob_sessrewrite');
167
168
// Start the session... known to scramble SSI includes in cases...
169
if (!headers_sent())
170
	loadSession();
171
else
172
{
173
	if (isset($_COOKIE[session_name()]) || isset($_REQUEST[session_name()]))
174
	{
175
		// Make a stab at it, but ignore the E_WARNINGs generated because we can't send headers.
176
		$temp = error_reporting(error_reporting() & !E_WARNING);
177
		loadSession();
178
		error_reporting($temp);
179
	}
180
181
	if (!isset($_SESSION['session_value']))
182
	{
183
		$_SESSION['session_var'] = substr(md5($smcFunc['random_int']() . session_id() . $smcFunc['random_int']()), 0, rand(7, 12));
184
		$_SESSION['session_value'] = md5(session_id() . $smcFunc['random_int']());
185
	}
186
	$sc = $_SESSION['session_value'];
187
}
188
189
// Get rid of $board and $topic... do stuff loadBoard would do.
190
unset($board, $topic);
191
$user_info['is_mod'] = false;
192
$context['user']['is_mod'] = &$user_info['is_mod'];
193
$context['linktree'] = array();
194
195
// Load the user and their cookie, as well as their settings.
196
loadUserSettings();
197
198
// Load the current user's permissions....
199
loadPermissions();
200
201
// Load the current or SSI theme. (just use $ssi_theme = id_theme;)
202
loadTheme(isset($ssi_theme) ? (int) $ssi_theme : 0);
203
204
// @todo: probably not the best place, but somewhere it should be set...
205
if (!headers_sent())
206
	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']));
207
208
// Take care of any banning that needs to be done.
209
if (isset($_REQUEST['ssi_ban']) || (isset($ssi_ban) && $ssi_ban === true))
210
	is_not_banned();
211
212
// Do we allow guests in here?
213
if (empty($ssi_guest_access) && empty($modSettings['allow_guestAccess']) && $user_info['is_guest'] && basename($_SERVER['PHP_SELF']) != 'SSI.php')
214
{
215
	require_once($sourcedir . '/Subs-Auth.php');
216
	KickGuest();
217
	obExit(null, true);
218
}
219
220
// Load the stuff like the menu bar, etc.
221
if (isset($ssi_layers))
222
{
223
	$context['template_layers'] = $ssi_layers;
224
	template_header();
225
}
226
else
227
	setupThemeContext();
228
229
// Make sure they didn't muss around with the settings... but only if it's not cli.
230
if (isset($_SERVER['REMOTE_ADDR']) && !isset($_SERVER['is_cli']) && session_id() == '')
231
	trigger_error($txt['ssi_session_broken'], E_USER_NOTICE);
232
233
// Without visiting the forum this session variable might not be set on submit.
234
if (!isset($_SESSION['USER_AGENT']) && (!isset($_GET['ssi_function']) || $_GET['ssi_function'] !== 'pollVote'))
235
	$_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
236
237
// Have the ability to easily add functions to SSI.
238
call_integration_hook('integrate_SSI');
239
240
// Ignore a call to ssi_* functions if we are not accessing SSI.php directly.
241
if (basename($_SERVER['PHP_SELF']) == 'SSI.php')
242
{
243
	// You shouldn't just access SSI.php directly by URL!!
244
	if (!isset($_GET['ssi_function']))
245
		die(sprintf($txt['ssi_not_direct'], $user_info['is_admin'] ? '\'' . addslashes(__FILE__) . '\'' : '\'SSI.php\''));
246
	// Call a function passed by GET.
247
	if (function_exists('ssi_' . $_GET['ssi_function']) && (!empty($modSettings['allow_guestAccess']) || !$user_info['is_guest']))
248
		call_user_func('ssi_' . $_GET['ssi_function']);
249
	exit;
250
}
251
252
// To avoid side effects later on.
253
unset($_GET['ssi_function']);
254
255
error_reporting($ssi_error_reporting);
256
257
return true;
258
259
/**
260
 * This shuts down the SSI and shows the footer.
261
 *
262
 * @return void
263
 */
264
function ssi_shutdown()
265
{
266
	if (!isset($_GET['ssi_function']) || $_GET['ssi_function'] != 'shutdown')
267
		template_footer();
268
}
269
270
/**
271
 * Show the SMF version.
272
 *
273
 * @param string $output_method If 'echo', displays the version, otherwise returns it
274
 * @return void|string Returns nothing if output_method is 'echo', otherwise returns the version
275
 */
276
function ssi_version($output_method = 'echo')
277
{
278
	if ($output_method == 'echo')
279
		echo SMF_VERSION;
280
	else
281
		return SMF_VERSION;
282
}
283
284
/**
285
 * Show the full SMF version string.
286
 *
287
 * @param string $output_method If 'echo', displays the full version string, otherwise returns it
288
 * @return void|string Returns nothing if output_method is 'echo', otherwise returns the version string
289
 */
290
function ssi_full_version($output_method = 'echo')
291
{
292
	if ($output_method == 'echo')
293
		echo SMF_FULL_VERSION;
294
	else
295
		return SMF_FULL_VERSION;
296
}
297
298
/**
299
 * Show the SMF software year.
300
 *
301
 * @param string $output_method If 'echo', displays the software year, otherwise returns it
302
 * @return void|string Returns nothing if output_method is 'echo', otherwise returns the software year
303
 */
304
function ssi_software_year($output_method = 'echo')
305
{
306
	if ($output_method == 'echo')
307
		echo SMF_SOFTWARE_YEAR;
308
	else
309
		return SMF_SOFTWARE_YEAR;
310
}
311
312
/**
313
 * Show the forum copyright. Only used in our ssi_examples files.
314
 *
315
 * @param string $output_method If 'echo', displays the forum copyright, otherwise returns it
316
 * @return void|string Returns nothing if output_method is 'echo', otherwise returns the copyright string
317
 */
318
function ssi_copyright($output_method = 'echo')
319
{
320
	global $forum_copyright, $scripturl;
321
322
	if ($output_method == 'echo')
323
		printf($forum_copyright, SMF_FULL_VERSION, SMF_SOFTWARE_YEAR, $scripturl);
324
	else
325
		return sprintf($forum_copyright, SMF_FULL_VERSION, SMF_SOFTWARE_YEAR, $scripturl);
326
}
327
328
/**
329
 * Display a welcome message, like: Hey, User, you have 0 messages, 0 are new.
330
 *
331
 * @param string $output_method The output method. If 'echo', will display everything. Otherwise returns an array of user info.
332
 * @return void|array Displays a welcome message or returns an array of user data depending on output_method.
333
 */
334
function ssi_welcome($output_method = 'echo')
335
{
336
	global $context, $txt, $scripturl;
337
338
	if ($output_method == 'echo')
339
	{
340
		if ($context['user']['is_guest'])
341
			echo sprintf($txt[$context['can_register'] ? 'welcome_guest_register' : 'welcome_guest'], $context['forum_name_html_safe'], $scripturl . '?action=login', 'return reqOverlayDiv(this.href, ' . JavaScriptEscape($txt['login']) . ');', $scripturl . '?action=signup');
342
		else
343
			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'])))) : '';
344
	}
345
	// Don't echo... then do what?!
346
	else
347
		return $context['user'];
348
}
349
350
/**
351
 * Display a menu bar, like is displayed at the top of the forum.
352
 *
353
 * @param string $output_method The output method. If 'echo', will display the menu, otherwise returns an array of menu data.
354
 * @return void|array Displays the menu or returns an array of menu data depending on output_method.
355
 */
356
function ssi_menubar($output_method = 'echo')
357
{
358
	global $context;
359
360
	if ($output_method == 'echo')
361
		template_menu();
362
	// What else could this do?
363
	else
364
		return $context['menu_buttons'];
365
}
366
367
/**
368
 * Show a logout link.
369
 *
370
 * @param string $redirect_to A URL to redirect the user to after they log out.
371
 * @param string $output_method The output method. If 'echo', shows a logout link, otherwise returns the HTML for it.
372
 * @return void|string Displays a logout link or returns its HTML depending on output_method.
373
 */
374
function ssi_logout($redirect_to = '', $output_method = 'echo')
375
{
376
	global $context, $txt, $scripturl;
377
378
	if ($redirect_to != '')
379
		$_SESSION['logout_url'] = $redirect_to;
380
381
	// Guests can't log out.
382
	if ($context['user']['is_guest'])
383
		return false;
384
385
	$link = '<a href="' . $scripturl . '?action=logout;' . $context['session_var'] . '=' . $context['session_id'] . '">' . $txt['logout'] . '</a>';
386
387
	if ($output_method == 'echo')
388
		echo $link;
389
	else
390
		return $link;
391
}
392
393
/**
394
 * Recent post list:   [board] Subject by Poster    Date
395
 *
396
 * @param int $num_recent How many recent posts to display
397
 * @param null|array $exclude_boards If set, doesn't show posts from the specified boards
398
 * @param null|array $include_boards If set, only includes posts from the specified boards
399
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of information about them.
400
 * @param bool $limit_body Whether or not to only show the first 384 characters of each post
401
 * @return void|array Displays a list of recent posts or returns an array of information about them depending on output_method.
402
 */
403
function ssi_recentPosts($num_recent = 8, $exclude_boards = null, $include_boards = null, $output_method = 'echo', $limit_body = true)
404
{
405
	global $modSettings, $context;
406
407
	// Excluding certain boards...
408
	if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']))
409
		$exclude_boards = array($modSettings['recycle_board']);
410
	else
411
		$exclude_boards = empty($exclude_boards) ? array() : (is_array($exclude_boards) ? $exclude_boards : array($exclude_boards));
0 ignored issues
show
The condition is_array($exclude_boards) is always true.
Loading history...
412
413
	// What about including certain boards - note we do some protection here as pre-2.0 didn't have this parameter.
414
	if (is_array($include_boards) || (int) $include_boards === $include_boards)
415
	{
416
		$include_boards = is_array($include_boards) ? $include_boards : array($include_boards);
0 ignored issues
show
The condition is_array($include_boards) is always true.
Loading history...
417
	}
418
	elseif ($include_boards != null)
0 ignored issues
show
The condition $include_boards != null is always false.
Loading history...
419
	{
420
		$include_boards = array();
421
	}
422
423
	// Let's restrict the query boys (and girls)
424
	$query_where = '
425
		m.id_msg >= {int:min_message_id}
426
		' . (empty($exclude_boards) ? '' : '
427
		AND b.id_board NOT IN ({array_int:exclude_boards})') . '
428
		' . ($include_boards === null ? '' : '
429
		AND b.id_board IN ({array_int:include_boards})') . '
430
		AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
431
		AND m.approved = {int:is_approved}' : '');
432
433
	$query_where_params = array(
434
		'is_approved' => 1,
435
		'include_boards' => $include_boards === null ? '' : $include_boards,
436
		'exclude_boards' => empty($exclude_boards) ? '' : $exclude_boards,
437
		'min_message_id' => $modSettings['maxMsgID'] - (!empty($context['min_message_posts']) ? $context['min_message_posts'] : 25) * min($num_recent, 5),
438
	);
439
440
	// Past to this simpleton of a function...
441
	return ssi_queryPosts($query_where, $query_where_params, $num_recent, 'm.id_msg DESC', $output_method, $limit_body);
442
}
443
444
/**
445
 * Fetches one or more posts by ID.
446
 *
447
 * @param array $post_ids An array containing the IDs of the posts to show
448
 * @param bool $override_permissions Whether to ignore permissions. If true, will show posts even if the user doesn't have permission to see them.
449
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of info about them
450
 * @return void|array Displays the specified posts or returns an array of info about them, depending on output_method.
451
 */
452
function ssi_fetchPosts($post_ids = array(), $override_permissions = false, $output_method = 'echo')
453
{
454
	global $modSettings;
455
456
	if (empty($post_ids))
457
		return;
458
459
	// Allow the user to request more than one - why not?
460
	$post_ids = is_array($post_ids) ? $post_ids : array($post_ids);
0 ignored issues
show
The condition is_array($post_ids) is always true.
Loading history...
461
462
	// Restrict the posts required...
463
	$query_where = '
464
		m.id_msg IN ({array_int:message_list})' . ($override_permissions ? '' : '
465
			AND {query_wanna_see_board}') . ($modSettings['postmod_active'] ? '
466
			AND m.approved = {int:is_approved}' : '');
467
	$query_where_params = array(
468
		'message_list' => $post_ids,
469
		'is_approved' => 1,
470
	);
471
472
	// Then make the query and dump the data.
473
	return ssi_queryPosts($query_where, $query_where_params, '', 'm.id_msg DESC', $output_method, false, $override_permissions);
0 ignored issues
show
'' of type string is incompatible with the type integer expected by parameter $query_limit of ssi_queryPosts(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

473
	return ssi_queryPosts($query_where, $query_where_params, /** @scrutinizer ignore-type */ '', 'm.id_msg DESC', $output_method, false, $override_permissions);
Loading history...
474
}
475
476
/**
477
 * This handles actually pulling post info. Called from other functions to eliminate duplication.
478
 *
479
 * @param string $query_where The WHERE clause for the query
480
 * @param array $query_where_params An array of parameters for the WHERE clause
481
 * @param int $query_limit The maximum number of rows to return
482
 * @param string $query_order The ORDER BY clause for the query
483
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of info about them.
484
 * @param bool $limit_body If true, will only show the first 384 characters of the post rather than all of it
485
 * @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
486
 * @return void|array Displays the posts or returns an array of info about them, depending on output_method
487
 */
488
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)
489
{
490
	global $scripturl, $txt, $user_info;
491
	global $modSettings, $smcFunc, $context;
492
493
	if (!empty($modSettings['enable_likes']))
494
		$context['can_like'] = allowedTo('likes_like');
495
496
	// Find all the posts. Newer ones will have higher IDs.
497
	$request = $smcFunc['db_query']('substring', '
498
		SELECT
499
			m.poster_time, m.subject, m.id_topic, m.id_member, m.id_msg, m.id_board, m.likes, b.name AS board_name,
500
			COALESCE(mem.real_name, m.poster_name) AS poster_name, ' . ($user_info['is_guest'] ? '1 AS is_read, 0 AS new_from' : '
501
			COALESCE(lt.id_msg, lmr.id_msg, 0) >= m.id_msg_modified AS is_read,
502
			COALESCE(lt.id_msg, lmr.id_msg, -1) + 1 AS new_from') . ', ' . ($limit_body ? 'SUBSTRING(m.body, 1, 384) AS body' : 'm.body') . ', m.smileys_enabled
503
		FROM {db_prefix}messages AS m
504
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)' . ($modSettings['postmod_active'] ? '
505
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)' : '') . '
506
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (!$user_info['is_guest'] ? '
507
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = m.id_topic AND lt.id_member = {int:current_member})
508
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = m.id_board AND lmr.id_member = {int:current_member})' : '') . '
509
		WHERE 1=1 ' . ($override_permissions ? '' : '
510
			AND {query_wanna_see_board}') . ($modSettings['postmod_active'] ? '
511
			AND m.approved = {int:is_approved}
512
			AND t.approved = {int:is_approved}' : '') . '
513
		' . (empty($query_where) ? '' : 'AND ' . $query_where) . '
514
		ORDER BY ' . $query_order . '
515
		' . ($query_limit == '' ? '' : 'LIMIT ' . $query_limit),
516
		array_merge($query_where_params, array(
517
			'current_member' => $user_info['id'],
518
			'is_approved' => 1,
519
		))
520
	);
521
	$posts = array();
522
	while ($row = $smcFunc['db_fetch_assoc']($request))
523
	{
524
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
525
526
		// Censor it!
527
		censorText($row['subject']);
528
		censorText($row['body']);
529
530
		$preview = strip_tags(strtr($row['body'], array('<br>' => '&#10;')));
531
532
		// Build the array.
533
		$posts[$row['id_msg']] = array(
534
			'id' => $row['id_msg'],
535
			'board' => array(
536
				'id' => $row['id_board'],
537
				'name' => $row['board_name'],
538
				'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
539
				'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['board_name'] . '</a>'
540
			),
541
			'topic' => $row['id_topic'],
542
			'poster' => array(
543
				'id' => $row['id_member'],
544
				'name' => $row['poster_name'],
545
				'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
546
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
547
			),
548
			'subject' => $row['subject'],
549
			'short_subject' => shorten_subject($row['subject'], 25),
550
			'preview' => $smcFunc['strlen']($preview) > 128 ? $smcFunc['substr']($preview, 0, 128) . '...' : $preview,
551
			'body' => $row['body'],
552
			'time' => timeformat($row['poster_time']),
553
			'timestamp' => $row['poster_time'],
554
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
555
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '" rel="nofollow">' . $row['subject'] . '</a>',
556
			'new' => !empty($row['is_read']),
557
			'is_new' => empty($row['is_read']),
558
			'new_from' => $row['new_from'],
559
		);
560
561
		// Get the likes for each message.
562
		if (!empty($modSettings['enable_likes']))
563
			$posts[$row['id_msg']]['likes'] = array(
564
				'count' => $row['likes'],
565
				'you' => in_array($row['id_msg'], prepareLikesContext($row['id_topic'])),
566
				'can_like' => !$context['user']['is_guest'] && $row['id_member'] != $context['user']['id'] && !empty($context['can_like']),
567
			);
568
	}
569
	$smcFunc['db_free_result']($request);
570
571
	// If mods want to do something with this list of posts, let them do that now.
572
	call_integration_hook('integrate_ssi_queryPosts', array(&$posts));
573
574
	// Just return it.
575
	if ($output_method != 'echo' || empty($posts))
576
		return $posts;
577
578
	echo '
579
		<table style="border: none" class="ssi_table">';
580
	foreach ($posts as $post)
581
		echo '
582
			<tr>
583
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
584
					[', $post['board']['link'], ']
585
				</td>
586
				<td style="vertical-align: top">
587
					<a href="', $post['href'], '">', $post['subject'], '</a>
588
					', $txt['by'], ' ', $post['poster']['link'], '
589
					', $post['is_new'] ? '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow" class="new_posts">' . $txt['new'] . '</a>' : '', '
590
				</td>
591
				<td style="text-align: right; white-space: nowrap">
592
					', $post['time'], '
593
				</td>
594
			</tr>';
595
	echo '
596
		</table>';
597
}
598
599
/**
600
 * Recent topic list:   [board] Subject by Poster   Date
601
 *
602
 * @param int $num_recent How many recent topics to show
603
 * @param null|array $exclude_boards If set, exclude topics from the specified board(s)
604
 * @param null|array $include_boards If set, only include topics from the specified board(s)
605
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
606
 * @return void|array Either displays a list of topics or returns an array of info about them, depending on output_method.
607
 */
608
function ssi_recentTopics($num_recent = 8, $exclude_boards = null, $include_boards = null, $output_method = 'echo')
609
{
610
	global $settings, $scripturl, $txt, $user_info;
611
	global $modSettings, $smcFunc, $context;
612
613
	if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0)
614
		$exclude_boards = array($modSettings['recycle_board']);
615
	else
616
		$exclude_boards = empty($exclude_boards) ? array() : (is_array($exclude_boards) ? $exclude_boards : array($exclude_boards));
0 ignored issues
show
The condition is_array($exclude_boards) is always true.
Loading history...
617
618
	// Only some boards?.
619
	if (is_array($include_boards) || (int) $include_boards === $include_boards)
620
	{
621
		$include_boards = is_array($include_boards) ? $include_boards : array($include_boards);
0 ignored issues
show
The condition is_array($include_boards) is always true.
Loading history...
622
	}
623
	elseif ($include_boards != null)
0 ignored issues
show
The condition $include_boards != null is always false.
Loading history...
624
	{
625
		$output_method = $include_boards;
626
		$include_boards = array();
627
	}
628
629
	$icon_sources = array();
630
	foreach ($context['stable_icons'] as $icon)
631
		$icon_sources[$icon] = 'images_url';
632
633
	// Find all the posts in distinct topics.  Newer ones will have higher IDs.
634
	$request = $smcFunc['db_query']('substring', '
635
		SELECT
636
			t.id_topic, b.id_board, b.name AS board_name
637
		FROM {db_prefix}topics AS t
638
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
639
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
640
		WHERE t.id_last_msg >= {int:min_message_id}' . (empty($exclude_boards) ? '' : '
641
			AND b.id_board NOT IN ({array_int:exclude_boards})') . '' . (empty($include_boards) ? '' : '
642
			AND b.id_board IN ({array_int:include_boards})') . '
643
			AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
644
			AND t.approved = {int:is_approved}
645
			AND ml.approved = {int:is_approved}' : '') . '
646
		ORDER BY t.id_last_msg DESC
647
		LIMIT ' . $num_recent,
648
		array(
649
			'include_boards' => empty($include_boards) ? '' : $include_boards,
650
			'exclude_boards' => empty($exclude_boards) ? '' : $exclude_boards,
651
			'min_message_id' => $modSettings['maxMsgID'] - (!empty($context['min_message_topics']) ? $context['min_message_topics'] : 35) * min($num_recent, 5),
652
			'is_approved' => 1,
653
		)
654
	);
655
	$topics = array();
656
	while ($row = $smcFunc['db_fetch_assoc']($request))
657
		$topics[$row['id_topic']] = $row;
658
	$smcFunc['db_free_result']($request);
659
660
	// Did we find anything? If not, bail.
661
	if (empty($topics))
662
		return array();
663
664
	$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
665
666
	// Find all the posts in distinct topics.  Newer ones will have higher IDs.
667
	$request = $smcFunc['db_query']('substring', '
668
		SELECT
669
			mf.poster_time, mf.subject, ml.id_topic, mf.id_member, ml.id_msg, t.num_replies, t.num_views, mg.online_color, t.id_last_msg,
670
			COALESCE(mem.real_name, mf.poster_name) AS poster_name, ' . ($user_info['is_guest'] ? '1 AS is_read, 0 AS new_from' : '
671
			COALESCE(lt.id_msg, lmr.id_msg, 0) >= ml.id_msg_modified AS is_read,
672
			COALESCE(lt.id_msg, lmr.id_msg, -1) + 1 AS new_from') . ', SUBSTRING(mf.body, 1, 384) AS body, mf.smileys_enabled, mf.icon
673
		FROM {db_prefix}topics AS t
674
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
675
			INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_last_msg)
676
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mf.id_member)' . (!$user_info['is_guest'] ? '
677
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
678
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})' : '') . '
679
			LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)
680
		WHERE t.id_topic IN ({array_int:topic_list})
681
		ORDER BY t.id_last_msg DESC',
682
		array(
683
			'current_member' => $user_info['id'],
684
			'topic_list' => array_keys($topics),
685
		)
686
	);
687
	$posts = array();
688
	while ($row = $smcFunc['db_fetch_assoc']($request))
689
	{
690
		$row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']), array('<br>' => '&#10;')));
691
		if ($smcFunc['strlen']($row['body']) > 128)
692
			$row['body'] = $smcFunc['substr']($row['body'], 0, 128) . '...';
693
694
		// Censor the subject.
695
		censorText($row['subject']);
696
		censorText($row['body']);
697
698
		// Recycled icon
699
		if (!empty($recycle_board) && $topics[$row['id_topic']]['id_board'] == $recycle_board)
700
			$row['icon'] = 'recycled';
701
702
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
703
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
704
		elseif (!isset($icon_sources[$row['icon']]))
705
			$icon_sources[$row['icon']] = 'images_url';
706
707
		// Build the array.
708
		$posts[] = array(
709
			'board' => array(
710
				'id' => $topics[$row['id_topic']]['id_board'],
711
				'name' => $topics[$row['id_topic']]['board_name'],
712
				'href' => $scripturl . '?board=' . $topics[$row['id_topic']]['id_board'] . '.0',
713
				'link' => '<a href="' . $scripturl . '?board=' . $topics[$row['id_topic']]['id_board'] . '.0">' . $topics[$row['id_topic']]['board_name'] . '</a>',
714
			),
715
			'topic' => $row['id_topic'],
716
			'poster' => array(
717
				'id' => $row['id_member'],
718
				'name' => $row['poster_name'],
719
				'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
720
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
721
			),
722
			'subject' => $row['subject'],
723
			'replies' => $row['num_replies'],
724
			'views' => $row['num_views'],
725
			'short_subject' => shorten_subject($row['subject'], 25),
726
			'preview' => $row['body'],
727
			'time' => timeformat($row['poster_time']),
728
			'timestamp' => $row['poster_time'],
729
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
730
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#new" rel="nofollow">' . $row['subject'] . '</a>',
731
			// Retained for compatibility - is technically incorrect!
732
			'new' => !empty($row['is_read']),
733
			'is_new' => empty($row['is_read']),
734
			'new_from' => $row['new_from'],
735
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" style="vertical-align:middle;" alt="' . $row['icon'] . '">',
736
		);
737
	}
738
	$smcFunc['db_free_result']($request);
739
740
	// If mods want to do somthing with this list of topics, let them do that now.
741
	call_integration_hook('integrate_ssi_recentTopics', array(&$posts));
742
743
	// Just return it.
744
	if ($output_method != 'echo' || empty($posts))
745
		return $posts;
746
747
	echo '
748
		<table style="border: none" class="ssi_table">';
749
	foreach ($posts as $post)
750
		echo '
751
			<tr>
752
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
753
					[', $post['board']['link'], ']
754
				</td>
755
				<td style="vertical-align: top">
756
					<a href="', $post['href'], '">', $post['subject'], '</a>
757
					', $txt['by'], ' ', $post['poster']['link'], '
758
					', !$post['is_new'] ? '' : '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow" class="new_posts">' . $txt['new'] . '</a>', '
759
				</td>
760
				<td style="text-align: right; white-space: nowrap">
761
					', $post['time'], '
762
				</td>
763
			</tr>';
764
	echo '
765
		</table>';
766
}
767
768
/**
769
 * Shows a list of top posters
770
 *
771
 * @param int $topNumber How many top posters to list
772
 * @param string $output_method The output method. If 'echo', will display a list of users, otherwise returns an array of info about them.
773
 * @return void|array Either displays a list of users or returns an array of info about them, depending on output_method.
774
 */
775
function ssi_topPoster($topNumber = 1, $output_method = 'echo')
776
{
777
	global $scripturl, $smcFunc;
778
779
	// Find the latest poster.
780
	$request = $smcFunc['db_query']('', '
781
		SELECT id_member, real_name, posts
782
		FROM {db_prefix}members
783
		ORDER BY posts DESC
784
		LIMIT ' . $topNumber,
785
		array(
786
		)
787
	);
788
	$return = array();
789
	while ($row = $smcFunc['db_fetch_assoc']($request))
790
		$return[] = array(
791
			'id' => $row['id_member'],
792
			'name' => $row['real_name'],
793
			'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
794
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>',
795
			'posts' => $row['posts']
796
		);
797
	$smcFunc['db_free_result']($request);
798
799
	// If mods want to do somthing with this list of members, let them do that now.
800
	call_integration_hook('integrate_ssi_topPoster', array(&$return));
801
802
	// Just return all the top posters.
803
	if ($output_method != 'echo')
804
		return $return;
805
806
	// Make a quick array to list the links in.
807
	$temp_array = array();
808
	foreach ($return as $member)
809
		$temp_array[] = $member['link'];
810
811
	echo implode(', ', $temp_array);
812
}
813
814
/**
815
 * Shows a list of top boards based on activity
816
 *
817
 * @param int $num_top How many boards to display
818
 * @param string $output_method The output method. If 'echo', displays a list of boards, otherwise returns an array of info about them.
819
 * @return void|array Displays a list of the top boards or returns an array of info about them, depending on output_method.
820
 */
821
function ssi_topBoards($num_top = 10, $output_method = 'echo')
822
{
823
	global $txt, $scripturl, $user_info, $modSettings, $smcFunc;
824
825
	// Find boards with lots of posts.
826
	$request = $smcFunc['db_query']('', '
827
		SELECT
828
			b.name, b.num_topics, b.num_posts, b.id_board,' . (!$user_info['is_guest'] ? ' 1 AS is_read' : '
829
			(COALESCE(lb.id_msg, 0) >= b.id_last_msg) AS is_read') . '
830
		FROM {db_prefix}boards AS b
831
			LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
832
		WHERE {query_wanna_see_board}' . (!empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? '
833
			AND b.id_board != {int:recycle_board}' : '') . '
834
		ORDER BY b.num_posts DESC
835
		LIMIT ' . $num_top,
836
		array(
837
			'current_member' => $user_info['id'],
838
			'recycle_board' => !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : null,
839
		)
840
	);
841
	$boards = array();
842
	while ($row = $smcFunc['db_fetch_assoc']($request))
843
		$boards[] = array(
844
			'id' => $row['id_board'],
845
			'num_posts' => $row['num_posts'],
846
			'num_topics' => $row['num_topics'],
847
			'name' => $row['name'],
848
			'new' => empty($row['is_read']),
849
			'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
850
			'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>'
851
		);
852
	$smcFunc['db_free_result']($request);
853
854
	// If mods want to do somthing with this list of boards, let them do that now.
855
	call_integration_hook('integrate_ssi_topBoards', array(&$boards));
856
857
	// If we shouldn't output or have nothing to output, just jump out.
858
	if ($output_method != 'echo' || empty($boards))
859
		return $boards;
860
861
	echo '
862
		<table class="ssi_table">
863
			<tr>
864
				<th style="text-align: left">', $txt['board'], '</th>
865
				<th style="text-align: left">', $txt['board_topics'], '</th>
866
				<th style="text-align: left">', $txt['posts'], '</th>
867
			</tr>';
868
	foreach ($boards as $sBoard)
869
		echo '
870
			<tr>
871
				<td>', $sBoard['link'], $sBoard['new'] ? ' <a href="' . $sBoard['href'] . '" class="new_posts">' . $txt['new'] . '</a>' : '', '</td>
872
				<td style="text-align: right">', comma_format($sBoard['num_topics']), '</td>
873
				<td style="text-align: right">', comma_format($sBoard['num_posts']), '</td>
874
			</tr>';
875
	echo '
876
		</table>';
877
}
878
879
// Shows the top topics.
880
/**
881
 * Shows a list of top topics based on views or replies
882
 *
883
 * @param string $type Can be either replies or views
884
 * @param int $num_topics How many topics to display
885
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them.
886
 * @return void|array Either displays a list of topics or returns an array of info about them, depending on output_method.
887
 */
888
function ssi_topTopics($type = 'replies', $num_topics = 10, $output_method = 'echo')
889
{
890
	global $txt, $scripturl, $modSettings, $smcFunc;
891
892
	if ($modSettings['totalMessages'] > 100000)
893
	{
894
		// @todo Why don't we use {query(_wanna)_see_board}?
895
		$request = $smcFunc['db_query']('', '
896
			SELECT id_topic
897
			FROM {db_prefix}topics
898
			WHERE num_' . ($type != 'replies' ? 'views' : 'replies') . ' != 0' . ($modSettings['postmod_active'] ? '
899
				AND approved = {int:is_approved}' : '') . '
900
			ORDER BY num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
901
			LIMIT {int:limit}',
902
			array(
903
				'is_approved' => 1,
904
				'limit' => $num_topics > 100 ? ($num_topics + ($num_topics / 2)) : 100,
905
			)
906
		);
907
		$topic_ids = array();
908
		while ($row = $smcFunc['db_fetch_assoc']($request))
909
			$topic_ids[] = $row['id_topic'];
910
		$smcFunc['db_free_result']($request);
911
	}
912
	else
913
		$topic_ids = array();
914
915
	$request = $smcFunc['db_query']('', '
916
		SELECT m.subject, m.id_topic, t.num_views, t.num_replies
917
		FROM {db_prefix}topics AS t
918
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
919
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
920
		WHERE {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
921
			AND t.approved = {int:is_approved}' : '') . (!empty($topic_ids) ? '
922
			AND t.id_topic IN ({array_int:topic_list})' : '') . (!empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? '
923
			AND b.id_board != {int:recycle_board}' : '') . '
924
		ORDER BY t.num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
925
		LIMIT {int:limit}',
926
		array(
927
			'topic_list' => $topic_ids,
928
			'is_approved' => 1,
929
			'recycle_board' => !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : null,
930
			'limit' => $num_topics,
931
		)
932
	);
933
	$topics = array();
934
	while ($row = $smcFunc['db_fetch_assoc']($request))
935
	{
936
		censorText($row['subject']);
937
938
		$topics[] = array(
939
			'id' => $row['id_topic'],
940
			'subject' => $row['subject'],
941
			'num_replies' => $row['num_replies'],
942
			'num_views' => $row['num_views'],
943
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
944
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
945
		);
946
	}
947
	$smcFunc['db_free_result']($request);
948
949
	// If mods want to do somthing with this list of topics, let them do that now.
950
	call_integration_hook('integrate_ssi_topTopics', array(&$topics, $type));
951
952
	if ($output_method != 'echo' || empty($topics))
953
		return $topics;
954
955
	echo '
956
		<table class="ssi_table">
957
			<tr>
958
				<th style="text-align: left"></th>
959
				<th style="text-align: left">', $txt['views'], '</th>
960
				<th style="text-align: left">', $txt['replies'], '</th>
961
			</tr>';
962
	foreach ($topics as $sTopic)
963
		echo '
964
			<tr>
965
				<td style="text-align: left">
966
					', $sTopic['link'], '
967
				</td>
968
				<td style="text-align: right">', comma_format($sTopic['num_views']), '</td>
969
				<td style="text-align: right">', comma_format($sTopic['num_replies']), '</td>
970
			</tr>';
971
	echo '
972
		</table>';
973
}
974
975
/**
976
 * Top topics based on replies
977
 *
978
 * @param int $num_topics How many topics to show
979
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
980
 * @return void|array Either displays a list of top topics or returns an array of info about them, depending on output_method.
981
 */
982
function ssi_topTopicsReplies($num_topics = 10, $output_method = 'echo')
983
{
984
	return ssi_topTopics('replies', $num_topics, $output_method);
985
}
986
987
/**
988
 * Top topics based on views
989
 *
990
 * @param int $num_topics How many topics to show
991
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
992
 * @return void|array Either displays a list of top topics or returns an array of info about them, depending on output_method.
993
 */
994
function ssi_topTopicsViews($num_topics = 10, $output_method = 'echo')
995
{
996
	return ssi_topTopics('views', $num_topics, $output_method);
997
}
998
999
/**
1000
 * Show a link to the latest member: Please welcome, Someone, our latest member.
1001
 *
1002
 * @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.
1003
 * @return void|array Displays a "welcome" message for the latest member or returns an array of info about them, depending on output_method.
1004
 */
1005
function ssi_latestMember($output_method = 'echo')
1006
{
1007
	global $txt, $context;
1008
1009
	if ($output_method == 'echo')
1010
		echo '
1011
	', sprintf($txt['welcome_newest_member'], $context['common_stats']['latest_member']['link']), '<br>';
1012
	else
1013
		return $context['common_stats']['latest_member'];
1014
}
1015
1016
/**
1017
 * Fetches a random member.
1018
 *
1019
 * @param string $random_type If 'day', only fetches a new random member once a day.
1020
 * @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.
1021
 * @return void|array Displays a link to a random member's profile or returns an array of info about them depending on output_method.
1022
 */
1023
function ssi_randomMember($random_type = '', $output_method = 'echo')
1024
{
1025
	global $modSettings;
1026
1027
	// If we're looking for something to stay the same each day then seed the generator.
1028
	if ($random_type == 'day')
1029
	{
1030
		// Set the seed to change only once per day.
1031
		mt_srand(floor(time() / 86400));
0 ignored issues
show
floor(time() / 86400) of type double is incompatible with the type integer expected by parameter $seed of mt_srand(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1031
		mt_srand(/** @scrutinizer ignore-type */ floor(time() / 86400));
Loading history...
1032
	}
1033
1034
	// Get the lowest ID we're interested in.
1035
	$member_id = mt_rand(1, $modSettings['latestMember']);
1036
1037
	$where_query = '
1038
		id_member >= {int:selected_member}
1039
		AND is_activated = {int:is_activated}';
1040
1041
	$query_where_params = array(
1042
		'selected_member' => $member_id,
1043
		'is_activated' => 1,
1044
	);
1045
1046
	$result = ssi_queryMembers($where_query, $query_where_params, 1, 'id_member ASC', $output_method);
1047
1048
	// If we got nothing do the reverse - in case of unactivated members.
1049
	if (empty($result))
1050
	{
1051
		$where_query = '
1052
			id_member <= {int:selected_member}
1053
			AND is_activated = {int:is_activated}';
1054
1055
		$query_where_params = array(
1056
			'selected_member' => $member_id,
1057
			'is_activated' => 1,
1058
		);
1059
1060
		$result = ssi_queryMembers($where_query, $query_where_params, 1, 'id_member DESC', $output_method);
1061
	}
1062
1063
	// Just to be sure put the random generator back to something... random.
1064
	if ($random_type != '')
1065
		mt_srand(time());
1066
1067
	return $result;
1068
}
1069
1070
/**
1071
 * Fetch specific members
1072
 *
1073
 * @param array $member_ids The IDs of the members to fetch
1074
 * @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.
1075
 * @return void|array Displays links to the specified members' profiles or returns an array of info about them, depending on output_method.
1076
 */
1077
function ssi_fetchMember($member_ids = array(), $output_method = 'echo')
1078
{
1079
	if (empty($member_ids))
1080
		return;
1081
1082
	// Can have more than one member if you really want...
1083
	$member_ids = is_array($member_ids) ? $member_ids : array($member_ids);
0 ignored issues
show
The condition is_array($member_ids) is always true.
Loading history...
1084
1085
	// Restrict it right!
1086
	$query_where = '
1087
		id_member IN ({array_int:member_list})';
1088
1089
	$query_where_params = array(
1090
		'member_list' => $member_ids,
1091
	);
1092
1093
	// Then make the query and dump the data.
1094
	return ssi_queryMembers($query_where, $query_where_params, '', 'id_member', $output_method);
1095
}
1096
1097
/**
1098
 * Get al members in the specified group
1099
 *
1100
 * @param int $group_id The ID of the group to get members from
1101
 * @param string $output_method The output method. If 'echo', returns a list of group members, otherwise returns an array of info about them.
1102
 * @return void|array Displays a list of group members or returns an array of info about them, depending on output_method.
1103
 */
1104
function ssi_fetchGroupMembers($group_id = null, $output_method = 'echo')
1105
{
1106
	if ($group_id === null)
1107
		return;
1108
1109
	$query_where = '
1110
		id_group = {int:id_group}
1111
		OR id_post_group = {int:id_group}
1112
		OR FIND_IN_SET({int:id_group}, additional_groups) != 0';
1113
1114
	$query_where_params = array(
1115
		'id_group' => $group_id,
1116
	);
1117
1118
	return ssi_queryMembers($query_where, $query_where_params, '', 'real_name', $output_method);
1119
}
1120
1121
/**
1122
 * Pulls info about members based on the specified parameters. Used by other functions to eliminate duplication.
1123
 *
1124
 * @param string $query_where The info for the WHERE clause of the query
1125
 * @param array $query_where_params The parameters for the WHERE clause
1126
 * @param string|int $query_limit The number of rows to return or an empty string to return all
1127
 * @param string $query_order The info for the ORDER BY clause of the query
1128
 * @param string $output_method The output method. If 'echo', displays a list of members, otherwise returns an array of info about them
1129
 * @return void|array Displays a list of members or returns an array of info about them, depending on output_method.
1130
 */
1131
function ssi_queryMembers($query_where = null, $query_where_params = array(), $query_limit = '', $query_order = 'id_member DESC', $output_method = 'echo')
1132
{
1133
	global $smcFunc, $memberContext;
1134
1135
	if ($query_where === null)
1136
		return;
1137
1138
	// Fetch the members in question.
1139
	$request = $smcFunc['db_query']('', '
1140
		SELECT id_member
1141
		FROM {db_prefix}members
1142
		WHERE ' . $query_where . '
1143
		ORDER BY ' . $query_order . '
1144
		' . ($query_limit == '' ? '' : 'LIMIT ' . $query_limit),
1145
		array_merge($query_where_params, array(
1146
		))
1147
	);
1148
	$members = array();
1149
	while ($row = $smcFunc['db_fetch_assoc']($request))
1150
		$members[] = $row['id_member'];
1151
	$smcFunc['db_free_result']($request);
1152
1153
	if (empty($members))
1154
		return array();
1155
1156
	// If mods want to do somthing with this list of members, let them do that now.
1157
	call_integration_hook('integrate_ssi_queryMembers', array(&$members));
1158
1159
	// Load the members.
1160
	loadMemberData($members);
1161
1162
	// Draw the table!
1163
	if ($output_method == 'echo')
1164
		echo '
1165
		<table style="border: none" class="ssi_table">';
1166
1167
	$query_members = array();
1168
	foreach ($members as $member)
1169
	{
1170
		// Load their context data.
1171
		if (!loadMemberContext($member))
1172
			continue;
1173
1174
		// Store this member's information.
1175
		$query_members[$member] = $memberContext[$member];
1176
1177
		// Only do something if we're echo'ing.
1178
		if ($output_method == 'echo')
1179
			echo '
1180
			<tr>
1181
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
1182
					', $query_members[$member]['link'], '
1183
					<br>', $query_members[$member]['blurb'], '
1184
					<br>', $query_members[$member]['avatar']['image'], '
1185
				</td>
1186
			</tr>';
1187
	}
1188
1189
	// End the table if appropriate.
1190
	if ($output_method == 'echo')
1191
		echo '
1192
		</table>';
1193
1194
	// Send back the data.
1195
	return $query_members;
1196
}
1197
1198
/**
1199
 * Show some basic stats:   Total This: XXXX, etc.
1200
 *
1201
 * @param string $output_method The output method. If 'echo', displays the stats, otherwise returns an array of info about them
1202
 * @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.
1203
 */
1204
function ssi_boardStats($output_method = 'echo')
1205
{
1206
	global $txt, $scripturl, $modSettings, $smcFunc;
1207
1208
	if (!allowedTo('view_stats'))
1209
		return;
1210
1211
	$totals = array(
1212
		'members' => $modSettings['totalMembers'],
1213
		'posts' => $modSettings['totalMessages'],
1214
		'topics' => $modSettings['totalTopics']
1215
	);
1216
1217
	$result = $smcFunc['db_query']('', '
1218
		SELECT COUNT(*)
1219
		FROM {db_prefix}boards',
1220
		array(
1221
		)
1222
	);
1223
	list ($totals['boards']) = $smcFunc['db_fetch_row']($result);
1224
	$smcFunc['db_free_result']($result);
1225
1226
	$result = $smcFunc['db_query']('', '
1227
		SELECT COUNT(*)
1228
		FROM {db_prefix}categories',
1229
		array(
1230
		)
1231
	);
1232
	list ($totals['categories']) = $smcFunc['db_fetch_row']($result);
1233
	$smcFunc['db_free_result']($result);
1234
1235
	// If mods want to do somthing with the board stats, let them do that now.
1236
	call_integration_hook('integrate_ssi_boardStats', array(&$totals));
1237
1238
	if ($output_method != 'echo')
1239
		return $totals;
1240
1241
	echo '
1242
		', $txt['total_members'], ': <a href="', $scripturl . '?action=mlist">', comma_format($totals['members']), '</a><br>
1243
		', $txt['total_posts'], ': ', comma_format($totals['posts']), '<br>
1244
		', $txt['total_topics'], ': ', comma_format($totals['topics']), ' <br>
1245
		', $txt['total_cats'], ': ', comma_format($totals['categories']), '<br>
1246
		', $txt['total_boards'], ': ', comma_format($totals['boards']);
1247
}
1248
1249
/**
1250
 * Shows a list of online users:  YY Guests, ZZ Users and then a list...
1251
 *
1252
 * @param string $output_method The output method. If 'echo', displays a list, otherwise returns an array of info about the online users.
1253
 * @return void|array Either displays a list of online users or returns an array of info about them, depending on output_method.
1254
 */
1255
function ssi_whosOnline($output_method = 'echo')
1256
{
1257
	global $user_info, $txt, $sourcedir, $settings;
1258
1259
	require_once($sourcedir . '/Subs-MembersOnline.php');
1260
	$membersOnlineOptions = array(
1261
		'show_hidden' => allowedTo('moderate_forum'),
1262
	);
1263
	$return = getMembersOnlineStats($membersOnlineOptions);
1264
1265
	// If mods want to do somthing with the list of who is online, let them do that now.
1266
	call_integration_hook('integrate_ssi_whosOnline', array(&$return));
1267
1268
	// Add some redundancy for backwards compatibility reasons.
1269
	if ($output_method != 'echo')
1270
		return $return + array(
1271
			'users' => $return['users_online'],
1272
			'guests' => $return['num_guests'],
1273
			'hidden' => $return['num_users_hidden'],
1274
			'buddies' => $return['num_buddies'],
1275
			'num_users' => $return['num_users_online'],
1276
			'total_users' => $return['num_users_online'] + $return['num_guests'],
1277
		);
1278
1279
	echo '
1280
		', 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'];
1281
1282
	$bracketList = array();
1283
	if (!empty($user_info['buddies']))
1284
		$bracketList[] = comma_format($return['num_buddies']) . ' ' . ($return['num_buddies'] == 1 ? $txt['buddy'] : $txt['buddies']);
1285
	if (!empty($return['num_spiders']))
1286
		$bracketList[] = comma_format($return['num_spiders']) . ' ' . ($return['num_spiders'] == 1 ? $txt['spider'] : $txt['spiders']);
1287
	if (!empty($return['num_users_hidden']))
1288
		$bracketList[] = comma_format($return['num_users_hidden']) . ' ' . $txt['hidden'];
1289
1290
	if (!empty($bracketList))
1291
		echo ' (' . implode(', ', $bracketList) . ')';
1292
1293
	echo '<br>
1294
			', implode(', ', $return['list_users_online']);
1295
1296
	// Showing membergroups?
1297
	if (!empty($settings['show_group_key']) && !empty($return['online_groups']))
1298
	{
1299
		$membergroups = cache_quick_get('membergroup_list', 'Subs-Membergroups.php', 'cache_getMembergroupList', array());
1300
1301
		$groups = array();
1302
		foreach ($return['online_groups'] as $group)
1303
		{
1304
			if (isset($membergroups[$group['id']]))
1305
				$groups[] = $membergroups[$group['id']];
1306
		}
1307
1308
		echo '<br>
1309
			[' . implode(']&nbsp;&nbsp;[', $groups) . ']';
1310
	}
1311
}
1312
1313
/**
1314
 * Just like whosOnline except it also logs the online presence.
1315
 *
1316
 * @param string $output_method The output method. If 'echo', displays a list, otherwise returns an array of info about the online users.
1317
 * @return void|array Either displays a list of online users or returns an aray of info about them, depending on output_method.
1318
 */
1319
function ssi_logOnline($output_method = 'echo')
1320
{
1321
	writeLog();
1322
1323
	if ($output_method != 'echo')
1324
		return ssi_whosOnline($output_method);
1325
	else
1326
		ssi_whosOnline($output_method);
1327
}
1328
1329
// Shows a login box.
1330
/**
1331
 * Shows a login box
1332
 *
1333
 * @param string $redirect_to The URL to redirect the user to after they login
1334
 * @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
1335
 * @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.
1336
 */
1337
function ssi_login($redirect_to = '', $output_method = 'echo')
1338
{
1339
	global $scripturl, $txt, $user_info, $context;
1340
1341
	if ($redirect_to != '')
1342
		$_SESSION['login_url'] = $redirect_to;
1343
1344
	if ($output_method != 'echo' || !$user_info['is_guest'])
1345
		return $user_info['is_guest'];
1346
1347
	// Create a login token
1348
	createToken('login');
1349
1350
	echo '
1351
		<form action="', $scripturl, '?action=login2" method="post" accept-charset="', $context['character_set'], '">
1352
			<table style="border: none" class="ssi_table">
1353
				<tr>
1354
					<td style="text-align: right; border-spacing: 1"><label for="user">', $txt['username'], ':</label>&nbsp;</td>
1355
					<td><input type="text" id="user" name="user" size="9" value="', $user_info['username'], '"></td>
1356
				</tr><tr>
1357
					<td style="text-align: right; border-spacing: 1"><label for="passwrd">', $txt['password'], ':</label>&nbsp;</td>
1358
					<td><input type="password" name="passwrd" id="passwrd" size="9"></td>
1359
				</tr>
1360
				<tr>
1361
					<td>
1362
						<input type="hidden" name="cookielength" value="-1">
1363
						<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
1364
						<input type="hidden" name="', $context['login_token_var'], '" value="', $context['login_token'], '">
1365
					</td>
1366
					<td><input type="submit" value="', $txt['login'], '" class="button"></td>
1367
				</tr>
1368
			</table>
1369
		</form>';
1370
1371
}
1372
1373
/**
1374
 * Show the top poll based on votes
1375
 *
1376
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it
1377
 * @return void|array Either shows the top poll or returns an array of info about it, depending on output_method.
1378
 */
1379
function ssi_topPoll($output_method = 'echo')
1380
{
1381
	// Just use recentPoll, no need to duplicate code...
1382
	return ssi_recentPoll(true, $output_method);
1383
}
1384
1385
// Show the most recently posted poll.
1386
/**
1387
 * Shows the most recent poll
1388
 *
1389
 * @param bool $topPollInstead Whether to show the top poll (based on votes) instead of the most recent one
1390
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it.
1391
 * @return void|array Either shows the poll or returns an array of info about it, depending on output_method.
1392
 */
1393
function ssi_recentPoll($topPollInstead = false, $output_method = 'echo')
1394
{
1395
	global $txt, $boardurl, $user_info, $context, $smcFunc, $modSettings;
1396
1397
	$boardsAllowed = array_intersect(boardsAllowedTo('poll_view'), boardsAllowedTo('poll_vote'));
1398
1399
	if (empty($boardsAllowed))
1400
		return array();
1401
1402
	$request = $smcFunc['db_query']('', '
1403
		SELECT p.id_poll, p.question, t.id_topic, p.max_votes, p.guest_vote, p.hide_results, p.expire_time
1404
		FROM {db_prefix}polls AS p
1405
			INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
1406
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)' . ($topPollInstead ? '
1407
			INNER JOIN {db_prefix}poll_choices AS pc ON (pc.id_poll = p.id_poll)' : '') . '
1408
			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})
1409
		WHERE p.voting_locked = {int:voting_opened}
1410
			AND (p.expire_time = {int:no_expiration} OR {int:current_time} < p.expire_time)
1411
			AND ' . ($user_info['is_guest'] ? 'p.guest_vote = {int:guest_vote_allowed}' : 'lp.id_choice IS NULL') . '
1412
			AND {query_wanna_see_board}' . (!in_array(0, $boardsAllowed) ? '
1413
			AND b.id_board IN ({array_int:boards_allowed_list})' : '') . (!empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? '
1414
			AND b.id_board != {int:recycle_board}' : '') . '
1415
		ORDER BY ' . ($topPollInstead ? 'pc.votes' : 'p.id_poll') . ' DESC
1416
		LIMIT 1',
1417
		array(
1418
			'current_member' => $user_info['id'],
1419
			'boards_allowed_list' => $boardsAllowed,
1420
			'is_approved' => 1,
1421
			'guest_vote_allowed' => 1,
1422
			'no_member' => 0,
1423
			'voting_opened' => 0,
1424
			'no_expiration' => 0,
1425
			'current_time' => time(),
1426
			'recycle_board' => !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : null,
1427
		)
1428
	);
1429
	$row = $smcFunc['db_fetch_assoc']($request);
1430
	$smcFunc['db_free_result']($request);
1431
1432
	// This user has voted on all the polls.
1433
	if (empty($row) || !is_array($row))
1434
		return array();
1435
1436
	// If this is a guest who's voted we'll through ourselves to show poll to show the results.
1437
	if ($user_info['is_guest'] && (!$row['guest_vote'] || (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))))
1438
		return ssi_showPoll($row['id_topic'], $output_method);
1439
1440
	$request = $smcFunc['db_query']('', '
1441
		SELECT COUNT(DISTINCT id_member)
1442
		FROM {db_prefix}log_polls
1443
		WHERE id_poll = {int:current_poll}',
1444
		array(
1445
			'current_poll' => $row['id_poll'],
1446
		)
1447
	);
1448
	list ($total) = $smcFunc['db_fetch_row']($request);
1449
	$smcFunc['db_free_result']($request);
1450
1451
	$request = $smcFunc['db_query']('', '
1452
		SELECT id_choice, label, votes
1453
		FROM {db_prefix}poll_choices
1454
		WHERE id_poll = {int:current_poll}',
1455
		array(
1456
			'current_poll' => $row['id_poll'],
1457
		)
1458
	);
1459
	$sOptions = array();
1460
	while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
1461
	{
1462
		censorText($rowChoice['label']);
1463
1464
		$sOptions[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
1465
	}
1466
	$smcFunc['db_free_result']($request);
1467
1468
	// Can they view it?
1469
	$is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
1470
	$allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || $is_expired;
1471
1472
	$return = array(
1473
		'id' => $row['id_poll'],
1474
		'image' => 'poll',
1475
		'question' => $row['question'],
1476
		'total_votes' => $total,
1477
		'is_locked' => false,
1478
		'topic' => $row['id_topic'],
1479
		'allow_view_results' => $allow_view_results,
1480
		'options' => array()
1481
	);
1482
1483
	// Calculate the percentages and bar lengths...
1484
	$divisor = $return['total_votes'] == 0 ? 1 : $return['total_votes'];
1485
	foreach ($sOptions as $i => $option)
1486
	{
1487
		$bar = floor(($option[1] * 100) / $divisor);
1488
		$return['options'][$i] = array(
1489
			'id' => 'options-' . ($topPollInstead ? 'top-' : 'recent-') . $i,
1490
			'percent' => $bar,
1491
			'votes' => $option[1],
1492
			'option' => parse_bbc($option[0]),
1493
			'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . ($topPollInstead ? 'top-' : 'recent-') . $i . '" value="' . $i . '">'
1494
		);
1495
	}
1496
1497
	$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options_limit'], min(count($sOptions), $row['max_votes'])) : '';
1498
1499
	// If mods want to do somthing with this list of polls, let them do that now.
1500
	call_integration_hook('integrate_ssi_recentPoll', array(&$return, $topPollInstead));
1501
1502
	if ($output_method != 'echo')
1503
		return $return;
1504
1505
	if ($allow_view_results)
1506
	{
1507
		echo '
1508
		<form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
1509
			<strong>', $return['question'], '</strong><br>
1510
			', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br>' : '';
1511
1512
		foreach ($return['options'] as $option)
1513
			echo '
1514
			<label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br>';
1515
1516
		echo '
1517
			<input type="submit" value="', $txt['poll_vote'], '" class="button">
1518
			<input type="hidden" name="poll" value="', $return['id'], '">
1519
			<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
1520
		</form>';
1521
	}
1522
	else
1523
		echo $txt['poll_cannot_see'];
1524
}
1525
1526
/**
1527
 * Shows the poll from the specified topic
1528
 *
1529
 * @param null|int $topic The topic to show the poll from. If null, $_REQUEST['ssi_topic'] will be used instead.
1530
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it.
1531
 * @return void|array Either displays the poll or returns an array of info about it, depending on output_method.
1532
 */
1533
function ssi_showPoll($topic = null, $output_method = 'echo')
1534
{
1535
	global $txt, $boardurl, $user_info, $context, $smcFunc, $modSettings;
1536
1537
	$boardsAllowed = boardsAllowedTo('poll_view');
1538
1539
	if (empty($boardsAllowed))
1540
		return array();
1541
1542
	if ($topic === null && isset($_REQUEST['ssi_topic']))
1543
		$topic = (int) $_REQUEST['ssi_topic'];
1544
	else
1545
		$topic = (int) $topic;
1546
1547
	$request = $smcFunc['db_query']('', '
1548
		SELECT
1549
			p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.guest_vote, b.id_board
1550
		FROM {db_prefix}topics AS t
1551
			INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
1552
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1553
		WHERE t.id_topic = {int:current_topic}
1554
			AND {query_see_board}' . (!in_array(0, $boardsAllowed) ? '
1555
			AND b.id_board IN ({array_int:boards_allowed_see})' : '') . ($modSettings['postmod_active'] ? '
1556
			AND t.approved = {int:is_approved}' : '') . '
1557
		LIMIT 1',
1558
		array(
1559
			'current_topic' => $topic,
1560
			'boards_allowed_see' => $boardsAllowed,
1561
			'is_approved' => 1,
1562
		)
1563
	);
1564
1565
	// Either this topic has no poll, or the user cannot view it.
1566
	if ($smcFunc['db_num_rows']($request) == 0)
1567
		return array();
1568
1569
	$row = $smcFunc['db_fetch_assoc']($request);
1570
	$smcFunc['db_free_result']($request);
1571
1572
	// Check if they can vote.
1573
	$already_voted = false;
1574
	if (!empty($row['expire_time']) && $row['expire_time'] < time())
1575
		$allow_vote = false;
1576
	elseif ($user_info['is_guest'])
1577
	{
1578
		// There's a difference between "allowed to vote" and "already voted"...
1579
		$allow_vote = $row['guest_vote'];
1580
1581
		// Did you already vote?
1582
		if (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1583
		{
1584
			$already_voted = true;
1585
		}
1586
	}
1587
	elseif (!empty($row['voting_locked']) || !allowedTo('poll_vote', $row['id_board']))
1588
		$allow_vote = false;
1589
	else
1590
	{
1591
		$request = $smcFunc['db_query']('', '
1592
			SELECT id_member
1593
			FROM {db_prefix}log_polls
1594
			WHERE id_poll = {int:current_poll}
1595
				AND id_member = {int:current_member}
1596
			LIMIT 1',
1597
			array(
1598
				'current_member' => $user_info['id'],
1599
				'current_poll' => $row['id_poll'],
1600
			)
1601
		);
1602
		$allow_vote = $smcFunc['db_num_rows']($request) == 0;
1603
		$already_voted = $allow_vote;
1604
		$smcFunc['db_free_result']($request);
1605
	}
1606
1607
	// Can they view?
1608
	$is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
1609
	$allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || ($row['hide_results'] == 1 && $already_voted) || $is_expired;
1610
1611
	$request = $smcFunc['db_query']('', '
1612
		SELECT COUNT(DISTINCT id_member)
1613
		FROM {db_prefix}log_polls
1614
		WHERE id_poll = {int:current_poll}',
1615
		array(
1616
			'current_poll' => $row['id_poll'],
1617
		)
1618
	);
1619
	list ($total) = $smcFunc['db_fetch_row']($request);
1620
	$smcFunc['db_free_result']($request);
1621
1622
	$request = $smcFunc['db_query']('', '
1623
		SELECT id_choice, label, votes
1624
		FROM {db_prefix}poll_choices
1625
		WHERE id_poll = {int:current_poll}',
1626
		array(
1627
			'current_poll' => $row['id_poll'],
1628
		)
1629
	);
1630
	$sOptions = array();
1631
	$total_votes = 0;
1632
	while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
1633
	{
1634
		censorText($rowChoice['label']);
1635
1636
		$sOptions[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
1637
		$total_votes += $rowChoice['votes'];
1638
	}
1639
	$smcFunc['db_free_result']($request);
1640
1641
	$return = array(
1642
		'id' => $row['id_poll'],
1643
		'image' => empty($row['voting_locked']) ? 'poll' : 'locked_poll',
1644
		'question' => $row['question'],
1645
		'total_votes' => $total,
1646
		'is_locked' => !empty($row['voting_locked']),
1647
		'allow_vote' => $allow_vote,
1648
		'allow_view_results' => $allow_view_results,
1649
		'topic' => $topic
1650
	);
1651
1652
	// Calculate the percentages and bar lengths...
1653
	$divisor = $total_votes == 0 ? 1 : $total_votes;
0 ignored issues
show
The condition $total_votes == 0 is always true.
Loading history...
1654
	foreach ($sOptions as $i => $option)
1655
	{
1656
		$bar = floor(($option[1] * 100) / $divisor);
1657
		$return['options'][$i] = array(
1658
			'id' => 'options-' . $i,
1659
			'percent' => $bar,
1660
			'votes' => $option[1],
1661
			'option' => parse_bbc($option[0]),
1662
			'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '">'
1663
		);
1664
	}
1665
1666
	$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options_limit'], min(count($sOptions), $row['max_votes'])) : '';
1667
1668
	// If mods want to do somthing with this poll, let them do that now.
1669
	call_integration_hook('integrate_ssi_showPoll', array(&$return));
1670
1671
	if ($output_method != 'echo')
1672
		return $return;
1673
1674
	if ($return['allow_vote'])
1675
	{
1676
		echo '
1677
			<form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
1678
				<strong>', $return['question'], '</strong><br>
1679
				', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br>' : '';
1680
1681
		foreach ($return['options'] as $option)
1682
			echo '
1683
				<label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br>';
1684
1685
		echo '
1686
				<input type="submit" value="', $txt['poll_vote'], '" class="button">
1687
				<input type="hidden" name="poll" value="', $return['id'], '">
1688
				<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
1689
			</form>';
1690
	}
1691
	else
1692
	{
1693
		echo '
1694
			<div class="ssi_poll">
1695
				<strong>', $return['question'], '</strong>
1696
				<dl>';
1697
1698
		foreach ($return['options'] as $option)
1699
		{
1700
			echo '
1701
					<dt>', $option['option'], '</dt>
1702
					<dd>';
1703
1704
			if ($return['allow_view_results'])
1705
			{
1706
				echo '
1707
						<div class="ssi_poll_bar" style="border: 1px solid #666; height: 1em">
1708
							<div class="ssi_poll_bar_fill" style="background: #ccf; height: 1em; width: ', $option['percent'], '%;">
1709
							</div>
1710
						</div>
1711
						', $option['votes'], ' (', $option['percent'], '%)';
1712
			}
1713
1714
			echo '
1715
					</dd>';
1716
		}
1717
1718
		echo '
1719
				</dl>', ($return['allow_view_results'] ? '
1720
				<strong>' . $txt['poll_total_voters'] . ': ' . $return['total_votes'] . '</strong>' : ''), '
1721
			</div>';
1722
	}
1723
}
1724
1725
/**
1726
 * Handles voting in a poll (done automatically)
1727
 */
1728
function ssi_pollVote()
1729
{
1730
	global $context, $db_prefix, $user_info, $sc, $smcFunc, $sourcedir, $modSettings;
1731
1732
	if (!isset($_POST[$context['session_var']]) || $_POST[$context['session_var']] != $sc || empty($_POST['options']) || !isset($_POST['poll']))
1733
	{
1734
		echo '<!DOCTYPE html>
1735
<html>
1736
<head>
1737
	<script>
1738
		history.go(-1);
1739
	</script>
1740
</head>
1741
<body>&laquo;</body>
1742
</html>';
1743
		return;
1744
	}
1745
1746
	// This can cause weird errors! (ie. copyright missing.)
1747
	checkSession();
1748
1749
	$_POST['poll'] = (int) $_POST['poll'];
1750
1751
	// Check if they have already voted, or voting is locked.
1752
	$request = $smcFunc['db_query']('', '
1753
		SELECT
1754
			p.id_poll, p.voting_locked, p.expire_time, p.max_votes, p.guest_vote,
1755
			t.id_topic,
1756
			COALESCE(lp.id_choice, -1) AS selected
1757
		FROM {db_prefix}polls AS p
1758
			INNER JOIN {db_prefix}topics AS t ON (t.id_poll = {int:current_poll})
1759
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1760
			LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_poll = p.id_poll AND lp.id_member = {int:current_member})
1761
		WHERE p.id_poll = {int:current_poll}
1762
			AND {query_see_board}' . ($modSettings['postmod_active'] ? '
1763
			AND t.approved = {int:is_approved}' : '') . '
1764
		LIMIT 1',
1765
		array(
1766
			'current_member' => $user_info['id'],
1767
			'current_poll' => $_POST['poll'],
1768
			'is_approved' => 1,
1769
		)
1770
	);
1771
	if ($smcFunc['db_num_rows']($request) == 0)
1772
		die;
0 ignored issues
show
Using exit here is not recommended.

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

Loading history...
1773
	$row = $smcFunc['db_fetch_assoc']($request);
1774
	$smcFunc['db_free_result']($request);
1775
1776
	if (!empty($row['voting_locked']) || ($row['selected'] != -1 && !$user_info['is_guest']) || (!empty($row['expire_time']) && time() > $row['expire_time']))
1777
		redirectexit('topic=' . $row['id_topic'] . '.0');
1778
1779
	// Too many options checked?
1780
	if (count($_REQUEST['options']) > $row['max_votes'])
1781
		redirectexit('topic=' . $row['id_topic'] . '.0');
1782
1783
	// It's a guest who has already voted?
1784
	if ($user_info['is_guest'])
1785
	{
1786
		// Guest voting disabled?
1787
		if (!$row['guest_vote'])
1788
			redirectexit('topic=' . $row['id_topic'] . '.0');
1789
		// Already voted?
1790
		elseif (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1791
			redirectexit('topic=' . $row['id_topic'] . '.0');
1792
	}
1793
1794
	$sOptions = array();
1795
	$inserts = array();
1796
	foreach ($_REQUEST['options'] as $id)
1797
	{
1798
		$id = (int) $id;
1799
1800
		$sOptions[] = $id;
1801
		$inserts[] = array($_POST['poll'], $user_info['id'], $id);
1802
	}
1803
1804
	// Add their vote in to the tally.
1805
	$smcFunc['db_insert']('insert',
1806
		$db_prefix . 'log_polls',
1807
		array('id_poll' => 'int', 'id_member' => 'int', 'id_choice' => 'int'),
1808
		$inserts,
1809
		array('id_poll', 'id_member', 'id_choice')
1810
	);
1811
	$smcFunc['db_query']('', '
1812
		UPDATE {db_prefix}poll_choices
1813
		SET votes = votes + 1
1814
		WHERE id_poll = {int:current_poll}
1815
			AND id_choice IN ({array_int:option_list})',
1816
		array(
1817
			'option_list' => $sOptions,
1818
			'current_poll' => $_POST['poll'],
1819
		)
1820
	);
1821
1822
	// Track the vote if a guest.
1823
	if ($user_info['is_guest'])
1824
	{
1825
		$_COOKIE['guest_poll_vote'] = !empty($_COOKIE['guest_poll_vote']) ? ($_COOKIE['guest_poll_vote'] . ',' . $row['id_poll']) : $row['id_poll'];
1826
1827
		require_once($sourcedir . '/Subs-Auth.php');
1828
		$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
1829
		smf_setcookie('guest_poll_vote', $_COOKIE['guest_poll_vote'], time() + 2500000, $cookie_url[1], $cookie_url[0], false, false);
1830
	}
1831
1832
	redirectexit('topic=' . $row['id_topic'] . '.0');
1833
}
1834
1835
// Show a search box.
1836
/**
1837
 * Shows a search box
1838
 *
1839
 * @param string $output_method The output method. If 'echo', displays a search box, otherwise returns the URL of the search page.
1840
 * @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.
1841
 */
1842
function ssi_quickSearch($output_method = 'echo')
1843
{
1844
	global $scripturl, $txt, $context;
1845
1846
	if (!allowedTo('search_posts'))
1847
		return;
1848
1849
	if ($output_method != 'echo')
1850
		return $scripturl . '?action=search';
1851
1852
	echo '
1853
		<form action="', $scripturl, '?action=search2" method="post" accept-charset="', $context['character_set'], '">
1854
			<input type="hidden" name="advanced" value="0"><input type="text" name="ssi_search" size="30"> <input type="submit" value="', $txt['search'], '" class="button">
1855
		</form>';
1856
}
1857
1858
/**
1859
 * Show a random forum news item
1860
 *
1861
 * @param string $output_method The output method. If 'echo', shows the news item, otherwise returns it.
1862
 * @return void|string Shows or returns a random forum news item, depending on output_method.
1863
 */
1864
function ssi_news($output_method = 'echo')
1865
{
1866
	global $context;
1867
1868
	$context['random_news_line'] = !empty($context['news_lines']) ? $context['news_lines'][mt_rand(0, count($context['news_lines']) - 1)] : '';
1869
1870
	// 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.
1871
	call_integration_hook('integrate_ssi_news');
1872
1873
	if ($output_method != 'echo')
1874
		return $context['random_news_line'];
1875
1876
	echo $context['random_news_line'];
1877
}
1878
1879
/**
1880
 * Show today's birthdays.
1881
 *
1882
 * @param string $output_method The output method. If 'echo', displays a list of users, otherwise returns an array of info about them.
1883
 * @return void|array Displays a list of users or returns an array of info about them depending on output_method.
1884
 */
1885
function ssi_todaysBirthdays($output_method = 'echo')
1886
{
1887
	global $scripturl, $modSettings, $user_info;
1888
1889
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view') || !allowedTo('profile_view'))
1890
		return;
1891
1892
	$eventOptions = array(
1893
		'include_birthdays' => true,
1894
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1895
	);
1896
	$return = cache_quick_get('calendar_index_offset_' . $user_info['time_offset'], 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1897
1898
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1899
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1900
1901
	if ($output_method != 'echo')
1902
		return $return['calendar_birthdays'];
1903
1904
	foreach ($return['calendar_birthdays'] as $member)
1905
		echo '
1906
			<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'] ? ', ' : '');
1907
}
1908
1909
/**
1910
 * Shows today's holidays.
1911
 *
1912
 * @param string $output_method The output method. If 'echo', displays a list of holidays, otherwise returns an array of info about them.
1913
 * @return void|array Displays a list of holidays or returns an array of info about them depending on output_method
1914
 */
1915
function ssi_todaysHolidays($output_method = 'echo')
1916
{
1917
	global $modSettings, $user_info;
1918
1919
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1920
		return;
1921
1922
	$eventOptions = array(
1923
		'include_holidays' => true,
1924
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1925
	);
1926
	$return = cache_quick_get('calendar_index_offset_' . $user_info['time_offset'], 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1927
1928
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1929
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1930
1931
	if ($output_method != 'echo')
1932
		return $return['calendar_holidays'];
1933
1934
	echo '
1935
		', implode(', ', $return['calendar_holidays']);
1936
}
1937
1938
/**
1939
 * Shows today's events.
1940
 *
1941
 * @param string $output_method The output method. If 'echo', displays a list of events, otherwise returns an array of info about them.
1942
 * @return void|array Displays a list of events or returns an array of info about them depending on output_method
1943
 */
1944
function ssi_todaysEvents($output_method = 'echo')
1945
{
1946
	global $modSettings, $user_info;
1947
1948
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1949
		return;
1950
1951
	$eventOptions = array(
1952
		'include_events' => true,
1953
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1954
	);
1955
	$return = cache_quick_get('calendar_index_offset_' . $user_info['time_offset'], 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1956
1957
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1958
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1959
1960
	if ($output_method != 'echo')
1961
		return $return['calendar_events'];
1962
1963
	foreach ($return['calendar_events'] as $event)
1964
	{
1965
		if ($event['can_edit'])
1966
			echo '
1967
	<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
1968
		echo '
1969
	' . $event['link'] . (!$event['is_last'] ? ', ' : '');
1970
	}
1971
}
1972
1973
/**
1974
 * Shows today's calendar items (events, birthdays and holidays)
1975
 *
1976
 * @param string $output_method The output method. If 'echo', displays a list of calendar items, otherwise returns an array of info about them.
1977
 * @return void|array Displays a list of calendar items or returns an array of info about them depending on output_method
1978
 */
1979
function ssi_todaysCalendar($output_method = 'echo')
1980
{
1981
	global $modSettings, $txt, $scripturl, $user_info;
1982
1983
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1984
		return;
1985
1986
	$eventOptions = array(
1987
		'include_birthdays' => allowedTo('profile_view'),
1988
		'include_holidays' => true,
1989
		'include_events' => true,
1990
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1991
	);
1992
	$return = cache_quick_get('calendar_index_offset_' . $user_info['time_offset'], 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1993
1994
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1995
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1996
1997
	if ($output_method != 'echo')
1998
		return $return;
1999
2000
	if (!empty($return['calendar_holidays']))
2001
		echo '
2002
			<span class="holiday">' . $txt['calendar_prompt'] . ' ' . implode(', ', $return['calendar_holidays']) . '<br></span>';
2003
	if (!empty($return['calendar_birthdays']))
2004
	{
2005
		echo '
2006
			<span class="birthday">' . $txt['birthdays_upcoming'] . '</span> ';
2007
		foreach ($return['calendar_birthdays'] as $member)
2008
			echo '
2009
			<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'] ? ', ' : '';
2010
		echo '
2011
			<br>';
2012
	}
2013
	if (!empty($return['calendar_events']))
2014
	{
2015
		echo '
2016
			<span class="event">' . $txt['events_upcoming'] . '</span> ';
2017
		foreach ($return['calendar_events'] as $event)
2018
		{
2019
			if ($event['can_edit'])
2020
				echo '
2021
			<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
2022
			echo '
2023
			' . $event['link'] . (!$event['is_last'] ? ', ' : '');
2024
		}
2025
	}
2026
}
2027
2028
/**
2029
 * Show the latest news, with a template... by board.
2030
 *
2031
 * @param null|int $board The ID of the board to get the info from. Defaults to $board or $_GET['board'] if not set.
2032
 * @param null|int $limit How many items to show. Defaults to $_GET['limit'] or 5 if not set.
2033
 * @param null|int $start Start with the specified item. Defaults to $_GET['start'] or 0 if not set.
2034
 * @param null|int $length How many characters to show from each post. Defaults to $_GET['length'] or 0 (no limit) if not set.
2035
 * @param string $output_method The output method. If 'echo', displays the news items, otherwise returns an array of info about them.
2036
 * @return void|array Displays the news items or returns an array of info about them, depending on output_method.
2037
 */
2038
function ssi_boardNews($board = null, $limit = null, $start = null, $length = null, $output_method = 'echo')
2039
{
2040
	global $scripturl, $txt, $settings, $modSettings, $context;
2041
	global $smcFunc;
2042
2043
	loadLanguage('Stats');
2044
2045
	// Must be integers....
2046
	if ($limit === null)
2047
		$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 5;
2048
	else
2049
		$limit = (int) $limit;
2050
2051
	if ($start === null)
2052
		$start = isset($_GET['start']) ? (int) $_GET['start'] : 0;
2053
	else
2054
		$start = (int) $start;
2055
2056
	if ($board !== null)
2057
		$board = (int) $board;
2058
	elseif (isset($_GET['board']))
2059
		$board = (int) $_GET['board'];
2060
2061
	if ($length === null)
2062
		$length = isset($_GET['length']) ? (int) $_GET['length'] : 0;
2063
	else
2064
		$length = (int) $length;
2065
2066
	$limit = max(0, $limit);
2067
	$start = max(0, $start);
2068
2069
	// Make sure guests can see this board.
2070
	$request = $smcFunc['db_query']('', '
2071
		SELECT id_board
2072
		FROM {db_prefix}boards
2073
		WHERE ' . ($board === null ? '' : 'id_board = {int:current_board}
2074
			AND ') . 'FIND_IN_SET(-1, member_groups) != 0
2075
		LIMIT 1',
2076
		array(
2077
			'current_board' => $board,
2078
		)
2079
	);
2080
	if ($smcFunc['db_num_rows']($request) == 0)
2081
	{
2082
		if ($output_method == 'echo')
2083
			die($txt['ssi_no_guests']);
0 ignored issues
show
Using exit here is not recommended.

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

Loading history...
2084
		else
2085
			return array();
2086
	}
2087
	list ($board) = $smcFunc['db_fetch_row']($request);
2088
	$smcFunc['db_free_result']($request);
2089
2090
	$icon_sources = array();
2091
	foreach ($context['stable_icons'] as $icon)
2092
		$icon_sources[$icon] = 'images_url';
2093
2094
	if (!empty($modSettings['enable_likes']))
2095
	{
2096
		$context['can_like'] = allowedTo('likes_like');
2097
	}
2098
2099
	// Find the post ids.
2100
	$request = $smcFunc['db_query']('', '
2101
		SELECT t.id_first_msg
2102
		FROM {db_prefix}topics as t
2103
			LEFT JOIN {db_prefix}boards as b ON (b.id_board = t.id_board)
2104
		WHERE t.id_board = {int:current_board}' . ($modSettings['postmod_active'] ? '
2105
			AND t.approved = {int:is_approved}' : '') . '
2106
			AND {query_see_board}
2107
		ORDER BY t.id_first_msg DESC
2108
		LIMIT ' . $start . ', ' . $limit,
2109
		array(
2110
			'current_board' => $board,
2111
			'is_approved' => 1,
2112
		)
2113
	);
2114
	$posts = array();
2115
	while ($row = $smcFunc['db_fetch_assoc']($request))
2116
		$posts[] = $row['id_first_msg'];
2117
	$smcFunc['db_free_result']($request);
2118
2119
	if (empty($posts))
2120
		return array();
2121
2122
	// Find the posts.
2123
	$request = $smcFunc['db_query']('', '
2124
		SELECT
2125
			m.icon, m.subject, m.body, COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.likes,
2126
			t.num_replies, t.id_topic, m.id_member, m.smileys_enabled, m.id_msg, t.locked, t.id_last_msg, m.id_board
2127
		FROM {db_prefix}topics AS t
2128
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
2129
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
2130
		WHERE t.id_first_msg IN ({array_int:post_list})
2131
		ORDER BY t.id_first_msg DESC
2132
		LIMIT ' . count($posts),
2133
		array(
2134
			'post_list' => $posts,
2135
		)
2136
	);
2137
	$return = array();
2138
	$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
2139
	while ($row = $smcFunc['db_fetch_assoc']($request))
2140
	{
2141
		// If we want to limit the length of the post.
2142
		if (!empty($length) && $smcFunc['strlen']($row['body']) > $length)
2143
		{
2144
			$row['body'] = $smcFunc['substr']($row['body'], 0, $length);
2145
			$cutoff = false;
2146
2147
			$last_space = strrpos($row['body'], ' ');
2148
			$last_open = strrpos($row['body'], '<');
2149
			$last_close = strrpos($row['body'], '>');
2150
			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)
2151
				$cutoff = $last_open;
2152
			elseif (empty($last_close) || $last_close < $last_open)
2153
				$cutoff = $last_space;
2154
2155
			if ($cutoff !== false)
2156
				$row['body'] = $smcFunc['substr']($row['body'], 0, $cutoff);
2157
			$row['body'] .= '...';
2158
		}
2159
2160
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
2161
2162
		if (!empty($recycle_board) && $row['id_board'] == $recycle_board)
2163
			$row['icon'] = 'recycled';
2164
2165
		// Check that this message icon is there...
2166
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
2167
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
2168
		elseif (!isset($icon_sources[$row['icon']]))
2169
			$icon_sources[$row['icon']] = 'images_url';
2170
2171
		censorText($row['subject']);
2172
		censorText($row['body']);
2173
2174
		$return[] = array(
2175
			'id' => $row['id_topic'],
2176
			'message_id' => $row['id_msg'],
2177
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" alt="' . $row['icon'] . '">',
2178
			'subject' => $row['subject'],
2179
			'time' => timeformat($row['poster_time']),
2180
			'timestamp' => $row['poster_time'],
2181
			'body' => $row['body'],
2182
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
2183
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['num_replies'] . ' ' . ($row['num_replies'] == 1 ? $txt['ssi_comment'] : $txt['ssi_comments']) . '</a>',
2184
			'replies' => $row['num_replies'],
2185
			'comment_href' => !empty($row['locked']) ? '' : $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . ';last_msg=' . $row['id_last_msg'],
2186
			'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>',
2187
			'new_comment' => !empty($row['locked']) ? '' : '<a href="' . $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . '">' . $txt['ssi_write_comment'] . '</a>',
2188
			'poster' => array(
2189
				'id' => $row['id_member'],
2190
				'name' => $row['poster_name'],
2191
				'href' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
2192
				'link' => !empty($row['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>' : $row['poster_name']
2193
			),
2194
			'locked' => !empty($row['locked']),
2195
			'is_last' => false,
2196
			// Nasty ternary for likes not messing around the "is_last" check.
2197
			'likes' => !empty($modSettings['enable_likes']) ? array(
2198
				'count' => $row['likes'],
2199
				'you' => in_array($row['id_msg'], prepareLikesContext((int) $row['id_topic'])),
2200
				'can_like' => !$context['user']['is_guest'] && $row['id_member'] != $context['user']['id'] && !empty($context['can_like']),
2201
			) : array(),
2202
		);
2203
	}
2204
	$smcFunc['db_free_result']($request);
2205
2206
	if (empty($return))
2207
		return $return;
2208
2209
	$return[count($return) - 1]['is_last'] = true;
2210
2211
	// If mods want to do somthing with this list of posts, let them do that now.
2212
	call_integration_hook('integrate_ssi_boardNews', array(&$return));
2213
2214
	if ($output_method != 'echo')
2215
		return $return;
2216
2217
	foreach ($return as $news)
2218
	{
2219
		echo '
2220
			<div class="news_item">
2221
				<h3 class="news_header">
2222
					', $news['icon'], '
2223
					<a href="', $news['href'], '">', $news['subject'], '</a>
2224
				</h3>
2225
				<div class="news_timestamp">', $news['time'], ' ', $txt['by'], ' ', $news['poster']['link'], '</div>
2226
				<div class="news_body" style="padding: 2ex 0;">', $news['body'], '</div>
2227
				', $news['link'], $news['locked'] ? '' : ' | ' . $news['comment_link'], '';
2228
2229
		// Is there any likes to show?
2230
		if (!empty($modSettings['enable_likes']))
2231
		{
2232
			echo '
2233
					<ul>';
2234
2235
			if (!empty($news['likes']['can_like']))
2236
			{
2237
				echo '
2238
						<li class="smflikebutton" 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>';
2239
			}
2240
2241
			if (!empty($news['likes']['count']))
2242
			{
2243
				$context['some_likes'] = true;
2244
				$count = $news['likes']['count'];
2245
				$base = 'likes_';
2246
				if ($news['likes']['you'])
2247
				{
2248
					$base = 'you_' . $base;
2249
					$count--;
2250
				}
2251
				$base .= (isset($txt[$base . $count])) ? $count : 'n';
2252
2253
				echo '
2254
						<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>';
2255
			}
2256
2257
			echo '
2258
					</ul>';
2259
		}
2260
2261
		// Close the main div.
2262
		echo '
2263
			</div>';
2264
2265
		if (!$news['is_last'])
2266
			echo '
2267
			<hr>';
2268
	}
2269
}
2270
2271
/**
2272
 * Show the most recent events
2273
 *
2274
 * @param int $max_events The maximum number of events to show
2275
 * @param string $output_method The output method. If 'echo', displays the events, otherwise returns an array of info about them.
2276
 * @return void|array Displays the events or returns an array of info about them, depending on output_method.
2277
 */
2278
function ssi_recentEvents($max_events = 7, $output_method = 'echo')
2279
{
2280
	global $user_info, $scripturl, $modSettings, $txt, $context, $smcFunc;
2281
2282
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
2283
		return;
2284
2285
	// Find all events which are happening in the near future that the member can see.
2286
	$request = $smcFunc['db_query']('', '
2287
		SELECT
2288
			cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
2289
			cal.start_time, cal.end_time, cal.timezone, cal.location,
2290
			cal.id_board, t.id_first_msg, t.approved
2291
		FROM {db_prefix}calendar AS cal
2292
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
2293
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
2294
		WHERE cal.start_date <= {date:current_date}
2295
			AND cal.end_date >= {date:current_date}
2296
			AND (cal.id_board = {int:no_board} OR {query_wanna_see_board})
2297
		ORDER BY cal.start_date DESC
2298
		LIMIT ' . $max_events,
2299
		array(
2300
			'current_date' => smf_strftime('%Y-%m-%d', time()),
2301
			'no_board' => 0,
2302
		)
2303
	);
2304
	$return = array();
2305
	$duplicates = array();
2306
	while ($row = $smcFunc['db_fetch_assoc']($request))
2307
	{
2308
		// 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.
2309
		if (!empty($duplicates[$row['title'] . $row['id_topic']]))
2310
			continue;
2311
2312
		// Censor the title.
2313
		censorText($row['title']);
2314
2315
		if ($row['start_date'] < smf_strftime('%Y-%m-%d', time()))
2316
			$date = smf_strftime('%Y-%m-%d', time());
2317
		else
2318
			$date = $row['start_date'];
2319
2320
		// If the topic it is attached to is not approved then don't link it.
2321
		if (!empty($row['id_first_msg']) && !$row['approved'])
2322
			$row['id_board'] = $row['id_topic'] = $row['id_first_msg'] = 0;
2323
2324
		$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;
0 ignored issues
show
timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) of type void is incompatible with the type array expected by parameter $haystack of in_array(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2324
		$allday = (empty($row['start_time']) || empty($row['end_time']) || empty($row['timezone']) || !in_array($row['timezone'], /** @scrutinizer ignore-type */ timezone_identifiers_list(DateTimeZone::ALL_WITH_BC))) ? true : false;
Loading history...
Are you sure the usage of timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2325
2326
		$return[$date][] = array(
2327
			'id' => $row['id_event'],
2328
			'title' => $row['title'],
2329
			'location' => $row['location'],
2330
			'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
2331
			'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'],
2332
			'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
2333
			'link' => $row['id_board'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
2334
			'start_date' => $row['start_date'],
2335
			'end_date' => $row['end_date'],
2336
			'start_time' => !$allday ? $row['start_time'] : null,
2337
			'end_time' => !$allday ? $row['end_time'] : null,
2338
			'tz' => !$allday ? $row['timezone'] : null,
2339
			'allday' => $allday,
2340
			'is_last' => false
2341
		);
2342
2343
		// Let's not show this one again, huh?
2344
		$duplicates[$row['title'] . $row['id_topic']] = true;
2345
	}
2346
	$smcFunc['db_free_result']($request);
2347
2348
	foreach ($return as $mday => $array)
2349
		$return[$mday][count($array) - 1]['is_last'] = true;
2350
2351
	// If mods want to do somthing with this list of events, let them do that now.
2352
	call_integration_hook('integrate_ssi_recentEvents', array(&$return));
2353
2354
	if ($output_method != 'echo' || empty($return))
2355
		return $return;
2356
2357
	// Well the output method is echo.
2358
	echo '
2359
			<span class="event">' . $txt['events'] . '</span> ';
2360
	foreach ($return as $mday => $array)
2361
		foreach ($array as $event)
2362
		{
2363
			if ($event['can_edit'])
2364
				echo '
2365
				<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
2366
2367
			echo '
2368
				' . $event['link'] . (!$event['is_last'] ? ', ' : '');
2369
		}
2370
}
2371
2372
/**
2373
 * Checks whether the specified password is correct for the specified user.
2374
 *
2375
 * @param int|string $id The ID or username of a user
2376
 * @param string $password The password to check
2377
 * @param bool $is_username If true, treats $id as a username rather than a user ID
2378
 * @return bool Whether or not the password is correct.
2379
 */
2380
function ssi_checkPassword($id = null, $password = null, $is_username = false)
2381
{
2382
	global $smcFunc;
2383
2384
	// If $id is null, this was most likely called from a query string and should do nothing.
2385
	if ($id === null)
2386
		return;
2387
2388
	$request = $smcFunc['db_query']('', '
2389
		SELECT passwd, member_name, is_activated
2390
		FROM {db_prefix}members
2391
		WHERE ' . ($is_username ? 'member_name' : 'id_member') . ' = {string:id}
2392
		LIMIT 1',
2393
		array(
2394
			'id' => $id,
2395
		)
2396
	);
2397
	list ($pass, $user, $active) = $smcFunc['db_fetch_row']($request);
2398
	$smcFunc['db_free_result']($request);
2399
2400
	return hash_verify_password($user, $password, $pass) && $active == 1;
2401
}
2402
2403
/**
2404
 * Shows the most recent attachments that the user can see
2405
 *
2406
 * @param int $num_attachments How many to show
2407
 * @param array $attachment_ext Only shows attachments with the specified extensions ('jpg', 'gif', etc.) if set
2408
 * @param string $output_method The output method. If 'echo', displays a table with links/info, otherwise returns an array with information about the attachments
2409
 * @return void|array Displays a table of attachment info or returns an array containing info about the attachments, depending on output_method.
2410
 */
2411
function ssi_recentAttachments($num_attachments = 10, $attachment_ext = array(), $output_method = 'echo')
2412
{
2413
	global $smcFunc, $modSettings, $scripturl, $txt, $settings;
2414
2415
	// We want to make sure that we only get attachments for boards that we can see *if* any.
2416
	$attachments_boards = boardsAllowedTo('view_attachments');
2417
2418
	// No boards?  Adios amigo.
2419
	if (empty($attachments_boards))
2420
		return array();
2421
2422
	// Is it an array?
2423
	$attachment_ext = (array) $attachment_ext;
2424
2425
	// Lets build the query.
2426
	$request = $smcFunc['db_query']('', '
2427
		SELECT
2428
			att.id_attach, att.id_msg, att.filename, COALESCE(att.size, 0) AS filesize, att.downloads, mem.id_member,
2429
			COALESCE(mem.real_name, m.poster_name) AS poster_name, m.id_topic, m.subject, t.id_board, m.poster_time,
2430
			att.width, att.height' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ', COALESCE(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
2431
		FROM {db_prefix}attachments AS att
2432
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = att.id_msg)
2433
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
2434
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
2435
			LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = att.id_thumb)') . '
2436
		WHERE att.attachment_type = 0' . ($attachments_boards === array(0) ? '' : '
2437
			AND m.id_board IN ({array_int:boards_can_see})') . (!empty($attachment_ext) ? '
2438
			AND att.fileext IN ({array_string:attachment_ext})' : '') .
2439
			(!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
2440
			AND t.approved = {int:is_approved}
2441
			AND m.approved = {int:is_approved}
2442
			AND att.approved = {int:is_approved}') . '
2443
		ORDER BY att.id_attach DESC
2444
		LIMIT {int:num_attachments}',
2445
		array(
2446
			'boards_can_see' => $attachments_boards,
2447
			'attachment_ext' => $attachment_ext,
2448
			'num_attachments' => $num_attachments,
2449
			'is_approved' => 1,
2450
		)
2451
	);
2452
2453
	// We have something.
2454
	$attachments = array();
2455
	while ($row = $smcFunc['db_fetch_assoc']($request))
2456
	{
2457
		$filename = preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($row['filename']));
2458
2459
		// Is it an image?
2460
		$attachments[$row['id_attach']] = array(
2461
			'member' => array(
2462
				'id' => $row['id_member'],
2463
				'name' => $row['poster_name'],
2464
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>',
2465
			),
2466
			'file' => array(
2467
				'filename' => $filename,
2468
				'filesize' => round($row['filesize'] / 1024, 2) . $txt['kilobyte'],
2469
				'downloads' => $row['downloads'],
2470
				'href' => $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'],
2471
				'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>',
2472
				'is_image' => !empty($row['width']) && !empty($row['height']) && !empty($modSettings['attachmentShowImages']),
2473
			),
2474
			'topic' => array(
2475
				'id' => $row['id_topic'],
2476
				'subject' => $row['subject'],
2477
				'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
2478
				'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>',
2479
				'time' => timeformat($row['poster_time']),
2480
			),
2481
		);
2482
2483
		// Images.
2484
		if ($attachments[$row['id_attach']]['file']['is_image'])
2485
		{
2486
			$id_thumb = empty($row['id_thumb']) ? $row['id_attach'] : $row['id_thumb'];
2487
			$attachments[$row['id_attach']]['file']['image'] = array(
2488
				'id' => $id_thumb,
2489
				'width' => $row['width'],
2490
				'height' => $row['height'],
2491
				'img' => '<img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . ';image" alt="' . $filename . '">',
2492
				'thumb' => '<img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image" alt="' . $filename . '">',
2493
				'href' => $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image',
2494
				'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>',
2495
			);
2496
		}
2497
	}
2498
	$smcFunc['db_free_result']($request);
2499
2500
	// If mods want to do somthing with this list of attachments, let them do that now.
2501
	call_integration_hook('integrate_ssi_recentAttachments', array(&$attachments));
2502
2503
	// So you just want an array?  Here you can have it.
2504
	if ($output_method == 'array' || empty($attachments))
2505
		return $attachments;
2506
2507
	// Give them the default.
2508
	echo '
2509
		<table class="ssi_downloads">
2510
			<tr>
2511
				<th style="text-align: left; padding: 2">', $txt['file'], '</th>
2512
				<th style="text-align: left; padding: 2">', $txt['posted_by'], '</th>
2513
				<th style="text-align: left; padding: 2">', $txt['downloads'], '</th>
2514
				<th style="text-align: left; padding: 2">', $txt['filesize'], '</th>
2515
			</tr>';
2516
	foreach ($attachments as $attach)
2517
		echo '
2518
			<tr>
2519
				<td>', $attach['file']['link'], '</td>
2520
				<td>', $attach['member']['link'], '</td>
2521
				<td style="text-align: center">', $attach['file']['downloads'], '</td>
2522
				<td>', $attach['file']['filesize'], '</td>
2523
			</tr>';
2524
	echo '
2525
		</table>';
2526
}
2527
2528
?>