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

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

1027
		mt_srand(/** @scrutinizer ignore-type */ floor(time() / 86400));
Loading history...
1028
	}
1029
1030
	// Get the lowest ID we're interested in.
1031
	$member_id = mt_rand(1, $modSettings['latestMember']);
1032
1033
	$where_query = '
1034
		id_member >= {int:selected_member}
1035
		AND is_activated = {int:is_activated}';
1036
1037
	$query_where_params = array(
1038
		'selected_member' => $member_id,
1039
		'is_activated' => 1,
1040
	);
1041
1042
	$result = ssi_queryMembers($where_query, $query_where_params, 1, 'id_member ASC', $output_method);
1043
1044
	// If we got nothing do the reverse - in case of unactivated members.
1045
	if (empty($result))
1046
	{
1047
		$where_query = '
1048
			id_member <= {int:selected_member}
1049
			AND is_activated = {int:is_activated}';
1050
1051
		$query_where_params = array(
1052
			'selected_member' => $member_id,
1053
			'is_activated' => 1,
1054
		);
1055
1056
		$result = ssi_queryMembers($where_query, $query_where_params, 1, 'id_member DESC', $output_method);
1057
	}
1058
1059
	// Just to be sure put the random generator back to something... random.
1060
	if ($random_type != '')
1061
		mt_srand(time());
1062
1063
	return $result;
1064
}
1065
1066
/**
1067
 * Fetch specific members
1068
 *
1069
 * @param array $member_ids The IDs of the members to fetch
1070
 * @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.
1071
 * @return void|array Displays links to the specified members' profiles or returns an array of info about them, depending on output_method.
1072
 */
1073
function ssi_fetchMember($member_ids = array(), $output_method = 'echo')
1074
{
1075
	if (empty($member_ids))
1076
		return;
1077
1078
	// Can have more than one member if you really want...
1079
	$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...
1080
1081
	// Restrict it right!
1082
	$query_where = '
1083
		id_member IN ({array_int:member_list})';
1084
1085
	$query_where_params = array(
1086
		'member_list' => $member_ids,
1087
	);
1088
1089
	// Then make the query and dump the data.
1090
	return ssi_queryMembers($query_where, $query_where_params, '', 'id_member', $output_method);
1091
}
1092
1093
/**
1094
 * Get al members in the specified group
1095
 *
1096
 * @param int $group_id The ID of the group to get members from
1097
 * @param string $output_method The output method. If 'echo', returns a list of group members, otherwise returns an array of info about them.
1098
 * @return void|array Displays a list of group members or returns an array of info about them, depending on output_method.
1099
 */
1100
function ssi_fetchGroupMembers($group_id = null, $output_method = 'echo')
1101
{
1102
	if ($group_id === null)
1103
		return;
1104
1105
	$query_where = '
1106
		id_group = {int:id_group}
1107
		OR id_post_group = {int:id_group}
1108
		OR FIND_IN_SET({int:id_group}, additional_groups) != 0';
1109
1110
	$query_where_params = array(
1111
		'id_group' => $group_id,
1112
	);
1113
1114
	return ssi_queryMembers($query_where, $query_where_params, '', 'real_name', $output_method);
1115
}
1116
1117
/**
1118
 * Pulls info about members based on the specified parameters. Used by other functions to eliminate duplication.
1119
 *
1120
 * @param string $query_where The info for the WHERE clause of the query
1121
 * @param array $query_where_params The parameters for the WHERE clause
1122
 * @param string|int $query_limit The number of rows to return or an empty string to return all
1123
 * @param string $query_order The info for the ORDER BY clause of the query
1124
 * @param string $output_method The output method. If 'echo', displays a list of members, otherwise returns an array of info about them
1125
 * @return void|array Displays a list of members or returns an array of info about them, depending on output_method.
1126
 */
1127
function ssi_queryMembers($query_where = null, $query_where_params = array(), $query_limit = '', $query_order = 'id_member DESC', $output_method = 'echo')
1128
{
1129
	global $smcFunc, $memberContext;
1130
1131
	if ($query_where === null)
1132
		return;
1133
1134
	// Fetch the members in question.
1135
	$request = $smcFunc['db_query']('', '
1136
		SELECT id_member
1137
		FROM {db_prefix}members
1138
		WHERE ' . $query_where . '
1139
		ORDER BY ' . $query_order . '
1140
		' . ($query_limit == '' ? '' : 'LIMIT ' . $query_limit),
1141
		array_merge($query_where_params, array(
1142
		))
1143
	);
1144
	$members = array();
1145
	while ($row = $smcFunc['db_fetch_assoc']($request))
1146
		$members[] = $row['id_member'];
1147
	$smcFunc['db_free_result']($request);
1148
1149
	if (empty($members))
1150
		return array();
1151
1152
	// If mods want to do somthing with this list of members, let them do that now.
1153
	call_integration_hook('integrate_ssi_queryMembers', array(&$members));
1154
1155
	// Load the members.
1156
	loadMemberData($members);
1157
1158
	// Draw the table!
1159
	if ($output_method == 'echo')
1160
		echo '
1161
		<table style="border: none" class="ssi_table">';
1162
1163
	$query_members = array();
1164
	foreach ($members as $member)
1165
	{
1166
		// Load their context data.
1167
		if (!loadMemberContext($member))
1168
			continue;
1169
1170
		// Store this member's information.
1171
		$query_members[$member] = $memberContext[$member];
1172
1173
		// Only do something if we're echo'ing.
1174
		if ($output_method == 'echo')
1175
			echo '
1176
			<tr>
1177
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
1178
					', $query_members[$member]['link'], '
1179
					<br>', $query_members[$member]['blurb'], '
1180
					<br>', $query_members[$member]['avatar']['image'], '
1181
				</td>
1182
			</tr>';
1183
	}
1184
1185
	// End the table if appropriate.
1186
	if ($output_method == 'echo')
1187
		echo '
1188
		</table>';
1189
1190
	// Send back the data.
1191
	return $query_members;
1192
}
1193
1194
/**
1195
 * Show some basic stats:   Total This: XXXX, etc.
1196
 *
1197
 * @param string $output_method The output method. If 'echo', displays the stats, otherwise returns an array of info about them
1198
 * @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.
1199
 */
