Completed
Push — release-2.1 ( 6f6d35...abeae7 )
by Mathias
08:46
created

Memberlist.php ➔ getCustFieldsMList()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 48
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 25
nc 3
nop 0
dl 0
loc 48
rs 9.125
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file contains the functions for displaying and searching in the
5
 * members list.
6
 *
7
 * Simple Machines Forum (SMF)
8
 *
9
 * @package SMF
10
 * @author Simple Machines http://www.simplemachines.org
11
 * @copyright 2017 Simple Machines and individual contributors
12
 * @license http://www.simplemachines.org/about/smf/license.php BSD
13
 *
14
 * @version 2.1 Beta 4
15
 */
16
17
if (!defined('SMF'))
18
	die('No direct access...');
19
20
/**
21
 * Shows a listing of registered members.
22
 * - If a subaction is not specified, lists all registered members.
23
 * - It allows searching for members with the 'search' sub action.
24
 * - It calls MLAll or MLSearch depending on the sub action.
25
 * - Requires the view_mlist permission.
26
 * - Accessed via ?action=mlist.
27
 *
28
 * @uses Memberlist template, main sub template.
29
 */
30
function Memberlist()
31
{
32
	global $scripturl, $txt, $modSettings, $context;
33
34
	// Make sure they can view the memberlist.
35
	isAllowedTo('view_mlist');
36
37
	loadTemplate('Memberlist');
38
39
	$context['listing_by'] = !empty($_GET['sa']) ? $_GET['sa'] : 'all';
40
41
	// $subActions array format:
42
	// 'subaction' => array('label', 'function', 'is_selected')
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
43
	$subActions = array(
44
		'all' => array($txt['view_all_members'], 'MLAll', $context['listing_by'] == 'all'),
45
		'search' => array($txt['mlist_search'], 'MLSearch', $context['listing_by'] == 'search'),
46
	);
47
48
	// Set up the sort links.
49
	$context['sort_links'] = array();
50
	foreach ($subActions as $act => $text)
51
	{
52
		$context['sort_links'][] = array(
53
			'label' => $text[0],
54
			'action' => $act,
55
			'selected' => $text[2],
56
		);
57
	}
58
59
	$context['num_members'] = $modSettings['totalMembers'];
60
61
	// Set up the columns...
62
	$context['columns'] = array(
63
		'is_online' => array(
64
			'label' => $txt['status'],
65
			'sort' => array(
66
				'down' => allowedTo('moderate_forum') ? 'COALESCE(lo.log_time, 1) ASC, real_name ASC' : 'CASE WHEN mem.show_online THEN COALESCE(lo.log_time, 1) ELSE 1 END ASC, real_name ASC',
67
				'up' => allowedTo('moderate_forum') ? 'COALESCE(lo.log_time, 1) DESC, real_name DESC' : 'CASE WHEN mem.show_online THEN COALESCE(lo.log_time, 1) ELSE 1 END DESC, real_name DESC'
68
			),
69
		),
70
		'real_name' => array(
71
			'label' => $txt['name'],
72
			'class' => 'lefttext',
73
			'sort' => array(
74
				'down' => 'mem.real_name DESC',
75
				'up' => 'mem.real_name ASC'
76
			),
77
		),
78
		'website_url' => array(
79
			'label' => $txt['website'],
80
			'link_with' => 'website',
81
			'sort' => array(
82
				'down' => 'LENGTH(mem.website_url) > 0 ASC, COALESCE(mem.website_url, 1=1) DESC, mem.website_url DESC',
83
				'up' => 'LENGTH(mem.website_url) > 0 DESC, COALESCE(mem.website_url, 1=1) ASC, mem.website_url ASC'
84
			),
85
		),
86
		'id_group' => array(
87
			'label' => $txt['position'],
88
			'sort' => array(
89
				'down' => 'COALESCE(mg.group_name, 1=1) DESC, mg.group_name DESC',
90
				'up' => 'COALESCE(mg.group_name, 1=1) ASC, mg.group_name ASC'
91
			),
92
		),
93
		'registered' => array(
94
			'label' => $txt['date_registered'],
95
			'sort' => array(
96
				'down' => 'mem.date_registered DESC',
97
				'up' => 'mem.date_registered ASC'
98
			),
99
		),
100
		'posts' => array(
101
			'label' => $txt['posts'],
102
			'colspan' => 2,
103
			'default_sort_rev' => true,
104
			'sort' => array(
105
				'down' => 'mem.posts DESC',
106
				'up' => 'mem.posts ASC'
107
			),
108
		)
109
	);
110
111
	$context['custom_profile_fields'] = getCustFieldsMList();
112
113
	if (!empty($context['custom_profile_fields']['columns']))
114
		$context['columns'] += $context['custom_profile_fields']['columns'];
115
116
	$context['colspan'] = 0;
117
	$context['disabled_fields'] = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
118
	foreach ($context['columns'] as $key => $column)
119
	{
120
		if (isset($context['disabled_fields'][$key]) || (isset($column['link_with']) && isset($context['disabled_fields'][$column['link_with']])))
121
		{
122
			unset($context['columns'][$key]);
123
			continue;
124
		}
125
126
		$context['colspan'] += isset($column['colspan']) ? $column['colspan'] : 1;
127
	}
128
129
	// Aesthetic stuff.
130
	end($context['columns']);
131
132
	$context['linktree'][] = array(
133
		'url' => $scripturl . '?action=mlist',
134
		'name' => $txt['members_list']
135
	);
136
137
	$context['can_send_pm'] = allowedTo('pm_send');
138
	$context['can_send_email'] = allowedTo('moderate_forum');
139
140
	// Build the memberlist button array.
141
	$context['memberlist_buttons'] = array(
142
		'view_all_members' => array('text' => 'view_all_members', 'image' => 'mlist.png', 'url' => $scripturl . '?action=mlist' . ';sa=all', 'active'=> true),
143
		'mlist_search' => array('text' => 'mlist_search', 'image' => 'mlist.png', 'url' => $scripturl . '?action=mlist' . ';sa=search'),
144
	);
145
146
	// Allow mods to add additional buttons here
147
	call_integration_hook('integrate_memberlist_buttons');
148
149
	// Jump to the sub action.
150
	if (isset($subActions[$context['listing_by']]))
151
		call_helper($subActions[$context['listing_by']][1]);
152
153
	else
154
		call_helper($subActions['all'][1]);
155
}
156
157
/**
158
 * List all members, page by page, with sorting.
159
 * Called from MemberList().
160
 * Can be passed a sort parameter, to order the display of members.
161
 * Calls printMemberListRows to retrieve the results of the query.
162
 */
