Completed
Push — master ( fd29c3...7c77d2 )
by Julito
91:07 queued 30:09
created

dashboard_add_users_to_user.php ➔ search_users()   F

Complexity

Conditions 25
Paths 1681

Size

Total Lines 112
Code Lines 106

Duplication

Lines 22
Ratio 19.64 %

Importance

Changes 0
Metric Value
cc 25
eloc 106
nc 1681
nop 2
dl 22
loc 112
rs 2
c 0
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
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Framework\Container;
5
6
/**
7
*	Interface for assigning users to Human Resources Manager
8
*	@package chamilo.admin
9
*/
10
// resetting the course id
11
$cidReset = true;
12
$ajax_search = false;
13
// create an ajax object
14
$xajax = new xajax();
15
$xajax->registerFunction('search_users');
16
17
// setting the section (for the tabs)
18
$this_section = SECTION_PLATFORM_ADMIN;
19
20
// Access restrictions
21
api_protect_admin_script(true);
22
23
// setting breadcrumbs
24
$interbreadcrumb[] = array('url' => Container::getRouter()->generate('administration'), 'name' => get_lang('PlatformAdmin'));
25
$interbreadcrumb[] = array('url' => 'user_list.php','name' => get_lang('UserList'));
26
27
// Database Table Definitions
28
$tbl_user = Database::get_main_table(TABLE_MAIN_USER);
29
$tbl_access_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
30
31
// initializing variables
32
$user_id = intval($_GET['user']);
33
$user_info = api_get_user_info($user_id);
34
$user_anonymous  = api_get_anonymous_id();
35
$current_user_id = api_get_user_id();
36
37
$userStatus = api_get_user_status($user_id);
38
39
$firstLetterUser = isset($_POST['firstLetterUser']) ? $_POST['firstLetterUser'] : null;
40
41
// setting the name of the tool
42
$isAdmin = UserManager::is_admin($user_id);
43
if ($isAdmin) {
44
    $userStatus = PLATFORM_ADMIN;
45
    $tool_name= get_lang('AssignUsersToPlatformAdministrator');
46
} else if ($user_info['status'] == SESSIONADMIN) {
47
    $tool_name= get_lang('AssignUsersToSessionsAdministrator');
48
} else if  ($user_info['status'] == STUDENT_BOSS) {
49
    $tool_name= get_lang('AssignUsersToBoss');
50
} else {
51
    $tool_name= get_lang('AssignUsersToHumanResourcesManager');
52
}
53
54
$add_type = 'multiple';
55 View Code Duplication
if (isset($_GET['add_type']) && $_GET['add_type']!='') {
56
	$add_type = Security::remove_XSS($_REQUEST['add_type']);
57
}
58
59
if (!api_is_platform_admin()) {
60
    api_not_allowed(true);
61
}
62
63
function search_users($needle, $type)
64
{
65
    global $tbl_access_url_rel_user,  $tbl_user, $user_anonymous, $current_user_id, $user_id, $userStatus;
66
67
    $xajax_response = new xajaxResponse();
68
    $return = '';
69
    if (!empty($needle) && !empty($type)) {
70
        $assigned_users_to_hrm = array();
71
72 View Code Duplication
        switch ($userStatus) {
73
            case DRH:
74
                //no break;
75
            case PLATFORM_ADMIN:
76
                $assigned_users_to_hrm = UserManager::get_users_followed_by_drh($user_id);
77
                break;
78
            case STUDENT_BOSS:
79
                $assigned_users_to_hrm = UserManager::getUsersFollowedByStudentBoss($user_id);
80
                break;
81
        }
82
83
        $assigned_users_id = array_keys($assigned_users_to_hrm);
84
        $without_assigned_users = '';
85
86
        $westernOrder = api_is_western_name_order();
87
        if ($westernOrder) {
88
            $order_clause = " ORDER BY firstname, lastname";
89
        } else {
90
            $order_clause = " ORDER BY lastname, firstname";
91
        }
92
93 View Code Duplication
        if (count($assigned_users_id) > 0) {
94
            $without_assigned_users = " AND user.user_id NOT IN(".implode(',', $assigned_users_id).")";
95
        }
96
97
        if (api_is_multiple_url_enabled()) {
98
            $sql = "SELECT user.user_id, username, lastname, firstname
99
                    FROM $tbl_user user
100
                    LEFT JOIN $tbl_access_url_rel_user au ON (au.user_id = user.user_id)
101
                    WHERE
102
                        ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%' AND
103
                        status NOT IN(".DRH.", ".SESSIONADMIN.", " . STUDENT_BOSS . ") AND
104
                        user.user_id NOT IN ($user_anonymous, $current_user_id, $user_id)
105
                        $without_assigned_users AND
106
                        access_url_id = ".api_get_current_access_url_id()."
107
                    $order_clause
108
                    ";
109
110
        } else {
111
            $sql = "SELECT user_id, username, lastname, firstname
112
                    FROM $tbl_user user
113
                    WHERE
114
                        ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%' AND
115
                        status NOT IN(".DRH.", ".SESSIONADMIN.", " . STUDENT_BOSS . ") AND
116
                        user_id NOT IN ($user_anonymous, $current_user_id, $user_id)
117
                    $without_assigned_users
118
                    $order_clause
119
            ";
120
        }
121
122
		$rs	= Database::query($sql);
123
		$xajax_response->addAssign('ajax_list_users_multiple','innerHTML',api_utf8_encode($return));
124
125
        if ($type == 'single') {
126
            $tbl_user_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
127
            $access_url_id = api_get_current_access_url_id();
128
129
            $sql = 'SELECT user.user_id, username, lastname, firstname
130
                    FROM '.$tbl_user.' user
131
                    INNER JOIN '.$tbl_user_rel_access_url.' url_user ON (url_user.user_id=user.user_id)
132
                    WHERE
133
                        access_url_id = '.$access_url_id.'  AND
134
                        (
135
                            username LIKE "'.$needle.'%" OR
136
                            firstname LIKE "'.$needle.'%" OR
137
                            lastname LIKE "'.$needle.'%"
138
                        ) AND ';
139
140
            switch ($userStatus) {
141
                case DRH:
142
                    $sql .= " user.status <> 6 AND user.status <> " . DRH;
143
                    break;
144
                case STUDENT_BOSS:
145
                    $sql .= " user.status <> 6 AND user.status <> " . STUDENT_BOSS;
146
                    break;
147
            }
148
149
            $sql .= " $order_clause LIMIT 11";
150
151
            $rs = Database::query($sql);
152
            $i = 0;
153 View Code Duplication
            while ($user = Database :: fetch_array($rs)) {
154
                $i++;
155
                if ($i <= 10) {
156
                    $person_name = api_get_person_name($user['firstname'], $user['lastname']);
157
                    $return .= '<a href="javascript: void(0);" onclick="javascript: add_user_to_user(\''.$user['user_id'].'\',\''.$person_name.' ('.$user['username'].')'.'\')">'.$person_name.' ('.$user['username'].')</a><br />';
158
                } else {
159
                    $return .= '...<br />';
160
                }
161
            }
162
           $xajax_response->addAssign('ajax_list_users_single','innerHTML',api_utf8_encode($return));
163
        } else {
164
            $return .= '<select id="origin" class="form-control" name="NoAssignedUsersList[]" multiple="multiple" size="15" ">';
165
            while($user = Database :: fetch_array($rs)) {
166
                $person_name = api_get_person_name($user['firstname'], $user['lastname']);
167
                $return .= '<option value="'.$user['user_id'].'" title="'.htmlspecialchars($person_name,ENT_QUOTES).'">'.$person_name.' ('.$user['username'].')</option>';
168
            }
169
            $return .= '</select>';
170
            $xajax_response->addAssign('ajax_list_users_multiple', 'innerHTML', api_utf8_encode($return));
171
        }
172
	}
173
	return $xajax_response;
174
}
175
176
$xajax->processRequests();
177
$htmlHeadXtra[] = $xajax->getJavascript('../inc/lib/xajax/');
178
$htmlHeadXtra[] = '<script>
179
function add_user_to_user (code, content) {
180
	document.getElementById("user_to_add").value = "";
181
	document.getElementById("ajax_list_users_single").innerHTML = "";
182
183
	destination = document.getElementById("destination");
184
185
	for (i=0;i<destination.length;i++) {
186
		if(destination.options[i].text == content) {
187
				return false;
188
		}
189
	}
190
	destination.options[destination.length] = new Option(content,code);
191
	destination.selectedIndex = -1;
192
	sortOptions(destination.options);
193
}
194
function moveItem(origin , destination) {
195
	for(var i = 0 ; i<origin.options.length ; i++) {
196
		if(origin.options[i].selected) {
197
			destination.options[destination.length] = new Option(origin.options[i].text,origin.options[i].value);
198
			origin.options[i]=null;
199
			i = i-1;
200
		}
201
	}
202
	destination.selectedIndex = -1;
203
	sortOptions(destination.options);
204
}
205
function sortOptions(options) {
206
	var newOptions = new Array();
207
	for (i = 0 ; i<options.length ; i++) {
208
		newOptions[i] = options[i];
209
	}
210
	newOptions = newOptions.sort(mysort);
211
	options.length = 0;
212
	for(i = 0 ; i < newOptions.length ; i++){
213
		options[i] = newOptions[i];
214
	}
215
}
216
function mysort(a, b) {
217
	if (a.text.toLowerCase() > b.text.toLowerCase()) {
218
		return 1;
219
	}
220
	if (a.text.toLowerCase() < b.text.toLowerCase()) {
221
		return -1;
222
	}
223
	return 0;
224
}
225
226
function valide() {
227
	var options = document.getElementById("destination").options;
228
	for (i = 0 ; i<options.length ; i++) {
229
		options[i].selected = true;
230
	}
231
	document.forms.formulaire.submit();
232
}
233
function remove_item(origin) {
234
	for(var i = 0 ; i<origin.options.length ; i++) {
235
		if(origin.options[i].selected) {
236
			origin.options[i]=null;
237
			i = i-1;
238
		}
239
	}
240
}
241
</script>';
242
243
$formSent=0;
244
$errorMsg = '';
245
$UserList = array();
246
247
// Filters
248
$filters = array(
249
    array('type' => 'text', 'name' => 'username', 'label' => get_lang('Username')),
250
    array('type' => 'text', 'name' => 'firstname', 'label' => get_lang('FirstName')),
251
    array('type' => 'text', 'name' => 'lastname', 'label' => get_lang('LastName')),
252
    array('type' => 'text', 'name' => 'official_code', 'label' => get_lang('OfficialCode')),
253
    array('type' => 'text', 'name' => 'email', 'label' => get_lang('Email'))
254
);
255
256
$searchForm = new FormValidator('search', 'get', api_get_self().'?user='.$user_id);
257
$searchForm->addHeader(get_lang('AdvancedSearch'));
258
$renderer =& $searchForm->defaultRenderer();
259
260
$searchForm->addElement('hidden', 'user', $user_id);
261
foreach ($filters as $param) {
262
    $searchForm->addElement($param['type'], $param['name'], $param['label']);
263
}
264
$searchForm->addButtonSearch(get_lang('Search'));
265
266
$filterData = array();
267
if ($searchForm->validate()) {
268
    $filterData = $searchForm->getSubmitValues();
269
}
270
271
$conditions = array();
272 View Code Duplication
if (!empty($filters) && !empty($filterData)) {
273
    foreach ($filters as $filter) {
274
        if (isset($filter['name']) && isset($filterData[$filter['name']])) {
275
            $value = $filterData[$filter['name']];
276
            if (!empty($value)) {
277
                $conditions[$filter['name']] = $value;
278
            }
279
        }
280
    }
281
}
282
283
$msg = '';
284
if (isset($_POST['formSent']) && intval($_POST['formSent']) == 1) {
285
	$user_list = $_POST['UsersList'];
286
287
    switch ($userStatus) {
288
        case DRH:
289
            //no break;
290
        case PLATFORM_ADMIN:
291
            $affected_rows = UserManager::subscribeUsersToHRManager($user_id, $user_list);
292
            break;
293
        case STUDENT_BOSS:
294
            $affected_rows = UserManager::subscribeBossToUsers($user_id, $user_list);
295
            break;
296
        default:
297
            $affected_rows = 0;
298
    }
299
300
    if ($affected_rows)	{
301
        $msg = get_lang('AssignedUsersHaveBeenUpdatedSuccessfully');
302
    }
303
}
304
305
// Display header
306
Display::display_header($tool_name);
307
308
// actions
309
310
$actionsLeft = '';
311
if ($userStatus != STUDENT_BOSS) {
312
    $actionsLeft = Display::url(
313
        Display::return_icon('course-add.png', get_lang('AssignCourses'), null, ICON_SIZE_MEDIUM),
314
        "dashboard_add_courses_to_user.php?user=$user_id"
315
    );
316
317
    $actionsLeft .= Display::url(
318
        Display::return_icon('session-add.png', get_lang('AssignSessions'), null, ICON_SIZE_MEDIUM),
319
        "dashboard_add_sessions_to_user.php?user=$user_id"
320
    );
321
}
322
323
$actionsRight = Display::url(
324
    '<em class="fa fa-search"></em> ' . get_lang('AdvancedSearch'),
325
    '#',
326
    array('class' => 'btn btn-default advanced_options', 'id' => 'advanced_search')
327
);
328
329
$toolbar = Display::toolbarAction('toolbar-dashboard', [$actionsLeft, $actionsRight]);
330
echo $toolbar;
331
332
echo '<div id="advanced_search_options" style="display:none">';
333
$searchForm->display();
334
echo '</div>';
335
336
echo Display::page_header(
337
    sprintf(
338
        get_lang('AssignUsersToX'),
339
        api_get_person_name($user_info['firstname'], $user_info['lastname'])
340
    ),
341
    null,
342
    'h3'
343
);
344
345
$assigned_users_to_hrm = array();
346
347 View Code Duplication
switch ($userStatus) {
348
    case DRH:
349
        //no break;
350
    case PLATFORM_ADMIN:
351
        $assigned_users_to_hrm = UserManager::get_users_followed_by_drh($user_id);
352
        break;
353
    case STUDENT_BOSS:
354
        $assigned_users_to_hrm = UserManager::getUsersFollowedByStudentBoss($user_id);
355
        break;
356
}
357
358
$assigned_users_id = array_keys($assigned_users_to_hrm);
359
$without_assigned_users = '';
360 View Code Duplication
if (count($assigned_users_id) > 0) {
361
	$without_assigned_users = " user.user_id NOT IN(".implode(',',$assigned_users_id).") AND ";
362
}
363
364
$search_user = '';
365
if (!empty($firstLetterUser)) {
366
	$needle = Database::escape_string($firstLetterUser);
367
	$search_user ="AND ".(api_sort_by_first_name() ? 'firstname' : 'lastname')." LIKE '$needle%'";
368
}
369
370
$sqlConditions = null;
371
if (!empty($conditions)) {
372
    $temp_conditions = array();
373 View Code Duplication
    foreach ($conditions as $field => $value) {
374
        $field = Database::escape_string($field);
375
        $value = Database::escape_string($value);
376
        $temp_conditions[] = $field.' LIKE \'%'.$value.'%\'';
377
    }
378
    if (!empty($temp_conditions)) {
379
        $sqlConditions .= implode(' AND ', $temp_conditions);
380
    }
381
    if (!empty($sqlConditions)) {
382
        $sqlConditions = " AND $sqlConditions";
383
    }
384
}
385
386
if (api_is_multiple_url_enabled()) {
387
	$sql = "SELECT user.user_id, username, lastname, firstname
388
	        FROM $tbl_user user  LEFT JOIN $tbl_access_url_rel_user au 
389
	        ON (au.user_id = user.user_id)
390
			WHERE
391
                $without_assigned_users
392
                user.user_id NOT IN ($user_anonymous, $current_user_id, $user_id) AND
393
                status NOT IN(".DRH.", ".SESSIONADMIN.") $search_user AND
394
                access_url_id = ".api_get_current_access_url_id()."
395
                $sqlConditions
396
            ORDER BY firstname";
397
} else {
398
	$sql = "SELECT user_id, username, lastname, firstname
399
	        FROM $tbl_user user
400
			WHERE
401
			    $without_assigned_users
402
			    user_id NOT IN ($user_anonymous, $current_user_id, $user_id) AND
403
			    status NOT IN(".DRH.", ".SESSIONADMIN.")
404
			    $search_user
405
			    $sqlConditions
406
            ORDER BY firstname ";
407
}
408
$result	= Database::query($sql);
409
?>
410
<form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?user=<?php echo $user_id ?>" class="form-horizontal" <?php if($ajax_search){echo ' onsubmit="valide();"';}?>>
411
<input type="hidden" name="formSent" value="1" />
412
<?php
413
if(!empty($msg)) {
414
	Display::display_normal_message($msg); //main API
415
}
416
?>
417
418
<div class="row">
419
    <div class="col-md-4">