1200
function ssi_boardStats($output_method = 'echo')
1201
{
1202
	global $txt, $scripturl, $modSettings, $smcFunc;
1203
1204
	if (!allowedTo('view_stats'))
1205
		return;
1206
1207
	$totals = array(
1208
		'members' => $modSettings['totalMembers'],
1209
		'posts' => $modSettings['totalMessages'],
1210
		'topics' => $modSettings['totalTopics']
1211
	);
1212
1213
	$result = $smcFunc['db_query']('', '
1214
		SELECT COUNT(*)
1215
		FROM {db_prefix}boards',
1216
		array(
1217
		)
1218
	);
1219
	list ($totals['boards']) = $smcFunc['db_fetch_row']($result);
1220
	$smcFunc['db_free_result']($result);
1221
1222
	$result = $smcFunc['db_query']('', '
1223
		SELECT COUNT(*)
1224
		FROM {db_prefix}categories',
1225
		array(
1226
		)
1227
	);
1228
	list ($totals['categories']) = $smcFunc['db_fetch_row']($result);
1229
	$smcFunc['db_free_result']($result);
1230
1231
	// If mods want to do somthing with the board stats, let them do that now.
1232
	call_integration_hook('integrate_ssi_boardStats', array(&$totals));
1233
1234
	if ($output_method != 'echo')
1235
		return $totals;
1236
1237
	echo '
1238
		', $txt['total_members'], ': <a href="', $scripturl . '?action=mlist">', comma_format($totals['members']), '</a><br>
1239
		', $txt['total_posts'], ': ', comma_format($totals['posts']), '<br>
1240
		', $txt['total_topics'], ': ', comma_format($totals['topics']), ' <br>
1241
		', $txt['total_cats'], ': ', comma_format($totals['categories']), '<br>
1242
		', $txt['total_boards'], ': ', comma_format($totals['boards']);
1243
}
1244
1245
/**
1246
 * Shows a list of online users:  YY Guests, ZZ Users and then a list...
1247
 *
1248
 * @param string $output_method The output method. If 'echo', displays a list, otherwise returns an array of info about the online users.
1249
 * @return void|array Either displays a list of online users or returns an array of info about them, depending on output_method.
1250
 */
1251
function ssi_whosOnline($output_method = 'echo')
1252
{
1253
	global $user_info, $txt, $sourcedir, $settings;
1254
1255
	require_once($sourcedir . '/Subs-MembersOnline.php');
1256
	$membersOnlineOptions = array(
1257
		'show_hidden' => allowedTo('moderate_forum'),
1258
	);
1259
	$return = getMembersOnlineStats($membersOnlineOptions);
1260
1261
	// If mods want to do somthing with the list of who is online, let them do that now.
1262
	call_integration_hook('integrate_ssi_whosOnline', array(&$return));
1263
1264
	// Add some redundancy for backwards compatibility reasons.
1265
	if ($output_method != 'echo')
1266
		return $return + array(
1267
			'users' => $return['users_online'],
1268
			'guests' => $return['num_guests'],
1269
			'hidden' => $return['num_users_hidden'],
1270
			'buddies' => $return['num_buddies'],
1271
			'num_users' => $return['num_users_online'],
1272
			'total_users' => $return['num_users_online'] + $return['num_guests'],
1273
		);
1274
1275
	echo '
1276
		', 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'];
1277
1278
	$bracketList = array();
1279
	if (!empty($user_info['buddies']))
1280
		$bracketList[] = comma_format($return['num_buddies']) . ' ' . ($return['num_buddies'] == 1 ? $txt['buddy'] : $txt['buddies']);
1281
	if (!empty($return['num_spiders']))
1282
		$bracketList[] = comma_format($return['num_spiders']) . ' ' . ($return['num_spiders'] == 1 ? $txt['spider'] : $txt['spiders']);
1283
	if (!empty($return['num_users_hidden']))
1284
		$bracketList[] = comma_format($return['num_users_hidden']) . ' ' . $txt['hidden'];
1285
1286
	if (!empty($bracketList))
1287
		echo ' (' . implode(', ', $bracketList) . ')';
1288
1289
	echo '<br>
1290
			', implode(', ', $return['list_users_online']);
1291
1292
	// Showing membergroups?
1293
	if (!empty($settings['show_group_key']) && !empty($return['online_groups']))
1294
	{
1295
		$membergroups = cache_quick_get('membergroup_list', 'Subs-Membergroups.php', 'cache_getMembergroupList', array());
1296
1297
		$groups = array();
1298
		foreach ($return['online_groups'] as $group)
1299
		{
1300
			if (isset($membergroups[$group['id']]))
1301
				$groups[] = $membergroups[$group['id']];
1302
		}
1303
1304
		echo '<br>
1305
			[' . implode(']&nbsp;&nbsp;[', $groups) . ']';
1306
	}
1307
}
1308
1309
/**
1310
 * Just like whosOnline except it also logs the online presence.
1311
 *
1312
 * @param string $output_method The output method. If 'echo', displays a list, otherwise returns an array of info about the online users.
1313
 * @return void|array Either displays a list of online users or returns an aray of info about them, depending on output_method.
1314
 */
1315
function ssi_logOnline($output_method = 'echo')
1316
{
1317
	writeLog();
1318
1319
	if ($output_method != 'echo')
1320
		return ssi_whosOnline($output_method);
1321
	else
1322
		ssi_whosOnline($output_method);
1323
}
1324
1325
// Shows a login box.
1326
/**
1327
 * Shows a login box
1328
 *
1329
 * @param string $redirect_to The URL to redirect the user to after they login
1330
 * @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
1331
 * @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.
1332
 */
