sportal_get_shouts()   F
last analyzed

Complexity

Conditions 26
Paths 2880

Size

Total Lines 116
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 26
eloc 57
nc 2880
nop 2
dl 0
loc 116
rs 0
c 2
b 0
f 0

How to fix   Long Method    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
 * @package SimplePortal ElkArte
5
 *
6
 * @author SimplePortal Team
7
 * @copyright 2015-2021 SimplePortal Team
8
 * @license BSD 3-clause
9
 * @version 1.0.0 Beta 1
10
 */
11
12
use BBC\BBCParser;
13
use BBC\Codes;
14
use BBC\ParserWrapper;
15
16
17
/**
18
 * Load a shout box's parameters by ID
19
 *
20
 * @param int|null $shoutbox_id
21
 * @param boolean $active
22
 * @param boolean $allowed
23
 *
24
 * @return array
25
 */
26
function sportal_get_shoutbox($shoutbox_id = null, $active = false, $allowed = false)
27
{
28
	global $context;
29
30
	$db = database();
31
32
	$query = array();
33
	$parameters = array();
34
35
	if ($shoutbox_id !== null)
36
	{
37
		$query[] = 'id_shoutbox = {int:shoutbox_id}';
38
		$parameters['shoutbox_id'] = $shoutbox_id;
39
	}
40
41
	if (!empty($allowed))
42
	{
43
		$query[] = sprintf($context['SPortal']['permissions']['query'], 'permissions');
44
	}
45
46
	if (!empty($active))
47
	{
48
		$query[] = 'status = {int:status}';
49
		$parameters['status'] = 1;
50
	}
51
52
	$request = $db->query('', '
53
		SELECT
54
			id_shoutbox, name, permissions, moderator_groups, warning, allowed_bbc, height,
55
			num_show, num_max, refresh, reverse, caching, status, num_shouts, last_update
56
		FROM {db_prefix}sp_shoutboxes' . (!empty($query) ? '
57
		WHERE ' . implode(' AND ', $query) : '') . '
58
		ORDER BY name',
59
		$parameters
60
	);
61
	$return = array();
62
	while ($row = $db->fetch_assoc($request))
63
	{
64
		$return[$row['id_shoutbox']] = array(
65
			'id' => $row['id_shoutbox'],
66
			'name' => $row['name'],
67
			'permissions' => $row['permissions'],
68
			'moderator_groups' => $row['moderator_groups'] !== '' ? explode(',', $row['moderator_groups']) : array(),
69
			'warning' => $row['warning'],
70
			'allowed_bbc' => explode(',', $row['allowed_bbc']),
71
			'height' => $row['height'],
72
			'num_show' => $row['num_show'],
73
			'num_max' => $row['num_max'],
74
			'refresh' => $row['refresh'],
75
			'reverse' => $row['reverse'],
76
			'caching' => $row['caching'],
77
			'status' => $row['status'],
78
			'num_shouts' => $row['num_shouts'],
79
			'last_update' => $row['last_update'],
80
		);
81
	}
82
	$db->free_result($request);
83
84
	return !empty($shoutbox_id) ? current($return) : $return;
85
}
86
87
/**
88
 * Loads all the shouts for a given shoutbox
89
 *
90
 * @param int $shoutbox id of the shoutbox to get data from
91
 * @param array $parameters
92
 *
93
 * @return array
94
 */