163
function MLAll()
164
{
165
	global $txt, $scripturl;
166
	global $modSettings, $context, $smcFunc;
167
168
	// The chunk size for the cached index.
169
	$cache_step_size = 500;
170
171
	// Only use caching if:
172
	// 1. there are at least 2k members,
173
	// 2. the default sorting method (real_name) is being used,
174
	// 3. the page shown is high enough to make a DB filesort unprofitable.
175
	$use_cache = $modSettings['totalMembers'] > 2000 && (!isset($_REQUEST['sort']) || $_REQUEST['sort'] === 'real_name') && isset($_REQUEST['start']) && $_REQUEST['start'] > $cache_step_size;
176
177
	if ($use_cache)
178
	{
179
		// Maybe there's something cached already.
180
		if (!empty($modSettings['memberlist_cache']))
181
			$memberlist_cache = $smcFunc['json_decode']($modSettings['memberlist_cache'], true);
182
183
		// The chunk size for the cached index.
184
		$cache_step_size = 500;
185
186
		// Only update the cache if something changed or no cache existed yet.
187
		if (empty($memberlist_cache) || empty($modSettings['memberlist_updated']) || $memberlist_cache['last_update'] < $modSettings['memberlist_updated'])
188
		{
189
			$request = $smcFunc['db_query']('', '
190
				SELECT real_name
191
				FROM {db_prefix}members
192
				WHERE is_activated = {int:is_activated}
193
				ORDER BY real_name',
194
				array(
195
					'is_activated' => 1,
196
				)
197
			);
198
199
			$memberlist_cache = array(
200
				'last_update' => time(),
201
				'num_members' => $smcFunc['db_num_rows']($request),
202
				'index' => array(),
203
			);
204
205
			for ($i = 0, $n = $smcFunc['db_num_rows']($request); $i < $n; $i += $cache_step_size)
206
			{
207
				$smcFunc['db_data_seek']($request, $i);
208
				list($memberlist_cache['index'][$i]) = $smcFunc['db_fetch_row']($request);
209
			}
210
			$smcFunc['db_data_seek']($request, $memberlist_cache['num_members'] - 1);
211
			list ($memberlist_cache['index'][$i]) = $smcFunc['db_fetch_row']($request);
212
			$smcFunc['db_free_result']($request);
213
214
			// Now we've got the cache...store it.
215
			updateSettings(array('memberlist_cache' => $smcFunc['json_encode']($memberlist_cache)));
216
		}
217
218
		$context['num_members'] = $memberlist_cache['num_members'];
219
	}
220
221
	// Without cache we need an extra query to get the amount of members.
222
	else
223
	{
224
		$request = $smcFunc['db_query']('', '
225
			SELECT COUNT(*)
226
			FROM {db_prefix}members
227
			WHERE is_activated = {int:is_activated}',
228
			array(
229
				'is_activated' => 1,
230
			)
231
		);
232
		list ($context['num_members']) = $smcFunc['db_fetch_row']($request);
233
		$smcFunc['db_free_result']($request);
234
	}
235
236
	// Set defaults for sort (real_name) and start. (0)
237 View Code Duplication
	if (!isset($_REQUEST['sort']) || !isset($context['columns'][$_REQUEST['sort']]))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
238
		$_REQUEST['sort'] = 'real_name';
239
240
	if (!is_numeric($_REQUEST['start']))
241
	{
242
		if (preg_match('~^[^\'\\\\/]~' . ($context['utf8'] ? 'u' : ''), $smcFunc['strtolower']($_REQUEST['start']), $match) === 0)
243
			fatal_error('Hacker?', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
244
245
		$_REQUEST['start'] = $match[0];
246
247
		$request = $smcFunc['db_query']('substring', '
248
			SELECT COUNT(*)
249
			FROM {db_prefix}members
250
			WHERE LOWER(SUBSTRING(real_name, 1, 1)) < {string:first_letter}
251
				AND is_activated = {int:is_activated}',
252
			array(
253
				'is_activated' => 1,
254
				'first_letter' => $_REQUEST['start'],
255
			)
256
		);
257
		list ($_REQUEST['start']) = $smcFunc['db_fetch_row']($request);
258
		$smcFunc['db_free_result']($request);
259
	}
260
261
	$context['letter_links'] = '';
262
	for ($i = 97; $i < 123; $i++)
263
		$context['letter_links'] .= '<a href="' . $scripturl . '?action=mlist;sa=all;start=' . chr($i) . '#letter' . chr($i) . '">' . strtoupper(chr($i)) . '</a> ';
264
265
	// Sort out the column information.
266
	foreach ($context['columns'] as $col => $column_details)
267
	{
268
		$context['columns'][$col]['href'] = $scripturl . '?action=mlist;sort=' . $col . ';start=0';
269
270
		if ((!isset($_REQUEST['desc']) && $col == $_REQUEST['sort']) || ($col != $_REQUEST['sort'] && !empty($column_details['default_sort_rev'])))
271
			$context['columns'][$col]['href'] .= ';desc';
272
273
		$context['columns'][$col]['link'] = '<a href="' . $context['columns'][$col]['href'] . '" rel="nofollow">' . $context['columns'][$col]['label'] . '</a>';
274
		$context['columns'][$col]['selected'] = $_REQUEST['sort'] == $col;
275
	}
276
277
	// Are we sorting the results
278
	$context['sort_by'] = $_REQUEST['sort'];
279
	$context['sort_direction'] = !isset($_REQUEST['desc']) ? 'up' : 'down';
280
281
	// Construct the page index.
282
	$context['page_index'] = constructPageIndex($scripturl . '?action=mlist;sort=' . $_REQUEST['sort'] . (isset($_REQUEST['desc']) ? ';desc' : ''), $_REQUEST['start'], $context['num_members'], $modSettings['defaultMaxMembers']);
283
284
	// Send the data to the template.
285
	$context['start'] = $_REQUEST['start'] + 1;
286
	$context['end'] = min($_REQUEST['start'] + $modSettings['defaultMaxMembers'], $context['num_members']);
287
288
	$context['can_moderate_forum'] = allowedTo('moderate_forum');
289
	$context['page_title'] = sprintf($txt['viewing_members'], $context['start'], $context['end']);
290
	$context['linktree'][] = array(
291
		'url' => $scripturl . '?action=mlist;sort=' . $_REQUEST['sort'] . ';start=' . $_REQUEST['start'],
292
		'name' => &$context['page_title'],
293
		'extra_after' => '(' . sprintf($txt['of_total_members'], $context['num_members']) . ')'
294
	);
295
296
	$limit = $_REQUEST['start'];
297
	$query_parameters = array(
298
		'regular_id_group' => 0,
299
		'is_activated' => 1,
300
		'sort' => $context['columns'][$_REQUEST['sort']]['sort'][$context['sort_direction']],
301
		'blank_string' => '',
302
	);
303
304
	// Using cache allows to narrow down the list to be retrieved.
305
	if ($use_cache && $_REQUEST['sort'] === 'real_name' && !isset($_REQUEST['desc']))
306
	{
307
		$first_offset = $_REQUEST['start'] - ($_REQUEST['start'] % $cache_step_size);
308
		$second_offset = ceil(($_REQUEST['start'] + $modSettings['defaultMaxMembers']) / $cache_step_size) * $cache_step_size;
309
310
		$where = 'mem.real_name BETWEEN {string:real_name_low} AND {string:real_name_high}';
311
		$query_parameters['real_name_low'] = $memberlist_cache['index'][$first_offset];
0 ignored issues
show
Bug introduced by
The variable $memberlist_cache does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
312
		$query_parameters['real_name_high'] = $memberlist_cache['index'][$second_offset];
313
		$limit -= $first_offset;
314
	}
315
316
	// Reverse sorting is a bit more complicated...
317
	elseif ($use_cache && $_REQUEST['sort'] === 'real_name')
318
	{
319
		$first_offset = floor(($memberlist_cache['num_members'] - $modSettings['defaultMaxMembers'] - $_REQUEST['start']) / $cache_step_size) * $cache_step_size;
320
		if ($first_offset < 0)
321
			$first_offset = 0;
322
		$second_offset = ceil(($memberlist_cache['num_members'] - $_REQUEST['start']) / $cache_step_size) * $cache_step_size;
323
324
		$where = 'mem.real_name BETWEEN {string:real_name_low} AND {string:real_name_high}';
325
		$query_parameters['real_name_low'] = $memberlist_cache['index'][$first_offset];
326
		$query_parameters['real_name_high'] = $memberlist_cache['index'][$second_offset];
327
		$limit = $second_offset - ($memberlist_cache['num_members'] - $_REQUEST['start']) - ($second_offset > $memberlist_cache['num_members'] ? $cache_step_size - ($memberlist_cache['num_members'] % $cache_step_size) : 0);
328
	}
329
330
	$custom_fields_qry = '';
331
	if (!empty($context['custom_profile_fields']['join'][$_REQUEST['sort']]))
332
		$custom_fields_qry = $context['custom_profile_fields']['join'][$_REQUEST['sort']];
333
334
	// Select the members from the database.
335
	$request = $smcFunc['db_query']('', '
336
		SELECT mem.id_member
337
		FROM {db_prefix}members AS mem' . ($_REQUEST['sort'] === 'is_online' ? '
338
			LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)' : '') . ($_REQUEST['sort'] === 'id_group' ? '
339
			LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:regular_id_group} THEN mem.id_post_group ELSE mem.id_group END)' : '') . '