420
        <?php echo get_lang('UserListInPlatform') ?>
421
422
        <div class="form-group">
423
            <div class="col-sm-12">
424
                <div id="ajax_list_users_multiple">
425
                    <select id="origin" class="form-control" name="NoAssignedUsersList[]" multiple="multiple" size="15">
426
                        <?php
427
                            while ($enreg = Database::fetch_array($result)) {
428
                                $person_name = api_get_person_name($enreg['firstname'], $enreg['lastname']); ?>
429
                                  <option value="<?php echo $enreg['user_id']; ?>" <?php echo 'title="'.htmlspecialchars($person_name,ENT_QUOTES).'"';?>>
430
                            <?php echo $person_name.' ('.$enreg['username'].')'; ?>
431
                        </option>
432
                        <?php } ?>
433
                    </select>
434
                </div>
435
            </div>
436
        </div>
437
438
439
    </div>
440
    <div class="col-md-4">
441
        <div class="code-course">
442
            <?php if($add_type == 'multiple') { ?>
443
                <p><?php echo get_lang('FirstLetterUser');?></p>
444
                <select class="selectpicker show-tick form-control" name="firstLetterUser" onchange = "xajax_search_users(this.value,'multiple')">
445
                    <option value="%">--</option>
446
                    <?php echo Display::get_alphabet_options($firstLetterUser); ?>
447
                </select>
448
            <?php } ?>
