Issues (1061)

1
<?php
2
3
/**
4
 * Simple Machines Forum (SMF)
5
 *
6
 * @package SMF
7
 * @author Simple Machines https://www.simplemachines.org
8
 * @copyright 2020 Simple Machines and individual contributors
9
 * @license https://www.simplemachines.org/about/smf/license.php BSD
10
 *
11
 * @version 2.1 RC2
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 RC2');
20
define('SMF_FULL_VERSION', 'SMF ' . SMF_VERSION);
21
define('SMF_SOFTWARE_YEAR', '2020');
22
define('JQUERY_VERSION', '3.4.1');
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
28
// We're going to want a few globals... these are all set later.
29
global $maintenance, $msubject, $mmessage, $mbname, $language;
30
global $boardurl, $boarddir, $sourcedir, $webmaster_email, $cookiename;
31
global $db_type, $db_server, $db_name, $db_user, $db_prefix, $db_persist, $db_error_send, $db_last_error, $db_show_debug;
32
global $db_connection, $db_port, $modSettings, $context, $sc, $user_info, $topic, $board, $txt;
33
global $smcFunc, $ssi_db_user, $scripturl, $ssi_db_passwd, $db_passwd, $cache_enable, $cachedir;
34
global $auth_secret;
35
36
if (!defined('TIME_START'))
37
	define('TIME_START', microtime(true));
38
39
// Just being safe...
40
foreach (array('db_character_set', 'cachedir') as $variable)
41
	unset($GLOBALS[$variable]);
42
43
// Get the forum's settings for database and file paths.
44
require_once(dirname(__FILE__) . '/Settings.php');
45
46
// Make absolutely sure the cache directory is defined and writable.
47
if (empty($cachedir) || !is_dir($cachedir) || !is_writable($cachedir))
48
{
49
	if (is_dir($boarddir . '/cache') && is_writable($boarddir . '/cache'))
50
		$cachedir = $boarddir . '/cache';
51
	else
52
	{
53
		$cachedir = sys_get_temp_dir() . '/smf_cache_' . md5($boarddir);
54
		@mkdir($cachedir, 0750);
55
	}
56
}
57
58
$ssi_error_reporting = error_reporting(!empty($db_show_debug) ? E_ALL : E_ALL & ~E_DEPRECATED);
59
/* Set this to one of three values depending on what you want to happen in the case of a fatal error.
60
	false:	Default, will just load the error sub template and die - not putting any theme layers around it.
61
	true:	Will load the error sub template AND put the SMF layers around it (Not useful if on total custom pages).
62
	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.
63
*/
64
$ssi_on_error_method = false;
65
66
// Don't do john didley if the forum's been shut down completely.
67
if ($maintenance == 2 && (!isset($ssi_maintenance_off) || $ssi_maintenance_off !== true))
68
	die($mmessage);
69
70
// Fix for using the current directory as a path.
71
if (substr($sourcedir, 0, 1) == '.' && substr($sourcedir, 1, 1) != '.')
72
	$sourcedir = dirname(__FILE__) . substr($sourcedir, 1);
73
74
// Load the important includes.
75
require_once($sourcedir . '/QueryString.php');
76
require_once($sourcedir . '/Session.php');
77
require_once($sourcedir . '/Subs.php');
78
require_once($sourcedir . '/Errors.php');
79
require_once($sourcedir . '/Logging.php');
80
require_once($sourcedir . '/Load.php');
81
require_once($sourcedir . '/Security.php');
82
require_once($sourcedir . '/Class-BrowserDetect.php');
83
require_once($sourcedir . '/Subs-Auth.php');
84
85
// Create a variable to store some SMF specific functions in.
86
$smcFunc = array();
87
88
// Initiate the database connection and define some database functions to use.
89
loadDatabase();
90
91
// Load installed 'Mods' settings.
92
reloadSettings();
93
// Clean the request variables.
94
cleanRequest();
95
96
// Seed the random generator?
97
if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69)
98
	smf_seed_generator();
99
100
// Check on any hacking attempts.
101
if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']))
102
	die('No direct access...');
103
elseif (isset($_REQUEST['ssi_theme']) && (int) $_REQUEST['ssi_theme'] == (int) $ssi_theme)
104
	die('No direct access...');
105
elseif (isset($_COOKIE['ssi_theme']) && (int) $_COOKIE['ssi_theme'] == (int) $ssi_theme)
106
	die('No direct access...');
107
elseif (isset($_REQUEST['ssi_layers'], $ssi_layers) && (@get_magic_quotes_gpc() ? stripslashes($_REQUEST['ssi_layers']) : $_REQUEST['ssi_layers']) == $ssi_layers)
108
	die('No direct access...');
109
if (isset($_REQUEST['context']))
110
	die('No direct access...');
111
112
// Gzip output? (because it must be boolean and true, this can't be hacked.)
113
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', '>='))
114
	ob_start('ob_gzhandler');
115
else
116
	$modSettings['enableCompressedOutput'] = '0';
117
118
/**
119
 * An autoloader for certain classes.
120
 *
121
 * @param string $class The fully-qualified class name.
122
 */
123
spl_autoload_register(function($class) use ($sourcedir)
124
{
125
	$classMap = array(
126
		'ReCaptcha\\' => 'ReCaptcha/',
127
		'MatthiasMullie\\Minify\\' => 'minify/src/',
128
		'MatthiasMullie\\PathConverter\\' => 'minify/path-converter/src/',
129
	);
130
131
	// Do any third-party scripts want in on the fun?
132
	call_integration_hook('integrate_autoload', array(&$classMap));
133
134
	foreach ($classMap as $prefix => $dirName)
135
	{
136
		// does the class use the namespace prefix?
137
		$len = strlen($prefix);
138
		if (strncmp($prefix, $class, $len) !== 0)
139
		{
140
			continue;
141
		}
142
143
		// get the relative class name
144
		$relativeClass = substr($class, $len);
145
146
		// replace the namespace prefix with the base directory, replace namespace
147
		// separators with directory separators in the relative class name, append
148
		// with .php
149
		$fileName = $dirName . strtr($relativeClass, '\\', '/') . '.php';
150
151
		// if the file exists, require it
152
		if (file_exists($fileName = $sourcedir . '/' . $fileName))
153
		{
154
			require_once $fileName;
155
156
			return;
157
		}
158
	}
159
});
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;
317
318
	if ($output_method == 'echo')