340
			' . $custom_fields_qry . '
341
		WHERE mem.is_activated = {int:is_activated}' . (empty($where) ? '' : '
342
			AND ' . $where) . '
343
		ORDER BY {raw:sort}
344
		LIMIT {int:start}, {int:max}',
345
		array_merge($query_parameters, array(
346
			'sort' => $query_parameters['sort'],
347
			'start' => $limit,
348
			'max' => $modSettings['defaultMaxMembers'],
349
		))
350
	);
351
	printMemberListRows($request);
352
	$smcFunc['db_free_result']($request);
353
354
	// Add anchors at the start of each letter.
355
	if ($_REQUEST['sort'] == 'real_name')
356
	{
357
		$last_letter = '';
358
		foreach ($context['members'] as $i => $dummy)
359
		{
360
			$this_letter = $smcFunc['strtolower']($smcFunc['substr']($context['members'][$i]['name'], 0, 1));
361
362
			if ($this_letter != $last_letter && preg_match('~[a-z]~', $this_letter) === 1)
363
			{
364
				$context['members'][$i]['sort_letter'] = $smcFunc['htmlspecialchars']($this_letter);
365
				$last_letter = $this_letter;
366
			}
367
		}
368
	}
369
}
370
371
/**
372
 * Search for members, or display search results.
373
 * - Called by MemberList().
374
 * - If variable 'search' is empty displays search dialog box, using the search sub template.
375
 * - Calls printMemberListRows to retrieve the results of the query.
376
 */