95
function sportal_get_shouts($shoutbox, $parameters)
96
{
97
	global $scripturl, $context, $user_info, $modSettings, $txt;
98
99
	$db = database();
100
101
	// Set defaults or used what was passed
102
	$shoutbox = !empty($shoutbox) ? (int) $shoutbox : 0;
103
	$start = !empty($parameters['start']) ? (int) $parameters['start'] : 0;
104
	$limit = !empty($parameters['limit']) ? (int) $parameters['limit'] : 20;
105
	$bbc = !empty($parameters['bbc']) ? $parameters['bbc'] : array();
106
	$reverse = !empty($parameters['reverse']);
107
	$cache = !empty($parameters['cache']);
108
	$can_delete = !empty($parameters['can_moderate']);
109
110
	// BBC Parser just for the shoutbox
111
	$parser = new BBCParser($codes = new Codes());
112
113
	// We only allow a few codes in the shoutbox, so turn off others
114
	foreach ($codes->getTags() as $key => $code)
115
	{
116
		if (!in_array($key, $bbc))
117
		{
118
			$codes->disable($key);
119
		}
120
	}
121
122
	// Cached, use it first
123
	if (!empty($start) || !$cache || ($shouts = cache_get_data('shoutbox_shouts-' . $shoutbox, 240)) === null)
124
	{
125
		$request = $db->query('', '
126
			SELECT
127
				sh.id_shout, sh.body, sh.log_time,
128
				IFNULL(mem.id_member, 0) AS id_member,
129
				IFNULL(mem.real_name, sh.member_name) AS member_name,
130
				mg.online_color AS member_group_color,
131
				pg.online_color AS post_group_color
132
			FROM {db_prefix}sp_shouts AS sh
133
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = sh.id_member)
134
				LEFT JOIN {db_prefix}membergroups AS pg ON (pg.id_group = mem.id_post_group)
135
				LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)
136
			WHERE sh.id_shoutbox = {int:id_shoutbox}
137
			ORDER BY sh.id_shout DESC
138
			LIMIT {int:start}, {int:limit}',
139
			array(
140
				'id_shoutbox' => $shoutbox,
141
				'start' => $start,
142
				'limit' => $limit,
143
			)
144
		);
145
		$shouts = array();
146
		while ($row = $db->fetch_assoc($request))
147
		{
148
			$online_color = !empty($row['member_group_color']) ? $row['member_group_color'] : $row['post_group_color'];
149
			$shouts[$row['id_shout']] = array(
150
				'id' => $row['id_shout'],
151
				'author' => array(
152
					'id' => $row['id_member'],
153
					'name' => $row['member_name'],
154
					'link' => $row['id_member']
155
						? ('<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" title="' . $txt['on'] . ' ' . strip_tags(standardTime($row['log_time'])) . '"' . (!empty($online_color)
156
								? ' style="color: ' . $online_color . ';"' : '') . '>' . $row['member_name'] . '</a>')
157
						: $row['member_name'],
158
					'color' => $online_color,
159
				),
160
				'time' => $row['log_time'],
161
				'text' => $parser->enableSmileys(true)->parse($row['body'])
162
			);
163
		}
164
		$db->free_result($request);
165
166
		if (empty($start) && $cache)
167
		{
168
			cache_put_data('shoutbox_shouts-' . $shoutbox, $shouts, 240);
0 ignored issues
show
Unused Code introduced by
The call to cache_put_data() has too many arguments starting with $shouts. ( Ignorable by Annotation )

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

168
			/** @scrutinizer ignore-call */ 
169
   cache_put_data('shoutbox_shouts-' . $shoutbox, $shouts, 240);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
169
		}
170
	}
171
172
	// Restore BBC codes
173
	unset($parser);
174
175
	foreach ($shouts as $shout)