319
		printf($forum_copyright, SMF_FULL_VERSION, SMF_SOFTWARE_YEAR);
320
	else
321
		return sprintf($forum_copyright, SMF_FULL_VERSION, SMF_SOFTWARE_YEAR);
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'], $txt['guest_title'], $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));
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);
413
	}
414
	elseif ($include_boards != null)
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);
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);
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));
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);
618
	}
619
	elseif ($include_boards != null)
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));
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);
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['membergroups']))
1294
		echo '<br>
1295
			[' . implode(']&nbsp;&nbsp;[', $return['membergroups']) . ']';
1296
}
1297
1298
/**
1299
 * Just like whosOnline except it also logs the online presence.
1300
 *
1301
 * @param string $output_method The output method. If 'echo', displays a list, otherwise returns an array of info about the online users.
1302
 * @return void|array Either displays a list of online users or returns an aray of info about them, depending on output_method.
1303
 */
1304
function ssi_logOnline($output_method = 'echo')
1305
{
1306
	writeLog();
1307
1308
	if ($output_method != 'echo')
1309
		return ssi_whosOnline($output_method);
1310
	else
1311
		ssi_whosOnline($output_method);
1312
}
1313
1314
// Shows a login box.
1315
/**
1316
 * Shows a login box
1317
 *
1318
 * @param string $redirect_to The URL to redirect the user to after they login
1319
 * @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
1320
 * @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.
1321
 */
1322
function ssi_login($redirect_to = '', $output_method = 'echo')
1323
{
1324
	global $scripturl, $txt, $user_info, $context;
1325
1326
	if ($redirect_to != '')
1327
		$_SESSION['login_url'] = $redirect_to;
1328
1329
	if ($output_method != 'echo' || !$user_info['is_guest'])
1330
		return $user_info['is_guest'];
1331
1332
	// Create a login token
1333
	createToken('login');
1334
1335
	echo '
1336
		<form action="', $scripturl, '?action=login2" method="post" accept-charset="', $context['character_set'], '">
1337
			<table style="border: none" class="ssi_table">
1338
				<tr>
1339
					<td style="text-align: right; border-spacing: 1"><label for="user">', $txt['username'], ':</label>&nbsp;</td>
1340
					<td><input type="text" id="user" name="user" size="9" value="', $user_info['username'], '"></td>
1341
				</tr><tr>
1342
					<td style="text-align: right; border-spacing: 1"><label for="passwrd">', $txt['password'], ':</label>&nbsp;</td>
1343
					<td><input type="password" name="passwrd" id="passwrd" size="9"></td>
1344
				</tr>
1345
				<tr>
1346
					<td>
1347
						<input type="hidden" name="cookielength" value="-1">
1348
						<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
1349
						<input type="hidden" name="', $context['login_token_var'], '" value="', $context['login_token'], '">
1350
					</td>
1351
					<td><input type="submit" value="', $txt['login'], '" class="button"></td>
1352
				</tr>
1353
			</table>
1354
		</form>';
1355
1356
}
1357
1358
/**
1359
 * Show the top poll based on votes
1360
 *
1361
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it
1362
 * @return void|array Either shows the top poll or returns an array of info about it, depending on output_method.
1363
 */
1364
function ssi_topPoll($output_method = 'echo')
1365
{
1366
	// Just use recentPoll, no need to duplicate code...
1367
	return ssi_recentPoll(true, $output_method);
1368
}
1369
1370
// Show the most recently posted poll.
1371
/**
1372
 * Shows the most recent poll
1373
 *
1374
 * @param bool $topPollInstead Whether to show the top poll (based on votes) instead of the most recent one
1375
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it.
1376
 * @return void|array Either shows the poll or returns an array of info about it, depending on output_method.
1377
 */
1378
function ssi_recentPoll($topPollInstead = false, $output_method = 'echo')
1379
{
1380
	global $txt, $boardurl, $user_info, $context, $smcFunc, $modSettings;
1381
1382
	$boardsAllowed = array_intersect(boardsAllowedTo('poll_view'), boardsAllowedTo('poll_vote'));
1383
1384
	if (empty($boardsAllowed))
1385
		return array();
1386
1387
	$request = $smcFunc['db_query']('', '
1388
		SELECT p.id_poll, p.question, t.id_topic, p.max_votes, p.guest_vote, p.hide_results, p.expire_time
1389
		FROM {db_prefix}polls AS p
1390
			INNER JOIN {db_prefix}topics AS t ON (t.id_poll = p.id_poll' . ($modSettings['postmod_active'] ? ' AND t.approved = {int:is_approved}' : '') . ')
1391
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)' . ($topPollInstead ? '
1392
			INNER JOIN {db_prefix}poll_choices AS pc ON (pc.id_poll = p.id_poll)' : '') . '
1393
			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})
1394
		WHERE p.voting_locked = {int:voting_opened}
1395
			AND (p.expire_time = {int:no_expiration} OR {int:current_time} < p.expire_time)
1396
			AND ' . ($user_info['is_guest'] ? 'p.guest_vote = {int:guest_vote_allowed}' : 'lp.id_choice IS NULL') . '
1397
			AND {query_wanna_see_board}' . (!in_array(0, $boardsAllowed) ? '
1398
			AND b.id_board IN ({array_int:boards_allowed_list})' : '') . (!empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? '
1399
			AND b.id_board != {int:recycle_board}' : '') . '