1333
function ssi_login($redirect_to = '', $output_method = 'echo')
1334
{
1335
	global $scripturl, $txt, $user_info, $context;
1336
1337
	if ($redirect_to != '')
1338
		$_SESSION['login_url'] = $redirect_to;
1339
1340
	if ($output_method != 'echo' || !$user_info['is_guest'])
1341
		return $user_info['is_guest'];
1342
1343
	// Create a login token
1344
	createToken('login');
1345
1346
	echo '
1347
		<form action="', $scripturl, '?action=login2" method="post" accept-charset="', $context['character_set'], '">
1348
			<table style="border: none" class="ssi_table">
1349
				<tr>
1350
					<td style="text-align: right; border-spacing: 1"><label for="user">', $txt['username'], ':</label>&nbsp;</td>
1351
					<td><input type="text" id="user" name="user" size="9" value="', $user_info['username'], '"></td>
1352
				</tr><tr>
1353
					<td style="text-align: right; border-spacing: 1"><label for="passwrd">', $txt['password'], ':</label>&nbsp;</td>
1354
					<td><input type="password" name="passwrd" id="passwrd" size="9"></td>
1355
				</tr>
1356
				<tr>
1357
					<td>
1358
						<input type="hidden" name="cookielength" value="-1">
1359
						<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
1360
						<input type="hidden" name="', $context['login_token_var'], '" value="', $context['login_token'], '">
1361
					</td>
1362
					<td><input type="submit" value="', $txt['login'], '" class="button"></td>
1363
				</tr>
1364
			</table>
1365
		</form>';
1366
1367
}
1368
1369
/**
1370
 * Show the top poll based on votes
1371
 *
1372
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it
1373
 * @return void|array Either shows the top poll or returns an array of info about it, depending on output_method.
1374
 */
1375
function ssi_topPoll($output_method = 'echo')
1376
{
1377
	// Just use recentPoll, no need to duplicate code...
1378
	return ssi_recentPoll(true, $output_method);
1379
}
1380
1381
// Show the most recently posted poll.
1382
/**
1383
 * Shows the most recent poll
1384
 *
1385
 * @param bool $topPollInstead Whether to show the top poll (based on votes) instead of the most recent one
1386
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it.
1387
 * @return void|array Either shows the poll or returns an array of info about it, depending on output_method.
1388
 */
1389
function ssi_recentPoll($topPollInstead = false, $output_method = 'echo')
1390
{
1391
	global $txt, $boardurl, $user_info, $context, $smcFunc, $modSettings;
1392
1393
	$boardsAllowed = array_intersect(boardsAllowedTo('poll_view'), boardsAllowedTo('poll_vote'));
1394
1395
	if (empty($boardsAllowed))
1396
		return array();
1397
1398
	$request = $smcFunc['db_query']('', '
1399
		SELECT p.id_poll, p.question, t.id_topic, p.max_votes, p.guest_vote, p.hide_results, p.expire_time
1400
		FROM {db_prefix}polls AS p
1401
			INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
1402
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)' . ($topPollInstead ? '
1403
			INNER JOIN {db_prefix}poll_choices AS pc ON (pc.id_poll = p.id_poll)' : '') . '
1404
			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})
1405
		WHERE p.voting_locked = {int:voting_opened}
1406
			AND (p.expire_time = {int:no_expiration} OR {int:current_time} < p.expire_time)
1407
			AND ' . ($user_info['is_guest'] ? 'p.guest_vote = {int:guest_vote_allowed}' : 'lp.id_choice IS NULL') . '
1408
			AND {query_wanna_see_board}' . (!in_array(0, $boardsAllowed) ? '
1409
			AND b.id_board IN ({array_int:boards_allowed_list})' : '') . (!empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? '
1410
			AND b.id_board != {int:recycle_board}' : '') . '
1411
		ORDER BY ' . ($topPollInstead ? 'pc.votes' : 'p.id_poll') . ' DESC
1412
		LIMIT 1',
1413
		array(
1414
			'current_member' => $user_info['id'],
1415
			'boards_allowed_list' => $boardsAllowed,
1416
			'is_approved' => 1,
1417
			'guest_vote_allowed' => 1,
1418
			'no_member' => 0,
1419
			'voting_opened' => 0,
1420
			'no_expiration' => 0,
1421
			'current_time' => time(),
1422
			'recycle_board' => !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : null,
1423
		)
1424
	);
1425
	$row = $smcFunc['db_fetch_assoc']($request);
1426
	$smcFunc['db_free_result']($request);
1427
1428
	// This user has voted on all the polls.
1429
	if (empty($row) || !is_array($row))
1430
		return array();
1431
1432
	// If this is a guest who's voted we'll through ourselves to show poll to show the results.
1433
	if ($user_info['is_guest'] && (!$row['guest_vote'] || (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))))
1434
		return ssi_showPoll($row['id_topic'], $output_method);
1435
1436
	$request = $smcFunc['db_query']('', '
1437
		SELECT COUNT(DISTINCT id_member)
1438
		FROM {db_prefix}log_polls
1439
		WHERE id_poll = {int:current_poll}',
1440
		array(
1441
			'current_poll' => $row['id_poll'],
1442
		)
1443
	);
1444
	list ($total) = $smcFunc['db_fetch_row']($request);
1445
	$smcFunc['db_free_result']($request);
1446
1447
	$request = $smcFunc['db_query']('', '
1448
		SELECT id_choice, label, votes
1449
		FROM {db_prefix}poll_choices
1450
		WHERE id_poll = {int:current_poll}',
1451
		array(
1452
			'current_poll' => $row['id_poll'],
1453
		)
1454
	);
1455
	$sOptions = array();
1456
	while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
