Passed
Push — release-2.1 ( b7b9b9...450da8 )
by Mathias
07:12
created
1
<?php
2
3
/**
4
 * Simple Machines Forum (SMF)
5
 *
6
 * @package SMF
7
 * @author Simple Machines http://www.simplemachines.org
8
 * @copyright 2018 Simple Machines and individual contributors
9
 * @license http://www.simplemachines.org/about/smf/license.php BSD
10
 *
11
 * @version 2.1 Beta 4
12
 */
13
14
// Don't do anything if SMF is already loaded.
15
if (defined('SMF'))
16
	return true;
17
18
define('SMF', 'SSI');
19
20
// We're going to want a few globals... these are all set later.
21
global $time_start, $maintenance, $msubject, $mmessage, $mbname, $language;
22
global $boardurl, $boarddir, $sourcedir, $webmaster_email, $cookiename;
23
global $db_type, $db_server, $db_name, $db_user, $db_prefix, $db_persist, $db_error_send, $db_last_error;
24
global $db_connection, $db_port, $modSettings, $context, $sc, $user_info, $topic, $board, $txt;
25
global $smcFunc, $ssi_db_user, $scripturl, $ssi_db_passwd, $db_passwd, $cache_enable, $cachedir;
26
27
// Remember the current configuration so it can be set back.
28
$time_start = microtime(true);
29
30
// Just being safe...
31
foreach (array('db_character_set', 'cachedir') as $variable)
32
	if (isset($GLOBALS[$variable]))
33
		unset($GLOBALS[$variable]);
34
35
// Get the forum's settings for database and file paths.
36
require_once(dirname(__FILE__) . '/Settings.php');
37
38
// Make absolutely sure the cache directory is defined.
39
if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache'))
40
	$cachedir = $boarddir . '/cache';
41
42
$ssi_error_reporting = error_reporting(E_ALL);
43
/* Set this to one of three values depending on what you want to happen in the case of a fatal error.
44
	false:	Default, will just load the error sub template and die - not putting any theme layers around it.
45
	true:	Will load the error sub template AND put the SMF layers around it (Not useful if on total custom pages).
46
	string:	Name of a callback function to call in the event of an error to allow you to define your own methods. Will die after function returns.
47
*/
48
$ssi_on_error_method = false;
49
50
// Don't do john didley if the forum's been shut down completely.
51
if ($maintenance == 2 && (!isset($ssi_maintenance_off) || $ssi_maintenance_off !== true))
52
	die($mmessage);
53
54
// Fix for using the current directory as a path.
55
if (substr($sourcedir, 0, 1) == '.' && substr($sourcedir, 1, 1) != '.')
56
	$sourcedir = dirname(__FILE__) . substr($sourcedir, 1);
57
58
// Load the important includes.
59
require_once($sourcedir . '/QueryString.php');
60
require_once($sourcedir . '/Session.php');
61
require_once($sourcedir . '/Subs.php');
62
require_once($sourcedir . '/Errors.php');
63
require_once($sourcedir . '/Logging.php');
64
require_once($sourcedir . '/Load.php');
65
require_once($sourcedir . '/Security.php');
66
require_once($sourcedir . '/Class-BrowserDetect.php');
67
require_once($sourcedir . '/Subs-Auth.php');
68
69
// Create a variable to store some SMF specific functions in.
70
$smcFunc = array();
71
72
// Initiate the database connection and define some database functions to use.
73
loadDatabase();
74
75
// Load installed 'Mods' settings.
76
reloadSettings();
77
// Clean the request variables.
78
cleanRequest();
79
80
// Seed the random generator?
81
if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69)
82
	smf_seed_generator();