1400
		ORDER BY ' . ($topPollInstead ? 'pc.votes' : 'p.id_poll') . ' DESC
1401
		LIMIT 1',
1402
		array(
1403
			'current_member' => $user_info['id'],
1404
			'boards_allowed_list' => $boardsAllowed,
1405
			'is_approved' => 1,
1406
			'guest_vote_allowed' => 1,
1407
			'no_member' => 0,
1408
			'voting_opened' => 0,
1409
			'no_expiration' => 0,
1410
			'current_time' => time(),
1411
			'recycle_board' => !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : null,
1412
		)
1413
	);
1414
	$row = $smcFunc['db_fetch_assoc']($request);
1415
	$smcFunc['db_free_result']($request);
1416
1417
	// This user has voted on all the polls.
1418
	if (empty($row) || !is_array($row))
1419
		return array();
1420
1421
	// If this is a guest who's voted we'll through ourselves to show poll to show the results.
1422
	if ($user_info['is_guest'] && (!$row['guest_vote'] || (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))))
1423
		return ssi_showPoll($row['id_topic'], $output_method);
1424
1425
	$request = $smcFunc['db_query']('', '
1426
		SELECT COUNT(DISTINCT id_member)
1427
		FROM {db_prefix}log_polls
1428
		WHERE id_poll = {int:current_poll}',
1429
		array(
1430
			'current_poll' => $row['id_poll'],
1431
		)
1432
	);
1433
	list ($total) = $smcFunc['db_fetch_row']($request);
1434
	$smcFunc['db_free_result']($request);
1435
1436
	$request = $smcFunc['db_query']('', '
1437
		SELECT id_choice, label, votes
1438
		FROM {db_prefix}poll_choices
1439
		WHERE id_poll = {int:current_poll}',
1440
		array(
1441
			'current_poll' => $row['id_poll'],
1442
		)
1443
	);
1444
	$sOptions = array();
1445
	while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
1446
	{
1447
		censorText($rowChoice['label']);
1448
1449
		$sOptions[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
1450
	}
1451
	$smcFunc['db_free_result']($request);
1452
1453
	// Can they view it?
1454
	$is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
1455
	$allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || $is_expired;
1456
1457
	$return = array(
1458
		'id' => $row['id_poll'],
1459
		'image' => 'poll',
1460
		'question' => $row['question'],
1461
		'total_votes' => $total,
1462
		'is_locked' => false,
1463
		'topic' => $row['id_topic'],
1464
		'allow_view_results' => $allow_view_results,
1465
		'options' => array()
1466
	);
1467
1468
	// Calculate the percentages and bar lengths...
1469
	$divisor = $return['total_votes'] == 0 ? 1 : $return['total_votes'];
1470
	foreach ($sOptions as $i => $option)
1471
	{
1472
		$bar = floor(($option[1] * 100) / $divisor);
1473
		$return['options'][$i] = array(
1474
			'id' => 'options-' . ($topPollInstead ? 'top-' : 'recent-') . $i,
1475
			'percent' => $bar,
1476
			'votes' => $option[1],
1477
			'option' => parse_bbc($option[0]),
1478
			'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . ($topPollInstead ? 'top-' : 'recent-') . $i . '" value="' . $i . '">'
1479
		);
1480
	}
1481
1482
	$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options_limit'], min(count($sOptions), $row['max_votes'])) : '';
1483
1484
	// If mods want to do somthing with this list of polls, let them do that now.
1485
	call_integration_hook('integrate_ssi_recentPoll', array(&$return, $topPollInstead));
1486
1487
	if ($output_method != 'echo')
1488
		return $return;
1489
1490
	if ($allow_view_results)
1491
	{
1492
		echo '
1493
		<form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
1494
			<strong>', $return['question'], '</strong><br>
1495
			', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br>' : '';
1496
1497
		foreach ($return['options'] as $option)
1498
			echo '
1499
			<label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br>';
1500
1501
		echo '
1502
			<input type="submit" value="', $txt['poll_vote'], '" class="button">
1503
			<input type="hidden" name="poll" value="', $return['id'], '">
1504
			<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
1505
		</form>';
1506
	}
1507
	else
1508
		echo $txt['poll_cannot_see'];
1509
}
1510
1511
/**
1512
 * Shows the poll from the specified topic
1513
 *
1514
 * @param null|int $topic The topic to show the poll from. If null, $_REQUEST['ssi_topic'] will be used instead.
1515
 * @param string $output_method The output method. If 'echo', displays the poll, otherwise returns an array of info about it.
1516
 * @return void|array Either displays the poll or returns an array of info about it, depending on output_method.
1517
 */