377
function MLSearch()
378
{
379
	global $txt, $scripturl, $context, $modSettings, $smcFunc;
380
381
	$context['page_title'] = $txt['mlist_search'];
382
	$context['can_moderate_forum'] = allowedTo('moderate_forum');
383
384
	// Can they search custom fields?
385
	$request = $smcFunc['db_query']('', '
386
		SELECT col_name, field_name, field_desc
387
		FROM {db_prefix}custom_fields
388
		WHERE active = {int:active}
389
			' . (allowedTo('admin_forum') ? '' : ' AND private < {int:private_level}') . '
390
			AND can_search = {int:can_search}
391
			AND (field_type = {string:field_type_text} OR field_type = {string:field_type_textarea} OR field_type = {string:field_type_select})',
392
		array(
393
			'active' => 1,
394
			'can_search' => 1,
395
			'private_level' => 2,
396
			'field_type_text' => 'text',
397
			'field_type_textarea' => 'textarea',
398
			'field_type_select' => 'select',
399
		)
400
	);
401
	$context['custom_search_fields'] = array();
402
	while ($row = $smcFunc['db_fetch_assoc']($request))
403
		$context['custom_search_fields'][$row['col_name']] = array(
404
			'colname' => $row['col_name'],
405
			'name' => $row['field_name'],
406
			'desc' => $row['field_desc'],
407
		);
408
	$smcFunc['db_free_result']($request);
409
410
	// They're searching..
411
	if (isset($_REQUEST['search']) && isset($_REQUEST['fields']))
412
	{
413
		$_POST['search'] = trim(isset($_GET['search']) ? $_GET['search'] : $_POST['search']);
414
		$_POST['fields'] = isset($_GET['fields']) ? explode(',', $_GET['fields']) : $_POST['fields'];
415
416
		$context['old_search'] = $_REQUEST['search'];
417
		$context['old_search_value'] = urlencode($_REQUEST['search']);
418
419
		// No fields?  Use default...
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
420
		if (empty($_POST['fields']))
421
			$_POST['fields'] = array('name');
422
423
		// Set defaults for how the results are sorted
424 View Code Duplication
		if (!isset($_REQUEST['sort']) || !isset($context['columns'][$_REQUEST['sort']]))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
425
			$_REQUEST['sort'] = 'real_name';
426
427
		// Build the column link / sort information.
428
		foreach ($context['columns'] as $col => $column_details)
429
		{
430
			$context['columns'][$col]['href'] = $scripturl . '?action=mlist;sa=search;start=0;sort=' . $col;
431
432
			if ((!isset($_REQUEST['desc']) && $col == $_REQUEST['sort']) || ($col != $_REQUEST['sort'] && !empty($column_details['default_sort_rev'])))
433
				$context['columns'][$col]['href'] .= ';desc';
434
435
			if (isset($_POST['search']) && isset($_POST['fields']))
436
				$context['columns'][$col]['href'] .= ';search=' . $_POST['search'] . ';fields=' . implode(',', $_POST['fields']);
437
438
			$context['columns'][$col]['link'] = '<a href="' . $context['columns'][$col]['href'] . '" rel="nofollow">' . $context['columns'][$col]['label'] . '</a>';
439
			$context['columns'][$col]['selected'] = $_REQUEST['sort'] == $col;
440
		}
441
442
		// set up some things for use in the template
443
		$context['sort_direction'] = !isset($_REQUEST['desc']) ? 'up' : 'down';
444
		$context['sort_by'] = $_REQUEST['sort'];
445
446
		$query_parameters = array(
447
			'regular_id_group' => 0,
448
			'is_activated' => 1,
449
			'blank_string' => '',
450
			'search' => '%' . strtr($smcFunc['htmlspecialchars']($_POST['search'], ENT_QUOTES), array('_' => '\\_', '%' => '\\%', '*' => '%')) . '%',
451
			'sort' => $context['columns'][$_REQUEST['sort']]['sort'][$context['sort_direction']],
452
		);
453
454
		// Search for a name
455
		if (in_array('name', $_POST['fields']))
456
		{
457
			$fields = allowedTo('moderate_forum') ? array('member_name', 'real_name') : array('real_name');
458
			$search_fields[] = 'name';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$search_fields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $search_fields = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
459
		}
460
		else
461
		{
462
			$fields = array();
463
			$search_fields = array();
464
		}
465
466
		// Search for websites.
467
		if (in_array('website', $_POST['fields']))
468
		{
469
			$fields += array(7 => 'website_title', 'website_url');
470
			$search_fields[] = 'website';
471
		}
472
		// Search for groups.
473
		if (in_array('group', $_POST['fields']))
474
		{
475
			$fields += array(9 => 'COALESCE(group_name, {string:blank_string})');
476
			$search_fields[] = 'group';
477
		}
478
		// Search for an email address?
479
		if (in_array('email', $_POST['fields']) && allowedTo('moderate_forum'))
480
		{
481
			$fields += array(2 => 'email_address');
482
			$search_fields[] = 'email';
483
		}
484
485
		if ($smcFunc['db_case_sensitive'])
486
			foreach ($fields as $key => $field)
487
				$fields[$key] = 'LOWER(' . $field . ')';
488
489
		$customJoin = array();
490
		$customCount = 10;
491
492
		// Any custom fields to search for - these being tricky?
493
		foreach ($_POST['fields'] as $field)
494
		{
495
			$row['col_name'] = substr($field, 5);
496
			if (substr($field, 0, 5) == 'cust_' && isset($context['custom_search_fields'][$row['col_name']]))
497
			{
498
				$customJoin[] = 'LEFT JOIN {db_prefix}themes AS t' . $row['col_name'] . ' ON (t' . $row['col_name'] . '.variable = {string:t' . $row['col_name'] . '} AND t' . $row['col_name'] . '.id_theme = 1 AND t' . $row['col_name'] . '.id_member = mem.id_member)';
499
				$query_parameters['t' . $row['col_name']] = $row['col_name'];
500
				$fields += array($customCount++ => 'COALESCE(t' . $row['col_name'] . '.value, {string:blank_string})');
501
				$search_fields[] = $field;
502
			}
503
		}
504
505
		// No search fields? That means you're trying to hack things
506
		if (empty($search_fields))
507
			fatal_lang_error('invalid_search_string', false);
508
509
		$query = $_POST['search'] == '' ? '= {string:blank_string}' : ($smcFunc['db_case_sensitive'] ? 'LIKE LOWER({string:search})' : 'LIKE {string:search}');
510
511
		$request = $smcFunc['db_query']('', '
512
			SELECT COUNT(*)
513
			FROM {db_prefix}members AS mem
514
				LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:regular_id_group} THEN mem.id_post_group ELSE mem.id_group END)' .
515
				(empty($customJoin) ? '' : implode('
516
				', $customJoin)) . '
517
			WHERE (' . implode(' ' . $query . ' OR ', $fields) . ' ' . $query . ')
518
				AND mem.is_activated = {int:is_activated}',
519
			$query_parameters
520
		);
521
		list ($numResults) = $smcFunc['db_fetch_row']($request);
522
		$smcFunc['db_free_result']($request);
523
524
		$context['page_index'] = constructPageIndex($scripturl . '?action=mlist;sa=search;search=' . $_POST['search'] . ';fields=' . implode(',', $_POST['fields']), $_REQUEST['start'], $numResults, $modSettings['defaultMaxMembers']);
525
526
		// Find the members from the database.
527
		$request = $smcFunc['db_query']('', '
528
			SELECT mem.id_member
529
			FROM {db_prefix}members AS mem
530
				LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)
531
				LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:regular_id_group} THEN mem.id_post_group ELSE mem.id_group END)' .