83
84
// Check on any hacking attempts.
85
if (isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS']))
86
	die('No direct access...');
87
elseif (isset($_REQUEST['ssi_theme']) && (int) $_REQUEST['ssi_theme'] == (int) $ssi_theme)
88
	die('No direct access...');
89
elseif (isset($_COOKIE['ssi_theme']) && (int) $_COOKIE['ssi_theme'] == (int) $ssi_theme)
90
	die('No direct access...');
91
elseif (isset($_REQUEST['ssi_layers'], $ssi_layers) && (@get_magic_quotes_gpc() ? stripslashes($_REQUEST['ssi_layers']) : $_REQUEST['ssi_layers']) == $ssi_layers)
92
	die('No direct access...');
93
if (isset($_REQUEST['context']))
94
	die('No direct access...');
95
96
// Gzip output? (because it must be boolean and true, this can't be hacked.)
97
if (isset($ssi_gzip) && $ssi_gzip === true && ini_get('zlib.output_compression') != '1' && ini_get('output_handler') != 'ob_gzhandler' && version_compare(PHP_VERSION, '4.2.0', '>='))
98
	ob_start('ob_gzhandler');
99
else
100
	$modSettings['enableCompressedOutput'] = '0';
101
102
/**
103
 * An autoloader for certain classes.
104
 *
105
 * @param string $class The fully-qualified class name.
106
 */
107
spl_autoload_register(function ($class) use ($sourcedir)
108
{
109
	$classMap = array(
110
		'ReCaptcha\\' => 'ReCaptcha/',
111
		'MatthiasMullie\\Minify\\' => 'minify/src/',
112
		'MatthiasMullie\\PathConverter\\' => 'minify/path-converter/src/',
113
	);
114
115
	// Do any third-party scripts want in on the fun?
116
	call_integration_hook('integrate_autoload', array(&$classMap));
117
118
	foreach ($classMap as $prefix => $dirName)
119
	{
120
		// does the class use the namespace prefix?
121
		$len = strlen($prefix);
122
		if (strncmp($prefix, $class, $len) !== 0)
123
		{
124
			continue;
125
		}
126
127
		// get the relative class name
128
		$relativeClass = substr($class, $len);
129
130
		// replace the namespace prefix with the base directory, replace namespace
131
		// separators with directory separators in the relative class name, append
132
		// with .php
133
		$fileName = $dirName . strtr($relativeClass, '\\', '/') . '.php';
134
135
		// if the file exists, require it
136
		if (file_exists($fileName = $sourcedir . '/' . $fileName))
137
		{
138
			require_once $fileName;
139
140
			return;
141
		}
142
	}
143
});
144
145
// Primarily, this is to fix the URLs...
146
ob_start('ob_sessrewrite');
147
148
// Start the session... known to scramble SSI includes in cases...
149
if (!headers_sent())
150
	loadSession();
151
else
152
{
153
	if (isset($_COOKIE[session_name()]) || isset($_REQUEST[session_name()]))
154
	{
155
		// Make a stab at it, but ignore the E_WARNINGs generated because we can't send headers.
156
		$temp = error_reporting(error_reporting() & !E_WARNING);
157
		loadSession();
158
		error_reporting($temp);
159
	}
160
161
	if (!isset($_SESSION['session_value']))
162
	{
163
		$_SESSION['session_var'] = substr(md5($smcFunc['random_int']() . session_id() . $smcFunc['random_int']()), 0, rand(7, 12));
164
		$_SESSION['session_value'] = md5(session_id() . $smcFunc['random_int']());
165
	}
166
	$sc = $_SESSION['session_value'];
167
}
168
169
// Get rid of $board and $topic... do stuff loadBoard would do.
170
unset($board, $topic);
171
$user_info['is_mod'] = false;
172
$context['user']['is_mod'] = &$user_info['is_mod'];
173
$context['linktree'] = array();
174
175
// Load the user and their cookie, as well as their settings.
176
loadUserSettings();
177
178
// Load the current user's permissions....
179
loadPermissions();
180
181
// Load the current or SSI theme. (just use $ssi_theme = id_theme;)
182
loadTheme(isset($ssi_theme) ? (int) $ssi_theme : 0);
183
184
// @todo: probably not the best place, but somewhere it should be set...
185
if (!headers_sent())
186
	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']));
187
188
// Take care of any banning that needs to be done.
189
if (isset($_REQUEST['ssi_ban']) || (isset($ssi_ban) && $ssi_ban === true))
190
	is_not_banned();
191
192
// Do we allow guests in here?
193
if (empty($ssi_guest_access) && empty($modSettings['allow_guestAccess']) && $user_info['is_guest'] && basename($_SERVER['PHP_SELF']) != 'SSI.php')
194
{
195
	require_once($sourcedir . '/Subs-Auth.php');
196
	KickGuest();
197
	obExit(null, true);
198
}
199
200
// Load the stuff like the menu bar, etc.
201
if (isset($ssi_layers))
202
{
203
	$context['template_layers'] = $ssi_layers;
204
	template_header();
205
}
206
else
207
	setupThemeContext();
208
209
// Make sure they didn't muss around with the settings... but only if it's not cli.
210
if (isset($_SERVER['REMOTE_ADDR']) && !isset($_SERVER['is_cli']) && session_id() == '')
211
	trigger_error($txt['ssi_session_broken'], E_USER_NOTICE);
212
213
// Without visiting the forum this session variable might not be set on submit.
214
if (!isset($_SESSION['USER_AGENT']) && (!isset($_GET['ssi_function']) || $_GET['ssi_function'] !== 'pollVote'))
215
	$_SESSION['USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
216
217
// Have the ability to easily add functions to SSI.
218
call_integration_hook('integrate_SSI');
219
220
// Ignore a call to ssi_* functions if we are not accessing SSI.php directly.
221
if (basename($_SERVER['PHP_SELF']) == 'SSI.php')
222
{
223
	// You shouldn't just access SSI.php directly by URL!!
224
	if (!isset($_GET['ssi_function']))
225
		die(sprintf($txt['ssi_not_direct'], $user_info['is_admin'] ? '\'' . addslashes(__FILE__) . '\'' : '\'SSI.php\''));
226
	// Call a function passed by GET.
227
	if (function_exists('ssi_' . $_GET['ssi_function']) && (!empty($modSettings['allow_guestAccess']) || !$user_info['is_guest']))
228
		call_user_func('ssi_' . $_GET['ssi_function']);
229
	exit;
230
}
231
232
// To avoid side effects later on.
233
unset($_GET['ssi_function']);
234
235
error_reporting($ssi_error_reporting);
236
237
return true;
238
239
/**
240
 * This shuts down the SSI and shows the footer.
241
 * @return void
242
 */
243
function ssi_shutdown()
244
{
245
	if (!isset($_GET['ssi_function']) || $_GET['ssi_function'] != 'shutdown')
246
		template_footer();
247
}
248
249
/**
250
 * Display a welcome message, like: Hey, User, you have 0 messages, 0 are new.
251
 * @param string $output_method The output method. If 'echo', will display everything. Otherwise returns an array of user info.
252
 * @return void|array Displays a welcome message or returns an array of user data depending on output_method.
253
 */
254
function ssi_welcome($output_method = 'echo')
255
{
256
	global $context, $txt, $scripturl;
257
258
	if ($output_method == 'echo')
259
	{
260
		if ($context['user']['is_guest'])
261
			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');
262
		else
263
			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'])))) : '';
264
	}
265
	// Don't echo... then do what?!
266
	else
267
		return $context['user'];
268
}
269
270
/**
271
 * Display a menu bar, like is displayed at the top of the forum.
272
 * @param string $output_method The output method. If 'echo', will display the menu, otherwise returns an array of menu data.
273
 * @return void|array Displays the menu or returns an array of menu data depending on output_method.
274
 */
275
function ssi_menubar($output_method = 'echo')
276
{
277
	global $context;
278
279
	if ($output_method == 'echo')
280
		template_menu();
281
	// What else could this do?
282
	else
283
		return $context['menu_buttons'];
284
}
285
286
/**
287
 * Show a logout link.
288
 * @param string $redirect_to A URL to redirect the user to after they log out.
289
 * @param string $output_method The output method. If 'echo', shows a logout link, otherwise returns the HTML for it.
290
 * @return void|string Displays a logout link or returns its HTML depending on output_method.
291
 */
292
function ssi_logout($redirect_to = '', $output_method = 'echo')
293
{
294
	global $context, $txt, $scripturl;
295
296
	if ($redirect_to != '')
297
		$_SESSION['logout_url'] = $redirect_to;
298
299
	// Guests can't log out.
300
	if ($context['user']['is_guest'])
301
		return false;
302
303
	$link = '<a href="' . $scripturl . '?action=logout;' . $context['session_var'] . '=' . $context['session_id'] . '">' . $txt['logout'] . '</a>';
304
305
	if ($output_method == 'echo')
306
		echo $link;
307
	else
308
		return $link;
309
}
310
311
/**
312
 * Recent post list:   [board] Subject by Poster    Date
313
 * @param int $num_recent How many recent posts to display
314
 * @param null|array $exclude_boards If set, doesn't show posts from the specified boards
315
 * @param null|array $include_boards If set, only includes posts from the specified boards
316
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of information about them.
317
 * @param bool $limit_body Whether or not to only show the first 384 characters of each post
318
 * @return void|array Displays a list of recent posts or returns an array of information about them depending on output_method.
319
 */
320
function ssi_recentPosts($num_recent = 8, $exclude_boards = null, $include_boards = null, $output_method = 'echo', $limit_body = true)
321
{
322
	global $modSettings, $context;
323
324
	// Excluding certain boards...
325
	if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0)
326
		$exclude_boards = array($modSettings['recycle_board']);
327
	else
328
		$exclude_boards = empty($exclude_boards) ? array() : (is_array($exclude_boards) ? $exclude_boards : array($exclude_boards));
329
330
	// What about including certain boards - note we do some protection here as pre-2.0 didn't have this parameter.
331
	if (is_array($include_boards) || (int) $include_boards === $include_boards)
332
	{
333
		$include_boards = is_array($include_boards) ? $include_boards : array($include_boards);
334
	}
335
	elseif ($include_boards != null)
336
	{
337
		$include_boards = array();
338
	}
339
340
	// Let's restrict the query boys (and girls)
341
	$query_where = '
342
		m.id_msg >= {int:min_message_id}
343
		' . (empty($exclude_boards) ? '' : '
344
		AND b.id_board NOT IN ({array_int:exclude_boards})') . '
345
		' . ($include_boards === null ? '' : '
346
		AND b.id_board IN ({array_int:include_boards})') . '
347
		AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
348
		AND m.approved = {int:is_approved}' : '');
349
350
	$query_where_params = array(
351
		'is_approved' => 1,
352
		'include_boards' => $include_boards === null ? '' : $include_boards,
353
		'exclude_boards' => empty($exclude_boards) ? '' : $exclude_boards,
354
		'min_message_id' => $modSettings['maxMsgID'] - (!empty($context['min_message_posts']) ? $context['min_message_posts'] : 25) * min($num_recent, 5),
355
	);
356
357
	// Past to this simpleton of a function...
358
	return ssi_queryPosts($query_where, $query_where_params, $num_recent, 'm.id_msg DESC', $output_method, $limit_body);
359
}
360
361
/**
362
 * Fetches one or more posts by ID.
363
 * @param array $post_ids An array containing the IDs of the posts to show
364
 * @param bool $override_permissions Whether to ignore permissions. If true, will show posts even if the user doesn't have permission to see them.
365
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of info about them
366
 * @return void|array Displays the specified posts or returns an array of info about them, depending on output_method.
367
 */
368
function ssi_fetchPosts($post_ids = array(), $override_permissions = false, $output_method = 'echo')
369
{
370
	global $modSettings;
371
372
	if (empty($post_ids))
373
		return;
374
375
	// Allow the user to request more than one - why not?
376
	$post_ids = is_array($post_ids) ? $post_ids : array($post_ids);
377
378
	// Restrict the posts required...
379
	$query_where = '
380
		m.id_msg IN ({array_int:message_list})' . ($override_permissions ? '' : '
381
			AND {query_wanna_see_board}') . ($modSettings['postmod_active'] ? '
382
			AND m.approved = {int:is_approved}' : '');
383
	$query_where_params = array(
384
		'message_list' => $post_ids,
385
		'is_approved' => 1,
386
	);
387
388
	// Then make the query and dump the data.
389
	return ssi_queryPosts($query_where, $query_where_params, '', 'm.id_msg DESC', $output_method, false, $override_permissions);
390
}
391
392
/**
393
 * This handles actually pulling post info. Called from other functions to eliminate duplication.
394
 * @param string $query_where The WHERE clause for the query
395
 * @param array $query_where_params An array of parameters for the WHERE clause
396
 * @param int $query_limit The maximum number of rows to return
397
 * @param string $query_order The ORDER BY clause for the query
398
 * @param string $output_method The output method. If 'echo', displays the posts, otherwise returns an array of info about them.
399
 * @param bool $limit_body If true, will only show the first 384 characters of the post rather than all of it
400
 * @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
401
 * @return void|array Displays the posts or returns an array of info about them, depending on output_method
402
 */
403
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)
404
{
405
	global $scripturl, $txt, $user_info;
406
	global $modSettings, $smcFunc, $context;
407
408
	if (!empty($modSettings['enable_likes']))
409
		$context['can_like'] = allowedTo('likes_like');
410
411
	// Find all the posts. Newer ones will have higher IDs.
412
	$request = $smcFunc['db_query']('substring', '
413
		SELECT
414
			m.poster_time, m.subject, m.id_topic, m.id_member, m.id_msg, m.id_board, m.likes, b.name AS board_name,
415
			IFNULL(mem.real_name, m.poster_name) AS poster_name, ' . ($user_info['is_guest'] ? '1 AS is_read, 0 AS new_from' : '
416
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) >= m.id_msg_modified AS is_read,
417
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from') . ', ' . ($limit_body ? 'SUBSTRING(m.body, 1, 384) AS body' : 'm.body') . ', m.smileys_enabled
418
		FROM {db_prefix}messages AS m
419
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
420
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (!$user_info['is_guest'] ? '
421
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = m.id_topic AND lt.id_member = {int:current_member})
422
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = m.id_board AND lmr.id_member = {int:current_member})' : '') . '
423
		WHERE 1=1 ' . ($override_permissions ? '' : '