1518
function ssi_showPoll($topic = null, $output_method = 'echo')
1519
{
1520
	global $txt, $boardurl, $user_info, $context, $smcFunc, $modSettings;
1521
1522
	$boardsAllowed = boardsAllowedTo('poll_view');
1523
1524
	if (empty($boardsAllowed))
1525
		return array();
1526
1527
	if ($topic === null && isset($_REQUEST['ssi_topic']))
1528
		$topic = (int) $_REQUEST['ssi_topic'];
1529
	else
1530
		$topic = (int) $topic;
1531
1532
	$request = $smcFunc['db_query']('', '
1533
		SELECT
1534
			p.id_poll, p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.guest_vote, b.id_board
1535
		FROM {db_prefix}topics AS t
1536
			INNER JOIN {db_prefix}polls AS p ON (p.id_poll = t.id_poll)
1537
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1538
		WHERE t.id_topic = {int:current_topic}
1539
			AND {query_see_board}' . (!in_array(0, $boardsAllowed) ? '
1540
			AND b.id_board IN ({array_int:boards_allowed_see})' : '') . ($modSettings['postmod_active'] ? '
1541
			AND t.approved = {int:is_approved}' : '') . '
1542
		LIMIT 1',
1543
		array(
1544
			'current_topic' => $topic,
1545
			'boards_allowed_see' => $boardsAllowed,
1546
			'is_approved' => 1,
1547
		)
1548
	);
1549
1550
	// Either this topic has no poll, or the user cannot view it.
1551
	if ($smcFunc['db_num_rows']($request) == 0)
1552
		return array();
1553
1554
	$row = $smcFunc['db_fetch_assoc']($request);
1555
	$smcFunc['db_free_result']($request);
1556
1557
	// Check if they can vote.
1558
	$already_voted = false;
1559
	if (!empty($row['expire_time']) && $row['expire_time'] < time())
1560
		$allow_vote = false;
1561
	elseif ($user_info['is_guest'])
1562
	{
1563
		// There's a difference between "allowed to vote" and "already voted"...
1564
		$allow_vote = $row['guest_vote'];
1565
1566
		// Did you already vote?
1567
		if (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1568
		{
1569
			$already_voted = true;
1570
		}
1571
	}
1572
	elseif (!empty($row['voting_locked']) || !allowedTo('poll_vote', $row['id_board']))
1573
		$allow_vote = false;
1574
	else
1575
	{
1576
		$request = $smcFunc['db_query']('', '
1577
			SELECT id_member
1578
			FROM {db_prefix}log_polls
1579
			WHERE id_poll = {int:current_poll}
1580
				AND id_member = {int:current_member}
1581
			LIMIT 1',
1582
			array(
1583
				'current_member' => $user_info['id'],
1584
				'current_poll' => $row['id_poll'],
1585
			)
1586
		);
1587
		$allow_vote = $smcFunc['db_num_rows']($request) == 0;
1588
		$already_voted = $allow_vote;
1589
		$smcFunc['db_free_result']($request);
1590
	}
1591
1592
	// Can they view?
1593
	$is_expired = !empty($row['expire_time']) && $row['expire_time'] < time();
1594
	$allow_view_results = allowedTo('moderate_board') || $row['hide_results'] == 0 || ($row['hide_results'] == 1 && $already_voted) || $is_expired;
1595
1596
	$request = $smcFunc['db_query']('', '
1597
		SELECT COUNT(DISTINCT id_member)
1598
		FROM {db_prefix}log_polls
1599
		WHERE id_poll = {int:current_poll}',
1600
		array(
1601
			'current_poll' => $row['id_poll'],
1602
		)
1603
	);
1604
	list ($total) = $smcFunc['db_fetch_row']($request);
1605
	$smcFunc['db_free_result']($request);
1606
1607
	$request = $smcFunc['db_query']('', '
1608
		SELECT id_choice, label, votes
1609
		FROM {db_prefix}poll_choices
1610
		WHERE id_poll = {int:current_poll}',
1611
		array(
1612
			'current_poll' => $row['id_poll'],
1613
		)
1614
	);
1615
	$sOptions = array();
1616
	$total_votes = 0;
1617
	while ($rowChoice = $smcFunc['db_fetch_assoc']($request))
1618
	{
1619
		censorText($rowChoice['label']);
1620
1621
		$sOptions[$rowChoice['id_choice']] = array($rowChoice['label'], $rowChoice['votes']);
1622
		$total_votes += $rowChoice['votes'];
1623
	}
1624
	$smcFunc['db_free_result']($request);
1625
1626
	$return = array(
1627
		'id' => $row['id_poll'],
1628
		'image' => empty($row['voting_locked']) ? 'poll' : 'locked_poll',
1629
		'question' => $row['question'],
1630
		'total_votes' => $total,
1631
		'is_locked' => !empty($row['voting_locked']),
1632
		'allow_vote' => $allow_vote,
1633
		'allow_view_results' => $allow_view_results,
1634
		'topic' => $topic
1635
	);
1636
1637
	// Calculate the percentages and bar lengths...
1638
	$divisor = $total_votes == 0 ? 1 : $total_votes;
1639
	foreach ($sOptions as $i => $option)
1640
	{
1641
		$bar = floor(($option[1] * 100) / $divisor);
1642
		$return['options'][$i] = array(
1643
			'id' => 'options-' . $i,
1644
			'percent' => $bar,
1645
			'votes' => $option[1],
1646
			'option' => parse_bbc($option[0]),
1647
			'vote_button' => '<input type="' . ($row['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '">'
1648
		);
1649
	}
1650
1651
	$return['allowed_warning'] = $row['max_votes'] > 1 ? sprintf($txt['poll_options_limit'], min(count($sOptions), $row['max_votes'])) : '';
1652
1653
	// If mods want to do somthing with this poll, let them do that now.
1654
	call_integration_hook('integrate_ssi_showPoll', array(&$return));
1655
1656
	if ($output_method != 'echo')
1657
		return $return;
1658
1659
	if ($return['allow_vote'])
1660
	{
1661
		echo '
1662
			<form class="ssi_poll" action="', $boardurl, '/SSI.php?ssi_function=pollVote" method="post" accept-charset="', $context['character_set'], '">
1663
				<strong>', $return['question'], '</strong><br>
1664
				', !empty($return['allowed_warning']) ? $return['allowed_warning'] . '<br>' : '';
1665
1666
		foreach ($return['options'] as $option)
1667
			echo '
1668
				<label for="', $option['id'], '">', $option['vote_button'], ' ', $option['option'], '</label><br>';
1669
1670
		echo '
1671
				<input type="submit" value="', $txt['poll_vote'], '" class="button">
1672
				<input type="hidden" name="poll" value="', $return['id'], '">
1673
				<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
1674
			</form>';
1675
	}
1676
	else
1677
	{
1678
		echo '
1679
			<div class="ssi_poll">
1680
				<strong>', $return['question'], '</strong>
1681
				<dl>';
1682
1683
		foreach ($return['options'] as $option)
1684
		{
1685
			echo '
1686
					<dt>', $option['option'], '</dt>
1687
					<dd>';
1688
1689
			if ($return['allow_view_results'])
1690
			{
1691
				echo '
1692
						<div class="ssi_poll_bar" style="border: 1px solid #666; height: 1em">
1693
							<div class="ssi_poll_bar_fill" style="background: #ccf; height: 1em; width: ', $option['percent'], '%;">
1694
							</div>
1695
						</div>
1696
						', $option['votes'], ' (', $option['percent'], '%)';
1697
			}
1698
1699
			echo '
1700
					</dd>';
1701
		}
1702
1703
		echo '
1704
				</dl>', ($return['allow_view_results'] ? '
1705
				<strong>' . $txt['poll_total_voters'] . ': ' . $return['total_votes'] . '</strong>' : ''), '
1706
			</div>';
1707
	}
1708
}
1709
1710
/**
1711
 * Handles voting in a poll (done automatically)
1712
 */
1713
function ssi_pollVote()
1714
{
1715
	global $context, $db_prefix, $user_info, $sc, $smcFunc, $sourcedir, $modSettings;
1716
1717
	if (!isset($_POST[$context['session_var']]) || $_POST[$context['session_var']] != $sc || empty($_POST['options']) || !isset($_POST['poll']))
1718
	{
1719
		echo '<!DOCTYPE html>
1720
<html>
1721
<head>
1722
	<script>
1723
		history.go(-1);
1724
	</script>
1725
</head>
1726
<body>&laquo;</body>
1727
</html>';
1728
		return;
1729
	}
1730
1731
	// This can cause weird errors! (ie. copyright missing.)
1732
	checkSession();
1733
1734
	$_POST['poll'] = (int) $_POST['poll'];
1735
1736
	// Check if they have already voted, or voting is locked.
1737
	$request = $smcFunc['db_query']('', '
1738
		SELECT
1739
			p.id_poll, p.voting_locked, p.expire_time, p.max_votes, p.guest_vote,
1740
			t.id_topic,
1741
			COALESCE(lp.id_choice, -1) AS selected
1742
		FROM {db_prefix}polls AS p
1743
			INNER JOIN {db_prefix}topics AS t ON (t.id_poll = {int:current_poll})
1744
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
1745
			LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_poll = p.id_poll AND lp.id_member = {int:current_member})
1746
		WHERE p.id_poll = {int:current_poll}
1747
			AND {query_see_board}' . ($modSettings['postmod_active'] ? '
1748
			AND t.approved = {int:is_approved}' : '') . '
1749
		LIMIT 1',
1750
		array(
1751
			'current_member' => $user_info['id'],
1752
			'current_poll' => $_POST['poll'],
1753
			'is_approved' => 1,
1754
		)
1755
	);
1756
	if ($smcFunc['db_num_rows']($request) == 0)
1757
		die;
1758
	$row = $smcFunc['db_fetch_assoc']($request);
1759
	$smcFunc['db_free_result']($request);
1760
1761
	if (!empty($row['voting_locked']) || ($row['selected'] != -1 && !$user_info['is_guest']) || (!empty($row['expire_time']) && time() > $row['expire_time']))
1762
		redirectexit('topic=' . $row['id_topic'] . '.0');
1763
1764
	// Too many options checked?
1765
	if (count($_REQUEST['options']) > $row['max_votes'])
1766
		redirectexit('topic=' . $row['id_topic'] . '.0');
1767
1768
	// It's a guest who has already voted?
1769
	if ($user_info['is_guest'])
1770
	{
1771
		// Guest voting disabled?
1772
		if (!$row['guest_vote'])
1773
			redirectexit('topic=' . $row['id_topic'] . '.0');
1774
		// Already voted?
1775
		elseif (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1776
			redirectexit('topic=' . $row['id_topic'] . '.0');
1777
	}
1778
1779
	$sOptions = array();
1780
	$inserts = array();
1781
	foreach ($_REQUEST['options'] as $id)
1782
	{
1783
		$id = (int) $id;
1784
1785
		$sOptions[] = $id;
1786
		$inserts[] = array($_POST['poll'], $user_info['id'], $id);
1787
	}
1788
1789
	// Add their vote in to the tally.
1790
	$smcFunc['db_insert']('insert',
1791
		$db_prefix . 'log_polls',
1792
		array('id_poll' => 'int', 'id_member' => 'int', 'id_choice' => 'int'),
1793
		$inserts,
1794
		array('id_poll', 'id_member', 'id_choice')
1795
	);
1796
	$smcFunc['db_query']('', '
1797
		UPDATE {db_prefix}poll_choices
1798
		SET votes = votes + 1
1799
		WHERE id_poll = {int:current_poll}
1800
			AND id_choice IN ({array_int:option_list})',
1801
		array(
1802
			'option_list' => $sOptions,
1803
			'current_poll' => $_POST['poll'],
1804
		)
1805
	);
1806
1807
	// Track the vote if a guest.
1808
	if ($user_info['is_guest'])
1809
	{
1810
		$_COOKIE['guest_poll_vote'] = !empty($_COOKIE['guest_poll_vote']) ? ($_COOKIE['guest_poll_vote'] . ',' . $row['id_poll']) : $row['id_poll'];
1811
1812
		require_once($sourcedir . '/Subs-Auth.php');
1813
		$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
1814
		smf_setcookie('guest_poll_vote', $_COOKIE['guest_poll_vote'], time() + 2500000, $cookie_url[1], $cookie_url[0], false, false);
1815
	}
1816
1817
	redirectexit('topic=' . $row['id_topic'] . '.0');
1818
}
1819
1820
// Show a search box.
1821
/**
1822
 * Shows a search box
1823
 *
1824
 * @param string $output_method The output method. If 'echo', displays a search box, otherwise returns the URL of the search page.
1825
 * @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.
1826
 */
1827
function ssi_quickSearch($output_method = 'echo')
1828
{
1829
	global $scripturl, $txt, $context;
1830
1831
	if (!allowedTo('search_posts'))
1832
		return;
1833
1834
	if ($output_method != 'echo')
1835
		return $scripturl . '?action=search';
1836
1837
	echo '
1838
		<form action="', $scripturl, '?action=search2" method="post" accept-charset="', $context['character_set'], '">
1839
			<input type="hidden" name="advanced" value="0"><input type="text" name="ssi_search" size="30"> <input type="submit" value="', $txt['search'], '" class="button">
1840
		</form>';
1841
}
1842
1843
/**
1844
 * Show a random forum news item
1845
 *
1846
 * @param string $output_method The output method. If 'echo', shows the news item, otherwise returns it.
1847
 * @return void|string Shows or returns a random forum news item, depending on output_method.
1848
 */
1849
function ssi_news($output_method = 'echo')
1850
{
1851
	global $context;
1852
1853
	$context['random_news_line'] = !empty($context['news_lines']) ? $context['news_lines'][mt_rand(0, count($context['news_lines']) - 1)] : '';
1854
1855
	// 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.
1856
	call_integration_hook('integrate_ssi_news');
1857
1858
	if ($output_method != 'echo')
1859
		return $context['random_news_line'];
1860
1861
	echo $context['random_news_line'];
1862
}
1863
1864
/**
1865
 * Show today's birthdays.
1866
 *
1867
 * @param string $output_method The output method. If 'echo', displays a list of users, otherwise returns an array of info about them.
1868
 * @return void|array Displays a list of users or returns an array of info about them depending on output_method.
1869
 */
1870
function ssi_todaysBirthdays($output_method = 'echo')
1871
{
1872
	global $scripturl, $modSettings, $user_info;
1873
1874
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view') || !allowedTo('profile_view'))
1875
		return;
1876
1877
	$eventOptions = array(
1878
		'include_birthdays' => true,
1879
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1880
	);
1881
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1882
1883
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1884
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1885
1886
	if ($output_method != 'echo')
1887
		return $return['calendar_birthdays'];
1888
1889
	foreach ($return['calendar_birthdays'] as $member)
1890
		echo '
1891
			<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'] ? ', ' : '');
1892
}
1893
1894
/**
1895
 * Shows today's holidays.
1896
 *
1897
 * @param string $output_method The output method. If 'echo', displays a list of holidays, otherwise returns an array of info about them.
1898
 * @return void|array Displays a list of holidays or returns an array of info about them depending on output_method
1899
 */
1900
function ssi_todaysHolidays($output_method = 'echo')
1901
{
1902
	global $modSettings, $user_info;
1903
1904
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1905
		return;
1906
1907
	$eventOptions = array(
1908
		'include_holidays' => true,
1909
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1910
	);
1911
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1912
1913
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1914
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1915
1916
	if ($output_method != 'echo')
1917
		return $return['calendar_holidays'];
1918
1919
	echo '
1920
		', implode(', ', $return['calendar_holidays']);
1921
}
1922
1923
/**
1924
 * Shows today's events.
1925
 *
1926
 * @param string $output_method The output method. If 'echo', displays a list of events, otherwise returns an array of info about them.
1927
 * @return void|array Displays a list of events or returns an array of info about them depending on output_method
1928
 */
1929
function ssi_todaysEvents($output_method = 'echo')
1930
{
1931
	global $modSettings, $user_info;
1932
1933
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1934
		return;
1935
1936
	$eventOptions = array(
1937
		'include_events' => true,
1938
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1939
	);
1940
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1941
1942
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1943
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1944
1945
	if ($output_method != 'echo')
1946
		return $return['calendar_events'];
1947
1948
	foreach ($return['calendar_events'] as $event)
1949
	{
1950
		if ($event['can_edit'])
1951
			echo '
1952
	<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
1953
		echo '
1954
	' . $event['link'] . (!$event['is_last'] ? ', ' : '');
1955
	}
1956
}
1957
1958
/**
1959
 * Shows today's calendar items (events, birthdays and holidays)
1960
 *
1961
 * @param string $output_method The output method. If 'echo', displays a list of calendar items, otherwise returns an array of info about them.
1962
 * @return void|array Displays a list of calendar items or returns an array of info about them depending on output_method
1963
 */
1964
function ssi_todaysCalendar($output_method = 'echo')
1965
{
1966
	global $modSettings, $txt, $scripturl, $user_info;
1967
1968
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1969
		return;
1970
1971
	$eventOptions = array(
1972
		'include_birthdays' => allowedTo('profile_view'),
1973
		'include_holidays' => true,
1974
		'include_events' => true,
1975
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1976
	);
1977
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1978
1979
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1980
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1981
1982
	if ($output_method != 'echo')
1983
		return $return;
1984
1985
	if (!empty($return['calendar_holidays']))
1986
		echo '
1987
			<span class="holiday">' . $txt['calendar_prompt'] . ' ' . implode(', ', $return['calendar_holidays']) . '<br></span>';
1988
	if (!empty($return['calendar_birthdays']))
1989
	{
1990
		echo '
1991
			<span class="birthday">' . $txt['birthdays_upcoming'] . '</span> ';
1992
		foreach ($return['calendar_birthdays'] as $member)
1993
			echo '
1994
			<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'] ? ', ' : '';
1995
		echo '
1996
			<br>';
1997
	}
1998
	if (!empty($return['calendar_events']))
1999
	{
2000
		echo '
2001
			<span class="event">' . $txt['events_upcoming'] . '</span> ';
2002
		foreach ($return['calendar_events'] as $event)
2003
		{
2004
			if ($event['can_edit'])
2005
				echo '
2006
			<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
2007
			echo '
2008
			' . $event['link'] . (!$event['is_last'] ? ', ' : '');
2009
		}
2010
	}
2011
}
2012
2013
/**
2014
 * Show the latest news, with a template... by board.
2015
 *
2016
 * @param null|int $board The ID of the board to get the info from. Defaults to $board or $_GET['board'] if not set.
2017
 * @param null|int $limit How many items to show. Defaults to $_GET['limit'] or 5 if not set.
2018
 * @param null|int $start Start with the specified item. Defaults to $_GET['start'] or 0 if not set.
2019
 * @param null|int $length How many characters to show from each post. Defaults to $_GET['length'] or 0 (no limit) if not set.
2020
 * @param string $output_method The output method. If 'echo', displays the news items, otherwise returns an array of info about them.
2021
 * @return void|array Displays the news items or returns an array of info about them, depending on output_method.
2022
 */
2023
function ssi_boardNews($board = null, $limit = null, $start = null, $length = null, $output_method = 'echo')
2024
{
2025
	global $scripturl, $txt, $settings, $modSettings, $context;
2026
	global $smcFunc;
2027
2028
	loadLanguage('Stats');
2029
2030
	// Must be integers....
2031
	if ($limit === null)
2032
		$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 5;
2033
	else
2034
		$limit = (int) $limit;
2035
2036
	if ($start === null)
2037
		$start = isset($_GET['start']) ? (int) $_GET['start'] : 0;
2038
	else
2039
		$start = (int) $start;
2040
2041
	if ($board !== null)
2042
		$board = (int) $board;
2043
	elseif (isset($_GET['board']))
2044
		$board = (int) $_GET['board'];
2045
2046
	if ($length === null)
2047
		$length = isset($_GET['length']) ? (int) $_GET['length'] : 0;
2048
	else
2049
		$length = (int) $length;
2050
2051
	$limit = max(0, $limit);
2052
	$start = max(0, $start);
2053
2054
	// Make sure guests can see this board.
2055
	$request = $smcFunc['db_query']('', '
2056
		SELECT id_board
2057
		FROM {db_prefix}boards
2058
		WHERE ' . ($board === null ? '' : 'id_board = {int:current_board}
2059
			AND ') . 'FIND_IN_SET(-1, member_groups) != 0
2060
		LIMIT 1',
2061
		array(
2062
			'current_board' => $board,
2063
		)
2064
	);
2065
	if ($smcFunc['db_num_rows']($request) == 0)
2066
	{
2067
		if ($output_method == 'echo')
2068
			die($txt['ssi_no_guests']);
2069
		else
2070
			return array();
2071
	}
2072
	list ($board) = $smcFunc['db_fetch_row']($request);
2073
	$smcFunc['db_free_result']($request);
2074
2075
	$icon_sources = array();
2076
	foreach ($context['stable_icons'] as $icon)
2077
		$icon_sources[$icon] = 'images_url';
2078
2079
	if (!empty($modSettings['enable_likes']))
2080
	{
2081
		$context['can_like'] = allowedTo('likes_like');
2082
	}
2083
2084
	// Find the post ids.
2085
	$request = $smcFunc['db_query']('', '
2086
		SELECT t.id_first_msg
2087
		FROM {db_prefix}topics as t
2088
			LEFT JOIN {db_prefix}boards as b ON (b.id_board = t.id_board)
2089
		WHERE t.id_board = {int:current_board}' . ($modSettings['postmod_active'] ? '
2090
			AND t.approved = {int:is_approved}' : '') . '
2091
			AND {query_see_board}
2092
		ORDER BY t.id_first_msg DESC
2093
		LIMIT ' . $start . ', ' . $limit,
2094
		array(
2095
			'current_board' => $board,
2096
			'is_approved' => 1,
2097
		)
2098
	);
2099
	$posts = array();
2100
	while ($row = $smcFunc['db_fetch_assoc']($request))
2101
		$posts[] = $row['id_first_msg'];
2102
	$smcFunc['db_free_result']($request);
2103
2104
	if (empty($posts))
2105
		return array();
2106
2107
	// Find the posts.
2108
	$request = $smcFunc['db_query']('', '
2109
		SELECT
2110
			m.icon, m.subject, m.body, COALESCE(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.likes,
2111
			t.num_replies, t.id_topic, m.id_member, m.smileys_enabled, m.id_msg, t.locked, t.id_last_msg, m.id_board
2112
		FROM {db_prefix}topics AS t
2113
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
2114
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
2115
		WHERE t.id_first_msg IN ({array_int:post_list})
2116
		ORDER BY t.id_first_msg DESC
2117
		LIMIT ' . count($posts),
2118
		array(
2119
			'post_list' => $posts,
2120
		)
2121
	);
2122
	$return = array();
2123
	$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
2124
	while ($row = $smcFunc['db_fetch_assoc']($request))
2125
	{
2126
		// If we want to limit the length of the post.
2127
		if (!empty($length) && $smcFunc['strlen']($row['body']) > $length)
2128
		{
2129
			$row['body'] = $smcFunc['substr']($row['body'], 0, $length);
2130
			$cutoff = false;
2131
2132
			$last_space = strrpos($row['body'], ' ');
2133
			$last_open = strrpos($row['body'], '<');
2134
			$last_close = strrpos($row['body'], '>');
2135
			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)
2136
				$cutoff = $last_open;
2137
			elseif (empty($last_close) || $last_close < $last_open)
2138
				$cutoff = $last_space;
2139
2140
			if ($cutoff !== false)
2141
				$row['body'] = $smcFunc['substr']($row['body'], 0, $cutoff);
2142
			$row['body'] .= '...';
2143
		}
2144
2145
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
2146
2147
		if (!empty($recycle_board) && $row['id_board'] == $recycle_board)
2148
			$row['icon'] = 'recycled';
2149
2150
		// Check that this message icon is there...
2151
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
2152
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
2153
		elseif (!isset($icon_sources[$row['icon']]))
2154
			$icon_sources[$row['icon']] = 'images_url';
2155
2156
		censorText($row['subject']);
2157
		censorText($row['body']);
2158
2159
		$return[] = array(
2160
			'id' => $row['id_topic'],
2161
			'message_id' => $row['id_msg'],
2162
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" alt="' . $row['icon'] . '">',
2163
			'subject' => $row['subject'],
2164
			'time' => timeformat($row['poster_time']),
2165
			'timestamp' => forum_time(true, $row['poster_time']),
2166
			'body' => $row['body'],
2167
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
2168
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['num_replies'] . ' ' . ($row['num_replies'] == 1 ? $txt['ssi_comment'] : $txt['ssi_comments']) . '</a>',
2169
			'replies' => $row['num_replies'],
2170
			'comment_href' => !empty($row['locked']) ? '' : $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . ';last_msg=' . $row['id_last_msg'],
2171
			'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>',
2172
			'new_comment' => !empty($row['locked']) ? '' : '<a href="' . $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . '">' . $txt['ssi_write_comment'] . '</a>',
2173
			'poster' => array(
2174
				'id' => $row['id_member'],
2175
				'name' => $row['poster_name'],
2176
				'href' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
2177
				'link' => !empty($row['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>' : $row['poster_name']
2178
			),
2179
			'locked' => !empty($row['locked']),
2180
			'is_last' => false,
2181
			// Nasty ternary for likes not messing around the "is_last" check.
2182
			'likes' => !empty($modSettings['enable_likes']) ? array(
2183
				'count' => $row['likes'],
2184
				'you' => in_array($row['id_msg'], prepareLikesContext((int) $row['id_topic'])),
2185
				'can_like' => !$context['user']['is_guest'] && $row['id_member'] != $context['user']['id'] && !empty($context['can_like']),
2186
			) : array(),
2187
		);
2188
	}
2189
	$smcFunc['db_free_result']($request);
2190
2191
	if (empty($return))
2192
		return $return;
2193
2194
	$return[count($return) - 1]['is_last'] = true;
2195
2196
	// If mods want to do somthing with this list of posts, let them do that now.
2197
	call_integration_hook('integrate_ssi_boardNews', array(&$return));
2198
2199
	if ($output_method != 'echo')
2200
		return $return;
2201
2202
	foreach ($return as $news)
2203
	{
2204
		echo '
2205
			<div class="news_item">
2206
				<h3 class="news_header">
2207
					', $news['icon'], '
2208
					<a href="', $news['href'], '">', $news['subject'], '</a>
2209
				</h3>
2210
				<div class="news_timestamp">', $news['time'], ' ', $txt['by'], ' ', $news['poster']['link'], '</div>
2211
				<div class="news_body" style="padding: 2ex 0;">', $news['body'], '</div>
2212
				', $news['link'], $news['locked'] ? '' : ' | ' . $news['comment_link'], '';
2213
2214
		// Is there any likes to show?
2215
		if (!empty($modSettings['enable_likes']))
2216
		{
2217
			echo '
2218
					<ul>';
2219
2220
			if (!empty($news['likes']['can_like']))
2221
			{
2222
				echo '
2223
						<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>';
2224
			}
2225
2226
			if (!empty($news['likes']['count']))
2227
			{
2228
				$context['some_likes'] = true;
2229
				$count = $news['likes']['count'];
2230
				$base = 'likes_';
2231
				if ($news['likes']['you'])
2232
				{
2233
					$base = 'you_' . $base;
2234
					$count--;
2235
				}
2236
				$base .= (isset($txt[$base . $count])) ? $count : 'n';
2237
2238
				echo '
2239
						<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>';
2240
			}
2241
2242
			echo '
2243
					</ul>';
2244
		}
2245
2246
		// Close the main div.
2247
		echo '
2248
			</div>';
2249
2250
		if (!$news['is_last'])
2251
			echo '
2252
			<hr>';
2253
	}
2254
}
2255
2256
/**
2257
 * Show the most recent events
2258
 *
2259
 * @param int $max_events The maximum number of events to show
2260
 * @param string $output_method The output method. If 'echo', displays the events, otherwise returns an array of info about them.
2261
 * @return void|array Displays the events or returns an array of info about them, depending on output_method.
2262
 */
2263
function ssi_recentEvents($max_events = 7, $output_method = 'echo')
2264
{
2265
	global $user_info, $scripturl, $modSettings, $txt, $context, $smcFunc;
2266
2267
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
2268
		return;
2269
2270
	// Find all events which are happening in the near future that the member can see.
2271
	$request = $smcFunc['db_query']('', '
2272
		SELECT
2273
			cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
2274
			cal.start_time, cal.end_time, cal.timezone, cal.location,
2275
			cal.id_board, t.id_first_msg, t.approved
2276
		FROM {db_prefix}calendar AS cal
2277
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
2278
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
2279
		WHERE cal.start_date <= {date:current_date}
2280
			AND cal.end_date >= {date:current_date}
2281
			AND (cal.id_board = {int:no_board} OR {query_wanna_see_board})
2282
		ORDER BY cal.start_date DESC
2283
		LIMIT ' . $max_events,
2284
		array(
2285
			'current_date' => strftime('%Y-%m-%d', forum_time(false)),
2286
			'no_board' => 0,
2287
		)
2288
	);
2289
	$return = array();
2290
	$duplicates = array();
2291
	while ($row = $smcFunc['db_fetch_assoc']($request))
2292
	{
2293
		// 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.
2294
		if (!empty($duplicates[$row['title'] . $row['id_topic']]))
2295
			continue;
2296
2297
		// Censor the title.
2298
		censorText($row['title']);
2299
2300
		if ($row['start_date'] < strftime('%Y-%m-%d', forum_time(false)))
2301
			$date = strftime('%Y-%m-%d', forum_time(false));
2302
		else
2303
			$date = $row['start_date'];
2304
2305
		// If the topic it is attached to is not approved then don't link it.
2306
		if (!empty($row['id_first_msg']) && !$row['approved'])
2307
			$row['id_board'] = $row['id_topic'] = $row['id_first_msg'] = 0;
2308
2309
		$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
It seems like timezone_identifiers_lis...eTimeZone::ALL_WITH_BC) can also be of type false; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

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