532
				(empty($customJoin) ? '' : implode('
533
				', $customJoin)) . '
534
			WHERE (' . implode(' ' . $query . ' OR ', $fields) . ' ' . $query . ')
535
				AND mem.is_activated = {int:is_activated}
536
			ORDER BY {raw:sort}
537
			LIMIT {int:start}, {int:max}',
538
			array_merge($query_parameters, array(
539
				'start' => $_REQUEST['start'],
540
				'max' => $modSettings['defaultMaxMembers'],
541
			))
542
		);
543
		printMemberListRows($request);
544
		$smcFunc['db_free_result']($request);
545
	}
546
	else
547
	{
548
		// These are all the possible fields.
549
		$context['search_fields'] = array(
550
			'name' => $txt['mlist_search_name'],
551
			'email' => $txt['mlist_search_email'],
552
			'website' => $txt['mlist_search_website'],
553
			'group' => $txt['mlist_search_group'],
554
		);
555
556
		// Sorry, but you can't search by email unless you can view emails
557
		if (!allowedTo('moderate_forum'))
558
		{
559
			unset($context['search_fields']['email']);
560
			$context['search_defaults'] = array('name');
561
		}
562
		else
563
		{
564
			$context['search_defaults'] = array('name', 'email');
565
		}
566
567
		foreach ($context['custom_search_fields'] as $field)
568
			$context['search_fields']['cust_' . $field['colname']] = sprintf($txt['mlist_search_by'], $field['name']);
569
570
		$context['sub_template'] = 'search';
571
		$context['old_search'] = isset($_GET['search']) ? $_GET['search'] : (isset($_POST['search']) ? $smcFunc['htmlspecialchars']($_POST['search']) : '');
572
573
		// Since we're nice we also want to default focus on to the search field.
574
		addInlineJavaScript('
575
	$(\'input[name="search"]\').focus();', true);
576
	}
577
578
	$context['linktree'][] = array(
579
		'url' => $scripturl . '?action=mlist;sa=search',
580
		'name' => &$context['page_title']
581
	);
582
583
	// Highlight the correct button, too!
584
	unset($context['memberlist_buttons']['view_all_members']['active']);
585
	$context['memberlist_buttons']['mlist_search']['active'] = true;
586
}
587
588
/**
589
 * Retrieves results of the request passed to it
590
 * Puts results of request into the context for the sub template.
591
 *
592
 * @param resource $request An SQL result resource
593
 */