424
			AND {query_wanna_see_board}') . ($modSettings['postmod_active'] ? '
425
			AND m.approved = {int:is_approved}' : '') . '
426
		' . (empty($query_where) ? '' : 'AND ' . $query_where) . '
427
		ORDER BY ' . $query_order . '
428
		' . ($query_limit == '' ? '' : 'LIMIT ' . $query_limit),
429
		array_merge($query_where_params, array(
430
			'current_member' => $user_info['id'],
431
			'is_approved' => 1,
432
		))
433
	);
434
	$posts = array();
435
	while ($row = $smcFunc['db_fetch_assoc']($request))
436
	{
437
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
438
439
		// Censor it!
440
		censorText($row['subject']);
441
		censorText($row['body']);
442
443
		$preview = strip_tags(strtr($row['body'], array('<br>' => '&#10;')));
444
445
		// Build the array.
446
		$posts[$row['id_msg']] = array(
447
			'id' => $row['id_msg'],
448
			'board' => array(
449
				'id' => $row['id_board'],
450
				'name' => $row['board_name'],
451
				'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
452
				'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['board_name'] . '</a>'
453
			),
454
			'topic' => $row['id_topic'],
455
			'poster' => array(
456
				'id' => $row['id_member'],
457
				'name' => $row['poster_name'],
458
				'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
459
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
460
			),
461
			'subject' => $row['subject'],
462
			'short_subject' => shorten_subject($row['subject'], 25),
463
			'preview' => $smcFunc['strlen']($preview) > 128 ? $smcFunc['substr']($preview, 0, 128) . '...' : $preview,
464
			'body' => $row['body'],
465
			'time' => timeformat($row['poster_time']),
466
			'timestamp' => forum_time(true, $row['poster_time']),
467
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
468
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '" rel="nofollow">' . $row['subject'] . '</a>',
469
			'new' => !empty($row['is_read']),
470
			'is_new' => empty($row['is_read']),
471
			'new_from' => $row['new_from'],
472
		);
473
474
		// Get the likes for each message.
475
		if (!empty($modSettings['enable_likes']))
476
			$posts[$row['id_msg']]['likes'] = array(
477
				'count' => $row['likes'],
478
				'you' => in_array($row['id_msg'], prepareLikesContext($row['id_topic'])),
479
				'can_like' => !$context['user']['is_guest'] && $row['id_member'] != $context['user']['id'] && !empty($context['can_like']),
480
			);
481
	}
482
	$smcFunc['db_free_result']($request);
483
484
	// If mods want to do something with this list of posts, let them do that now.
485
	call_integration_hook('integrate_ssi_queryPosts', array(&$posts));
486
487
	// Just return it.
488
	if ($output_method != 'echo' || empty($posts))
489
		return $posts;
490
491
	echo '
492
		<table style="border: none" class="ssi_table">';
493
	foreach ($posts as $post)
494
		echo '
495
			<tr>
496
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
497
					[', $post['board']['link'], ']
498
				</td>
499
				<td style="vertical-align: top">
500
					<a href="', $post['href'], '">', $post['subject'], '</a>
501
					', $txt['by'], ' ', $post['poster']['link'], '
502
					', $post['is_new'] ? '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow" class="new_posts">' . $txt['new'] . '</a>' : '', '
503
				</td>
504
				<td style="text-align: right; white-space: nowrap">
505
					', $post['time'], '
506
				</td>
507
			</tr>';
508
	echo '
509
		</table>';
510
}
511
512
/**
513
 * Recent topic list:   [board] Subject by Poster   Date
514
 * @param int $num_recent How many recent topics to show
515
 * @param null|array $exclude_boards If set, exclude topics from the specified board(s)
516
 * @param null|array $include_boards If set, only include topics from the specified board(s)
517
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
518
 * @return void|array Either displays a list of topics or returns an array of info about them, depending on output_method.
519
 */
520
function ssi_recentTopics($num_recent = 8, $exclude_boards = null, $include_boards = null, $output_method = 'echo')
521
{
522
	global $settings, $scripturl, $txt, $user_info;
523
	global $modSettings, $smcFunc, $context;
524
525
	if ($exclude_boards === null && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0)
526
		$exclude_boards = array($modSettings['recycle_board']);
527
	else
528
		$exclude_boards = empty($exclude_boards) ? array() : (is_array($exclude_boards) ? $exclude_boards : array($exclude_boards));
529
530
	// Only some boards?.
531
	if (is_array($include_boards) || (int) $include_boards === $include_boards)
532
	{
533
		$include_boards = is_array($include_boards) ? $include_boards : array($include_boards);
534
	}
535
	elseif ($include_boards != null)
536
	{
537
		$output_method = $include_boards;
538
		$include_boards = array();
539
	}
540
541
	$icon_sources = array();
542
	foreach ($context['stable_icons'] as $icon)
543
		$icon_sources[$icon] = 'images_url';
544
545
	// Find all the posts in distinct topics.  Newer ones will have higher IDs.
546
	$request = $smcFunc['db_query']('substring', '
547
		SELECT
548
			t.id_topic, b.id_board, b.name AS board_name
549
		FROM {db_prefix}topics AS t
550
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
551
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
552
		WHERE t.id_last_msg >= {int:min_message_id}' . (empty($exclude_boards) ? '' : '
553
			AND b.id_board NOT IN ({array_int:exclude_boards})') . '' . (empty($include_boards) ? '' : '
554
			AND b.id_board IN ({array_int:include_boards})') . '
555
			AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
556
			AND t.approved = {int:is_approved}
557
			AND ml.approved = {int:is_approved}' : '') . '
558
		ORDER BY t.id_last_msg DESC
559
		LIMIT ' . $num_recent,
560
		array(
561
			'include_boards' => empty($include_boards) ? '' : $include_boards,
562
			'exclude_boards' => empty($exclude_boards) ? '' : $exclude_boards,
563
			'min_message_id' => $modSettings['maxMsgID'] - (!empty($context['min_message_topics']) ? $context['min_message_topics'] : 35) * min($num_recent, 5),
564
			'is_approved' => 1,
565
		)
566
	);
567
	$topics = array();
568
	while ($row = $smcFunc['db_fetch_assoc']($request))
569
		$topics[$row['id_topic']] = $row;
570
	$smcFunc['db_free_result']($request);
571
572
	// Did we find anything? If not, bail.
573
	if (empty($topics))
574
		return array();
575
576
	$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
577
578
	// Find all the posts in distinct topics.  Newer ones will have higher IDs.
579
	$request = $smcFunc['db_query']('substring', '
580
		SELECT
581
			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
582
			IFNULL(mem.real_name, mf.poster_name) AS poster_name, ' . ($user_info['is_guest'] ? '1 AS is_read, 0 AS new_from' : '
583
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, 0)) >= ml.id_msg_modified AS is_read,
584
			IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from') . ', SUBSTRING(mf.body, 1, 384) AS body, mf.smileys_enabled, mf.icon
585
		FROM {db_prefix}topics AS t
586
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
587
			INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_last_msg)
588
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mf.id_member)' . (!$user_info['is_guest'] ? '
589
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
590
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})' : '') . '
591
			LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)
592
		WHERE t.id_topic IN ({array_int:topic_list})
593
		ORDER BY t.id_last_msg DESC',
594
		array(
595
			'current_member' => $user_info['id'],
596
			'topic_list' => array_keys($topics),
597
		)
598
	);
599
	$posts = array();
600
	while ($row = $smcFunc['db_fetch_assoc']($request))
