Passed
Push — 1.11.x ( 7508b6...24d213 )
by Angel Fernando Quiroz
09:19
created

formatCompleteName()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 10
rs 10
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
// resetting the course id
5
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
6
use Symfony\Component\HttpFoundation\JsonResponse;
7
8
$cidReset = true;
9
10
// including some necessary files
11
require_once __DIR__.'/../inc/global.inc.php';
12
13
// setting the section (for the tabs)
14
$this_section = SECTION_PLATFORM_ADMIN;
15
16
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
17
$relation = isset($_REQUEST['relation']) ? (int) $_REQUEST['relation'] : 0;
18
$usergroup = new UserGroup();
19
$groupInfo = $usergroup->get($id);
20
$usergroup->protectScript($groupInfo);
21
22
// setting breadcrumbs
23
$interbreadcrumb[] = ['url' => 'index.php', 'name' => get_lang('PlatformAdmin')];
24
$interbreadcrumb[] = ['url' => 'usergroups.php', 'name' => get_lang('Classes')];
25
26
// setting the name of the tool
27
$tool_name = get_lang('SubscribeUsersToClass');
28
29
$htmlHeadXtra[] = '
30
<script>
31
32
$(function () {
33
    $("#relation").change(function() {
34
        window.location = "add_users_to_usergroup.php?id='.$id.'" +"&relation=" + $(this).val();
35
    });
36
});
37
38
function add_user_to_session (code, content) {
39
    document.getElementById("user_to_add").value = "";
40
    document.getElementById("ajax_list_users_single").innerHTML = "";
41
    destination = document.getElementById("elements_in");
42
    for (i=0;i<destination.length;i++) {
43
        if(destination.options[i].text == content) {
44
                return false;
45
        }
46
    }
47
48
    destination.options[destination.length] = new Option(content,code);
49
    destination.selectedIndex = -1;
50
    sortOptions(destination.options);
51
}
52
function remove_item(origin) {
53
    for(var i = 0 ; i<origin.options.length ; i++) {
54
        if(origin.options[i].selected) {
55
            origin.options[i]=null;
56
            i = i-1;
57
        }
58
    }
59
}
60
61
function validate_filter() {
62
    document.formulaire.form_sent.value=0;
63
    document.formulaire.submit();
64
}
65
66
function checked_in_no_group(checked)
67
{
68
    $("#relation")
69
    .find("option")
70
    .attr("selected", false);
71
72
    $("#first_letter_user")
73
    .find("option")
74
    .attr("selected", false);
75
        document.formulaire.form_sent.value="2";
76
    document.formulaire.submit();
77
}
78
79
function change_select(reset) {
80
    $("#user_with_any_group_id").attr("checked", false);
81
    document.formulaire["form_sent"].value = "2";
82
83
    var select = $(document.formulaire["elements_not_in_name"]);
84
85
    select.empty();
86
87
    if (reset) {
88
        document.formulaire["first_letter_user"].value = "";
89
90
        if ('.(api_get_configuration_value('usergroup_add_user_show_all_student_by_default') ? 0 : 1).') {
91
            document.formulaire["form_sent"].value = "1";
92
93
            return;
94
        }
95
    }
96
97
    $.post("'.api_get_self().'", $(document.formulaire).serialize(), function(data) {
98
        document.formulaire["form_sent"].value = "1";
99
100
        $.each(data, function(index, item) {
101
            select.append($("<option>", {
102
                value: index,
103
                text: item
104
            }));
105
        });
106
    });
107
}
108
109
</script>';
110
111
$form_sent = 0;
112
$extra_field_list = UserManager::get_extra_fields();
113
$new_field_list = [];
114
if (is_array($extra_field_list)) {
115
    foreach ($extra_field_list as $extra_field) {
116
        //if is enabled to filter and is a "<select>" field type
117
        if ($extra_field[8] == 1 && $extra_field[2] == 4) {
118
            $new_field_list[] = [
119
                'name' => $extra_field[3],
120
                'variable' => $extra_field[1], 'data' => $extra_field[9],
121
            ];
122
        }
123
    }
124
}
125
126
if (empty($id)) {
127
    api_not_allowed(true);
128
}
129
130
$first_letter_user = '';
131
132
if (isset($_POST['form_sent']) && $_POST['form_sent']) {
133
    $form_sent = $_POST['form_sent'];
134
    $elements_posted = $_POST['elements_in_name'] ?? null;
135
    $first_letter_user = $_POST['firstLetterUser'];
136
137
    if (!is_array($elements_posted)) {
138
        $elements_posted = [];
139
    }
140
141
    // If "social group" you need to select a role
142
    if ($groupInfo['group_type'] == UserGroup::SOCIAL_CLASS && empty($relation)) {
143
        Display::addFlash(Display::return_message(get_lang('SelectRole'), 'warning'));
144
        header('Location: '.api_get_self().'?id='.$id);
145
        exit;
146
    }
147
148
    if ($form_sent == 1) {
149
        Display::addFlash(Display::return_message(get_lang('Updated')));
150
        // Added a parameter to send emails when registering a user
151
        $usergroup->subscribe_users_to_usergroup(
152
            $id,
153
            $elements_posted,
154
            true,
155
            $relation
156
        );
157
        header('Location: usergroups.php');
158
        exit;
159
    }
160
}
161
162
if (isset($_GET['action']) && $_GET['action'] == 'export') {
163
    $users = $usergroup->getUserListByUserGroup($id);
164
    if (!empty($users)) {
165
        $data = [
166
            ['UserName', 'ClassName'],
167
        ];
168
        foreach ($users as $user) {
169
            $data[] = [$user['username'], $groupInfo['name']];
170
        }
171
        $filename = 'export_user_class_'.api_get_local_time();
172
        Export::arrayToCsv($data, $filename);
173
        exit;
174
    }
175
}
176
177
// Filter by Extra Fields
178
$use_extra_fields = false;
179
$extra_field_result = [];
180
if (is_array($extra_field_list)) {
181
    if (is_array($new_field_list) && count($new_field_list) > 0) {
182
        foreach ($new_field_list as $new_field) {
183
            $varname = 'field_'.$new_field['variable'];
184
            if (UserManager::is_extra_field_available($new_field['variable'])) {
185
                if (isset($_POST[$varname]) && $_POST[$varname] != '0') {
186
                    $use_extra_fields = true;
187
                    $extra_field_result[] = UserManager::get_extra_user_data_by_value(
188
                        $new_field['variable'],
189
                        $_POST[$varname]
190
                    );
191
                }
192
            }
193
        }
194
    }
195
}
196
197
if ($use_extra_fields) {
198
    $final_result = [];
199
    if (count($extra_field_result) > 1) {
200
        for ($i = 0; $i < count($extra_field_result) - 1; $i++) {
201
            if (is_array($extra_field_result[$i + 1])) {
202
                $final_result = array_intersect($extra_field_result[$i], $extra_field_result[$i + 1]);
203
            }
204
        }
205
    } else {
206
        $final_result = $extra_field_result[0];
207
    }
208
}
209
210
// Filters
211
$filters = [
212
    ['type' => 'text', 'name' => 'username', 'label' => get_lang('Username')],
213
    ['type' => 'text', 'name' => 'firstname', 'label' => get_lang('FirstName')],
214
    ['type' => 'text', 'name' => 'lastname', 'label' => get_lang('LastName')],
215
    ['type' => 'text', 'name' => 'official_code', 'label' => get_lang('OfficialCode')],
216
    ['type' => 'text', 'name' => 'email', 'label' => get_lang('Email')],
217
];
218
219
$searchForm = new FormValidator('search', 'get', api_get_self().'?id='.$id);
220
$searchForm->addHeader(get_lang('AdvancedSearch'));
221
222
$searchForm->addElement('hidden', 'id', $id);
223
$searchForm->addHidden('relation', $relation);
224
foreach ($filters as $param) {
225
    $searchForm->addElement($param['type'], $param['name'], $param['label']);
226
}
227
$searchForm->addButtonSearch();
228
229
$data = $usergroup->get($id);
230
$list_in = $usergroup->getUsersByUsergroupAndRelation($id, $relation);
231
$list_all = $usergroup->get_users_by_usergroup();
232
233
$order = ['lastname'];
234
if (api_is_western_name_order()) {
235
    $order = ['firstname'];
236
}
237
238
$orderListByOfficialCode = 'true' === api_get_setting('order_user_list_by_official_code');
239
if ($orderListByOfficialCode) {
240
    $order = ['official_code', 'lastname'];
241
}
242
243
$conditions = [];
244
if (!empty($first_letter_user) && strlen($first_letter_user) >= 3) {
245
    foreach ($filters as $filter) {
246
        $conditions[$filter['name']] = $first_letter_user;
247
    }
248
}
249
250
$filterData = [];
251
if ($searchForm->validate()) {
252
    $filterData = $searchForm->getSubmitValues();
253
254
    foreach ($filters as $filter) {
255
        if (isset($filterData[$filter['name']])) {
256
            $value = $filterData[$filter['name']];
257
            if (!empty($value)) {
258
                $conditions[$filter['name']] = $value;
259
            }
260
        }
261
    }
262
}
263
264
$elements_not_in = $elements_in = [];
265
266
foreach ($list_in as $listedUserId) {
267
    $userInfo = api_get_user_info($listedUserId);
268
269
    $elements_in[$listedUserId] = formatCompleteName($userInfo, $orderListByOfficialCode);
270
}
271
272
$user_with_any_group = !empty($_REQUEST['user_with_any_group']);
273
$user_list = [];
274
275
if (!empty($conditions)) {
276
    $user_list = UserManager::getUserListLike($conditions, $order, true, 'OR');
277
}
278
279
if ($user_with_any_group) {
280
    $new_user_list = [];
281
    foreach ($user_list as $item) {
282
        if (!in_array($item['user_id'], $list_all)) {
283
            $new_user_list[] = $item;
284
        }
285
    }
286
    $user_list = $new_user_list;
287
}
288
289
if (!empty($user_list)) {
290
    foreach ($user_list as $item) {
291
        if ($use_extra_fields) {
292
            if (!in_array($item['user_id'], $final_result)) {
293
                continue;
294
            }
295
        }
296
297
        // Avoid anonymous users
298
        if ($item['status'] == ANONYMOUS) {
299
            continue;
300
        }
301
302
        if (!in_array($item['user_id'], $list_in)) {
303
            $elements_not_in[$item['user_id']] = formatCompleteName($item, $orderListByOfficialCode);
304
        }
305
    }
306
}
307
308
if (api_get_configuration_value('usergroup_add_user_show_all_student_by_default')
309
    && empty($elements_not_in)
310
    && empty($first_letter_user)
311
) {
312
    $initialUserList = UserManager::getUserListLike([], $order, true, 'OR');
313
    $elements_not_in = [];
314
315
    foreach ($initialUserList as $userInfo) {
316
        if (!in_array($userInfo['id'], $list_in)) {
317
            $elements_not_in[$userInfo['id']] = formatCompleteName($userInfo, $orderListByOfficialCode);
318
        }
319
    }
320
}
321
322
function formatCompleteName(array $userInfo, bool $orderListByOfficialCode): string
323
{
324
    if ($orderListByOfficialCode) {
325
        $officialCode = !empty($userInfo['official_code']) ? $userInfo['official_code'].' - ' : '? - ';
326
        return  $officialCode.$userInfo['complete_name_with_username'];
327
    }
328
329
    $officialCode = !empty($userInfo['official_code']) ? ' - '.$userInfo['official_code'] : null;
330
331
    return $userInfo['complete_name_with_username']." $officialCode";
332
}
333
334
if (ChamiloApi::isAjaxRequest()) {
335
    JsonResponse::create($elements_not_in)->send();
336
    exit;
337
}
338
339
Display::display_header($tool_name);
340
341
echo '<div class="actions">';
342
echo '<a href="usergroups.php">'.
343
    Display::return_icon('back.png', get_lang('Back'), [], ICON_SIZE_MEDIUM).'</a>';