176
	{
177
		// Private shouts @username: only get shown to the shouter and shoutee, and the admin ;)
178
		if (preg_match('~^@(.+?): ~u', $shout['text'], $target) && Util::strtolower($target[1]) !== Util::strtolower($user_info['name']) && $shout['author']['id'] != $user_info['id'] && !$user_info['is_admin'])
179
		{
180
			unset($shouts[$shout['id']]);
181
			continue;
182
		}
183
184
		$shouts[$shout['id']] += array(
185
			'is_me' => preg_match('~^<div\sclass="meaction">\* ' . preg_quote($shout['author']['name'], '~') . '.+</div>$~', $shout['text']) != 0,
186
			'delete_link' => $can_delete
187
				? '<a class="dot dotdelete" href="' . $scripturl . '?action=shoutbox;shoutbox_id=' . $shoutbox . ';delete=' . $shout['id'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '"></a> ' : '',
188
			'delete_link_js' => $can_delete
189
				? '<a class="dot dotdelete" href="' . $scripturl . '?action=shoutbox;shoutbox_id=' . $shoutbox . ';delete=' . $shout['id'] . ';' . $context['session_var'] . '=' . $context['session_id'] . '" onclick="sp_delete_shout(' . $shoutbox . ', ' . $shout['id'] . ', \'' . $context['session_var'] . '\', \'' . $context['session_id'] . '\'); return false;"></a> ' : '',
190
		);
191
192
		// Prepare for display in the box
193
		$shouts[$shout['id']]['time'] = standardTime($shouts[$shout['id']]['time']);
194
		$shouts[$shout['id']]['text'] = preg_replace('~(</?)div([^<]*>)~', '$1span$2', $shouts[$shout['id']]['text']);
195
		$shouts[$shout['id']]['text'] = preg_replace('~<a([^>]+>)([^<]+)</a>~', '<a$1' . $txt['sp_link'] . '</a>', $shouts[$shout['id']]['text']);
196
		$shouts[$shout['id']]['text'] = censor($shouts[$shout['id']]['text']);
197
198
		// Ignored user, hide the shout with option to show it
199
		if (!empty($modSettings['enable_buddylist']) && in_array($shout['author']['id'], $context['user']['ignoreusers']))
200
		{
201
			$shouts[$shout['id']]['text'] = '<a href="#toggle" id="ignored_shout_link_' . $shout['id'] . '" onclick="sp_show_ignored_shout(' . $shout['id'] . '); return false;">[' . $txt['sp_shoutbox_show_ignored'] . ']</a><span id="ignored_shout_' . $shout['id'] . '" style="display: none;">' . $shouts[$shout['id']]['text'] . '</span>';
202
		}
203
	}
204
205
	if ($reverse)
206
	{
207
		$shouts = array_reverse($shouts);
0 ignored issues
show
Bug introduced by
It seems like $shouts can also be of type boolean; however, parameter $array of array_reverse() 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

207
		$shouts = array_reverse(/** @scrutinizer ignore-type */ $shouts);
Loading history...
208
	}
209
210
	return $shouts;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $shouts also could return the type boolean which is incompatible with the documented return type array.
Loading history...
211
}
212
213
/**
214
 * Return the number of shouts in a given shoutbox
215
 *
216
 * @param int $shoutbox_id ID of the shoutbox
217
 *
218
 * @return int
219
 */
220
function sportal_get_shoutbox_count($shoutbox_id)
221
{
222
	$db = database();
223
224
	$request = $db->query('', '
225
		SELECT 
226
			COUNT(*)
227
		FROM {db_prefix}sp_shouts
228
		WHERE id_shoutbox = {int:current}',
229
		array(
230
			'current' => $shoutbox_id,
231
		)
232
	);
233
	list ($total_shouts) = $db->fetch_row($request);
234
	$db->free_result($request);
235
236
	return $total_shouts;
237
}
238
239
/**
240
 * Adds a new shout to a given box
241
 *
242
 * - Prevents guest from adding a shout
243
 * - Checks the shout total and archives if over the display limit for the box
244
 *
245
 * @param array $shoutbox
246
 * @param string $shout
247
 *
248
 * @return bool
249
 */