1457
	{
1458
		censorText($rowChoice['label']);
1459
1460
		$sOptions[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
1461
	}
1462
	$smcFunc['db_free_result']($request);
1463
1464
	// Can they view it?
1465
	$is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
1466
	$allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || $is_expired;
1467
1468
	$return = array(
1469
		'id' => $row['id_poll'],
1470
		'image' => 'poll',
1471
		'question' => $row['question'],
1472
		'total_votes' => $total,
1473
		'is_locked' => false,
1474
		'topic' => $row['id_topic'],
1475
		'allow_view_results' => $allow_view_results,
1476
		'options' => array()
1477
	);
1478
1479
	// Calculate the percentages and bar lengths...
1480
	$divisor = $return['total_votes'] == 0 ? 1 : $return['total_votes'];
1481
	foreach ($sOptions as $i => $option)
1482
	{
1483
		$bar = floor(($option[1] * 100) / $divisor);
1484
		$return['options'][$i] = array(
1485
			'id' => 'options-' . ($topPollInstead ? 'top-' : 'recent-') . $i,
1486
			'percent' => $bar,
1487
			'votes' => $option[1],
1488
			'option' => parse_bbc($option[0]),
1489
			'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . ($topPollInstead ? 'top-' : 'recent-') . $i . '" value="' . $i . '">'
1490
		);
1491
	}
1492
1493
	$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options_limit'], min(count($sOptions), $row['max_votes'])) : '';
1494
1495
	// If mods want to do somthing with this list of polls, let them do that now.
1496
	call_integration_hook('integrate_ssi_recentPoll', array(&$return, $topPollInstead));
1497
1498
	if ($output_method != 'echo')
1499
		return $return;
1500
1501
	if ($allow_view_results)
1502
	{
1503
		echo '
1504
		<form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
1505
			<strong>', $return['question'], '</strong><br>
1506
			', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br>' : '';
1507
1508
		foreach ($return['options'] as $option)
1509
			echo '
1510
			<label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br>';
1511
1512
		echo '
1513
			<input type="submit" value="', $txt['poll_vote'], '" class="button">
1514
			<input type="hidden" name="poll" value="', $return['id'], '">
1515
			<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
1516
		</form>';
1517
	}
1518
	else
1519
		echo $txt['poll_cannot_see'];
1520
}
1521
1522
/**
1523
 * Shows the poll from the specified topic
1524
 *
1525
 * @param null|int $topic The topic to show the poll from. If null, $_REQUEST['ssi_topic'] will be used instead.
1526
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it.
1527
 * @return void|array Either displays the poll or returns an array of info about it, depending on output_method.
1528
 */