594
function printMemberListRows($request)
595
{
596
	global $context, $memberContext, $smcFunc, $txt;
597
	global $scripturl, $settings;
598
599
	// Get the most posts.
600
	$result = $smcFunc['db_query']('', '
601
		SELECT MAX(posts)
602
		FROM {db_prefix}members',
603
		array(
604
		)
605
	);
606
	list ($most_posts) = $smcFunc['db_fetch_row']($result);
607
	$smcFunc['db_free_result']($result);
608
609
	// Avoid division by zero...
610
	if ($most_posts == 0)
611
		$most_posts = 1;
612
613
	$members = array();
614
	while ($row = $smcFunc['db_fetch_assoc']($request))
615
		$members[] = $row['id_member'];
616
617
	// Load all the members for display.
618
	loadMemberData($members);
619
620
	$context['members'] = array();
621
	foreach ($members as $member)
622
	{
623
		if (!loadMemberContext($member))
624
			continue;
625
626
		$context['members'][$member] = $memberContext[$member];
627
		$context['members'][$member]['post_percent'] = round(($context['members'][$member]['real_posts'] * 100) / $most_posts);
628
		$context['members'][$member]['registered_date'] = strftime('%Y-%m-%d', $context['members'][$member]['registered_timestamp']);
629
630
		if (!empty($context['custom_profile_fields']['columns']))
631
		{
632
			foreach ($context['custom_profile_fields']['columns'] as $key => $column)
633
			{
634
				// Don't show anything if there isn't anything to show.
635 View Code Duplication
				if (!isset($context['members'][$member]['options'][$key]))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
636
				{
637
					$context['members'][$member]['options'][$key] = '';
638
					continue;
639
				}
640
641 View Code Duplication
				if ($column['bbc'] && !empty($context['members'][$member]['options'][$key]))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
642
					$context['members'][$member]['options'][$key] = strip_tags(parse_bbc($context['members'][$member]['options'][$key]));
643
644
				elseif ($column['type'] == 'check')
645
					$context['members'][$member]['options'][$key] = $context['members'][$member]['options'][$key] == 0 ? $txt['no'] : $txt['yes'];
646
647
				// Enclosing the user input within some other text?
648
				if (!empty($column['enclose']))
649
					$context['members'][$member]['options'][$key] = strtr($column['enclose'], array(
650
						'{SCRIPTURL}' => $scripturl,
651
						'{IMAGES_URL}' => $settings['images_url'],
652
						'{DEFAULT_IMAGES_URL}' => $settings['default_images_url'],
653
						'{INPUT}' => $context['members'][$member]['options'][$key],
654
					));
655
			}
656
		}
657
	}
658
}
659
660
/**
661
 * Sets the label, sort and join info for every custom field column.
662
 *
663
 * @return array An array of info about the custom fields for the member list
664
 */