344
345
echo Display::url(get_lang('AdvancedSearch'), '#', ['class' => 'advanced_options', 'id' => 'advanced_search']);
346
347
echo '<a href="usergroup_user_import.php">'.
348
    Display::return_icon('import_csv.png', get_lang('Import'), [], ICON_SIZE_MEDIUM).'</a>';
349
350
echo '<a href="'.api_get_self().'?id='.$id.'&action=export">'.
351
    Display::return_icon('export_csv.png', get_lang('Export'), [], ICON_SIZE_MEDIUM).'</a>';
352
echo '</div>';
353
354
echo '<div id="advanced_search_options" style="display:none">';
355
$searchForm->display();
356
echo '</div>';
357
?>
358
    <form name="formulaire" method="post" action="<?php echo api_get_self(); ?>?id=<?php echo $id;
359
    if (!empty($_GET['add'])) {
360
        echo '&add=true';
361
    } ?>" style="margin:0px;">
362
        <?php
363
        echo '<legend>'.$tool_name.': '.$data['name'].'</legend>';
364
365
        if (is_array($extra_field_list)) {
366
            if (is_array($new_field_list) && count($new_field_list) > 0) {
367
                echo '<h3>'.get_lang('FilterByUser').'</h3>';
368
                foreach ($new_field_list as $new_field) {
369
                    echo $new_field['name'];
370
                    $varname = 'field_'.$new_field['variable'];
371
                    echo '&nbsp;<select name="'.$varname.'">';
372
                    echo '<option value="0">--'.get_lang('Select').'--</option>';
373
                    foreach ($new_field['data'] as $option) {
374
                        $checked = '';
375
                        if (isset($_POST[$varname])) {
376
                            if ($_POST[$varname] == $option[1]) {
377
                                $checked = 'selected="true"';
378
                            }
379
                        }
380
                        echo '<option value="'.$option[1].'" '.$checked.'>'.$option[1].'</option>';
381
                    }
382
                    echo '</select>';
383
                    echo '&nbsp;&nbsp;';
384
                }
385
                echo '<input type="button" value="'.get_lang('Filter').'" onclick="validate_filter()" />';
386
                echo '<br /><br />';
387
            }
388
        }
