Passed
Push — release-2.1 ( b7b9b9...450da8 )
by Mathias
07:12
created

SSI.php (6 issues)

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,
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
		array(
594
			'current_member' => $user_info['id'],
595
			'topic_list' => array_keys($topics),
596
		)
597
	);
598
	$posts = array();
599
	while ($row = $smcFunc['db_fetch_assoc']($request))
600
	{
601
		$row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']), array('<br>' => '&#10;')));
602
		if ($smcFunc['strlen']($row['body']) > 128)
603
			$row['body'] = $smcFunc['substr']($row['body'], 0, 128) . '...';
604
605
		// Censor the subject.
606
		censorText($row['subject']);
607
		censorText($row['body']);
608
609
		// Recycled icon
610
		if (!empty($recycle_board) && $topics[$row['id_topic']]['id_board'])
611
			$row['icon'] = 'recycled';
612
613
		if (!empty($modSettings['messageIconChecks_enable']) && !isset($icon_sources[$row['icon']]))
614
			$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
615
		elseif (!isset($icon_sources[$row['icon']]))
616
			$icon_sources[$row['icon']] = 'images_url';
617
618
		// Build the array.
619
		$posts[] = array(
620
			'board' => array(
621
				'id' => $topics[$row['id_topic']]['id_board'],
622
				'name' => $topics[$row['id_topic']]['board_name'],
623
				'href' => $scripturl . '?board=' . $topics[$row['id_topic']]['id_board'] . '.0',
624
				'link' => '<a href="' . $scripturl . '?board=' . $topics[$row['id_topic']]['id_board'] . '.0">' . $topics[$row['id_topic']]['board_name'] . '</a>',
625
			),
626
			'topic' => $row['id_topic'],
627
			'poster' => array(
628
				'id' => $row['id_member'],
629
				'name' => $row['poster_name'],
630
				'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'],
631
				'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>'
632
			),
633
			'subject' => $row['subject'],
634
			'replies' => $row['num_replies'],
635
			'views' => $row['num_views'],
636
			'short_subject' => shorten_subject($row['subject'], 25),
637
			'preview' => $row['body'],
638
			'time' => timeformat($row['poster_time']),
639
			'timestamp' => forum_time(true, $row['poster_time']),
640
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#new',
641
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . '#new" rel="nofollow">' . $row['subject'] . '</a>',
642
			// Retained for compatibility - is technically incorrect!
643
			'new' => !empty($row['is_read']),
644
			'is_new' => empty($row['is_read']),
645
			'new_from' => $row['new_from'],
646
			'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" style="vertical-align:middle;" alt="' . $row['icon'] . '">',
647
		);
648
	}
649
	$smcFunc['db_free_result']($request);
650
651
	// If mods want to do somthing with this list of topics, let them do that now.
652
	call_integration_hook('integrate_ssi_recentTopics', array(&$posts));
653
654
	// Just return it.
655
	if ($output_method != 'echo' || empty($posts))
656
		return $posts;
657
658
	echo '
659
		<table style="border: none" class="ssi_table">';
660
	foreach ($posts as $post)
661
		echo '
662
			<tr>
663
				<td style="text-align: right; vertical-align: top; white-space: nowrap">
664
					[', $post['board']['link'], ']
665
				</td>
666
				<td style="vertical-align: top">
667
					<a href="', $post['href'], '">', $post['subject'], '</a>
668
					', $txt['by'], ' ', $post['poster']['link'], '
669
					', !$post['is_new'] ? '' : '<a href="' . $scripturl . '?topic=' . $post['topic'] . '.msg' . $post['new_from'] . ';topicseen#new" rel="nofollow" class="new_posts">' . $txt['new'] . '</a>', '
670
				</td>
671
				<td style="text-align: right; white-space: nowrap">
672
					', $post['time'], '
673
				</td>
674
			</tr>';
675
	echo '
676
		</table>';
677
}
678
679
/**
680
 * Shows a list of top posters
681
 * @param int $topNumber How many top posters to list
682
 * @param string $output_method The output method. If 'echo', will display a list of users, otherwise returns an array of info about them.
683
 * @return void|array Either displays a list of users or returns an array of info about them, depending on output_method.
684
 */
