Completed
Push — 1.10.x ( ba0bf0...97c0d2 )
by Angel Fernando Quiroz
44:06
created

user_list.php ➔ prepare_user_sql_query()   F

Complexity

Conditions 28
Paths 2016

Size

Total Lines 124
Code Lines 79

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 28
eloc 79
nc 2016
nop 1
dl 0
loc 124
rs 2

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
/* For licensing terms, see /license.txt */
3
4
/**
5
 * @author Bart Mollet
6
 * @author Julio Montoya <[email protected]> BeezNest 2011
7
 * @package chamilo.admin
8
*/
9
10
use ChamiloSession as Session;
11
12
$cidReset = true;
13
require_once '../inc/global.inc.php';
14
15
$current_access_url_id = api_get_current_access_url_id();
16
17
$action = isset($_REQUEST["action"]) ? $_REQUEST["action"] : null;
18
19
// Blocks the possibility to delete a user
20
$deleteUserAvailable = true;
21
if (api_get_configuration_value('deny_delete_users')) {
22
    $deleteUserAvailable = false;
23
}
24
25
$url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=get_user_courses';
26
$urlSession = api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=get_user_sessions';
27
28
$htmlHeadXtra[] = '<script>
29
function load_course_list (div_course,my_user_id) {
30
	 $.ajax({
31
		contentType: "application/x-www-form-urlencoded",
32
		beforeSend: function(objeto) {
33
            $("div#"+div_course).html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
34
		type: "POST",
35
		url: "'.$url.'",
36
		data: "user_id="+my_user_id,
37
		success: function(datos) {
38
			$("div#"+div_course).html(datos);
39
			$("div#div_"+my_user_id).attr("class","blackboard_show");
40
			$("div#div_"+my_user_id).attr("style","");
41
		}
42
	});
43
}
44
45
function load_session_list(div_session, my_user_id) {
46
	 $.ajax({
47
		contentType: "application/x-www-form-urlencoded",
48
		beforeSend: function(objeto) {
49
            $("div#"+div_session).html("<img src=\'../inc/lib/javascript/indicator.gif\' />"); },
50
		type: "POST",
51
		url: "'.$urlSession.'",
52
		data: "user_id="+my_user_id,
53
		success: function(datos) {
54
			$("div#"+div_session).html(datos);
55
			$("div#div_s_"+my_user_id).attr("class","blackboard_show");
56
			$("div#div_s_"+my_user_id).attr("style","");
57
		}
58
	});
59
}
60
61
function active_user(element_div) {
62
	id_image=$(element_div).attr("id");
63
	image_clicked=$(element_div).attr("src");
64
	image_clicked_info = image_clicked.split("/");
65
	image_real_clicked = image_clicked_info[image_clicked_info.length-1];
66
	var status = 1;
67
	if (image_real_clicked == "accept.png") {
68
		status = 0;
69
	}
70
	user_id=id_image.split("_");
71
	ident="#img_"+user_id[1];
72
	if (confirm("'.get_lang('AreYouSureToEditTheUserStatus', '').'")) {
73
		 $.ajax({
74
			contentType: "application/x-www-form-urlencoded",
75
			beforeSend: function(objeto) {
76
				$(ident).attr("src","'.Display::returnIconPath('loading1.gif').'"); }, //candy eye stuff
77
			type: "GET",
78
			url: "'.api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=active_user",
79
			data: "user_id="+user_id[1]+"&status="+status,
80
			success: function(data) {
81
				if (data == 1) {
82
					$(ident).attr("src", "'.Display::returnIconPath('accept.png').'");
83
					$(ident).attr("title","'.get_lang('Lock').'");
84
				}
85
                if (data == 0) {
86
					$(ident).attr("src","'.Display::returnIconPath('error.png').'");
87
					$(ident).attr("title","'.get_lang('Unlock').'");
88
				}
89
                if (data == -1) {
90
                    $(ident).attr("src", "'.Display::returnIconPath('warning.png').'");
91
					$(ident).attr("title","'.get_lang('ActionNotAllowed').'");
92
                }
93
			}
94
		});
95
	}
96
}
97
98
function clear_course_list(div_course) {
99
	$("div#"+div_course).html("&nbsp;");
100
	$("div#"+div_course).hide("");
101
}
102
function clear_session_list(div_session) {
103
	$("div#"+div_session).html("&nbsp;");
104
	$("div#"+div_session).hide("");
105
}
106
107
function display_advanced_search_form () {
108
    if ($("#advanced_search_form").css("display") == "none") {
109
        $("#advanced_search_form").css("display","block");
110
        $("#img_plus_and_minus").html(\'&nbsp;'.Display::return_icon('div_hide.gif',get_lang('Hide'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedSearch').'\');
111
    } else {
112
        $("#advanced_search_form").css("display","none");
113
        $("#img_plus_and_minus").html(\'&nbsp;'.Display::return_icon('div_show.gif',get_lang('Show'),array('style'=>'vertical-align:middle')).'&nbsp;'.get_lang('AdvancedSearch').'\');
114
    }
115
}
116
117
$(document).ready(function() {
118
    var select_val = $("#input_select_extra_data").val();
119
    if ( document.getElementById(\'extra_data_text\')) {
120
121
        if (select_val != 0) {
122
            document.getElementById(\'extra_data_text\').style.display="block";
123
            if (document.getElementById(\'input_extra_text\'))
124
                document.getElementById(\'input_extra_text\').value = "";
125
        } else {
126
            document.getElementById(\'extra_data_text\').style.display="none";
127
        }
128
    }
129
});
130
131
//Load user calendar
132
function load_calendar(user_id, month, year) {
133
 	var url = "'.api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?a=get_user_agenda&user_id=" +user_id + "&month="+month+"&year="+year;
134
	$(".modal-body").load(url);
135
}
136
</script>';
137
138
$this_section = SECTION_PLATFORM_ADMIN;
139
140
if ($action == 'login_as') {
141
    $check = Security::check_token('get');
142 View Code Duplication
    if (isset($_GET['user_id']) && $check) {
143
        $result = loginUser($_GET['user_id']);
144
        if ($result == false) {
145
            api_not_allowed(true);
146
        }
147
    }
148
    Security::clear_token();
149
}
150
151
api_protect_admin_script(true);
152
153
/**
154
 * Prepares the shared SQL query for the user table.
155
 * See get_user_data() and get_number_of_users().
156
 *
157
 * @param boolean $is_count Whether to count, or get data
158
 * @return string SQL query
159
 */
160
function prepare_user_sql_query($is_count)
161
{
162
    $sql = "";
163
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
164
    $admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
165
166
    if ($is_count) {
167
        $sql .= "SELECT COUNT(u.id) AS total_number_of_items FROM $user_table u";
168
    } else {
169
        $sql .= "SELECT u.id AS col0, u.official_code AS col2, ";
170
171
        if (api_is_western_name_order()) {
172
            $sql .= "u.firstname AS col3, u.lastname AS col4, ";
173
        } else {
174
            $sql .= "u.lastname AS col3, u.firstname AS col4, ";
175
        }
176
177
        $sql .= " u.username AS col5,
178
                    u.email AS col6,
179
                    u.status AS col7,
180
                    u.active AS col8,
181
                    u.id AS col9,
182
                    u.registration_date AS col10,
183
                    u.expiration_date AS exp,
184
                    u.password
185
                FROM $user_table u";
186
    }
187
188
    // adding the filter to see the user's only of the current access_url
189
    if ((api_is_platform_admin() || api_is_session_admin()) && api_get_multiple_access_url()) {
190
        $access_url_rel_user_table = Database :: get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
191
        $sql.= " INNER JOIN $access_url_rel_user_table url_rel_user ON (u.id=url_rel_user.user_id)";
192
    }
193
194
    $keywordList = array(
195
        'keyword_firstname',
196
        'keyword_lastname',
197
        'keyword_username',
198
        'keyword_email',
199
        'keyword_officialcode',
200
        'keyword_status',
201
        'keyword_active',
202
        'check_easy_passwords'
203
    );
204
205
    $keywordListValues = array();
206
    $atLeastOne = false;
207
    foreach ($keywordList as $keyword) {
208
        $keywordListValues[$keyword] = null;
209
        if (isset($_GET[$keyword]) && !empty($_GET[$keyword])) {
210
            $keywordListValues[$keyword] = $_GET[$keyword];
211
            $atLeastOne = true;
212
        }
213
    }
214
215
    if ($atLeastOne == false) {
216
        $keywordListValues = array();
217
    }
218
219
    if (isset($keyword_extra_data) && !empty($keyword_extra_data)) {
0 ignored issues
show
Bug introduced by
The variable $keyword_extra_data seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
220
        $extra_info = UserManager::get_extra_field_information_by_name($keyword_extra_data);
221
        $field_id = $extra_info['id'];
222
        $sql.= " INNER JOIN user_field_values ufv ON u.id=ufv.user_id AND ufv.field_id=$field_id ";
223
    }
224
225
    if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
226
        $keywordFiltered = Database::escape_string("%". $_GET['keyword'] ."%");
227
        $sql .= " WHERE (
228
                    u.firstname LIKE '$keywordFiltered' OR
229
                    u.lastname LIKE '$keywordFiltered' OR
230
                    concat(u.firstname, ' ', u.lastname) LIKE '$keywordFiltered' OR
231
                    concat(u.lastname,' ',u.firstname) LIKE '$keywordFiltered' OR
232
                    u.username LIKE '$keywordFiltered' OR
233
                    u.official_code LIKE '$keywordFiltered' OR
234
                    u.email LIKE '$keywordFiltered'
235
                )
236
        ";
237
    } elseif (isset($keywordListValues) && !empty($keywordListValues)) {
238
        $query_admin_table = '';
239
        $keyword_admin = '';
240
241
        if (isset($keywordListValues['keyword_status']) &&
242
            $keywordListValues['keyword_status'] == PLATFORM_ADMIN
243
        ) {
244
            $query_admin_table = " , $admin_table a ";
245
            $keyword_admin = ' AND a.user_id = u.id ';
246
            $keywordListValues['keyword_status'] = '%';
247
        }
248
249
        $keyword_extra_value = '';
250
        if (isset($keyword_extra_data) && !empty($keyword_extra_data) &&
251
            !empty($keyword_extra_data_text)) {
0 ignored issues
show
Bug introduced by
The variable $keyword_extra_data_text seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
252
            $keyword_extra_value = " AND ufv.field_value LIKE '%".trim($keyword_extra_data_text)."%' ";
253
        }
254
255
        $sql .= " $query_admin_table
256
                WHERE (
257
                    u.firstname LIKE '". Database::escape_string("%".$keywordListValues['keyword_firstname']."%")."' AND
258
                    u.lastname LIKE '". Database::escape_string("%".$keywordListValues['keyword_lastname']."%")."' AND
259
                    u.username LIKE '". Database::escape_string("%".$keywordListValues['keyword_username']."%")."' AND
260
                    u.email LIKE '". Database::escape_string("%".$keywordListValues['keyword_email']."%")."' AND
261
                    u.official_code LIKE '". Database::escape_string("%".$keywordListValues['keyword_officialcode']."%")."' AND
262
                    u.status LIKE '".Database::escape_string($keywordListValues['keyword_status'])."'
263
                    $keyword_admin
264
                    $keyword_extra_value
265
                ";
266
267
        if (isset($keyword_active) && !isset($keyword_inactive)) {
0 ignored issues
show
Bug introduced by
The variable $keyword_inactive seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
268
            $sql .= " AND u.active='1'";
269
        } elseif (isset($keyword_inactive) && !isset($keyword_active)) {
0 ignored issues
show
Bug introduced by
The variable $keyword_active seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
270
            $sql .= " AND u.active='0'";
271
        }
272
        $sql .= " ) ";
273
    }
274
275
    // adding the filter to see the user's only of the current access_url
276
    if ((api_is_platform_admin() || api_is_session_admin())
277
        && api_get_multiple_access_url()
278
    ) {
279
        $sql .= " AND url_rel_user.access_url_id=".api_get_current_access_url_id();
280
    }
281
282
    return $sql;
283
}
284
285
/**
286
 * Make sure this function is protected because it does NOT check password!
287
 *
288
 * This function defines globals.
289
 * @param  int $userId
290
 *
291
 * @return bool    False on failure, redirection on success
292
 * @author Evie Embrechts
293
 * @author Yannick Warnier <[email protected]>
294
*/
295
function loginUser($userId)
296
{
297
    $userId = intval($userId);
298
    $userInfo = api_get_user_info($userId);
299
300
    // Check if the user is allowed to 'login_as'
301
    $canLoginAs = api_can_login_as($userId);
302
303
    if (!$canLoginAs || empty($userInfo)) {
304
305
        return false;
306
    }
307
308
    $firstname = $userInfo['firstname'];
309
    $lastname = $userInfo['lastname'];
310
311
	if (api_is_western_name_order()) {
312
		$message = sprintf(get_lang('AttemptingToLoginAs'),$firstname, $lastname, $userId);
313
	} else {
314
		$message = sprintf(get_lang('AttemptingToLoginAs'), $lastname, $firstname, $userId);
315
	}
316
317
	if ($userId) {
318
319
        // Logout the current user
320
        LoginDelete(api_get_user_id());
321
322
        Session::erase('_user');
323
        Session::erase('is_platformAdmin');
324
        Session::erase('is_allowedCreateCourse');
325
        Session::erase('_uid');
326
        // Cleaning session variables
327
328
        $_user['firstName'] = $userInfo['firstname'];
329
        $_user['lastName'] = $userInfo['lastname'];
330
        $_user['mail'] = $userInfo['email'];
331
        $_user['official_code'] = $userInfo['official_code'];
332
        $_user['picture_uri'] = $userInfo['picture_uri'];
333
        $_user['user_id'] = $userId;
334
        $_user['id'] = $userId;
335
        $_user['status'] = $userInfo['status'];
336
337
        // Filling session variables with new data
338
        Session::write('_uid', $userId);
339
        Session::write('_user', $userInfo);
340
        Session::write('is_platformAdmin', (bool) (UserManager::is_admin($userId)));
341
        Session::write('is_allowedCreateCourse', (bool) ($userInfo['status'] == 1));
342
        // will be useful later to know if the user is actually an admin or not (example reporting)
343
        Session::write('login_as', true);
344
345
        $target_url = api_get_path(WEB_PATH)."user_portal.php";
346
        $message .= '<br />'.sprintf(get_lang('LoginSuccessfulGoToX'),'<a href="'.$target_url.'">'.$target_url.'</a>');
347
        Display :: display_header(get_lang('UserList'));
348
        Display :: display_normal_message($message, false);
349
        Display :: display_footer();
350
        exit;
351
352
	}
353
}
354
355
/**
356
 * Get the total number of users on the platform
357
 * @see SortableTable#get_total_number_of_items()
358
 */
359
function get_number_of_users()
360
{
361
    $sql = prepare_user_sql_query(true);
362
363
    $res = Database::query($sql);
364
    $obj = Database::fetch_object($res);
365
    return $obj->total_number_of_items;
366
}
367
368
/**
369
 * Get the users to display on the current page (fill the sortable-table)
370
 * @param   int     offset of first user to recover
371
 * @param   int     Number of users to get
372
 * @param   int     Column to sort on
373
 * @param   string  Order (ASC,DESC)
374
 * @see SortableTable#get_table_data($from)
375
 */
376
function get_user_data($from, $number_of_items, $column, $direction) {
377
    $sql = prepare_user_sql_query(false);
378
379
    /* @todo will not work because now we use the salt field
380
    $checkPassStrength = isset($_GET['check_easy_passwords']) && $_GET['check_easy_passwords'] == 1 ? true : false;
381
    if ($checkPassStrength) {
382
        $easyPasswordList = api_get_easy_password_list();
383
        $easyPasswordList = array_map('api_get_encrypted_password', $easyPasswordList);
384
        $easyPasswordList = array_map(array('Database', 'escape_string'), $easyPasswordList);
385
        $easyPassword = implode("' OR password LIKE '", $easyPasswordList);
386
387
        $sql .= "AND password LIKE '$easyPassword' ";
388
    }*/
389
390
    if (!in_array($direction, array('ASC','DESC'))) {
391
    	$direction = 'ASC';
392
    }
393
    $column = intval($column);
394
    $from 	= intval($from);
395
    $number_of_items = intval($number_of_items);
396
397
    $preventSessionAdminsToManageAllUsers = api_get_setting('prevent_session_admins_to_manage_all_users');
398
    if (api_is_session_admin() && $preventSessionAdminsToManageAllUsers === 'true') {
399
        $sql .= " WHERE u.creator_id = ".api_get_user_id();
400
    }
401
402
	$sql .= " ORDER BY col$column $direction ";
403
	$sql .= " LIMIT $from,$number_of_items";
404
405
	$res = Database::query($sql);
406
407
	$users = array ();
408
    $t = time();
409
	while ($user = Database::fetch_row($res)) {
410
		$userPicture = UserManager::getUserPicture($user[0], USER_IMAGE_SIZE_SMALL);
411
		$photo = '<img src="'.$userPicture.'" width="22" height="22" alt="'.api_get_person_name($user[2], $user[3]).'" title="'.api_get_person_name($user[2], $user[3]).'" />';
412
413
        if ($user[7] == 1 && !empty($user[10])) {
414
            // check expiration date
415
            $expiration_time = convert_sql_date($user[10]);
416
            // if expiration date is passed, store a special value for active field
417
            if ($expiration_time < $t) {
418
        	   $user[7] = '-1';
419
            }
420
        }
421
422
        // forget about the expiration date field
423
        $users[] = array(
424
            $user[0],
425
            $photo,
426
            $user[1],
427
            $user[2],
428
            $user[3],
429
            $user[4],
430
            $user[5],
431
            $user[6],
432
            $user[7],
433
            api_get_local_time($user[9]),
434
            $user[0]
435
        );
436
	}
437
438
	return $users;
439
}
440
441
/**
442
* Returns a mailto-link
443
* @param string $email An email-address
444
* @return string HTML-code with a mailto-link
445
*/
446
function email_filter($email) {
0 ignored issues
show
Best Practice introduced by
The function email_filter() has been defined more than once; this definition is ignored, only the first definition in main/admin/course_request_review.php (L177-183) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
447
	return Display :: encrypted_mailto_link($email, $email);
448
}
449
450
/**
451
* Returns a mailto-link
452
* @param string $email An email-address
0 ignored issues
show
Bug introduced by
There is no parameter named $email. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
453
* @return string HTML-code with a mailto-link
454
*/
455
function user_filter($name, $params, $row) {
456
	return '<a href="'.api_get_path(WEB_PATH).'whoisonline.php?origin=user_list&id='.$row[0].'">'.$name.'</a>';
457
}
458
459
/**
460
 * Build the modify-column of the table
461
 * @param   int     The user id
462
 * @param   string  URL params to add to table links
463
 * @param   array   Row of elements to alter
464
 * @return string Some HTML-code with modify-buttons
465
 */
466
function modify_filter($user_id, $url_params, $row) {
0 ignored issues
show
Best Practice introduced by
The function modify_filter() has been defined more than once; this definition is ignored, only the first definition in main/admin/class_list.php (L61-68) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
467
	global $charset, $_admins_list;
468
	$is_admin   = in_array($user_id,$_admins_list);
469
	$statusname = api_get_status_langvars();
470
	$user_is_anonymous = false;
471
    $current_user_status_label = $row['7'];
472
473
	if ($current_user_status_label == $statusname[ANONYMOUS]) {
474
		$user_is_anonymous =true;
475
	}
476
	$result = '';
477
	if (!$user_is_anonymous) {
478
		$icon = Display::return_icon('course.png', get_lang('Courses'), array('onmouseout' => 'clear_course_list (\'div_'.$user_id.'\')'));
479
		$result .= '<a href="javascript:void(0)" onclick="load_course_list(\'div_'.$user_id.'\','.$user_id.')" >
480
			        '.$icon.'
481
					<div class="blackboard_hide" id="div_'.$user_id.'">&nbsp;&nbsp;</div>
482
					</a>';
483
484
        $icon = Display::return_icon('session.png', get_lang('Sessions'), array('onmouseout' => 'clear_session_list (\'div_s_'.$user_id.'\')'));
485
		$result .= '<a href="javascript:void(0)" onclick="load_session_list(\'div_s_'.$user_id.'\','.$user_id.')" >
486
					'.$icon.'
487
					<div class="blackboard_hide" id="div_s_'.$user_id.'">&nbsp;&nbsp;</div>
488
					</a>';
489
	} else {
490
		$result .= Display::return_icon('course_na.png',get_lang('Courses')).'&nbsp;&nbsp;';
491
		$result .= Display::return_icon('course_na.png',get_lang('Sessions')).'&nbsp;&nbsp;';
492
	}
493
494
	if (api_is_platform_admin()) {
495
		if (!$user_is_anonymous) {
496
			$result .= '<a href="user_information.php?user_id='.$user_id.'">'.Display::return_icon('synthese_view.gif', get_lang('Info')).'</a>&nbsp;&nbsp;';
497
		} else {
498
			$result .= Display::return_icon('synthese_view_na.gif', get_lang('Info')).'&nbsp;&nbsp;';
499
		}
500
	}
501
502
    //only allow platform admins to login_as, or session admins only for students (not teachers nor other admins)
503
    if (api_is_platform_admin() || (api_is_session_admin() && $current_user_status_label == $statusname[STUDENT])) {
504
    	if (!$user_is_anonymous) {
505
            if (api_global_admin_can_edit_admin($user_id)) {
506
                $result .= '<a href="user_list.php?action=login_as&user_id='.$user_id.'&sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.png', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
507
            } else {
508
                $result .= Display::return_icon('login_as_na.png', get_lang('LoginAs')).'&nbsp;&nbsp;';
509
            }
510
    	} else {
511
    		$result .= Display::return_icon('login_as_na.png', get_lang('LoginAs')).'&nbsp;&nbsp;';
512
    	}
513
    } else {
514
    	$result .= Display::return_icon('login_as_na.png', get_lang('LoginAs')).'&nbsp;&nbsp;';
515
    }
516
517 View Code Duplication
	if ($current_user_status_label != $statusname[STUDENT]) {
518
		$result .= Display::return_icon('statistics_na.gif', get_lang('Reporting')).'&nbsp;&nbsp;';
519
	} else {
520
		$result .= '<a href="../mySpace/myStudents.php?student='.$user_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;&nbsp;';
521
	}
522
523
	if (api_is_platform_admin(true)) {
524
        $editProfileUrl = Display::getProfileEditionLink($user_id, true);
525
526
        if (!$user_is_anonymous && api_global_admin_can_edit_admin($user_id, null, true)) {
527
            $result .= '<a href="' . $editProfileUrl . '">'.Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
528
		} else {
529
            $result .= Display::return_icon('edit_na.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
530
		}
531
	}
532
533
	if ($is_admin) {
534
		$result .= Display::return_icon('admin_star.png', get_lang('IsAdministrator'),array('width'=> ICON_SIZE_SMALL, 'heigth'=> ICON_SIZE_SMALL));
535
	} else {
536
		$result .= Display::return_icon('admin_star_na.png', get_lang('IsNotAdministrator'));
537
	}
538
539
	// actions for assigning sessions, courses or users
540
	if (api_is_session_admin()) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
541
		/*if ($row[0] == api_get_user_id()) {
542
			$result .= '<a href="dashboard_add_sessions_to_user.php?user='.$user_id.'">'.Display::return_icon('view_more_stats.gif', get_lang('AssignSessions')).'</a>&nbsp;&nbsp;';
543
		}*/
544
	} else {
545
        if ($current_user_status_label == $statusname[SESSIONADMIN]) {
546
            $result .= Display::url(
547
                Display::return_icon('view_more_stats.gif', get_lang('AssignSessions')),
548
                "dashboard_add_sessions_to_user.php?user={$user_id}"
549
            );
550
        } else {
551
            if (
552
                $current_user_status_label == $statusname[DRH] ||
553
                UserManager::is_admin($user_id) ||
554
                $current_user_status_label == $statusname[STUDENT_BOSS]
555
            ) {
556
                $result .= Display::url(
557
                    Display::return_icon('user_subscribe_course.png', get_lang('AssignUsers'), '', ICON_SIZE_SMALL),
558
                    "dashboard_add_users_to_user.php?user={$user_id}"
559
                );
560
            }
561
562
            if ($current_user_status_label == $statusname[DRH] || UserManager::is_admin($user_id)) {
563
                $result .= Display::url(
564
                    Display::return_icon('course_add.gif', get_lang('AssignCourses')),
565
                    "dashboard_add_courses_to_user.php?user={$user_id}"
566
                );
567
568
                $result .= Display::url(
569
                    Display::return_icon('view_more_stats.gif', get_lang('AssignSessions')),
570
                    "dashboard_add_sessions_to_user.php?user={$user_id}"
571
                );
572
            }
573
        }
574
	}
575
576
    if (api_is_platform_admin()) {
577
        $result .= ' <a data-title="'.get_lang('FreeBusyCalendar').'" href="'.api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?a=get_user_agenda&user_id='.$user_id.'&modal_size=lg" class="agenda_opener ajax">'.
578
            Display::return_icon('calendar.png', get_lang('FreeBusyCalendar'), array(), ICON_SIZE_SMALL).'</a>';
579
        $deleteAllowed = !api_get_configuration_value('deny_delete_users');
580
        if ($deleteAllowed) {
581
            if ($user_id != api_get_user_id() &&
582
                !$user_is_anonymous &&
583
                api_global_admin_can_edit_admin($user_id)
584
            ) {
585
                // you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
586
                $result .= ' <a href="user_list.php?action=delete_user&user_id='.$user_id.'&'.$url_params.'&sec_token='.$_SESSION['sec_token'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
587
            } else {
588
                $result .= Display::return_icon('delete_na.png', get_lang('Delete'), array(), ICON_SIZE_SMALL);
589
            }
590
        }
591
    }
592
	return $result;
593
}
594
595
596
/**
597
 * Build the active-column of the table to lock or unlock a certain user
598
 * lock = the user can no longer use this account
599
 * @author Patrick Cool <[email protected]>, Ghent University
600
 * @param int $active the current state of the account
601
 * @param string $params
602
 * @param array $row
603
 * @return string Some HTML-code with the lock/unlock button
604
 */
605
function active_filter($active, $params, $row)
0 ignored issues
show
Best Practice introduced by
The function active_filter() has been defined more than once; this definition is ignored, only the first definition in main/admin/group_list.php (L211-232) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
606
{
607
    $_user = api_get_user_info();
608
609 View Code Duplication
    if ($active == '1') {
610
        $action = 'Lock';
611
        $image = 'accept';
612
    } elseif ($active == '-1') {
613
        $action = 'edit';
614
        $image = 'warning';
615
    } elseif ($active == '0') {
616
        $action = 'Unlock';
617
        $image = 'error';
618
    }
619
620
    $result = '';
621
622
    if ($action == 'edit') {
623
        $result = Display::return_icon($image.'.png', get_lang('AccountExpired'), array(), 16);
624
    } elseif ($row['0']<>$_user['user_id']) {
625
    	// you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
626
		$result = Display::return_icon($image.'.png', get_lang(ucfirst($action)), array('onclick'=>'active_user(this);', 'id'=>'img_'.$row['0']), 16).'</a>';
627
	}
628
	return $result;
629
}
630
631
/**
632
 * Instead of displaying the integer of the status, we give a translation for the status
633
 *
634
 * @param integer $status
635
 * @return string translation
636
 *
637
 * @version march 2008
638
 * @author Patrick Cool <[email protected]>, Ghent University, Belgium
639
 */
640
function status_filter($status) {
0 ignored issues
show
Best Practice introduced by
The function status_filter() has been defined more than once; this definition is ignored, only the first definition in main/admin/group_list.php (L272-275) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
641
	$statusname = api_get_status_langvars();
642
	return $statusname[$status];
643
}
644
645
if (isset($_GET['keyword']) || isset($_GET['keyword_firstname'])) {
646
    $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
647
    $interbreadcrumb[] = array ("url" => 'user_list.php', "name" => get_lang('UserList'));
648
    $tool_name = get_lang('SearchUsers');
649
} else {
650
    $interbreadcrumb[] = array ("url" => 'index.php', "name" => get_lang('PlatformAdmin'));
651
    $tool_name = get_lang('UserList');
652
}
653
654
$message = '';
655
656
if (!empty($action)) {
657
    $check = Security::check_token('get');
658
	if ($check) {
659
		switch ($action) {
660
            case 'add_user_to_my_url':
661
                $user_id = $_REQUEST["user_id"];
662
                $result = UrlManager::add_user_to_url($user_id, $current_access_url_id);
663
                if ($result ) {
664
                    $user_info = api_get_user_info($user_id);
665
                    $message = get_lang('UserAdded').' '.$user_info['firstname'].' '.$user_info['lastname'].' ('.$user_info['username'].')';
666
                    $message  = Display::return_message($message, 'confirmation');
667
                }
668
                break;
669
			case 'delete_user':
670
				if (api_is_platform_admin()) {
671
                    $user_to_delete = $_GET['user_id'];
672
                    $current_user_id = api_get_user_id();
673
674
					if ($deleteUserAvailable && api_global_admin_can_edit_admin($_GET['user_id'])) {
675 View Code Duplication
						if ($user_to_delete != $current_user_id && UserManager :: delete_user($_GET['user_id'])) {
676
							$message = Display :: return_message(get_lang('UserDeleted'), 'confirmation');
677
						} else {
678
							$message = Display :: return_message(get_lang('CannotDeleteUserBecauseOwnsCourse'), 'error');
679
						}
680
					} else {
681
						$message = Display :: return_message(get_lang('CannotDeleteUser'),'error');
682
					}
683
				}
684
				break;
685
            case 'delete':
686
				if (api_is_platform_admin()) {
687
					$number_of_selected_users = count($_POST['id']);
688
					$number_of_deleted_users = 0;
689
					if (is_array($_POST['id'])) {
690
						foreach ($_POST['id'] as $index => $user_id) {
691
							if ($user_id != $_user['user_id']) {
692
								if (UserManager::delete_user($user_id)) {
693
									$number_of_deleted_users++;
694
								}
695
							}
696
						}
697
					}
698
					if ($number_of_selected_users == $number_of_deleted_users) {
699
                        $message = Display :: return_message(get_lang('SelectedUsersDeleted'), 'confirmation');
700
					} else {
701
                        $message = Display :: return_message(get_lang('SomeUsersNotDeleted'), 'error');
702
					}
703
				}
704
				break;
705
		}
706
		Security::clear_token();
707
	}
708
}
709
710
// Create a search-box
711
$form = new FormValidator('search_simple', 'get', '', '', array(), FormValidator::LAYOUT_INLINE);
712
$form->addElement('text', 'keyword');
713
$form->addButtonSearch(get_lang('Search'));
714
$form->addElement(
715
    'static',
716
    'search_advanced_link',
717
    null,
718
    '<a href="javascript://" class = "advanced_parameters" onclick="display_advanced_search_form();">
719
        <span id="img_plus_and_minus">&nbsp;'.
720
        Display::return_icon('div_show.gif', get_lang('Show'), array('style'=>'vertical-align:middle')).' '.get_lang('AdvancedSearch').'
721
        </span>
722
    </a>'
723
);
724
725
$actions  = '';
726
if (api_is_platform_admin()) {
727
	$actions .= '<div style="float:right;">'.
728
		 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.
729
         Display::return_icon('new_user.png',get_lang('AddUsers'),'',ICON_SIZE_MEDIUM).'</a>'.
730
		 '</div>';
731
}
732
$actions .= $form->return_form();
0 ignored issues
show
Deprecated Code introduced by
The method FormValidator::return_form() has been deprecated with message: use returnForm()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
733
734
if (isset ($_GET['keyword'])) {
735
	$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
736
} elseif (isset ($_GET['keyword_firstname'])) {
737
	$parameters['keyword_firstname'] 	= Security::remove_XSS($_GET['keyword_firstname']);
738
	$parameters['keyword_lastname']	 	= Security::remove_XSS($_GET['keyword_lastname']);
739
	$parameters['keyword_username']	 	= Security::remove_XSS($_GET['keyword_username']);
740
	$parameters['keyword_email'] 	 	= Security::remove_XSS($_GET['keyword_email']);
741
	$parameters['keyword_officialcode'] = Security::remove_XSS($_GET['keyword_officialcode']);
742
	$parameters['keyword_status'] 		= Security::remove_XSS($_GET['keyword_status']);
743
	$parameters['keyword_active'] 		= Security::remove_XSS($_GET['keyword_active']);
744
	$parameters['keyword_inactive'] 	= Security::remove_XSS($_GET['keyword_inactive']);
745
}
746
// Create a sortable table with user-data
747
$parameters['sec_token'] = Security::get_token();
748
749
// get the list of all admins to mark them in the users list
750
$admin_table = Database::get_main_table(TABLE_MAIN_ADMIN);
751
$sql_admin = "SELECT user_id FROM $admin_table";
752
$res_admin = Database::query($sql_admin);
753
$_admins_list = array();
754
while ($row_admin = Database::fetch_row($res_admin)) {
755
	$_admins_list[] = $row_admin[0];
756
}
757
758
// Display Advanced search form.
759
$form = new FormValidator('advanced_search', 'get', '', '', array(), FormValidator::LAYOUT_HORIZONTAL);
760
761
$form->addElement('html','<div id="advanced_search_form" style="display:none;">');
762
$form->addElement('header', get_lang('AdvancedSearch'));
763
$form->addText('keyword_firstname',get_lang('FirstName'),false);
764
$form->addText('keyword_lastname',get_lang('LastName'),false);
765
766
$form->addText('keyword_username',get_lang('LoginName'),false);
767
$form->addText('keyword_email',get_lang('Email'),false);
768
769
$form->addText('keyword_officialcode',get_lang('OfficialCode'),false);
770
771
$status_options = array();
772
$status_options['%'] = get_lang('All');
773
$status_options[STUDENT] = get_lang('Student');
774
$status_options[COURSEMANAGER] = get_lang('Teacher');
775
$status_options[DRH] = get_lang('Drh');
776
$status_options[SESSIONADMIN] = get_lang('SessionsAdmin');
777
$status_options[PLATFORM_ADMIN] = get_lang('Administrator');
778
779
$form->addElement('select','keyword_status',get_lang('Profile'), $status_options    );
780
781
$active_group = array();
782
$active_group[] = $form->createElement('checkbox','keyword_active','', get_lang('Active'));
783
$active_group[] = $form->createElement('checkbox','keyword_inactive','', get_lang('Inactive'));
784
$form->addGroup($active_group,'',get_lang('ActiveAccount'), '<br/>',false);
785
786
$form->addElement('checkbox', 'check_easy_passwords', null, get_lang('CheckEasyPasswords'));
787
788
$form->addButtonSearch(get_lang('SearchUsers'));
789
790
791
$defaults = array();
792
$defaults['keyword_active'] = 1;
793
$defaults['keyword_inactive'] = 1;
794
$form->setDefaults($defaults);
795
$form->addElement('html','</div>');
796
797
$form = $form->returnForm();
798
799
$table = new SortableTable(
800
    'users',
801
    'get_number_of_users',
802
    'get_user_data',
803
    (api_is_western_name_order() xor api_sort_by_first_name()) ? 3 : 2
804
);
805
$table->set_additional_parameters($parameters);
806
$table->set_header(0, '', false, 'width="18px"');
807
$table->set_header(1, get_lang('Photo'), false);
808
$table->set_header(2, get_lang('OfficialCode'));
809
810 View Code Duplication
if (api_is_western_name_order()) {
811
	$table->set_header(3, get_lang('FirstName'));
812
	$table->set_header(4, get_lang('LastName'));
813
} else {
814
	$table->set_header(3, get_lang('LastName'));
815
	$table->set_header(4, get_lang('FirstName'));
816
}
817
$table->set_header(5, get_lang('LoginName'));
818
$table->set_header(6, get_lang('Email'));
819
$table->set_header(7, get_lang('Profile'));
820
$table->set_header(8, get_lang('Active'), true, 'width="15px"');
821
$table->set_header(9, get_lang('RegistrationDate'), true, 'width="90px"');
822
$table->set_header(10, get_lang('Action'), false, 'width="220px"');
823
824
$table->set_column_filter(3, 'user_filter');
825
$table->set_column_filter(4, 'user_filter');
826
$table->set_column_filter(6, 'email_filter');
827
$table->set_column_filter(7, 'status_filter');
828
$table->set_column_filter(8, 'active_filter');
829
$table->set_column_filter(10, 'modify_filter');
830
831
// Only show empty actions bar if delete users has been blocked
832
if (api_is_platform_admin() && !(api_get_configuration_value('deny_delete_users'))) {
833
    $table->set_form_actions(array('delete' => get_lang('DeleteFromPlatform')));
834
} else {
835
    $table->set_form_actions(array('none' => get_lang('NoActionAvailable')));
836
}
837
838
$table_result = $table->return_table();
839
$extra_search_options = '';
840
841
//Try to search the user everywhere
842
if ($table->get_total_number_of_items() == 0) {
843
844
    if (api_get_multiple_access_url() && isset($_REQUEST['keyword'])) {
845
        $keyword = Database::escape_string($_REQUEST['keyword']);
846
        $conditions = array('username' => $keyword);
847
        $user_list = UserManager::get_user_list($conditions, array(), false, ' OR ');
848
        if (!empty($user_list)) {
849
850
            $extra_search_options = Display::page_subheader(get_lang('UsersFoundInOtherPortals'));
851
852
            $table = new HTML_Table(array('class' => 'data_table'));
853
            $column = 0;
854
            $row = 0;
855
            $headers = array(get_lang('User'), 'URL', get_lang('Actions'));
856
            foreach ($headers as $header) {
857
                $table->setHeaderContents($row, $column, $header);
858
                $column++;
859
            }
860
            $row++;
861
862
            foreach ($user_list as $user) {
863
                $column = 0;
864
                $access_info = UrlManager::get_access_url_from_user($user['id']);
865
                $access_info_to_string = '';
866
                $add_user = true;
867
                if (!empty($access_info)) {
868
                    foreach ($access_info as $url_info) {
869
                        if ($current_access_url_id == $url_info['access_url_id']) {
870
                            $add_user = false;
871
                        }
872
                        $access_info_to_string .= $url_info['url'].'<br />';
873
                    }
874
                }
875
                if ($add_user) {
876
                    $row_table = array();
877
                    $row_table[] =  api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].') ';
878
                    $row_table[] =  $access_info_to_string;
879
                    $url = api_get_self().'?action=add_user_to_my_url&user_id='.$user['id'].'&sec_token='.$_SESSION['sec_token'];
880
                    $row_table[] =  Display::url(get_lang('AddUserToMyURL'), $url, array('class' => 'btn'));
881
882
                    foreach ($row_table as $cell) {
883
                        $table->setCellContents($row, $column, $cell);
884
                        $table->updateCellAttributes($row, $column, 'align="center"');
885
                        $column++;
886
                    }
887
                    $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
888
                    $row++;
889
                }
890
            }
891
            $extra_search_options .= $table->toHtml();
892
            $table_result = '';
893
        }
894
    }
895
}
896
897
$tpl = new Template($tool_name);
898
$tpl->assign('actions', $actions);
899
$tpl->assign('message', $message);
900
$tpl->assign('content', $form.$table_result.$extra_search_options);
901
$tpl->display_one_col_template();
902