389
390
        echo Display::input('hidden', 'id', $id);
391
        echo Display::input('hidden', 'form_sent', '1');
392
        echo Display::input('hidden', 'add_type', null);
393
394
        ?>
395
        <div class="row">
396
            <div class="col-md-5">
397
                <?php if ($data['group_type'] == UserGroup::SOCIAL_CLASS) {
398
            ?>
399
                    <select name="relation" id="relation" class="form-control">
400
                        <option value=""><?php echo get_lang('SelectARelationType'); ?></option>
401
                        <option
402
                            value="<?php echo GROUP_USER_PERMISSION_ADMIN; ?>" <?php echo (isset($relation) && $relation == GROUP_USER_PERMISSION_ADMIN) ? 'selected=selected' : ''; ?> >
403
                            <?php echo get_lang('Admin'); ?></option>
404
                        <option
405
                            value="<?php echo GROUP_USER_PERMISSION_READER; ?>" <?php echo (isset($relation) && $relation == GROUP_USER_PERMISSION_READER) ? 'selected=selected' : ''; ?> >
406
                            <?php echo get_lang('Reader'); ?></option>
407
                        <option
408
                            value="<?php echo GROUP_USER_PERMISSION_PENDING_INVITATION; ?>" <?php echo (isset($relation) && $relation == GROUP_USER_PERMISSION_PENDING_INVITATION) ? 'selected=selected' : ''; ?> >
409
                            <?php echo get_lang('PendingInvitation'); ?></option>
410
                        <option
411
                            value="<?php echo GROUP_USER_PERMISSION_MODERATOR; ?>" <?php echo (isset($relation) && $relation == GROUP_USER_PERMISSION_MODERATOR) ? 'selected=selected' : ''; ?> >
412
                            <?php echo get_lang('Moderator'); ?></option>
413
                        <option
414
                            value="<?php echo GROUP_USER_PERMISSION_HRM; ?>" <?php echo (isset($relation) && $relation == GROUP_USER_PERMISSION_HRM) ? 'selected=selected' : ''; ?> >
415
                            <?php echo get_lang('Drh'); ?></option>
416
                    </select>
417
                    <?php
418
        } ?>
