ssi_todaysCalendar()   C
last analyzed

Complexity

Conditions 15
Paths 69

Size

Total Lines 45
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 31
nop 1
dl 0
loc 45
rs 5.9166
c 0
b 0
f 0
nc 69

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

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