665
function getCustFieldsMList()
666
{
667
	global $smcFunc;
668
669
	$cpf = array();
670
671
	$request = $smcFunc['db_query']('', '
672
		SELECT col_name, field_name, field_desc, field_type, bbc, enclose
673
		FROM {db_prefix}custom_fields
674
		WHERE active = {int:active}
675
			AND show_mlist = {int:show}
676
			AND private < {int:private_level}',
677
		array(
678
			'active' => 1,
679
			'show' => 1,
680
			'private_level' => 2,
681
		)
682
	);
683
684
	while ($row = $smcFunc['db_fetch_assoc']($request))
685
	{
686
		// Get all the data we're gonna need.
687
		$cpf['columns'][$row['col_name']] = array(
688
			'label' => $row['field_name'],
689
			'type' => $row['field_type'],
690
			'bbc' => !empty($row['bbc']),
691
			'enclose' => $row['enclose'],
692
		);
693
694
		// Get the right sort method depending on the cust field type.
695
		if ($row['field_type'] != 'check')
696
			$cpf['columns'][$row['col_name']]['sort'] = array(
697
				'down' => 'LENGTH(t' . $row['col_name'] . '.value) > 0 ASC, COALESCE(t' . $row['col_name'] . '.value, \'\') DESC',
698
				'up' => 'LENGTH(t' . $row['col_name'] . '.value) > 0 DESC, COALESCE(t' . $row['col_name'] . '.value, \'\') ASC'
699
			);
700
701
		else
702
			$cpf['columns'][$row['col_name']]['sort'] = array(
703
				'down' => 't' . $row['col_name'] . '.value DESC',
704
				'up' => 't' . $row['col_name'] . '.value ASC'
705
			);
706
707
		$cpf['join'][$row['col_name']] = 'LEFT JOIN {db_prefix}themes AS t' . $row['col_name'] . ' ON (t' . $row['col_name'] . '.variable = {literal:' . $row['col_name'] . '} AND t' . $row['col_name'] . '.id_theme = 1 AND t' . $row['col_name'] . '.id_member = mem.id_member)';
708
	}
709
	$smcFunc['db_free_result']($request);
710
711
	return $cpf;
712
}
713
714
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...