Passed
Push — release-2.1 ( 3fda31...d9a616 )
by Mathias
27s
created

ssi_copyright()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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