419
420
                <div class="multiple_select_header">
421
                    <b><?php echo get_lang('UsersInPlatform'); ?> :</b>
422
                    <div class="input-group">
423
                        <input id="first_letter_user" name="firstLetterUser" type="text" class="form-control"
424
                               value="<?php echo Security::remove_XSS($first_letter_user); ?>"
425
                               placeholder="<?php echo get_lang('Search'); ?>"
426
                               onkeydown="return 13 !== event.keyCode;">
427
                        <span class="input-group-btn">
428
                    <button class="btn btn-default" type="button" onclick="change_select();">
429
                        <?php echo get_lang('Filter'); ?>
430
                    </button>
431
                    <button class="btn btn-default" type="button" onclick="change_select(true);">
432
                        <?php echo get_lang('Reset'); ?>
433
                    </button>
434
                </span>
435
                    </div>
436
                </div>
437
                <?php
438
                echo Display::select(
439
                    'elements_not_in_name',
440
                    $elements_not_in,
441
                    '',
442
                    [
443
                        'class' => 'form-control',
444
                        'multiple' => 'multiple',
445
                        'id' => 'elements_not_in',
446
                        'size' => '15px',
447
                    ],
448
                    false
449
                );
450
                ?>
451
                <br/>
452
                <label class="control-label">