685
function ssi_topPoster($topNumber = 1, $output_method = 'echo')
686
{
687
	global $scripturl, $smcFunc;
688
689
	// Find the latest poster.
690
	$request = $smcFunc['db_query']('', '
691
		SELECT id_member, real_name, posts
692
		FROM {db_prefix}members
693
		ORDER BY posts DESC
694
		LIMIT ' . $topNumber,
695
		array(
696
		)
697
	);
698
	$return = array();
699
	while ($row = $smcFunc['db_fetch_assoc']($request))
700
		$return[] = array(
701
			'id' => $row['id_member'],
702
			'name' => $row['real_name'],
703
			'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
704
			'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>',
705
			'posts' => $row['posts']
706
		);
707
	$smcFunc['db_free_result']($request);
708
709
	// If mods want to do somthing with this list of members, let them do that now.
710
	call_integration_hook('integrate_ssi_topPoster', array(&$return));
711
712
	// Just return all the top posters.
713
	if ($output_method != 'echo')
714
		return $return;
715
716
	// Make a quick array to list the links in.
717
	$temp_array = array();
718
	foreach ($return as $member)
719
		$temp_array[] = $member['link'];
720
721
	echo implode(', ', $temp_array);
722
}
723
724
/**
725
 * Shows a list of top boards based on activity
726
 * @param int $num_top How many boards to display
727
 * @param string $output_method The output method. If 'echo', displays a list of boards, otherwise returns an array of info about them.
728
 * @return void|array Displays a list of the top boards or returns an array of info about them, depending on output_method.
729
 */
730
function ssi_topBoards($num_top = 10, $output_method = 'echo')
731
{
732
	global $txt, $scripturl, $user_info, $modSettings, $smcFunc;
733
734
	// Find boards with lots of posts.
735
	$request = $smcFunc['db_query']('', '
736
		SELECT
737
			b.name, b.num_topics, b.num_posts, b.id_board,' . (!$user_info['is_guest'] ? ' 1 AS is_read' : '
738
			(IFNULL(lb.id_msg, 0) >= b.id_last_msg) AS is_read') . '
739
		FROM {db_prefix}boards AS b
740
			LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = b.id_board AND lb.id_member = {int:current_member})
741
		WHERE {query_wanna_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
742
			AND b.id_board != {int:recycle_board}' : '') . '
743
		ORDER BY b.num_posts DESC
744
		LIMIT ' . $num_top,
745
		array(
746
			'current_member' => $user_info['id'],
747
			'recycle_board' => (int) $modSettings['recycle_board'],
748
		)
749
	);
750
	$boards = array();
751
	while ($row = $smcFunc['db_fetch_assoc']($request))
752
		$boards[] = array(
753
			'id' => $row['id_board'],
754
			'num_posts' => $row['num_posts'],
755
			'num_topics' => $row['num_topics'],
756
			'name' => $row['name'],
757
			'new' => empty($row['is_read']),
758
			'href' => $scripturl . '?board=' . $row['id_board'] . '.0',
759
			'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['name'] . '</a>'
760
		);
761
	$smcFunc['db_free_result']($request);
762
763
	// If mods want to do somthing with this list of boards, let them do that now.
764
	call_integration_hook('integrate_ssi_topBoards', array(&$boards));
765
766
	// If we shouldn't output or have nothing to output, just jump out.
767
	if ($output_method != 'echo' || empty($boards))
768
		return $boards;
769
770
	echo '
771
		<table class="ssi_table">
772
			<tr>
773
				<th style="text-align: left">', $txt['board'], '</th>
774
				<th style="text-align: left">', $txt['board_topics'], '</th>
775
				<th style="text-align: left">', $txt['posts'], '</th>
776
			</tr>';
777
	foreach ($boards as $sBoard)
778
		echo '
779
			<tr>
780
				<td>', $sBoard['link'], $sBoard['new'] ? ' <a href="' . $sBoard['href'] . '" class="new_posts">' . $txt['new'] . '</a>' : '', '</td>
781
				<td style="text-align: right">', comma_format($sBoard['num_topics']), '</td>
782
				<td style="text-align: right">', comma_format($sBoard['num_posts']), '</td>
783
			</tr>';
784
	echo '
785
		</table>';
786
}
787
788
// Shows the top topics.
789
/**
790
 * Shows a list of top topics based on views or replies
791
 * @param string $type Can be either replies or views
792
 * @param int $num_topics How many topics to display
793
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them.
794
 * @return void|array Either displays a list of topics or returns an array of info about them, depending on output_method.
795
 */