601
	{
602
		$row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']), array('<br>' => '&#10;')));
603
		if ($smcFunc['strlen']($row['body']) > 128)
604
			$row['body'] = $smcFunc['substr']($row['body'], 0, 128) . '...';
605
606
		// Censor the subject.
607
		censorText($row['subject']);
608
		censorText($row['body']);
609
610
		// Recycled icon
611
		if (!empty($recycle_board) && $topics[$row['id_topic']]['id_board'])
612
			$row['icon'] = 'recycled';
613
614
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
615
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
616
		elseif (!isset($icon_sources[$row['icon']]))
617
			$icon_sources[$row['icon']] = 'images_url';
618
619
		// Build the array.
620
		$posts[] = array(
621
			'board' => array(
622
				'id' => $topics[$row['id_topic']]['id_board'],
623
				'name' => $topics[$row['id_topic']]['board_name'],
624
				'href' => $scripturl . '?board=' . $topics[$row['id_topic']]['id_board'] . '.0',
625
				'link' => '<a href="' . $scripturl . '?board=' . $topics[$row['id_topic']]['id_board'] . '.0">' . $topics[$row['id_topic']]['board_name'] . '</a>',
626
			),
627
			'topic' => $row['id_topic'],
628
			'poster' => array(
629
				'id' => $row['id_member'],
630
				'name' => $row['poster_name'],
631
				'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
632
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
633
			),
634
			'subject' => $row['subject'],
635
			'replies' => $row['num_replies'],
636
			'views' => $row['num_views'],
637
			'short_subject' => shorten_subject($row['subject'], 25),
638
			'preview' => $row['body'],
639
			'time' => timeformat($row['poster_time']),
640
			'timestamp' => forum_time(true, $row['poster_time']),
641
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
642
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#new" rel="nofollow">' . $row['subject'] . '</a>',
643
			// Retained for compatibility - is technically incorrect!
644
			'new' => !empty($row['is_read']),
645
			'is_new' => empty($row['is_read']),
646
			'new_from' => $row['new_from'],
647
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" style="vertical-align:middle;" alt="' . $row['icon'] . '">',
648
		);
649
	}
650
	$smcFunc['db_free_result']($request);
651
652
	// If mods want to do somthing with this list of topics, let them do that now.
653
	call_integration_hook('integrate_ssi_recentTopics', array(&$posts));
654
655
	// Just return it.
656
	if ($output_method != 'echo' || empty($posts))
657
		return $posts;
658
659
	echo '
660
		<table style="border: none" class="ssi_table">';
661
	foreach ($posts as $post)
662
		echo '
663
			<tr>
664
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
665
					[', $post['board']['link'], ']
666
				</td>
667
				<td style="vertical-align: top">
668
					<a href="', $post['href'], '">', $post['subject'], '</a>
669
					', $txt['by'], ' ', $post['poster']['link'], '
670
					', !$post['is_new'] ? '' : '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow" class="new_posts">' . $txt['new'] . '</a>', '
671
				</td>
672
				<td style="text-align: right; white-space: nowrap">
673
					', $post['time'], '
674
				</td>
675
			</tr>';
676
	echo '
677
		</table>';
678
}
679
680
/**
681
 * Shows a list of top posters
682
 * @param int $topNumber How many top posters to list
683
 * @param string $output_method The output method. If 'echo', will display a list of users, otherwise returns an array of info about them.
684
 * @return void|array Either displays a list of users or returns an array of info about them, depending on output_method.
685
 */
686
function ssi_topPoster($topNumber = 1, $output_method = 'echo')
687
{
688
	global $scripturl, $smcFunc;
689
690
	// Find the latest poster.
691
	$request = $smcFunc['db_query']('', '
692
		SELECT id_member, real_name, posts
693
		FROM {db_prefix}members
694
		ORDER BY posts DESC
695
		LIMIT ' . $topNumber,
696
		array(
697
		)
698
	);
699
	$return = array();
700
	while ($row = $smcFunc['db_fetch_assoc']($request))
701
		$return[] = array(
702
			'id' => $row['id_member'],
703
			'name' => $row['real_name'],
704
			'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
705
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>',
706
			'posts' => $row['posts']
707
		);
708
	$smcFunc['db_free_result']($request);
709
710
	// If mods want to do somthing with this list of members, let them do that now.
711
	call_integration_hook('integrate_ssi_topPoster', array(&$return));
712
713
	// Just return all the top posters.
714
	if ($output_method != 'echo')
715
		return $return;
716
717
	// Make a quick array to list the links in.
718
	$temp_array = array();
719
	foreach ($return as $member)
720
		$temp_array[] = $member['link'];
721
722
	echo implode(', ', $temp_array);
723
}
724
725
/**
726
 * Shows a list of top boards based on activity
727
 * @param int $num_top How many boards to display
728
 * @param string $output_method The output method. If 'echo', displays a list of boards, otherwise returns an array of info about them.
729
 * @return void|array Displays a list of the top boards or returns an array of info about them, depending on output_method.
730
 */