449
        </div>
450
        <div class="control-course">
451
        <?php if ($ajax_search) { ?>
452
            <div class="separate-action">
453
                <button class="btn btn-primary" type="button" onclick="remove_item(document.getElementById('destination'))"></button>
454
            </div>
455
          <?php } else { ?>
456
            <div class="separate-action">
457
                <button class="btn btn-primary" type="button" onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))" onclick="moveItem(document.getElementById('origin'), document.getElementById('destination'))">
458
                <em class="fa fa-chevron-right"></em>
459
            </button>
460
            </div>
461
            <div class="separate-action">
462
                <button class="btn btn-primary" type="button" onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))" onclick="moveItem(document.getElementById('destination'), document.getElementById('origin'))">
463
                <em class="fa fa-chevron-left"></em>
464
                </button>
465
            </div>
466
467
          <?php
468
          }
469
          ?>
470
            <div class="separate-action">
471
                <?php
472
		echo '<button class="btn btn-success" type="button" value="" onclick="valide()" >'.$tool_name.'</button>';
473
            ?>
474
            </div>
475
        </div>
476
    </div>
477
    <div class="col-md-4">
478
        <?php
479
	if (UserManager::is_admin($user_id)) {
480
		echo get_lang('AssignedUsersListToPlatformAdministrator');
481
            } else if ($user_info['status'] == SESSIONADMIN) {
482
                    echo get_lang('AssignedUsersListToSessionsAdministrator');
483
            } else if ($user_info['status'] == STUDENT_BOSS) {
484
                    echo get_lang('AssignedUsersListToStudentBoss');
485
            } else {
486
                    echo get_lang('AssignedUsersListToHumanResourcesManager');
487
	}
488
        ?>
489
        <div class="form-group">
490
            <div class="col-sm-12">
491
                <br>
492
                <select id='destination' class="form-control" name="UsersList[]" multiple="multiple" size="15" >
493
                    <?php
494
                    if (is_array($assigned_users_to_hrm)) {
495
                            foreach($assigned_users_to_hrm as $enreg) {
496
                                    $person_name = api_get_person_name($enreg['firstname'], $enreg['lastname']);
497
                    ?>
498
                            <option value="<?php echo $enreg['user_id']; ?>" <?php echo 'title="'.htmlspecialchars($person_name,ENT_QUOTES).'"'; ?>>
499
                        <?php echo $person_name.' ('.$enreg['username'].')'; ?>
500
                    </option>
501
                    <?php }
502
                    }?>
503
                </select>
504
            </div>
505
        </div>
506
507
    </div>
508
</div>
509
510
</form>
511
512
<?php
513
Display::display_footer();
514