250
function sportal_create_shout($shoutbox, $shout)
251
{
252
	global $user_info;
253
254
	$db = database();
255
	$parser = ParserWrapper::instance();
256
257
	// If a guest shouts in the woods, and no one is there to hear them
258
	if ($user_info['is_guest'])
259
	{
260
		return false;
261
	}
262
263
	// What, its not like we can shout to nothing
264
	if (empty($shoutbox))
265
	{
266
		return false;
267
	}
268
269
	if (trim(strip_tags($parser->parseMessage($shout, false), '<img>')) === '')
270
	{
271
		return false;
272
	}
273
274
	// Add the shout
275
	$db->insert('', '
276
		{db_prefix}sp_shouts',
277
		array('id_shoutbox' => 'int', 'id_member' => 'int', 'member_name' => 'string', 'log_time' => 'int', 'body' => 'string',),
278
		array($shoutbox['id'], $user_info['id'], $user_info['name'], time(), $shout,),
279
		array('id_shout')
280
	);
281
282
	// To many shouts in the box, then its archive maintenance time
283
	$shoutbox['num_shouts']++;
284
	if ($shoutbox['num_shouts'] > $shoutbox['num_max'])
285
	{
286
		$request = $db->query('', '
287
			SELECT
288
				id_shout
289
			FROM {db_prefix}sp_shouts
290
			WHERE id_shoutbox = {int:shoutbox}
291
			ORDER BY log_time
292
			LIMIT {int:limit}',
293
			array(
294
				'shoutbox' => $shoutbox['id'],
295
				'limit' => $shoutbox['num_shouts'] - $shoutbox['num_max'],
296
			)
297
		);
298
		$old_shouts = array();
299
		while ($row = $db->fetch_assoc($request))
300
			$old_shouts[] = $row['id_shout'];
301
		$db->free_result($request);
302
303
		sportal_delete_shout($shoutbox['id'], $old_shouts, true);
304
	}
305
	else
306
	{
307
		sportal_update_shoutbox($shoutbox['id'], true);
308
	}
309
310
	return true;
311
}
312
313
/**
314
 * Removes a shout from the shoutbox by id
315
 *
316
 * @param int $shoutbox_id
317
 * @param int[]|int $shouts
318
 * @param bool $prune
319
 *
320
 * @return null
321
 */
322
function sportal_delete_shout($shoutbox_id, $shouts, $prune = false)
323
{
324
	$db = database();
325
326
	if (!is_array($shouts))
327
	{
328
		$shouts = array($shouts);
329
	}
330
331
	// Remove it
332
	$db->query('', '
333
		DELETE FROM {db_prefix}sp_shouts
334
		WHERE id_shout IN ({array_int:shouts})',
335
		array(
336
			'shouts' => $shouts,
337
		)
338
	);
339
340
	// Update the view
341
	sportal_update_shoutbox($shoutbox_id, $prune ? count($shouts) - 1 : count($shouts));
342
}
343
344
/**
345
 * Updates the number of shouts for a given shoutbox
346
 *
347
 * Can supply a specific number to update the count to
348
 * Use true to increment by 1
349
 *
350
 * @param int $shoutbox_id
351
 * @param int|bool $num_shouts if true increase the count by 1
352
 *
353
 * @return null
354
 */
355
function sportal_update_shoutbox($shoutbox_id, $num_shouts = 0)
356
{
357
	$db = database();
358
359
	$db->query('', '
360
		UPDATE {db_prefix}sp_shoutboxes
361
		SET last_update = {int:time}' . ($num_shouts === 0 ? '' : ',
362
			num_shouts = {raw:shouts}') . '
363
		WHERE id_shoutbox = {int:shoutbox}',
364
		array(
365
			'shoutbox' => $shoutbox_id,
366
			'time' => time(),
367
			'shouts' => $num_shouts === true ? 'num_shouts + 1' : 'num_shouts - ' . $num_shouts,
368
		)
369
	);
370
371
	cache_put_data('shoutbox_shouts-' . $shoutbox_id, null, 240);
0 ignored issues
show
Unused Code introduced by
The call to cache_put_data() has too many arguments starting with null. ( Ignorable by Annotation )

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

371
	/** @scrutinizer ignore-call */ 
372
 cache_put_data('shoutbox_shouts-' . $shoutbox_id, null, 240);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
372
}