453
                    <input type="checkbox" <?php if ($user_with_any_group) {
454
                    echo 'checked="checked"';
455
                } ?> onchange="checked_in_no_group(this.checked);" name="user_with_any_group" id="user_with_any_group_id">
456
                    <?php echo get_lang('UsersRegisteredInAnyGroup'); ?>
457
                </label>
458
            </div>
459
            <div class="col-md-2">
460
                <div style="padding-top:54px;width:auto;text-align: center;">
461
                    <button class="btn btn-default" type="button" onclick="moveItem(document.getElementById('elements_not_in'), document.getElementById('elements_in'))">
462
                        <em class="fa fa-arrow-right"></em>
463
                    </button>
464
                    <br/><br/>
465
                    <button class="btn btn-default" type="button" onclick="moveItem(document.getElementById('elements_in'), document.getElementById('elements_not_in'))">
466
                        <em class="fa fa-arrow-left"></em>
467
                    </button>
468
                </div>
469
            </div>
470
            <div class="col-md-5">
471
                <div class="multiple_select_header">
472
                    <b><?php echo get_lang('UsersInGroup'); ?> :</b>
473
                </div>
474
                <?php
475
                echo Display::select(
476
                    'elements_in_name[]',
477
                    $elements_in,
478
                    '',
479
                    [
480
                        'class' => 'form-control',
481
                        'multiple' => 'multiple',
482
                        'id' => 'elements_in',
483
                        'size' => '15px',
484
                    ],
485
                    false
486
                );
487
                unset($sessionUsersList);
488
                ?>
489
            </div>
490
        </div>
491
        <?php
492
        echo '<button class="btn btn-primary" type="button" value="" onclick="valide()" ><em class="fa fa-check"></em>'.
493
            get_lang('SubscribeUsersToClass').'</button>';
494
        ?>
495
    </form>
496
    <script>
497
        function moveItem(origin, destination) {
498
            for (var i = 0; i < origin.options.length; i++) {
499
                if (origin.options[i].selected) {
500
                    destination.options[destination.length] = new Option(origin.options[i].text, origin.options[i].value);
501
                    origin.options[i] = null;
502
                    i = i - 1;
503
                }
504
            }
505
            destination.selectedIndex = -1;
506
            sortOptions(destination.options);
507
        }
508
509
        function sortOptions(options) {
510
            newOptions = [];
511
            for (i = 0; i < options.length; i++)
512
                newOptions[i] = options[i];
513
514
            newOptions = newOptions.sort(mysort);
515
            options.length = 0;
516
            for (i = 0; i < newOptions.length; i++)
517
                options[i] = newOptions[i];
518
        }
519
520
        function mysort(a, b) {
521
            if (a.text.toLowerCase() > b.text.toLowerCase()) {
522
                return 1;
523
            }
524
            if (a.text.toLowerCase() < b.text.toLowerCase()) {
525
                return -1;
526
            }
527
            return 0;
528
        }
529
530
        function valide() {
531
            var options = document.getElementById('elements_in').options;
532
            for (i = 0; i < options.length; i++)
533
                options[i].selected = true;
534
            document.forms.formulaire.submit();
535
        }
536
    </script>
537
<?php
538
Display::display_footer();
539