1529
function ssi_showPoll($topic = null, $output_method = 'echo')
1530
{
1531
	global $txt, $boardurl, $user_info, $context, $smcFunc, $modSettings;
1532
1533
	$boardsAllowed = boardsAllowedTo('poll_view');
1534
1535
	if (empty($boardsAllowed))
1536
		return array();
1537
1538
	if ($topic === null && isset($_REQUEST['ssi_topic']))
1539
		$topic = (int) $_REQUEST['ssi_topic'];
1540
	else
1541
		$topic = (int) $topic;
1542
1543
	$request = $smcFunc['db_query']('', '
1544
		SELECT
1545
			p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.guest_vote, b.id_board
1546
		FROM {db_prefix}topics AS t
1547
			INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
1548
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1549
		WHERE t.id_topic = {int:current_topic}
1550
			AND {query_see_board}' . (!in_array(0, $boardsAllowed) ? '
1551
			AND b.id_board IN ({array_int:boards_allowed_see})' : '') . ($modSettings['postmod_active'] ? '
1552
			AND t.approved = {int:is_approved}' : '') . '
1553
		LIMIT 1',
1554
		array(
1555
			'current_topic' => $topic,
1556
			'boards_allowed_see' => $boardsAllowed,
1557
			'is_approved' => 1,
1558
		)
1559
	);
1560
1561
	// Either this topic has no poll, or the user cannot view it.
1562
	if ($smcFunc['db_num_rows']($request) == 0)
1563
		return array();
1564
1565
	$row = $smcFunc['db_fetch_assoc']($request);
1566
	$smcFunc['db_free_result']($request);
1567
1568
	// Check if they can vote.
1569
	$already_voted = false;
1570
	if (!empty($row['expire_time']) && $row['expire_time'] < time())
1571
		$allow_vote = false;
1572
	elseif ($user_info['is_guest'])
1573
	{
1574
		// There's a difference between "allowed to vote" and "already voted"...
1575
		$allow_vote = $row['guest_vote'];
1576
1577
		// Did you already vote?
1578
		if (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1579
		{
1580
			$already_voted = true;
1581
		}
1582
	}
1583
	elseif (!empty($row['voting_locked']) || !allowedTo('poll_vote', $row['id_board']))
1584
		$allow_vote = false;
1585
	else
1586
	{
1587
		$request = $smcFunc['db_query']('', '
1588
			SELECT id_member
1589
			FROM {db_prefix}log_polls
1590
			WHERE id_poll = {int:current_poll}
1591
				AND id_member = {int:current_member}
1592
			LIMIT 1',
1593
			array(
1594
				'current_member' => $user_info['id'],
1595
				'current_poll' => $row['id_poll'],
1596
			)
1597
		);
1598
		$allow_vote = $smcFunc['db_num_rows']($request) == 0;
1599
		$already_voted = $allow_vote;
1600
		$smcFunc['db_free_result']($request);
1601
	}
1602
1603
	// Can they view?
1604
	$is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
1605
	$allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || ($row['hide_results'] == 1 && $already_voted) || $is_expired;
1606
1607
	$request = $smcFunc['db_query']('', '
1608
		SELECT COUNT(DISTINCT id_member)
1609
		FROM {db_prefix}log_polls
1610
		WHERE id_poll = {int:current_poll}',
1611
		array(
1612
			'current_poll' => $row['id_poll'],
1613
		)
1614
	);
1615
	list ($total) = $smcFunc['db_fetch_row']($request);
1616
	$smcFunc['db_free_result']($request);
1617
1618
	$request = $smcFunc['db_query']('', '
1619
		SELECT id_choice, label, votes
1620
		FROM {db_prefix}poll_choices
1621
		WHERE id_poll = {int:current_poll}',
1622
		array(
1623
			'current_poll' => $row['id_poll'],
1624
		)
1625
	);
1626
	$sOptions = array();
1627
	$total_votes = 0;
1628
	while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
1629
	{
1630
		censorText($rowChoice['label']);
1631
1632
		$sOptions[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
1633
		$total_votes += $rowChoice['votes'];
1634
	}
1635
	$smcFunc['db_free_result']($request);
1636
1637
	$return = array(
1638
		'id' => $row['id_poll'],
1639
		'image' => empty($row['voting_locked']) ? 'poll' : 'locked_poll',
1640
		'question' => $row['question'],
1641
		'total_votes' => $total,
1642
		'is_locked' => !empty($row['voting_locked']),
1643
		'allow_vote' => $allow_vote,
1644
		'allow_view_results' => $allow_view_results,
1645
		'topic' => $topic
1646
	);
1647
1648
	// Calculate the percentages and bar lengths...
1649
	$divisor = $total_votes == 0 ? 1 : $total_votes;
0 ignored issues
show
The condition $total_votes == 0 is always true.
Loading history...
1650
	foreach ($sOptions as $i => $option)
1651
	{
1652
		$bar = floor(($option[1] * 100) / $divisor);
1653
		$return['options'][$i] = array(
1654
			'id' => 'options-' . $i,
1655
			'percent' => $bar,
1656
			'votes' => $option[1],
1657
			'option' => parse_bbc($option[0]),
1658
			'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '">'
1659
		);
1660
	}
1661
1662
	$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options_limit'], min(count($sOptions), $row['max_votes'])) : '';
1663
1664
	// If mods want to do somthing with this poll, let them do that now.
1665
	call_integration_hook('integrate_ssi_showPoll', array(&$return));
1666
1667
	if ($output_method != 'echo')
1668
		return $return;
1669
1670
	if ($return['allow_vote'])
1671
	{
1672
		echo '
1673
			<form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
1674
				<strong>', $return['question'], '</strong><br>
1675
				', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br>' : '';
1676
1677
		foreach ($return['options'] as $option)
1678
			echo '
1679
				<label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br>';
1680
1681
		echo '
1682
				<input type="submit" value="', $txt['poll_vote'], '" class="button">
1683
				<input type="hidden" name="poll" value="', $return['id'], '">
1684
				<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
1685
			</form>';
1686
	}
1687
	else
1688
	{
1689
		echo '
1690
			<div class="ssi_poll">
1691
				<strong>', $return['question'], '</strong>
1692
				<dl>';
1693
1694
		foreach ($return['options'] as $option)
1695
		{
1696
			echo '
1697
					<dt>', $option['option'], '</dt>
1698
					<dd>';
1699
1700
			if ($return['allow_view_results'])
1701
			{
1702
				echo '
1703
						<div class="ssi_poll_bar" style="border: 1px solid #666; height: 1em">
1704
							<div class="ssi_poll_bar_fill" style="background: #ccf; height: 1em; width: ', $option['percent'], '%;">
1705
							</div>
1706
						</div>
1707
						', $option['votes'], ' (', $option['percent'], '%)';
1708
			}
1709
1710
			echo '
1711
					</dd>';
1712
		}
1713
1714
		echo '
1715
				</dl>', ($return['allow_view_results'] ? '
1716
				<strong>' . $txt['poll_total_voters'] . ': ' . $return['total_votes'] . '</strong>' : ''), '
1717
			</div>';
1718
	}
1719
}
1720
1721
/**
1722
 * Handles voting in a poll (done automatically)
1723
 */
1724
function ssi_pollVote()
1725
{
1726
	global $context, $db_prefix, $user_info, $sc, $smcFunc, $sourcedir, $modSettings;
1727
1728
	if (!isset($_POST[$context['session_var']]) || $_POST[$context['session_var']] != $sc || empty($_POST['options']) || !isset($_POST['poll']))
1729
	{
1730
		echo '<!DOCTYPE html>
1731
<html>
1732
<head>
1733
	<script>
1734
		history.go(-1);
1735
	</script>
1736
</head>
1737
<body>&laquo;</body>
1738
</html>';
1739
		return;
1740
	}
1741
1742
	// This can cause weird errors! (ie. copyright missing.)
1743
	checkSession();
1744
1745
	$_POST['poll'] = (int) $_POST['poll'];
1746
1747
	// Check if they have already voted, or voting is locked.
1748
	$request = $smcFunc['db_query']('', '
1749
		SELECT
1750
			p.id_poll, p.voting_locked, p.expire_time, p.max_votes, p.guest_vote,
1751
			t.id_topic,
1752
			COALESCE(lp.id_choice, -1) AS selected
1753
		FROM {db_prefix}polls AS p
1754
			INNER JOIN {db_prefix}topics AS t ON (t.id_poll = {int:current_poll})
1755
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1756
			LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_poll = p.id_poll AND lp.id_member = {int:current_member})
1757
		WHERE p.id_poll = {int:current_poll}
1758
			AND {query_see_board}' . ($modSettings['postmod_active'] ? '
1759
			AND t.approved = {int:is_approved}' : '') . '
1760
		LIMIT 1',
1761
		array(
1762
			'current_member' => $user_info['id'],
1763
			'current_poll' => $_POST['poll'],
1764
			'is_approved' => 1,
1765
		)
1766
	);
1767
	if ($smcFunc['db_num_rows']($request) == 0)
1768
		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...
1769
	$row = $smcFunc['db_fetch_assoc']($request);
1770
	$smcFunc['db_free_result']($request);
1771
1772
	if (!empty($row['voting_locked']) || ($row['selected'] != -1 && !$user_info['is_guest']) || (!empty($row['expire_time']) && time() > $row['expire_time']))
1773
		redirectexit('topic=' . $row['id_topic'] . '.0');
1774
1775
	// Too many options checked?
1776
	if (count($_REQUEST['options']) > $row['max_votes'])
1777
		redirectexit('topic=' . $row['id_topic'] . '.0');
1778
1779
	// It's a guest who has already voted?
1780
	if ($user_info['is_guest'])
1781
	{
1782
		// Guest voting disabled?
1783
		if (!$row['guest_vote'])
1784
			redirectexit('topic=' . $row['id_topic'] . '.0');
1785
		// Already voted?
1786
		elseif (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1787
			redirectexit('topic=' . $row['id_topic'] . '.0');
1788
	}
1789
1790
	$sOptions = array();
1791
	$inserts = array();
1792
	foreach ($_REQUEST['options'] as $id)
1793
	{
1794
		$id = (int) $id;
1795
1796
		$sOptions[] = $id;
1797
		$inserts[] = array($_POST['poll'], $user_info['id'], $id);
1798
	}
1799
1800
	// Add their vote in to the tally.
1801
	$smcFunc['db_insert']('insert',
1802
		$db_prefix . 'log_polls',
1803
		array('id_poll' => 'int', 'id_member' => 'int', 'id_choice' => 'int'),
1804
		$inserts,
1805
		array('id_poll', 'id_member', 'id_choice')
1806
	);
1807
	$smcFunc['db_query']('', '
1808
		UPDATE {db_prefix}poll_choices
1809
		SET votes = votes + 1
1810
		WHERE id_poll = {int:current_poll}
1811
			AND id_choice IN ({array_int:option_list})',
1812
		array(
1813
			'option_list' => $sOptions,
1814
			'current_poll' => $_POST['poll'],
1815
		)
1816
	);
1817
1818
	// Track the vote if a guest.
1819
	if ($user_info['is_guest'])
1820
	{
1821
		$_COOKIE['guest_poll_vote'] = !empty($_COOKIE['guest_poll_vote']) ? ($_COOKIE['guest_poll_vote'] . ',' . $row['id_poll']) : $row['id_poll'];
1822
1823
		require_once($sourcedir . '/Subs-Auth.php');
1824
		$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
1825
		smf_setcookie('guest_poll_vote', $_COOKIE['guest_poll_vote'], time() + 2500000, $cookie_url[1], $cookie_url[0], false, false);
1826
	}
1827
1828
	redirectexit('topic=' . $row['id_topic'] . '.0');
1829
}
1830
1831
// Show a search box.
1832
/**
1833
 * Shows a search box
1834
 *
1835
 * @param string $output_method The output method. If 'echo', displays a search box, otherwise returns the URL of the search page.
1836
 * @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.
1837
 */
1838
function ssi_quickSearch($output_method = 'echo')
1839
{
1840
	global $scripturl, $txt, $context;
1841
1842
	if (!allowedTo('search_posts'))
1843
		return;
1844
1845
	if ($output_method != 'echo')
1846
		return $scripturl . '?action=search';
1847
1848
	echo '
1849
		<form action="', $scripturl, '?action=search2" method="post" accept-charset="', $context['character_set'], '">
1850
			<input type="hidden" name="advanced" value="0"><input type="text" name="ssi_search" size="30"> <input type="submit" value="', $txt['search'], '" class="button">
1851
		</form>';
1852
}
1853
1854
/**
1855
 * Show a random forum news item
1856
 *
1857
 * @param string $output_method The output method. If 'echo', shows the news item, otherwise returns it.
1858
 * @return void|string Shows or returns a random forum news item, depending on output_method.
1859
 */
1860
function ssi_news($output_method = 'echo')
1861
{
1862
	global $context;
1863
1864
	$context['random_news_line'] = !empty($context['news_lines']) ? $context['news_lines'][mt_rand(0, count($context['news_lines']) - 1)] : '';
1865
1866
	// 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.
1867
	call_integration_hook('integrate_ssi_news');
1868
1869
	if ($output_method != 'echo')
1870
		return $context['random_news_line'];
1871
1872
	echo $context['random_news_line'];
1873
}
1874
1875
/**
1876
 * Show today's birthdays.
1877
 *
1878
 * @param string $output_method The output method. If 'echo', displays a list of users, otherwise returns an array of info about them.
1879
 * @return void|array Displays a list of users or returns an array of info about them depending on output_method.
1880
 */
1881
function ssi_todaysBirthdays($output_method = 'echo')
1882
{
1883
	global $scripturl, $modSettings, $user_info;
1884
1885
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view') || !allowedTo('profile_view'))
1886
		return;
1887
1888
	$eventOptions = array(
1889
		'include_birthdays' => true,
1890
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1891
	);
1892
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1893
1894
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1895
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1896
1897
	if ($output_method != 'echo')
1898
		return $return['calendar_birthdays'];
1899
1900
	foreach ($return['calendar_birthdays'] as $member)
1901
		echo '
1902
			<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'] ? ', ' : '');
1903
}
1904
1905
/**
1906
 * Shows today's holidays.
1907
 *
1908
 * @param string $output_method The output method. If 'echo', displays a list of holidays, otherwise returns an array of info about them.
1909
 * @return void|array Displays a list of holidays or returns an array of info about them depending on output_method
1910
 */
1911
function ssi_todaysHolidays($output_method = 'echo')
1912
{
1913
	global $modSettings, $user_info;
1914
1915
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1916
		return;
1917
1918
	$eventOptions = array(
1919
		'include_holidays' => true,
1920
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1921
	);
1922
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1923
1924
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1925
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1926
1927
	if ($output_method != 'echo')
1928
		return $return['calendar_holidays'];
1929
1930
	echo '
1931
		', implode(', ', $return['calendar_holidays']);
1932
}
1933
1934
/**
1935
 * Shows today's events.
1936
 *
1937
 * @param string $output_method The output method. If 'echo', displays a list of events, otherwise returns an array of info about them.
1938
 * @return void|array Displays a list of events or returns an array of info about them depending on output_method
1939
 */
1940
function ssi_todaysEvents($output_method = 'echo')
1941
{
1942
	global $modSettings, $user_info;
1943
1944
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1945
		return;
1946
1947
	$eventOptions = array(
1948
		'include_events' => true,
1949
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1950
	);
1951
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1952
1953
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1954
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1955
1956
	if ($output_method != 'echo')
1957
		return $return['calendar_events'];
1958
1959
	foreach ($return['calendar_events'] as $event)
1960
	{
1961
		if ($event['can_edit'])
1962
			echo '
1963
	<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
1964
		echo '
1965
	' . $event['link'] . (!$event['is_last'] ? ', ' : '');
1966
	}
1967
}
1968
1969
/**
1970
 * Shows today's calendar items (events, birthdays and holidays)
1971
 *
1972
 * @param string $output_method The output method. If 'echo', displays a list of calendar items, otherwise returns an array of info about them.
1973
 * @return void|array Displays a list of calendar items or returns an array of info about them depending on output_method
1974
 */
1975
function ssi_todaysCalendar($output_method = 'echo')
1976
{
1977
	global $modSettings, $txt, $scripturl, $user_info;
1978
1979
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1980
		return;
1981
1982
	$eventOptions = array(
1983
		'include_birthdays' => allowedTo('profile_view'),
1984
		'include_holidays' => true,
1985
		'include_events' => true,
1986
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1987
	);
1988
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1989
1990
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1991
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1992
1993
	if ($output_method != 'echo')
1994
		return $return;
1995
1996
	if (!empty($return['calendar_holidays']))
1997
		echo '
1998
			<span class="holiday">' . $txt['calendar_prompt'] . ' ' . implode(', ', $return['calendar_holidays']) . '<br></span>';
1999
	if (!empty($return['calendar_birthdays']))
2000
	{
2001
		echo '
2002
			<span class="birthday">' . $txt['birthdays_upcoming'] . '</span> ';
2003
		foreach ($return['calendar_birthdays'] as $member)
2004
			echo '
2005
			<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'] ? ', ' : '';
2006
		echo '
2007
			<br>';
2008
	}
2009
	if (!empty($return['calendar_events']))
2010
	{
2011
		echo '
2012
			<span class="event">' . $txt['events_upcoming'] . '</span> ';
2013
		foreach ($return['calendar_events'] as $event)
2014
		{
2015
			if ($event['can_edit'])
2016
				echo '
2017
			<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
2018
			echo '
2019
			' . $event['link'] . (!$event['is_last'] ? ', ' : '');
2020
		}
2021
	}
2022
}
2023
2024
/**
2025
 * Show the latest news, with a template... by board.
2026
 *
2027
 * @param null|int $board The ID of the board to get the info from. Defaults to $board or $_GET['board'] if not set.
2028
 * @param null|int $limit How many items to show. Defaults to $_GET['limit'] or 5 if not set.
2029
 * @param null|int $start Start with the specified item. Defaults to $_GET['start'] or 0 if not set.
2030
 * @param null|int $length How many characters to show from each post. Defaults to $_GET['length'] or 0 (no limit) if not set.
2031
 * @param string $output_method The output method. If 'echo', displays the news items, otherwise returns an array of info about them.
2032
 * @return void|array Displays the news items or returns an array of info about them, depending on output_method.
2033
 */
2034
function ssi_boardNews($board = null, $limit = null, $start = null, $length = null, $output_method = 'echo')
2035
{
2036
	global $scripturl, $txt, $settings, $modSettings, $context;
2037
	global $smcFunc;
2038
2039
	loadLanguage('Stats');
2040
2041
	// Must be integers....
2042
	if ($limit === null)
2043
		$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 5;
2044
	else
2045
		$limit = (int) $limit;
2046
2047
	if ($start === null)
2048
		$start = isset($_GET['start']) ? (int) $_GET['start'] : 0;
2049
	else
2050
		$start = (int) $start;
2051
2052
	if ($board !== null)
2053
		$board = (int) $board;
2054
	elseif (isset($_GET['board']))
2055
		$board = (int) $_GET['board'];
2056
2057
	if ($length === null)
2058
		$length = isset($_GET['length']) ? (int) $_GET['length'] : 0;
2059
	else
2060
		$length = (int) $length;
2061
2062
	$limit = max(0, $limit);
2063
	$start = max(0, $start);
2064
2065
	// Make sure guests can see this board.
2066
	$request = $smcFunc['db_query']('', '
2067
		SELECT id_board
2068
		FROM {db_prefix}boards
2069
		WHERE ' . ($board === null ? '' : 'id_board = {int:current_board}
2070
			AND ') . 'FIND_IN_SET(-1, member_groups) != 0
2071
		LIMIT 1',
2072
		array(
2073
			'current_board' => $board,
2074
		)
2075
	);
2076
	if ($smcFunc['db_num_rows']($request) == 0)
2077
	{
2078
		if ($output_method == 'echo')
2079
			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...
2080
		else
2081
			return array();
2082
	}
2083
	list ($board) = $smcFunc['db_fetch_row']($request);
2084
	$smcFunc['db_free_result']($request);
2085
2086
	$icon_sources = array();
2087
	foreach ($context['stable_icons'] as $icon)
2088
		$icon_sources[$icon] = 'images_url';
2089
2090
	if (!empty($modSettings['enable_likes']))
2091
	{
2092
		$context['can_like'] = allowedTo('likes_like');
2093
	}
2094
2095
	// Find the post ids.
2096
	$request = $smcFunc['db_query']('', '
2097
		SELECT t.id_first_msg
2098
		FROM {db_prefix}topics as t
2099
			LEFT JOIN {db_prefix}boards as b ON (b.id_board = t.id_board)
2100
		WHERE t.id_board = {int:current_board}' . ($modSettings['postmod_active'] ? '
2101
			AND t.approved = {int:is_approved}' : '') . '
2102
			AND {query_see_board}
2103
		ORDER BY t.id_first_msg DESC
2104
		LIMIT ' . $start . ', ' . $limit,
2105
		array(
2106
			'current_board' => $board,
2107
			'is_approved' => 1,
2108
		)
2109
	);
2110
	$posts = array();
2111
	while ($row = $smcFunc['db_fetch_assoc']($request))
2112
		$posts[] = $row['id_first_msg'];
2113
	$smcFunc['db_free_result']($request);
2114
2115
	if (empty($posts))
2116
		return array();
2117
2118
	// Find the posts.
2119
	$request = $smcFunc['db_query']('', '
2120
		SELECT
2121
			m.icon, m.subject, m.body, COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.likes,
2122
			t.num_replies, t.id_topic, m.id_member, m.smileys_enabled, m.id_msg, t.locked, t.id_last_msg, m.id_board
2123
		FROM {db_prefix}topics AS t
2124
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
2125
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
2126
		WHERE t.id_first_msg IN ({array_int:post_list})
2127
		ORDER BY t.id_first_msg DESC
2128
		LIMIT ' . count($posts),
2129
		array(
2130
			'post_list' => $posts,
2131
		)
2132
	);
2133
	$return = array();
2134
	$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
2135
	while ($row = $smcFunc['db_fetch_assoc']($request))
2136
	{
2137
		// If we want to limit the length of the post.
2138
		if (!empty($length) && $smcFunc['strlen']($row['body']) > $length)
2139
		{
2140
			$row['body'] = $smcFunc['substr']($row['body'], 0, $length);
2141
			$cutoff = false;
2142
2143
			$last_space = strrpos($row['body'], ' ');
2144
			$last_open = strrpos($row['body'], '<');
2145
			$last_close = strrpos($row['body'], '>');
2146
			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)
2147
				$cutoff = $last_open;
2148
			elseif (empty($last_close) || $last_close < $last_open)
2149
				$cutoff = $last_space;
2150
2151
			if ($cutoff !== false)
2152
				$row['body'] = $smcFunc['substr']($row['body'], 0, $cutoff);
2153
			$row['body'] .= '...';
2154
		}
2155
2156
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
2157
2158
		if (!empty($recycle_board) && $row['id_board'] == $recycle_board)
2159
			$row['icon'] = 'recycled';
2160
2161
		// Check that this message icon is there...
2162
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
2163
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
2164
		elseif (!isset($icon_sources[$row['icon']]))
2165
			$icon_sources[$row['icon']] = 'images_url';
2166
2167
		censorText($row['subject']);
2168
		censorText($row['body']);
2169
2170
		$return[] = array(
2171
			'id' => $row['id_topic'],
2172
			'message_id' => $row['id_msg'],
2173
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" alt="' . $row['icon'] . '">',
2174
			'subject' => $row['subject'],
2175
			'time' => timeformat($row['poster_time']),
2176
			'timestamp' => forum_time(true, $row['poster_time']),
2177
			'body' => $row['body'],
2178
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
2179
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['num_replies'] . ' ' . ($row['num_replies'] == 1 ? $txt['ssi_comment'] : $txt['ssi_comments']) . '</a>',
2180
			'replies' => $row['num_replies'],
2181
			'comment_href' => !empty($row['locked']) ? '' : $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . ';last_msg=' . $row['id_last_msg'],
2182
			'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>',
2183
			'new_comment' => !empty($row['locked']) ? '' : '<a href="' . $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . '">' . $txt['ssi_write_comment'] . '</a>',
2184
			'poster' => array(
2185
				'id' => $row['id_member'],
2186
				'name' => $row['poster_name'],
2187
				'href' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
2188
				'link' => !empty($row['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>' : $row['poster_name']
2189
			),
2190
			'locked' => !empty($row['locked']),
2191
			'is_last' => false,
2192
			// Nasty ternary for likes not messing around the "is_last" check.
2193
			'likes' => !empty($modSettings['enable_likes']) ? array(
2194
				'count' => $row['likes'],
2195
				'you' => in_array($row['id_msg'], prepareLikesContext((int) $row['id_topic'])),
2196
				'can_like' => !$context['user']['is_guest'] && $row['id_member'] != $context['user']['id'] && !empty($context['can_like']),
2197
			) : array(),
2198
		);
2199
	}
2200
	$smcFunc['db_free_result']($request);
2201
2202
	if (empty($return))
2203
		return $return;
2204
2205
	$return[count($return) - 1]['is_last'] = true;
2206
2207
	// If mods want to do somthing with this list of posts, let them do that now.
2208
	call_integration_hook('integrate_ssi_boardNews', array(&$return));
2209
2210
	if ($output_method != 'echo')
2211
		return $return;
2212
2213
	foreach ($return as $news)
2214
	{
2215
		echo '
2216
			<div class="news_item">
2217
				<h3 class="news_header">
2218
					', $news['icon'], '
2219
					<a href="', $news['href'], '">', $news['subject'], '</a>
2220
				</h3>
2221
				<div class="news_timestamp">', $news['time'], ' ', $txt['by'], ' ', $news['poster']['link'], '</div>
2222
				<div class="news_body" style="padding: 2ex 0;">', $news['body'], '</div>
2223
				', $news['link'], $news['locked'] ? '' : ' | ' . $news['comment_link'], '';
2224
2225
		// Is there any likes to show?
2226
		if (!empty($modSettings['enable_likes']))
2227
		{
2228
			echo '
2229
					<ul>';
2230
2231
			if (!empty($news['likes']['can_like']))
2232
			{
2233
				echo '
2234
						<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>';
2235
			}
2236
2237
			if (!empty($news['likes']['count']))
2238
			{
2239
				$context['some_likes'] = true;
2240
				$count = $news['likes']['count'];
2241
				$base = 'likes_';
2242
				if ($news['likes']['you'])
2243
				{
2244
					$base = 'you_' . $base;
2245
					$count--;
2246
				}
2247
				$base .= (isset($txt[$base . $count])) ? $count : 'n';
2248
2249
				echo '
2250
						<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>';
2251
			}
2252
2253
			echo '
2254
					</ul>';
2255
		}
2256
2257
		// Close the main div.
2258
		echo '
2259
			</div>';
2260
2261
		if (!$news['is_last'])
2262
			echo '
2263
			<hr>';
2264
	}
2265
}
2266
2267
/**
2268
 * Show the most recent events
2269
 *
2270
 * @param int $max_events The maximum number of events to show
2271
 * @param string $output_method The output method. If 'echo', displays the events, otherwise returns an array of info about them.
2272
 * @return void|array Displays the events or returns an array of info about them, depending on output_method.
2273
 */
2274
function ssi_recentEvents($max_events = 7, $output_method = 'echo')
2275
{
2276
	global $user_info, $scripturl, $modSettings, $txt, $context, $smcFunc;
2277
2278
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
2279
		return;
2280
2281
	// Find all events which are happening in the near future that the member can see.
2282
	$request = $smcFunc['db_query']('', '
2283
		SELECT
2284
			cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
2285
			cal.start_time, cal.end_time, cal.timezone, cal.location,
2286
			cal.id_board, t.id_first_msg, t.approved
2287
		FROM {db_prefix}calendar AS cal
2288
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
2289
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
2290
		WHERE cal.start_date <= {date:current_date}
2291
			AND cal.end_date >= {date:current_date}
2292
			AND (cal.id_board = {int:no_board} OR {query_wanna_see_board})
2293
		ORDER BY cal.start_date DESC
2294
		LIMIT ' . $max_events,
2295
		array(
2296
			'current_date' => strftime('%Y-%m-%d', forum_time(false)),
2297
			'no_board' => 0,
2298
		)
2299
	);
2300
	$return = array();
2301
	$duplicates = array();
2302
	while ($row = $smcFunc['db_fetch_assoc']($request))
2303
	{
2304
		// 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.
2305
		if (!empty($duplicates[$row['title'] . $row['id_topic']]))
2306
			continue;
2307
2308
		// Censor the title.
2309
		censorText($row['title']);
2310
2311
		if ($row['start_date'] < strftime('%Y-%m-%d', forum_time(false)))
2312
			$date = strftime('%Y-%m-%d', forum_time(false));
2313
		else
2314
			$date = $row['start_date'];
2315
2316
		// If the topic it is attached to is not approved then don't link it.
2317
		if (!empty($row['id_first_msg']) && !$row['approved'])
2318
			$row['id_board'] = $row['id_topic'] = $row['id_first_msg'] = 0;
2319
2320
		$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
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...
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

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