731
function ssi_topBoards($num_top = 10, $output_method = 'echo')
732
{
733
	global $txt, $scripturl, $user_info, $modSettings, $smcFunc;
734
735
	// Find boards with lots of posts.
736
	$request = $smcFunc['db_query']('', '
737
		SELECT
738
			b.name, b.num_topics, b.num_posts, b.id_board,' . (!$user_info['is_guest'] ? ' 1 AS is_read' : '
739
			(IFNULL(lb.id_msg, 0) >= b.id_last_msg) AS is_read') . '
740
		FROM {db_prefix}boards AS b
741
			LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
742
		WHERE {query_wanna_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
743
			AND b.id_board != {int:recycle_board}' : '') . '
744
		ORDER BY b.num_posts DESC
745
		LIMIT ' . $num_top,
746
		array(
747
			'current_member' => $user_info['id'],
748
			'recycle_board' => (int) $modSettings['recycle_board'],
749
		)
750
	);
751
	$boards = array();
752
	while ($row = $smcFunc['db_fetch_assoc']($request))
753
		$boards[] = array(
754
			'id' => $row['id_board'],
755
			'num_posts' => $row['num_posts'],
756
			'num_topics' => $row['num_topics'],
757
			'name' => $row['name'],
758
			'new' => empty($row['is_read']),
759
			'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
760
			'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>'
761
		);
762
	$smcFunc['db_free_result']($request);
763
764
	// If mods want to do somthing with this list of boards, let them do that now.
765
	call_integration_hook('integrate_ssi_topBoards', array(&$boards));
766
767
	// If we shouldn't output or have nothing to output, just jump out.
768
	if ($output_method != 'echo' || empty($boards))
769
		return $boards;
770
771
	echo '
772
		<table class="ssi_table">
773
			<tr>
774
				<th style="text-align: left">', $txt['board'], '</th>
775
				<th style="text-align: left">', $txt['board_topics'], '</th>
776
				<th style="text-align: left">', $txt['posts'], '</th>
777
			</tr>';
778
	foreach ($boards as $sBoard)
779
		echo '
780
			<tr>
781
				<td>', $sBoard['link'], $sBoard['new'] ? ' <a href="' . $sBoard['href'] . '" class="new_posts">' . $txt['new'] . '</a>' : '', '</td>
782
				<td style="text-align: right">', comma_format($sBoard['num_topics']), '</td>
783
				<td style="text-align: right">', comma_format($sBoard['num_posts']), '</td>
784
			</tr>';
785
	echo '
786
		</table>';
787
}
788
789
// Shows the top topics.
790
/**
791
 * Shows a list of top topics based on views or replies
792
 * @param string $type Can be either replies or views
793
 * @param int $num_topics How many topics to display
794
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them.
795
 * @return void|array Either displays a list of topics or returns an array of info about them, depending on output_method.
796
 */
797
function ssi_topTopics($type = 'replies', $num_topics = 10, $output_method = 'echo')
798
{
799
	global $txt, $scripturl, $modSettings, $smcFunc;
800
801
	if ($modSettings['totalMessages'] > 100000)
802
	{
803
		// @todo Why don't we use {query(_wanna)_see_board}?
804
		$request = $smcFunc['db_query']('', '
805
			SELECT id_topic
806
			FROM {db_prefix}topics
807
			WHERE num_' . ($type != 'replies' ? 'views' : 'replies') . ' != 0' . ($modSettings['postmod_active'] ? '
808
				AND approved = {int:is_approved}' : '') . '
809
			ORDER BY num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
810
			LIMIT {int:limit}',
811
			array(
812
				'is_approved' => 1,
813
				'limit' => $num_topics > 100 ? ($num_topics + ($num_topics / 2)) : 100,
814
			)
815
		);
816
		$topic_ids = array();
817
		while ($row = $smcFunc['db_fetch_assoc']($request))
818
			$topic_ids[] = $row['id_topic'];
819
		$smcFunc['db_free_result']($request);
820
	}
821
	else
822
		$topic_ids = array();
823
824
	$request = $smcFunc['db_query']('', '
825
		SELECT m.subject, m.id_topic, t.num_views, t.num_replies
826
		FROM {db_prefix}topics AS t
827
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
828
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
829
		WHERE {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
830
			AND t.approved = {int:is_approved}' : '') . (!empty($topic_ids) ? '
831
			AND t.id_topic IN ({array_int:topic_list})' : '') . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
832
			AND b.id_board != {int:recycle_enable}' : '') . '
833
		ORDER BY t.num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
834
		LIMIT {int:limit}',
835
		array(
836
			'topic_list' => $topic_ids,
837
			'is_approved' => 1,
838
			'recycle_enable' => $modSettings['recycle_board'],
839
			'limit' => $num_topics,
840
		)
841
	);
842
	$topics = array();
843
	while ($row = $smcFunc['db_fetch_assoc']($request))
844
	{
845
		censorText($row['subject']);
846
847
		$topics[] = array(
848
			'id' => $row['id_topic'],
849
			'subject' => $row['subject'],
850
			'num_replies' => $row['num_replies'],
851
			'num_views' => $row['num_views'],
852
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
853
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
854
		);
855
	}
856
	$smcFunc['db_free_result']($request);
857
858
	// If mods want to do somthing with this list of topics, let them do that now.
859
	call_integration_hook('integrate_ssi_topTopics', array(&$topics, $type));
860
861
	if ($output_method != 'echo' || empty($topics))
862
		return $topics;
863
864
	echo '
865
		<table class="ssi_table">
866
			<tr>
867
				<th style="text-align: left"></th>
868
				<th style="text-align: left">', $txt['views'], '</th>
869
				<th style="text-align: left">', $txt['replies'], '</th>
870
			</tr>';
871
	foreach ($topics as $sTopic)
872
		echo '
873
			<tr>
874
				<td style="text-align: left">
875
					', $sTopic['link'], '
876
				</td>
877
				<td style="text-align: right">', comma_format($sTopic['num_views']), '</td>
878
				<td style="text-align: right">', comma_format($sTopic['num_replies']), '</td>
879
			</tr>';
880
	echo '
881
		</table>';
882
}
883
884
/**
885
 * Top topics based on replies
886
 * @param int $num_topics How many topics to show
887
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
888
 * @return void|array Either displays a list of top topics or returns an array of info about them, depending on output_method.
889
 */
890
function ssi_topTopicsReplies($num_topics = 10, $output_method = 'echo')
891
{
892
	return ssi_topTopics('replies', $num_topics, $output_method);
893
}
894
895
/**
896
 * Top topics based on views
897
 * @param int $num_topics How many topics to show
898
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
899
 * @return void|array Either displays a list of top topics or returns an array of info about them, depending on output_method.
900
 */
901
function ssi_topTopicsViews($num_topics = 10, $output_method = 'echo')
902
{
903
	return ssi_topTopics('views', $num_topics, $output_method);
904
}
905
906
/**
907
 * Show a link to the latest member: Please welcome, Someone, our latest member.
908
 * @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.
909
 * @return void|array Displays a "welcome" message for the latest member or returns an array of info about them, depending on output_method.
910
 */
911
function ssi_latestMember($output_method = 'echo')
912
{
913
	global $txt, $context;
914
915
	if ($output_method == 'echo')
916
		echo '
917
	', sprintf($txt['welcome_newest_member'], $context['common_stats']['latest_member']['link']), '<br>';
918
	else
919
		return $context['common_stats']['latest_member'];
920
}
921
922
/**
923
 * Fetches a random member.
924
 * @param string $random_type If 'day', only fetches a new random member once a day.
925
 * @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.
926
 * @return void|array Displays a link to a random member's profile or returns an array of info about them depending on output_method.
927
 */
928
function ssi_randomMember($random_type = '', $output_method = 'echo')
929
{
930
	global $modSettings;
931
932
	// If we're looking for something to stay the same each day then seed the generator.
933
	if ($random_type == 'day')
934
	{
935
		// Set the seed to change only once per day.
936
		mt_srand(floor(time() / 86400));
0 ignored issues
show
floor(time() / 86400) of type double is incompatible with the type integer expected by parameter $seed of mt_srand(). ( Ignorable by Annotation )

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

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

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

Loading history...
1657
	$row = $smcFunc['db_fetch_assoc']($request);
1658
	$smcFunc['db_free_result']($request);
1659
1660
	if (!empty($row['voting_locked']) || ($row['selected'] != -1 && !$user_info['is_guest']) || (!empty($row['expire_time']) && time() > $row['expire_time']))
1661
		redirectexit('topic=' . $row['id_topic'] . '.0');
1662
1663
	// Too many options checked?
1664
	if (count($_REQUEST['options']) > $row['max_votes'])
1665
		redirectexit('topic=' . $row['id_topic'] . '.0');
1666
1667
	// It's a guest who has already voted?
1668
	if ($user_info['is_guest'])
1669
	{
1670
		// Guest voting disabled?
1671
		if (!$row['guest_vote'])
1672
			redirectexit('topic=' . $row['id_topic'] . '.0');
1673
		// Already voted?
1674
		elseif (isset($_COOKIE['guest_poll_vote']) && in_array($row['id_poll'], explode(',', $_COOKIE['guest_poll_vote'])))
1675
			redirectexit('topic=' . $row['id_topic'] . '.0');
1676
	}
1677
1678
	$sOptions = array();
1679
	$inserts = array();
1680
	foreach ($_REQUEST['options'] as $id)
1681
	{
1682
		$id = (int) $id;
1683
1684
		$sOptions[] = $id;
1685
		$inserts[] = array($_POST['poll'], $user_info['id'], $id);
1686
	}
1687
1688
	// Add their vote in to the tally.
1689
	$smcFunc['db_insert']('insert',
1690
		$db_prefix . 'log_polls',
1691
		array('id_poll' => 'int', 'id_member' => 'int', 'id_choice' => 'int'),
1692
		$inserts,
1693
		array('id_poll', 'id_member', 'id_choice')
1694
	);
1695
	$smcFunc['db_query']('', '
1696
		UPDATE {db_prefix}poll_choices
1697
		SET votes = votes + 1
1698
		WHERE id_poll = {int:current_poll}
1699
			AND id_choice IN ({array_int:option_list})',
1700
		array(
1701
			'option_list' => $sOptions,
1702
			'current_poll' => $_POST['poll'],
1703
		)
1704
	);
1705
1706
	// Track the vote if a guest.
1707
	if ($user_info['is_guest'])
1708
	{
1709
		$_COOKIE['guest_poll_vote'] = !empty($_COOKIE['guest_poll_vote']) ? ($_COOKIE['guest_poll_vote'] . ',' . $row['id_poll']) : $row['id_poll'];
1710
1711
		require_once($sourcedir . '/Subs-Auth.php');
1712
		$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
1713
		smf_setcookie('guest_poll_vote', $_COOKIE['guest_poll_vote'], time() + 2500000, $cookie_url[1], $cookie_url[0], false, false);
1714
	}
1715
1716
	redirectexit('topic=' . $row['id_topic'] . '.0');
1717
}
1718
1719
// Show a search box.
1720
/**
1721
 * Shows a search box
1722
 * @param string $output_method The output method. If 'echo', displays a search box, otherwise returns the URL of the search page.
1723
 * @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.
1724
 */
1725
function ssi_quickSearch($output_method = 'echo')
1726
{
1727
	global $scripturl, $txt, $context;
1728
1729
	if (!allowedTo('search_posts'))
1730
		return;
1731
1732
	if ($output_method != 'echo')
1733
		return $scripturl . '?action=search';
1734
1735
	echo '
1736
		<form action="', $scripturl, '?action=search2" method="post" accept-charset="', $context['character_set'], '">
1737
			<input type="hidden" name="advanced" value="0"><input type="text" name="ssi_search" size="30"> <input type="submit" value="', $txt['search'], '" class="button">
1738
		</form>';
1739
}
1740
1741
/**
1742
 * Show a random forum news item
1743
 * @param string $output_method The output method. If 'echo', shows the news item, otherwise returns it.
1744
 * @return void|string Shows or returns a random forum news item, depending on output_method.
1745
 */
1746
function ssi_news($output_method = 'echo')
1747
{
1748
	global $context;
1749
1750
	$context['random_news_line'] = !empty($context['news_lines']) ? $context['news_lines'][mt_rand(0, count($context['news_lines']) - 1)] : '';
1751
1752
	// 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.
1753
	call_integration_hook('integrate_ssi_news');
1754
1755
	if ($output_method != 'echo')
1756
		return $context['random_news_line'];
1757
1758
	echo $context['random_news_line'];
1759
}
1760
1761
/**
1762
 * Show today's birthdays.
1763
 * @param string $output_method The output method. If 'echo', displays a list of users, otherwise returns an array of info about them.
1764
 * @return void|array Displays a list of users or returns an array of info about them depending on output_method.
1765
 */
1766
function ssi_todaysBirthdays($output_method = 'echo')
1767
{
1768
	global $scripturl, $modSettings, $user_info;
1769
1770
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view') || !allowedTo('profile_view'))
1771
		return;
1772
1773
	$eventOptions = array(
1774
		'include_birthdays' => true,
1775
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1776
	);
1777
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1778
1779
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1780
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1781
1782
	if ($output_method != 'echo')
1783
		return $return['calendar_birthdays'];
1784
1785
	foreach ($return['calendar_birthdays'] as $member)
1786
		echo '
1787
			<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'] ? ', ' : '');
1788
}
1789
1790
/**
1791
 * Shows today's holidays.
1792
 * @param string $output_method The output method. If 'echo', displays a list of holidays, otherwise returns an array of info about them.
1793
 * @return void|array Displays a list of holidays or returns an array of info about them depending on output_method
1794
 */
1795
function ssi_todaysHolidays($output_method = 'echo')
1796
{
1797
	global $modSettings, $user_info;
1798
1799
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1800
		return;
1801
1802
	$eventOptions = array(
1803
		'include_holidays' => true,
1804
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1805
	);
1806
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1807
1808
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1809
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1810
1811
	if ($output_method != 'echo')
1812
		return $return['calendar_holidays'];
1813
1814
	echo '
1815
		', implode(', ', $return['calendar_holidays']);
1816
}
1817
1818
/**
1819
 * @param string $output_method The output method. If 'echo', displays a list of events, otherwise returns an array of info about them.
1820
 * @return void|array Displays a list of events or returns an array of info about them depending on output_method
1821
 */
1822
function ssi_todaysEvents($output_method = 'echo')
1823
{
1824
	global $modSettings, $user_info;
1825
1826
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1827
		return;
1828
1829
	$eventOptions = array(
1830
		'include_events' => true,
1831
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1832
	);
1833
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1834
1835
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1836
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1837
1838
	if ($output_method != 'echo')
1839
		return $return['calendar_events'];
1840
1841
	foreach ($return['calendar_events'] as $event)
1842
	{
1843
		if ($event['can_edit'])
1844
			echo '
1845
	<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
1846
		echo '
1847
	' . $event['link'] . (!$event['is_last'] ? ', ' : '');
1848
	}
1849
}
1850
1851
/**
1852
 * Shows today's calendar items (events, birthdays and holidays)
1853
 * @param string $output_method The output method. If 'echo', displays a list of calendar items, otherwise returns an array of info about them.
1854
 * @return void|array Displays a list of calendar items or returns an array of info about them depending on output_method
1855
 */
1856
function ssi_todaysCalendar($output_method = 'echo')
1857
{
1858
	global $modSettings, $txt, $scripturl, $user_info;
1859
1860
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
1861
		return;
1862
1863
	$eventOptions = array(
1864
		'include_birthdays' => allowedTo('profile_view'),
1865
		'include_holidays' => true,
1866
		'include_events' => true,
1867
		'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
1868
	);
1869
	$return = cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
1870
1871
	// The ssi_todaysCalendar variants all use the same hook and just pass on $eventOptions so the hooked code can distinguish different cases if necessary
1872
	call_integration_hook('integrate_ssi_calendar', array(&$return, $eventOptions));
1873
1874
	if ($output_method != 'echo')
1875
		return $return;
1876
1877
	if (!empty($return['calendar_holidays']))
1878
		echo '
1879
			<span class="holiday">' . $txt['calendar_prompt'] . ' ' . implode(', ', $return['calendar_holidays']) . '<br></span>';
1880
	if (!empty($return['calendar_birthdays']))
1881
	{
1882
		echo '
1883
			<span class="birthday">' . $txt['birthdays_upcoming'] . '</span> ';
1884
		foreach ($return['calendar_birthdays'] as $member)
1885
			echo '
1886
			<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'] ? ', ' : '';
1887
		echo '
1888
			<br>';
1889
	}
1890
	if (!empty($return['calendar_events']))
1891
	{
1892
		echo '
1893
			<span class="event">' . $txt['events_upcoming'] . '</span> ';
1894
		foreach ($return['calendar_events'] as $event)
1895
		{
1896
			if ($event['can_edit'])
1897
				echo '
1898
			<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
1899
			echo '
1900
			' . $event['link'] . (!$event['is_last'] ? ', ' : '');
1901
		}
1902
	}
1903
}
1904
1905
/**
1906
 * Show the latest news, with a template... by board.
1907
 * @param null|int $board The ID of the board to get the info from. Defaults to $board or $_GET['board'] if not set.
1908
 * @param null|int $limit How many items to show. Defaults to $_GET['limit'] or 5 if not set.
1909
 * @param null|int $start Start with the specified item. Defaults to $_GET['start'] or 0 if not set.
1910
 * @param null|int $length How many characters to show from each post. Defaults to $_GET['length'] or 0 (no limit) if not set.
1911
 * @param string $output_method The output method. If 'echo', displays the news items, otherwise returns an array of info about them.
1912
 * @return void|array Displays the news items or returns an array of info about them, depending on output_method.
1913
 */
1914
function ssi_boardNews($board = null, $limit = null, $start = null, $length = null, $output_method = 'echo')
1915
{
1916
	global $scripturl, $txt, $settings, $modSettings, $context;
1917
	global $smcFunc;
1918
1919
	loadLanguage('Stats');
1920
1921
	// Must be integers....
1922
	if ($limit === null)
1923
		$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 5;
1924
	else
1925
		$limit = (int) $limit;
1926
1927
	if ($start === null)
1928
		$start = isset($_GET['start']) ? (int) $_GET['start'] : 0;
1929
	else
1930
		$start = (int) $start;
1931
1932
	if ($board !== null)
1933
		$board = (int) $board;
1934
	elseif (isset($_GET['board']))
1935
		$board = (int) $_GET['board'];
1936
1937
	if ($length === null)
1938
		$length = isset($_GET['length']) ? (int) $_GET['length'] : 0;
1939
	else
1940
		$length = (int) $length;
1941
1942
	$limit = max(0, $limit);
1943
	$start = max(0, $start);
1944
1945
	// Make sure guests can see this board.
1946
	$request = $smcFunc['db_query']('', '
1947
		SELECT id_board
1948
		FROM {db_prefix}boards
1949
		WHERE ' . ($board === null ? '' : 'id_board = {int:current_board}
1950
			AND ') . 'FIND_IN_SET(-1, member_groups) != 0
1951
		LIMIT 1',
1952
		array(
1953
			'current_board' => $board,
1954
		)
1955
	);
1956
	if ($smcFunc['db_num_rows']($request) == 0)
1957
	{
1958
		if ($output_method == 'echo')
1959
			die($txt['ssi_no_guests']);
0 ignored issues
show
Using exit here is not recommended.

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

Loading history...
1960
		else
1961
			return array();
1962
	}
1963
	list ($board) = $smcFunc['db_fetch_row']($request);
1964
	$smcFunc['db_free_result']($request);
1965
1966
	$icon_sources = array();
1967
	foreach ($context['stable_icons'] as $icon)
1968
		$icon_sources[$icon] = 'images_url';
1969
1970
	if (!empty($modSettings['enable_likes']))
1971
	{
1972
		$context['can_like'] = allowedTo('likes_like');
1973
	}
1974
1975
	// Find the post ids.
1976
	$request = $smcFunc['db_query']('', '
1977
		SELECT t.id_first_msg
1978
		FROM {db_prefix}topics as t
1979
		LEFT JOIN {db_prefix}boards as b ON (b.id_board = t.id_board)
1980
		WHERE t.id_board = {int:current_board}' . ($modSettings['postmod_active'] ? '
1981
			AND t.approved = {int:is_approved}' : '') . '
1982
			AND {query_see_board}
1983
		ORDER BY t.id_first_msg DESC
1984
		LIMIT ' . $start . ', ' . $limit,
1985
		array(
1986
			'current_board' => $board,
1987
			'is_approved' => 1,
1988
		)
1989
	);
1990
	$posts = array();
1991
	while ($row = $smcFunc['db_fetch_assoc']($request))
1992
		$posts[] = $row['id_first_msg'];
1993
	$smcFunc['db_free_result']($request);
1994
1995
	if (empty($posts))
1996
		return array();
1997
1998
	// Find the posts.
1999
	$request = $smcFunc['db_query']('', '
2000
		SELECT
2001
			m.icon, m.subject, m.body, IFNULL(mem.real_name, m.poster_name) AS poster_name, m.poster_time, m.likes,
2002
			t.num_replies, t.id_topic, m.id_member, m.smileys_enabled, m.id_msg, t.locked, t.id_last_msg, m.id_board
2003
		FROM {db_prefix}topics AS t
2004
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
2005
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
2006
		WHERE t.id_first_msg IN ({array_int:post_list})
2007
		ORDER BY t.id_first_msg DESC
2008
		LIMIT ' . count($posts),
2009
		array(
2010
			'post_list' => $posts,
2011
		)
2012
	);
2013
	$return = array();
2014
	$recycle_board = !empty($modSettings['recycle_enable']) && !empty($modSettings['recycle_board']) ? (int) $modSettings['recycle_board'] : 0;
2015
	while ($row = $smcFunc['db_fetch_assoc']($request))
2016
	{
2017
		// If we want to limit the length of the post.
2018
		if (!empty($length) && $smcFunc['strlen']($row['body']) > $length)
2019
		{
2020
			$row['body'] = $smcFunc['substr']($row['body'], 0, $length);
2021
			$cutoff = false;
2022
2023
			$last_space = strrpos($row['body'], ' ');
2024
			$last_open = strrpos($row['body'], '<');
2025
			$last_close = strrpos($row['body'], '>');
2026
			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)
2027
				$cutoff = $last_open;
2028
			elseif (empty($last_close) || $last_close < $last_open)
2029
				$cutoff = $last_space;
2030
2031
			if ($cutoff !== false)
2032
				$row['body'] = $smcFunc['substr']($row['body'], 0, $cutoff);
2033
			$row['body'] .= '...';
2034
		}
2035
2036
		$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
2037
2038
		if (!empty($recycle_board) && $row['id_board'] == $recycle_board)
2039
			$row['icon'] = 'recycled';
2040
2041
		// Check that this message icon is there...
2042
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
2043
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
2044
		elseif (!isset($icon_sources[$row['icon']]))
2045
			$icon_sources[$row['icon']] = 'images_url';
2046
2047
		censorText($row['subject']);
2048
		censorText($row['body']);
2049
2050
		$return[] = array(
2051
			'id' => $row['id_topic'],
2052
			'message_id' => $row['id_msg'],
2053
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" alt="' . $row['icon'] . '">',
2054
			'subject' => $row['subject'],
2055
			'time' => timeformat($row['poster_time']),
2056
			'timestamp' => forum_time(true, $row['poster_time']),
2057
			'body' => $row['body'],
2058
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
2059
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['num_replies'] . ' ' . ($row['num_replies'] == 1 ? $txt['ssi_comment'] : $txt['ssi_comments']) . '</a>',
2060
			'replies' => $row['num_replies'],
2061
			'comment_href' => !empty($row['locked']) ? '' : $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . ';last_msg=' . $row['id_last_msg'],
2062
			'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>',
2063
			'new_comment' => !empty($row['locked']) ? '' : '<a href="' . $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . '">' . $txt['ssi_write_comment'] . '</a>',
2064
			'poster' => array(
2065
				'id' => $row['id_member'],
2066
				'name' => $row['poster_name'],
2067
				'href' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
2068
				'link' => !empty($row['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>' : $row['poster_name']
2069
			),
2070
			'locked' => !empty($row['locked']),
2071
			'is_last' => false,
2072
			// Nasty ternary for likes not messing around the "is_last" check.
2073
			'likes' => !empty($modSettings['enable_likes']) ? array(
2074
				'count' => $row['likes'],
2075
				'you' => in_array($row['id_msg'], prepareLikesContext((int) $row['id_topic'])),
2076
				'can_like' => !$context['user']['is_guest'] && $row['id_member'] != $context['user']['id'] && !empty($context['can_like']),
2077
			) : array(),
2078
		);
2079
	}
2080
	$smcFunc['db_free_result']($request);
2081
2082
	if (empty($return))
2083
		return $return;
2084
2085
	$return[count($return) - 1]['is_last'] = true;
2086
2087
	// If mods want to do somthing with this list of posts, let them do that now.
2088
	call_integration_hook('integrate_ssi_boardNews', array(&$return));
2089
2090
	if ($output_method != 'echo')
2091
		return $return;
2092
2093
	foreach ($return as $news)
2094
	{
2095
		echo '
2096
			<div class="news_item">
2097
				<h3 class="news_header">
2098
					', $news['icon'], '
2099
					<a href="', $news['href'], '">', $news['subject'], '</a>
2100
				</h3>
2101
				<div class="news_timestamp">', $news['time'], ' ', $txt['by'], ' ', $news['poster']['link'], '</div>
2102
				<div class="news_body" style="padding: 2ex 0;">', $news['body'], '</div>
2103
				', $news['link'], $news['locked'] ? '' : ' | ' . $news['comment_link'], '';
2104
2105
2106
		// Is there any likes to show?
2107
		if (!empty($modSettings['enable_likes']))
2108
		{
2109
			echo '
2110
					<ul>';
2111
2112
			if (!empty($news['likes']['can_like']))
2113
			{
2114
				echo '
2115
						<li class="like_button" id="msg_', $news['message_id'], '_likes"><a href="', $scripturl, '?action=likes;ltype=msg;sa=like;like=', $news['message_id'], ';', $context['session_var'], '=', $context['session_id'], '" class="msg_like"><span class="', $news['likes']['you'] ? 'unlike' : 'like', '"></span>', $news['likes']['you'] ? $txt['unlike'] : $txt['like'], '</a></li>';
2116
			}
2117
2118
			if (!empty($news['likes']['count']))
2119
			{
2120
				$context['some_likes'] = true;
2121
				$count = $news['likes']['count'];
2122
				$base = 'likes_';
2123
				if ($news['likes']['you'])
2124
				{
2125
					$base = 'you_' . $base;
2126
					$count--;
2127
				}
2128
				$base .= (isset($txt[$base . $count])) ? $count : 'n';
2129
2130
				echo '
2131
						<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>';
2132
			}
2133
2134
			echo '
2135
					</ul>';
2136
		}
2137
2138
2139
		// Close the main div.
2140
		echo '
2141
			</div>';
2142
2143
		if (!$news['is_last'])
2144
			echo '
2145
			<hr>';
2146
	}
2147
}
2148
2149
/**
2150
 * Show the most recent events
2151
 * @param int $max_events The maximum number of events to show
2152
 * @param string $output_method The output method. If 'echo', displays the events, otherwise returns an array of info about them.
2153
 * @return void|array Displays the events or returns an array of info about them, depending on output_method.
2154
 */
2155
function ssi_recentEvents($max_events = 7, $output_method = 'echo')
2156
{
2157
	global $user_info, $scripturl, $modSettings, $txt, $context, $smcFunc;
2158
2159
	if (empty($modSettings['cal_enabled']) || !allowedTo('calendar_view'))
2160
		return;
2161
2162
	// Find all events which are happening in the near future that the member can see.
2163
	$request = $smcFunc['db_query']('', '
2164
		SELECT
2165
			cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
2166
			cal.start_time, cal.end_time, cal.timezone, cal.location,
2167
			cal.id_board, t.id_first_msg, t.approved
2168
		FROM {db_prefix}calendar AS cal
2169
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
2170
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
2171
		WHERE cal.start_date <= {date:current_date}
2172
			AND cal.end_date >= {date:current_date}
2173
			AND (cal.id_board = {int:no_board} OR {query_wanna_see_board})
2174
		ORDER BY cal.start_date DESC
2175
		LIMIT ' . $max_events,
2176
		array(
2177
			'current_date' => strftime('%Y-%m-%d', forum_time(false)),
2178
			'no_board' => 0,
2179
		)
2180
	);
2181
	$return = array();
2182
	$duplicates = array();
2183
	while ($row = $smcFunc['db_fetch_assoc']($request))
2184
	{
2185
		// 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.
2186
		if (!empty($duplicates[$row['title'] . $row['id_topic']]))
2187
			continue;
2188
2189
		// Censor the title.
2190
		censorText($row['title']);
2191
2192
		if ($row['start_date'] < strftime('%Y-%m-%d', forum_time(false)))
2193
			$date = strftime('%Y-%m-%d', forum_time(false));
2194
		else
2195
			$date = $row['start_date'];
2196
2197
		// If the topic it is attached to is not approved then don't link it.
2198
		if (!empty($row['id_first_msg']) && !$row['approved'])
2199
			$row['id_board'] = $row['id_topic'] = $row['id_first_msg'] = 0;
2200
2201
		$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

2201
		$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...
2202
2203
		$return[$date][] = array(
2204
			'id' => $row['id_event'],
2205
			'title' => $row['title'],
2206
			'location' => $row['location'],
2207
			'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
2208
			'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'],
2209
			'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
2210
			'link' => $row['id_board'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
2211
			'start_date' => $row['start_date'],
2212
			'end_date' => $row['end_date'],
2213
			'start_time' => !$allday ? $row['start_time'] : null,
2214
			'end_time' => !$allday ? $row['end_time'] : null,
2215
			'tz' => !$allday ? $row['timezone'] : null,
2216
			'allday' => $allday,
2217
			'is_last' => false
2218
		);
2219
2220
		// Let's not show this one again, huh?
2221
		$duplicates[$row['title'] . $row['id_topic']] = true;
2222
	}
2223
	$smcFunc['db_free_result']($request);
2224
2225
	foreach ($return as $mday => $array)
2226
		$return[$mday][count($array) - 1]['is_last'] = true;
2227
2228
	// If mods want to do somthing with this list of events, let them do that now.
2229
	call_integration_hook('integrate_ssi_recentEvents', array(&$return));
2230
2231
	if ($output_method != 'echo' || empty($return))
2232
		return $return;
2233
2234
	// Well the output method is echo.
2235
	echo '
2236
			<span class="event">' . $txt['events'] . '</span> ';
2237
	foreach ($return as $mday => $array)
2238
		foreach ($array as $event)
2239
		{
2240
			if ($event['can_edit'])
2241
				echo '
2242
				<a href="' . $event['modify_href'] . '" style="color: #ff0000;">*</a> ';
2243
2244
			echo '
2245
				' . $event['link'] . (!$event['is_last'] ? ', ' : '');
2246
		}
2247
}
2248
2249
/**
2250
 * Checks whether the specified password is correct for the specified user.
2251
 * @param int|string $id The ID or username of a user
2252
 * @param string $password The password to check
2253
 * @param bool $is_username If true, treats $id as a username rather than a user ID
2254
 * @return bool Whether or not the password is correct.
2255
 */
2256
function ssi_checkPassword($id = null, $password = null, $is_username = false)
2257
{
2258
	global $smcFunc;
2259
2260
	// If $id is null, this was most likely called from a query string and should do nothing.
2261
	if ($id === null)
2262
		return;
2263
2264
	$request = $smcFunc['db_query']('', '
2265
		SELECT passwd, member_name, is_activated
2266
		FROM {db_prefix}members
2267
		WHERE ' . ($is_username ? 'member_name' : 'id_member') . ' = {string:id}
2268
		LIMIT 1',
2269
		array(
2270
			'id' => $id,
2271
		)
2272
	);
2273
	list ($pass, $user, $active) = $smcFunc['db_fetch_row']($request);
2274
	$smcFunc['db_free_result']($request);
2275
2276
	return hash_verify_password($user, $password, $pass) && $active == 1;
2277
}
2278
2279
/**
2280
 * Shows the most recent attachments that the user can see
2281
 * @param int $num_attachments How many to show
2282
 * @param array $attachment_ext Only shows attachments with the specified extensions ('jpg', 'gif', etc.) if set
2283
 * @param string $output_method The output method. If 'echo', displays a table with links/info, otherwise returns an array with information about the attachments
2284
 * @return void|array Displays a table of attachment info or returns an array containing info about the attachments, depending on output_method.
2285
 */
2286
function ssi_recentAttachments($num_attachments = 10, $attachment_ext = array(), $output_method = 'echo')
2287
{
2288
	global $smcFunc, $modSettings, $scripturl, $txt, $settings;
2289
2290
	// We want to make sure that we only get attachments for boards that we can see *if* any.
2291
	$attachments_boards = boardsAllowedTo('view_attachments');
2292
2293
	// No boards?  Adios amigo.
2294
	if (empty($attachments_boards))
2295
		return array();
2296
2297
	// Is it an array?
2298
	$attachment_ext = (array) $attachment_ext;
2299
2300
	// Lets build the query.
2301
	$request = $smcFunc['db_query']('', '
2302
		SELECT
2303
			att.id_attach, att.id_msg, att.filename, IFNULL(att.size, 0) AS filesize, att.downloads, mem.id_member,
2304
			IFNULL(mem.real_name, m.poster_name) AS poster_name, m.id_topic, m.subject, t.id_board, m.poster_time,
2305
			att.width, att.height' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ', IFNULL(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
2306
		FROM {db_prefix}attachments AS att
2307
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = att.id_msg)
2308
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
2309
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
2310
			LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = att.id_thumb)') . '
2311
		WHERE att.attachment_type = 0' . ($attachments_boards === array(0) ? '' : '
2312
			AND m.id_board IN ({array_int:boards_can_see})') . (!empty($attachment_ext) ? '
2313
			AND att.fileext IN ({array_string:attachment_ext})' : '') .
2314
			(!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
2315
			AND t.approved = {int:is_approved}
2316
			AND m.approved = {int:is_approved}
2317
			AND att.approved = {int:is_approved}') . '
2318
		ORDER BY att.id_attach DESC
2319
		LIMIT {int:num_attachments}',
2320
		array(
2321
			'boards_can_see' => $attachments_boards,
2322
			'attachment_ext' => $attachment_ext,
2323
			'num_attachments' => $num_attachments,
2324
			'is_approved' => 1,
2325
		)
2326
	);
2327
2328
	// We have something.
2329
	$attachments = array();
2330
	while ($row = $smcFunc['db_fetch_assoc']($request))
2331
	{
2332
		$filename = preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($row['filename']));
2333
2334
		// Is it an image?
2335
		$attachments[$row['id_attach']] = array(
2336
			'member' => array(
2337
				'id' => $row['id_member'],
2338
				'name' => $row['poster_name'],
2339
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>',
2340
			),
2341
			'file' => array(
2342
				'filename' => $filename,
2343
				'filesize' => round($row['filesize'] / 1024, 2) . $txt['kilobyte'],
2344
				'downloads' => $row['downloads'],
2345
				'href' => $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'],
2346
				'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>',
2347
				'is_image' => !empty($row['width']) && !empty($row['height']) && !empty($modSettings['attachmentShowImages']),
2348
			),
2349
			'topic' => array(
2350
				'id' => $row['id_topic'],
2351
				'subject' => $row['subject'],
2352
				'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'],
2353
				'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#msg' . $row['id_msg'] . '">' . $row['subject'] . '</a>',
2354
				'time' => timeformat($row['poster_time']),
2355
			),
2356
		);
2357
2358
		// Images.
2359
		if ($attachments[$row['id_attach']]['file']['is_image'])
2360
		{
2361
			$id_thumb = empty($row['id_thumb']) ? $row['id_attach'] : $row['id_thumb'];
2362
			$attachments[$row['id_attach']]['file']['image'] = array(
2363
				'id' => $id_thumb,
2364
				'width' => $row['width'],
2365
				'height' => $row['height'],
2366
				'img' => '<img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $row['id_attach'] . ';image" alt="' . $filename . '">',
2367
				'thumb' => '<img src="' . $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image" alt="' . $filename . '">',
2368
				'href' => $scripturl . '?action=dlattach;topic=' . $row['id_topic'] . '.0;attach=' . $id_thumb . ';image',
2369
				'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>',
2370
			);
2371
		}
2372
	}
2373
	$smcFunc['db_free_result']($request);
2374
2375
	// If mods want to do somthing with this list of attachments, let them do that now.
2376
	call_integration_hook('integrate_ssi_recentAttachments', array(&$attachments));
2377
2378
	// So you just want an array?  Here you can have it.
2379
	if ($output_method == 'array' || empty($attachments))
2380
		return $attachments;
2381
2382
	// Give them the default.
2383
	echo '
2384
		<table class="ssi_downloads">
2385
			<tr>
2386
				<th style="text-align: left; padding: 2">', $txt['file'], '</th>
2387
				<th style="text-align: left; padding: 2">', $txt['posted_by'], '</th>
2388
				<th style="text-align: left; padding: 2">', $txt['downloads'], '</th>
2389
				<th style="text-align: left; padding: 2">', $txt['filesize'], '</th>
2390
			</tr>';
2391
	foreach ($attachments as $attach)
2392
		echo '
2393
			<tr>
2394
				<td>', $attach['file']['link'], '</td>
2395
				<td>', $attach['member']['link'], '</td>
2396
				<td style="text-align: center">', $attach['file']['downloads'], '</td>
2397
				<td>', $attach['file']['filesize'], '</td>
2398
			</tr>';
2399
	echo '
2400
		</table>';
2401
}
2402
2403
?>