796
function ssi_topTopics($type = 'replies', $num_topics = 10, $output_method = 'echo')
797
{
798
	global $txt, $scripturl, $modSettings, $smcFunc;
799
800
	if ($modSettings['totalMessages'] > 100000)
801
	{
802
		// @todo Why don't we use {query(_wanna)_see_board}?
803
		$request = $smcFunc['db_query']('', '
804
			SELECT id_topic
805
			FROM {db_prefix}topics
806
			WHERE num_' . ($type != 'replies' ? 'views' : 'replies') . ' != 0' . ($modSettings['postmod_active'] ? '
807
				AND approved = {int:is_approved}' : '') . '
808
			ORDER BY num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
809
			LIMIT {int:limit}',
810
			array(
811
				'is_approved' => 1,
812
				'limit' => $num_topics > 100 ? ($num_topics + ($num_topics / 2)) : 100,
813
			)
814
		);
815
		$topic_ids = array();
816
		while ($row = $smcFunc['db_fetch_assoc']($request))
817
			$topic_ids[] = $row['id_topic'];
818
		$smcFunc['db_free_result']($request);
819
	}
820
	else
821
		$topic_ids = array();
822
823
	$request = $smcFunc['db_query']('', '
824
		SELECT m.subject, m.id_topic, t.num_views, t.num_replies
825
		FROM {db_prefix}topics AS t
826
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
827
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
828
		WHERE {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
829
			AND t.approved = {int:is_approved}' : '') . (!empty($topic_ids) ? '
830
			AND t.id_topic IN ({array_int:topic_list})' : '') . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
831
			AND b.id_board != {int:recycle_enable}' : '') . '
832
		ORDER BY t.num_' . ($type != 'replies' ? 'views' : 'replies') . ' DESC
833
		LIMIT {int:limit}',
834
		array(
835
			'topic_list' => $topic_ids,
836
			'is_approved' => 1,
837
			'recycle_enable' => $modSettings['recycle_board'],
838
			'limit' => $num_topics,
839
		)
840
	);
841
	$topics = array();
842
	while ($row = $smcFunc['db_fetch_assoc']($request))
843
	{
844
		censorText($row['subject']);
845
846
		$topics[] = array(
847
			'id' => $row['id_topic'],
848
			'subject' => $row['subject'],
849
			'num_replies' => $row['num_replies'],
850
			'num_views' => $row['num_views'],
851
			'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
852
			'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
853
		);
854
	}
855
	$smcFunc['db_free_result']($request);
856
857
	// If mods want to do somthing with this list of topics, let them do that now.
858
	call_integration_hook('integrate_ssi_topTopics', array(&$topics, $type));
859
860
	if ($output_method != 'echo' || empty($topics))
861
		return $topics;
862
863
	echo '
864
		<table class="ssi_table">
865
			<tr>
866
				<th style="text-align: left"></th>
867
				<th style="text-align: left">', $txt['views'], '</th>
868
				<th style="text-align: left">', $txt['replies'], '</th>
869
			</tr>';
870
	foreach ($topics as $sTopic)
871
		echo '
872
			<tr>
873
				<td style="text-align: left">
874
					', $sTopic['link'], '
875
				</td>
876
				<td style="text-align: right">', comma_format($sTopic['num_views']), '</td>
877
				<td style="text-align: right">', comma_format($sTopic['num_replies']), '</td>
878
			</tr>';
879
	echo '
880
		</table>';
881
}
882
883
/**
884
 * Top topics based on replies
885
 * @param int $num_topics How many topics to show
886
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
887
 * @return void|array Either displays a list of top topics or returns an array of info about them, depending on output_method.
888
 */
889
function ssi_topTopicsReplies($num_topics = 10, $output_method = 'echo')
890
{
891
	return ssi_topTopics('replies', $num_topics, $output_method);
892
}
893
894
/**
895
 * Top topics based on views
896
 * @param int $num_topics How many topics to show
897
 * @param string $output_method The output method. If 'echo', displays a list of topics, otherwise returns an array of info about them
898
 * @return void|array Either displays a list of top topics or returns an array of info about them, depending on output_method.
899
 */
900
function ssi_topTopicsViews($num_topics = 10, $output_method = 'echo')
901
{
902
	return ssi_topTopics('views', $num_topics, $output_method);
903
}
904
905
/**
906
 * Show a link to the latest member: Please welcome, Someone, our latest member.
907
 * @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.
908
 * @return void|array Displays a "welcome" message for the latest member or returns an array of info about them, depending on output_method.
909
 */
910
function ssi_latestMember($output_method = 'echo')
911
{
912
	global $txt, $context;
913
914
	if ($output_method == 'echo')
915
		echo '
916
	', sprintf($txt['welcome_newest_member'], $context['common_stats']['latest_member']['link']), '<br>';
917
	else
918
		return $context['common_stats']['latest_member'];
919
}
920
921
/**
922
 * Fetches a random member.
923
 * @param string $random_type If 'day', only fetches a new random member once a day.
924
 * @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.
925
 * @return void|array Displays a link to a random member's profile or returns an array of info about them depending on output_method.
926
 */
927
function ssi_randomMember($random_type = '', $output_method = 'echo')
928
{
929
	global $modSettings;
930
931
	// If we're looking for something to stay the same each day then seed the generator.
932
	if ($random_type == 'day')
933
	{
934
		// Set the seed to change only once per day.
935
		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

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

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