Passed
Pull Request — 1.11.x (#4321)
by Angel Fernando Quiroz
10:25
created

getRestrictedSessionUserList()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 37
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 37
rs 9.536
cc 3
nc 4
nop 4
1
<?php
2
3
/* For licensing terms, see /license.txt*/
4
5
use Chamilo\CoreBundle\Entity\ExtraField;
6
use ExtraField as ExtraFieldModel;
7
8
/**
9
 * This script allows teachers to subscribe existing users
10
 * to their course.
11
 */
12
require_once __DIR__.'/../inc/global.inc.php';
13
$current_course_tool = TOOL_USER;
14
15
// the section (for the tabs)
16
$this_section = SECTION_COURSES;
17
18
// notice for unauthorized people.
19
api_protect_course_script(true);
20
21
if (api_get_setting('allow_user_course_subscription_by_course_admin') === 'false') {
22
    if (!api_is_platform_admin()) {
23
        api_not_allowed(true);
24
    }
25
}
26
27
// Access restriction
28
if (!api_is_allowed_to_edit()) {
29
    api_not_allowed(true);
30
}
31
32
$tool_name = get_lang('SubscribeUserToCourse');
33
$type = isset($_REQUEST['type']) ? (int) $_REQUEST['type'] : STUDENT;
34
$keyword = isset($_REQUEST['keyword']) ? Security::remove_XSS($_REQUEST['keyword']) : null;
35
36
$courseInfo = api_get_course_info();
37
38
if ($type == COURSEMANAGER) {
39
    $tool_name = get_lang('SubscribeUserToCourseAsTeacher');
40
}
41
42
//extra entries in breadcrumb
43
$interbreadcrumb[] = [
44
    'url' => 'user.php?'.api_get_cidreq(),
45
    'name' => get_lang('ToolUser'),
46
];
47
if ($keyword) {
48
    $interbreadcrumb[] = [
49
        'url' => 'subscribe_user.php?type='.$type.'&'.api_get_cidreq(),
50
        'name' => $tool_name,
51
    ];
52
    $tool_name = get_lang('SearchResults');
53
}
54
55
$sessionId = api_get_session_id();
56
$list_register_user = '';
57
$list_not_register_user = '';
58
59
if (isset($_REQUEST['register'])) {
60
    $userInfo = api_get_user_info($_REQUEST['user_id']);
61
    if ($userInfo) {
62
        if ($type === COURSEMANAGER) {
63
            if (!empty($sessionId)) {
64
                $message = $userInfo['complete_name_with_username'].' '.get_lang('AddedToCourse');
65
                SessionManager::set_coach_to_course_session(
66
                    $_REQUEST['user_id'],
67
                    $sessionId,
68
                    $courseInfo['real_id']
69
                );
70
                Display::addFlash(Display::return_message($message));
71
            } else {
72
                CourseManager::subscribeUser(
73
                    $_REQUEST['user_id'],
74
                    $courseInfo['code'],
75
                    COURSEMANAGER
76
                );
77
            }
78
        } else {
79
            CourseManager::subscribeUser(
80
                $_REQUEST['user_id'],
81
                $courseInfo['code']
82
            );
83
        }
84
    }
85
    header('Location:'.api_get_path(WEB_CODE_PATH).'user/user.php?'.api_get_cidreq().'&type='.$type);
86
    exit;
87
}
88
89
if (isset($_POST['action'])) {
90
    switch ($_POST['action']) {
91
        case 'subscribe':
92
            if (is_array($_POST['user'])) {
93
                $isSuscribe = [];
94
                foreach ($_POST['user'] as $index => $user_id) {
95
                    $userInfo = api_get_user_info($user_id);
96
                    if ($userInfo) {
97
                        if ($type === COURSEMANAGER) {
98
                            if (!empty($sessionId)) {
99
                                $message = $userInfo['complete_name_with_username'].' '.get_lang('AddedToCourse');
100
                                $result = SessionManager::set_coach_to_course_session(
101
                                    $user_id,
102
                                    $sessionId,
103
                                    $courseInfo['real_id']
104
                                );
105
                                if ($result) {
106
                                    $isSuscribe[] = $message;
107
                                }
108
                            } else {
109
                                CourseManager::subscribeUser($user_id, $courseInfo['code'], COURSEMANAGER);
110
                            }
111
                        } else {
112
                            CourseManager::subscribeUser($user_id, $courseInfo['code']);
113
                        }
114
                    }
115
                }
116
117
                if (!empty($isSuscribe)) {
118
                    foreach ($isSuscribe as $info) {
119
                        Display::addFlash(Display::return_message($info));
120
                    }
121
                }
122
            }
123
124
            header('Location:'.api_get_path(WEB_CODE_PATH).'user/user.php?'.api_get_cidreq().'&type='.$type);
125
            exit;
126
        break;
127
    }
128
}
129
130
$is_western_name_order = api_is_western_name_order();
131
$sort_by_first_name = api_sort_by_first_name();
132
133
// Build table
134
if (api_get_configuration_value('course_users_subscription_restricted_from_session') && !empty($sessionId)) {
135
    $table = new SortableTable(
136
        'subscribe_users',
137
        'getRestrictedSessionNumberOfUsers',
138
        'getRestrictedSessionUserList',
139
        ($is_western_name_order xor $sort_by_first_name) ? 3 : 2
140
    );
141
} else {
142
    $table = new SortableTable(
143
        'subscribe_users',
144
        'get_number_of_users',
145
        'get_user_data',
146
        ($is_western_name_order xor $sort_by_first_name) ? 3 : 2
147
    );
148
}
149
$parameters['keyword'] = $keyword;
150
$parameters['type'] = $type;
151
$table->set_additional_parameters($parameters);
152
$col = 0;
153
$table->set_header($col++, '', false);
154
$table->set_header($col++, get_lang('OfficialCode'));
155
if (api_is_western_name_order()) {
156
    $table->set_header($col++, get_lang('FirstName'));
157
    $table->set_header($col++, get_lang('LastName'));
158
} else {
159
    $table->set_header($col++, get_lang('LastName'));
160
    $table->set_header($col++, get_lang('FirstName'));
161
}
162
163
if (api_get_setting('show_email_addresses') == 'true') {
164
    $table->set_header($col++, get_lang('Email'));
165
    $table->set_column_filter($col - 1, 'email_filter');
166
}
167
$table->set_header($col++, get_lang('Active'), false);
168
$table->set_column_filter($col - 1, 'active_filter');
169
$table->set_header($col++, get_lang('Actions'), false);
170
$table->set_column_filter($col - 1, 'reg_filter');
171
$table->set_form_actions(['subscribe' => get_lang('reg')], 'user');
172
173
if (!empty($_POST['keyword'])) {
174
    $keyword_name = Security::remove_XSS($_POST['keyword']);
175
    echo '<br/>'.get_lang('SearchResultsFor').' <span style="font-style: italic ;"> '.$keyword_name.' </span><br>';
176
}
177
178
Display::display_header($tool_name, 'User');
179
180
// Build search-form
181
switch ($type) {
182
    case STUDENT:
183
        $url = api_get_path(WEB_CODE_PATH).'user/user.php?'.api_get_cidreq().'';
184
        break;
185
    case COURSEMANAGER:
186
        $url = api_get_path(WEB_CODE_PATH).'user/user.php?'.api_get_cidreq().'&type='.COURSEMANAGER;
187
        break;
188
}
189
190
$actionsLeft = Display::url(
191
    Display::return_icon('back.png', get_lang('Back'), '', ICON_SIZE_MEDIUM),
192
    $url
193
);
194
195
if (isset($_GET['subscribe_user_filter_value']) && !empty($_GET['subscribe_user_filter_value'])) {
196
    $actionsLeft .= '<a href="subscribe_user.php?type='.$type.'">'.
197
        Display::return_icon('clean_group.gif').' '.get_lang('ClearFilterResults').'</a>';
198
}
199
$extraForm = '';
200
if (api_get_setting('ProfilingFilterAddingUsers') === 'true') {
201
    $extraForm = display_extra_profile_fields_filter();
202
}
203
204
// Build search-form
205
$form = new FormValidator(
206
    'search_user',
207
    'get',
208
    api_get_self().'?'.api_get_cidreq(),
209
    '',
210
    null,
211
    FormValidator::LAYOUT_INLINE
212
);
213
$form->addText('keyword', '', false);
214
$form->addElement('hidden', 'type', $type);
215
$form->addElement('hidden', 'cidReq', api_get_course_id());
216
$form->addButtonSearch(get_lang('Search'));
217
echo Display::toolbarAction('toolbar-subscriber', [$actionsLeft, $extraForm, $form->returnForm()], [4, 4, 4]);
218
219
$option = $type == COURSEMANAGER ? 2 : 1;
220
echo UserManager::getUserSubscriptionTab($option);
221
222
// Display table
223
$table->display();
224
Display::display_footer();
225
226
/*		SHOW LIST OF USERS  */
227
228
function getRestrictedSessionNumberOfUsers(): int
229
{
230
    $tblUser = Database::get_main_table(TABLE_MAIN_USER);
231
    $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
232
    $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
233
    $urlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
234
235
    $sessionId = api_get_session_id();
236
    $courseId = api_get_course_int_id();
237
    $urlAccessId = api_get_current_access_url_id();
238
239
    $sql = "SELECT COUNT(DISTINCT u.id) nbr
240
        FROM $tblSessionRelUser s
241
        INNER JOIN $tblUser u ON (u.id = s.user_id)
242
        INNER JOIN $urlTable url ON (url.user_id = u.id)
243
        LEFT JOIN $tblSessionRelCourseRelUser scru
244
            ON (s.session_id = scru.session_id AND s.user_id = scru.user_id AND scru.c_id = $courseId)
245
        WHERE
246
            s.session_id = $sessionId
247
            AND url.access_url_id = $urlAccessId
248
            AND scru.user_id IS NULL";
249
250
    $sql = getSqlFilters($sql);
251
252
    $result = Database::fetch_assoc(Database::query($sql));
253
254
    return (int) $result['nbr'];
255
}
256
257
function getRestrictedSessionUserList($from, $number_of_items, $column, $direction): array
258
{
259
    $tblUser = Database::get_main_table(TABLE_MAIN_USER);
260
    $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
261
    $tblSessionRelCourseRelUser = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
262
    $urlTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
263
264
    $selectNames = api_is_western_name_order()
265
        ? "u.firstname AS col2, u.lastname AS col3"
266
        : "u.lastname AS col2, u.firstname AS col3";
267
268
    $selectFields = "u.user_id AS col0, u.official_code AS col1, $selectNames, u.active AS col4, u.user_id AS col5";
269
270
    if (api_get_setting('show_email_addresses') === 'true') {
271
        $selectFields = "u.id AS col0, u.official_code AS col1, $selectNames, u.email AS col4, u.active AS col5, u.user_id AS col6";
272
    }
273
274
    $sessionId = api_get_session_id();
275
    $courseId = api_get_course_int_id();
276
    $urlAccessId = api_get_current_access_url_id();
277
278
    $sql = "SELECT $selectFields
279
        FROM $tblSessionRelUser s
280
        INNER JOIN $tblUser u ON (u.id = s.user_id)
281
        INNER JOIN $urlTable url ON (url.user_id = u.id)
282
        LEFT JOIN $tblSessionRelCourseRelUser scru
283
            ON (s.session_id = scru.session_id AND s.user_id = scru.user_id AND scru.c_id = $courseId)
284
        WHERE
285
            s.session_id = $sessionId
286
            AND url.access_url_id = $urlAccessId
287
            AND scru.user_id IS NULL";
288
289
    $sql = getSqlFilters($sql);
290
291
    $sql .= " ORDER BY col$column $direction LIMIT $from, $number_of_items";
292
293
    return Database::store_result(Database::query($sql));
294
}
295
296
function getSqlFilters(string $sql): string
297
{
298
    if (isset($_REQUEST['type']) && $_REQUEST['type'] == COURSEMANAGER) {
299
        $sql .= " AND u.status = ".COURSEMANAGER;
300
    } else {
301
        $sql .= " AND u.status <> ".DRH;
302
    }
303
304
    if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
305
        $keyword = Database::escape_string(trim($_REQUEST['keyword']));
306
        $sql .= " AND (
307
            u.firstname LIKE '%".$keyword."%' OR
308
            u.lastname LIKE '%".$keyword."%' OR
309
            u.email LIKE '%".$keyword."%' OR
310
            u.username LIKE '%".$keyword."%' OR
311
            u.official_code LIKE '%".$keyword."%'
312
        )";
313
    }
314
315
    return $sql;
316
}
317
318
/**
319
 ** Get the users to display on the current page.
320
 */
321
function get_number_of_users()
322
{
323
    // Database table definition
324
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
325
    $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
326
    $tbl_session_rel_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
327
    $table_user_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
328
329
    $courseCode = api_get_course_id();
330
    $sessionId = api_get_session_id();
331
332
    if (isset($_REQUEST['type']) && $_REQUEST['type'] == COURSEMANAGER) {
333
        if (api_get_session_id() != 0) {
334
            $sql = "SELECT COUNT(u.id)
335
                    FROM $user_table u
336
                    LEFT JOIN $tbl_session_rel_course_user cu
337
                    ON
338
                        u.id = cu.user_id AND
339
                        c_id = '".api_get_course_int_id()."' AND
340
                        session_id ='".$sessionId."'
341
                    WHERE
342
                        cu.user_id IS NULL AND
343
                        u.status = 1 AND
344
                        (u.official_code <> 'ADMIN' OR u.official_code IS NULL) ";
345
346
            if (api_is_multiple_url_enabled()) {
347
                $url_access_id = api_get_current_access_url_id();
348
                if ($url_access_id != -1) {
349
                    $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
350
                    $sql = "SELECT COUNT(u.id)
351
                            FROM $user_table u
352
                            LEFT JOIN $tbl_session_rel_course_user cu
353
                            ON
354
                                u.id = cu.user_id AND cu.c_id = '".api_get_course_int_id()."' AND
355
                                session_id ='".$sessionId."'
356
                            INNER JOIN  $tbl_url_rel_user as url_rel_user
357
                            ON (url_rel_user.user_id = u.id)
358
                            WHERE
359
                                cu.user_id IS NULL AND
360
                                access_url_id= $url_access_id AND
361
                                u.status = 1 AND
362
                                (u.official_code <> 'ADMIN' OR u.official_code IS NULL)
363
                            ";
364
                }
365
            }
366
        } else {
367
            $sql = "SELECT COUNT(u.id)
368
                    FROM $user_table u
369
                    LEFT JOIN $course_user_table cu
370
                    ON u.id = cu.user_id and c_id='".api_get_course_int_id()."'
371
                    WHERE cu.user_id IS NULL AND u.status<>".DRH." ";
372
373
            if (api_is_multiple_url_enabled()) {
374
                $url_access_id = api_get_current_access_url_id();
375
                if ($url_access_id != -1) {
376
                    $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
377
378
                    $sql = "SELECT COUNT(u.id)
379
                        FROM $user_table u
380
                        LEFT JOIN $course_user_table cu
381
                        ON u.id = cu.user_id AND c_id='".api_get_course_int_id()."'
382
                        INNER JOIN  $tbl_url_rel_user as url_rel_user
383
                        ON (url_rel_user.user_id = u.id)
384
                        WHERE cu.user_id IS NULL AND u.status<>".DRH." AND access_url_id= $url_access_id ";
385
                }
386
            }
387
        }
388
    } else {
389
        // students
390
        if ($sessionId != 0) {
391
            $sql = "SELECT COUNT(u.id)
392
                    FROM $user_table u
393
                    LEFT JOIN $tbl_session_rel_course_user cu
394
                    ON
395
                        u.id = cu.user_id AND
396
                        c_id='".api_get_course_int_id()."' AND
397
                        session_id ='".$sessionId."'
398
                    WHERE
399
                        cu.user_id IS NULL AND
400
                        u.status<>".DRH." AND
401
                        (u.official_code <> 'ADMIN' OR u.official_code IS NULL) ";
402
403
            if (api_is_multiple_url_enabled()) {
404
                $url_access_id = api_get_current_access_url_id();
405
                if ($url_access_id != -1) {
406
                    $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
407
                    $sql = "SELECT COUNT(u.id)
408
                            FROM $user_table u
409
                            LEFT JOIN $tbl_session_rel_course_user cu
410
                            ON
411
                                u.id = cu.user_id AND
412
                                c_id='".api_get_course_int_id()."' AND
413
                                session_id ='".$sessionId."'
414
                            INNER JOIN $tbl_url_rel_user as url_rel_user
415
                            ON (url_rel_user.user_id = u.id)
416
                            WHERE
417
                                cu.user_id IS NULL AND
418
                                u.status<>".DRH." AND
419
                                access_url_id= $url_access_id AND
420
                                (u.official_code <> 'ADMIN' OR u.official_code IS NULL) ";
421
                }
422
            }
423
        } else {
424
            $sql = "SELECT COUNT(u.id)
425
                    FROM $user_table u
426
                    LEFT JOIN $course_user_table cu
427
                    ON u.id = cu.user_id AND c_id='".api_get_course_int_id()."'";
428
429
            // we change the SQL when we have a filter
430
            if (isset($_GET['subscribe_user_filter_value']) &&
431
                !empty($_GET['subscribe_user_filter_value']) &&
432
                api_get_setting('ProfilingFilterAddingUsers') === 'true'
433
            ) {
434
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
435
                $sql .= "
436
                    LEFT JOIN $table_user_field_values field_values
437
                    ON field_values.item_id = u.id
438
                    WHERE
439
                        cu.user_id IS NULL AND
440
                        u.status <> ".DRH." AND
441
                        field_values.field_id = '".intval($field_identification[0])."' AND
442
                        field_values.value = '".Database::escape_string($field_identification[1])."'
443
                    ";
444
            } else {
445
                $sql .= "WHERE cu.user_id IS NULL AND u.status <> ".DRH." ";
446
            }
447
448
            if (api_is_multiple_url_enabled()) {
449
                $url_access_id = api_get_current_access_url_id();
450
451
                if ($url_access_id != -1) {
452
                    $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
453
                    $sql = "SELECT COUNT(u.id)
454
                            FROM $user_table u
455
                            LEFT JOIN $course_user_table cu
456
                            ON u.id = cu.user_id AND c_id='".api_get_course_int_id()."'
457
                            INNER JOIN $tbl_url_rel_user as url_rel_user
458
                            ON (url_rel_user.user_id = u.id)
459
                            WHERE cu.user_id IS NULL AND access_url_id= $url_access_id AND u.status <> ".DRH." ";
460
                }
461
            }
462
        }
463
    }
464
465
    // when there is a keyword then we are searching and we have to change the SQL statement
466
    if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
467
        $keyword = Database::escape_string(trim($_REQUEST['keyword']));
468
        $sql .= " AND (
469
            firstname LIKE '%".$keyword."%' OR
470
            lastname LIKE '%".$keyword."%' OR
471
            email LIKE '%".$keyword."%' OR
472
            username LIKE '%".$keyword."%' OR
473
            official_code LIKE '%".$keyword."%'
474
        )";
475
476
        // we also want to search for users who have something in their profile fields that matches the keyword
477
        if (api_get_setting('ProfilingFilterAddingUsers') === 'true') {
478
            $additional_users = search_additional_profile_fields($keyword);
479
        }
480
481
        // getting all the users of the course (to make sure that we do not display users that are already in the course)
482
        if (!empty($sessionId)) {
483
            $a_course_users = CourseManager::get_user_list_from_course_code(
484
                $courseCode,
485
                $sessionId
486
            );
487
        } else {
488
            $a_course_users = CourseManager::get_user_list_from_course_code(
489
                $courseCode,
490
                0
491
            );
492
        }
493
        foreach ($a_course_users as $user_id => $course_user) {
494
            $users_of_course[] = $course_user['user_id'];
495
        }
496
    }
497
    $sql .= " AND u.status <> ".ANONYMOUS." ";
498
    $res = Database::query($sql);
499
    $count_user = 0;
500
501
    if ($res) {
502
        $row = Database::fetch_row($res);
503
        $count_user = $row[0];
504
    }
505
506
    return $count_user;
507
}
508
/**
509
 * Get the users to display on the current page.
510
 */
511
function get_user_data($from, $number_of_items, $column, $direction)
512
{
513
    $url_access_id = api_get_current_access_url_id();
514
    $course_code = api_get_course_id();
515
    $sessionId = api_get_session_id();
516
    $courseId = api_get_course_int_id();
517
518
    // Database table definitions
519
    $user_table = Database::get_main_table(TABLE_MAIN_USER);
520
    $course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
521
    $tbl_session_rel_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
522
    $table_user_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
523
    $tbl_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
524
525
    // adding teachers
526
    $is_western_name_order = api_is_western_name_order();
527
528
    if (api_get_setting('show_email_addresses') === 'true') {
529
        $select_fields = "u.id              AS col0,
530
                u.official_code        AS col1,
531
                ".($is_western_name_order
532
                ? "u.firstname         AS col2,
533
                u.lastname             AS col3,"
534
                : "u.lastname          AS col2,
535
                u.firstname            AS col3,")."
536
                u.email 	           AS col4,
537
                u.active               AS col5,
538
                u.user_id              AS col6";
539
    } else {
540
        $select_fields = "u.user_id    AS col0,
541
                u.official_code        AS col1,
542
                ".($is_western_name_order
543
                ? "u.firstname         AS col2,
544
                u.lastname             AS col3,"
545
                : "u.lastname          AS col2,
546
                u.firstname            AS col3,")."
547
                u.active               AS col4,
548
                u.user_id              AS col5";
549
    }
550
    if (isset($_REQUEST['type']) && $_REQUEST['type'] == COURSEMANAGER) {
551
        // adding a teacher through a session
552
        if (!empty($sessionId)) {
553
            $sql = "SELECT $select_fields
554
                    FROM $user_table u
555
                    LEFT JOIN $tbl_session_rel_course_user cu
556
                    ON
557
                        u.user_id = cu.user_id AND
558
                        c_id ='".$courseId."' AND
559
                        session_id ='".$sessionId."'
560
                    INNER JOIN  $tbl_url_rel_user as url_rel_user
561
                    ON (url_rel_user.user_id = u.user_id) ";
562
563
            // applying the filter of the additional user profile fields
564
            if (isset($_GET['subscribe_user_filter_value']) &&
565
                !empty($_GET['subscribe_user_filter_value']) &&
566
                api_get_setting('ProfilingFilterAddingUsers') == 'true'
567
            ) {
568
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
569
                $sql .= "
570
                    LEFT JOIN $table_user_field_values field_values
571
                        ON field_values.item_id = u.user_id
572
                    WHERE
573
                        cu.user_id IS NULL AND
574
                        u.status = 1 AND
575
                        (u.official_code <> 'ADMIN' OR u.official_code IS NULL) AND
576
                        field_values.field_id = '".intval($field_identification[0])."' AND
577
                        field_values.value = '".Database::escape_string($field_identification[1])."'";
578
            } else {
579
                $sql .= "WHERE cu.user_id IS NULL AND u.status=1 AND (u.official_code <> 'ADMIN' OR u.official_code IS NULL) ";
580
            }
581
            $sql .= " AND access_url_id = $url_access_id";
582
        } else {
583
            // adding a teacher NOT through a session
584
            $sql = "SELECT $select_fields
585
                    FROM $user_table u
586
                    LEFT JOIN $course_user_table cu
587
                    ON u.user_id = cu.user_id AND c_id = '".$courseId."'";
588
            // applying the filter of the additional user profile fields
589
            if (isset($_GET['subscribe_user_filter_value']) &&
590
                !empty($_GET['subscribe_user_filter_value']) &&
591
                api_get_setting('ProfilingFilterAddingUsers') == 'true'
592
            ) {
593
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
594
                $sql .= "
595
                    LEFT JOIN $table_user_field_values field_values
596
                        ON field_values.item_id = u.user_id
597
                    WHERE
598
                        cu.user_id IS NULL AND u.status<>".DRH." AND
599
                        field_values.field_id = '".intval($field_identification[0])."' AND
600
                        field_values.value = '".Database::escape_string($field_identification[1])."'";
601
            } else {
602
                $sql .= "WHERE cu.user_id IS NULL AND u.status <> ".DRH." ";
603
            }
604
605
            // adding a teacher NOT trough a session on a portal with multiple URLs
606
            if (api_is_multiple_url_enabled()) {
607
                if ($url_access_id != -1) {
608
                    $sql = "SELECT $select_fields
609
                            FROM $user_table u
610
                            LEFT JOIN $course_user_table cu
611
                            ON u.user_id = cu.user_id and c_id='".$courseId."'
612
                            INNER JOIN  $tbl_url_rel_user as url_rel_user
613
                            ON (url_rel_user.user_id = u.user_id) ";
614
615
                    // applying the filter of the additional user profile fields
616
                    if (isset($_GET['subscribe_user_filter_value']) &&
617
                        !empty($_GET['subscribe_user_filter_value']) &&
618
                        api_get_setting('ProfilingFilterAddingUsers') == 'true'
619
                    ) {
620
                        $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
621
                        $sql .= "
622
                            LEFT JOIN $table_user_field_values field_values
623
                                ON field_values.item_id = u.user_id
624
                            WHERE
625
                                cu.user_id IS NULL AND
626
                                u.status<>".DRH." AND
627
                                field_values.field_id = '".intval($field_identification[0])."' AND
628
                                field_values.value = '".Database::escape_string($field_identification[1])."'";
629
                    } else {
630
                        $sql .= "WHERE cu.user_id IS NULL AND u.status <> ".DRH." AND access_url_id= $url_access_id ";
631
                    }
632
                }
633
            }
634
        }
635
    } else {
636
        // adding a student
637
        if (!empty($sessionId)) {
638
            $sql = "SELECT $select_fields
639
                    FROM $user_table u
640
                    LEFT JOIN $tbl_session_rel_course_user cu
641
                    ON
642
                        u.user_id = cu.user_id AND
643
                        c_id = $courseId AND
644
                        session_id = $sessionId ";
645
646
            if (api_is_multiple_url_enabled()) {
647
                $sql .= " INNER JOIN $tbl_url_rel_user as url_rel_user ON (url_rel_user.user_id = u.user_id) ";
648
            }
649
650
            // applying the filter of the additional user profile fields
651
            if (isset($_GET['subscribe_user_filter_value']) &&
652
                !empty($_GET['subscribe_user_filter_value'])
653
            ) {
654
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
655
                $sql .= "
656
                    LEFT JOIN $table_user_field_values field_values
657
                        ON field_values.item_id = u.user_id
658
                    WHERE
659
                        cu.user_id IS NULL AND
660
                        u.status<>".DRH." AND
661
                        (u.official_code <> 'ADMIN' OR u.official_code IS NULL) AND
662
                        field_values.field_id = '".intval($field_identification[0])."' AND
663
                        field_values.value = '".Database::escape_string($field_identification[1])."'";
664
            } else {
665
                $sql .= "WHERE
666
                            cu.user_id IS NULL AND
667
                            u.status <> ".DRH." AND
668
                            (u.official_code <> 'ADMIN' OR u.official_code IS NULL) ";
669
            }
670
            if (api_is_multiple_url_enabled()) {
671
                $sql .= "AND access_url_id = $url_access_id";
672
            }
673
        } else {
674
            $sql = "SELECT $select_fields
675
                    FROM $user_table u
676
                    LEFT JOIN $course_user_table cu
677
                    ON
678
                        u.user_id = cu.user_id AND
679
                        c_id = $courseId ";
680
681
            // applying the filter of the additional user profile fields
682
            if (isset($_GET['subscribe_user_filter_value']) && !empty($_GET['subscribe_user_filter_value'])) {
683
                $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
684
                $sql .= "
685
                    LEFT JOIN $table_user_field_values field_values
686
                        ON field_values.item_id = u.user_id
687
                    WHERE
688
                        cu.user_id IS NULL AND
689
                        u.status <> ".DRH." AND
690
                        field_values.field_id = '".intval($field_identification[0])."' AND
691
                        field_values.value = '".Database::escape_string($field_identification[1])."'";
692
            } else {
693
                $sql .= "WHERE cu.user_id IS NULL AND u.status <> ".DRH." ";
694
            }
695
696
            //showing only the courses of the current Chamilo access_url_id
697
            if (api_is_multiple_url_enabled()) {
698
                if ($url_access_id != -1) {
699
                    $sql = "SELECT $select_fields
700
                        FROM $user_table u
701
                        LEFT JOIN $course_user_table cu
702
                        ON u.user_id = cu.user_id AND c_id='".$courseId."'
703
                        INNER JOIN  $tbl_url_rel_user as url_rel_user
704
                        ON (url_rel_user.user_id = u.user_id) ";
705
706
                    // applying the filter of the additional user profile fields
707
                    if (isset($_GET['subscribe_user_filter_value']) &&
708
                        !empty($_GET['subscribe_user_filter_value']) &&
709
                        api_get_setting('ProfilingFilterAddingUsers') == 'true'
710
                    ) {
711
                        $field_identification = explode('*', $_GET['subscribe_user_filter_value']);
712
                        $sql .= "
713
                            LEFT JOIN $table_user_field_values field_values
714
                                ON field_values.item_id = u.user_id
715
                            WHERE
716
                                cu.user_id IS NULL AND
717
                                u.status<>".DRH." AND
718
                                field_values.field_id = '".intval($field_identification[0])."' AND
719
                                field_values.value = '".Database::escape_string($field_identification[1])."' AND
720
                                access_url_id = $url_access_id
721
                            ";
722
                    } else {
723
                        $sql .= "WHERE cu.user_id IS NULL AND u.status<>".DRH." AND access_url_id = $url_access_id ";
724
                    }
725
                }
726
            }
727
        }
728
    }
729
730
    // adding additional WHERE statements to the SQL for the search functionality
731
    if (isset($_REQUEST['keyword'])) {
732
        $keyword = Database::escape_string(trim($_REQUEST['keyword']));
733
        $sql .= " AND (
734
                    firstname LIKE '%".$keyword."%' OR
735
                    lastname LIKE '%".$keyword."%' OR
736
                    email LIKE '%".$keyword."%' OR
737
                    username LIKE '%".$keyword."%' OR
738
                    official_code LIKE '%".$keyword."%'
739
                    )
740
                ";
741
742
        if (api_get_setting('ProfilingFilterAddingUsers') === 'true') {
743
            // we also want to search for users who have something in
744
            // their profile fields that matches the keyword
745
            $additional_users = search_additional_profile_fields($keyword);
746
        }
747
748
        // getting all the users of the course (to make sure that we do not
749
        // display users that are already in the course)
750
        if (!empty($sessionId)) {
751
            $a_course_users = CourseManager::get_user_list_from_course_code($course_code, $sessionId);
752
        } else {
753
            $a_course_users = CourseManager::get_user_list_from_course_code($course_code, 0);
754
        }
755
        foreach ($a_course_users as $user_id => $course_user) {
756
            $users_of_course[] = $course_user['user_id'];
757
        }
758
    }
759
760
    $sql .= " AND u.status != ".ANONYMOUS." ";
761
    $column = (int) $column;
762
    $direction = !in_array(strtolower(trim($direction)), ['asc', 'desc']) ? 'asc' : $direction;
763
    // Sorting and pagination (used by the sortable table)
764
    $sql .= " ORDER BY col$column $direction ";
765
    $from = (int) $from;
766
    $number_of_items = (int) $number_of_items;
767
    $sql .= " LIMIT $from, $number_of_items";
768
769
    $res = Database::query($sql);
770
    $users = [];
771
    while ($user = Database::fetch_row($res)) {
772
        $users[] = $user;
773
    }
774
775
    return $users;
776
}
777
/**
778
 * Returns a mailto-link.
779
 *
780
 * @param string $email An email-address
781
 *
782
 * @return string HTML-code with a mailto-link
783
 */
784
function email_filter($email)
785
{
786
    return Display::encrypted_mailto_link($email, $email);
787
}
788
/**
789
 * Build the reg-column of the table.
790
 *
791
 * @param int $user_id The user id
792
 *
793
 * @return string Some HTML-code
794
 */
795
function reg_filter($user_id)
796
{
797
    if (isset($_REQUEST['type']) && $_REQUEST['type'] == COURSEMANAGER) {
798
        $type = COURSEMANAGER;
799
    } else {
800
        $type = STUDENT;
801
    }
802
    $user_id = (int) $user_id;
803
804
    $result = '<a class="btn btn-small btn-primary" href="'.api_get_self().'?'.api_get_cidreq().'&register=yes&type='.$type.'&user_id='.$user_id.'">'.
805
        get_lang("reg").'</a>';
806
807
    return $result;
808
}
809
810
/**
811
 * Build the active-column of the table to lock or unlock a certain user
812
 * lock = the user can no longer use this account.
813
 *
814
 * @author Patrick Cool <[email protected]>, Ghent University
815
 *
816
 * @param int    $active     the current state of the account
817
 * @param string $url_params
818
 *
819
 * @return string Some HTML-code with the lock/unlock button
820
 */
821
function active_filter($active, $url_params, $row)
822
{
823
    $_user = api_get_user_info();
824
    if ($active == '1') {
825
        $action = 'AccountActive';
826
        $image = 'accept';
827
    }
828
829
    if ($active == '0') {
830
        $action = 'AccountInactive';
831
        $image = 'error';
832
    }
833
    $result = '';
834
    if ($row['0'] != $_user['user_id']) {
835
        // you cannot lock yourself out otherwise you could disable all the accounts
836
        // including your own => everybody is locked out and nobody can change it anymore.
837
        $result = Display::return_icon(
838
            $image.'.png',
839
            get_lang(ucfirst($action)),
840
            [],
841
            ICON_SIZE_TINY
842
        );
843
    }
844
845
    return $result;
846
}
847
848
/**
849
 * Search the additional user profile fields defined by the platform administrator in
850
 * platform administration > profiling for a given keyword.
851
 * We not only search in the predefined options but also in the input fields wherer
852
 * the user can enter some text.
853
 *
854
 * For this we get the additional profile field options that match the (search) keyword,
855
 * then we find all the users who have entered the (search)keyword in a input field of the
856
 * additional profile fields or have chosen one of the matching predefined options
857
 *
858
 * @param string $keyword a keyword we are looking for in the additional profile fields
859
 *
860
 * @return array $additional_users an array with the users who have an additional profile field that matches the keyword
861
 */
862
function search_additional_profile_fields($keyword)
863
{
864
    // database table definitions
865
    $table_user_field_options = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
866
    $table_user_field_values = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
867
    $tableExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
868
    $table_user = Database::get_main_table(TABLE_MAIN_USER);
869
870
    $keyword = Database::escape_string($keyword);
871
    // getting the field option text that match this keyword (for radio buttons and checkboxes)
872
    $sql = "SELECT * FROM $table_user_field_options
873
            WHERE display_text LIKE '%".$keyword."%'";
874
    $result_profiling = Database::query($sql);
875
    while ($profiling_field_options = Database::fetch_array($result_profiling)) {
876
        $profiling_field_options_exact_values[] = $profiling_field_options;
877
    }
878
    $profiling_field_options_exact_values_sql = '';
879
    foreach ($profiling_field_options_exact_values as $profilingkey => $profilingvalue) {
880
        $profiling_field_options_exact_values_sql .= " OR (field_id = '".$profilingvalue['field_id']."' AND value='".$profilingvalue['option_value']."') ";
881
    }
882
883
    $extraFieldType = ExtraField::USER_FIELD_TYPE;
884
885
    // getting all the user ids of the users who have chosen on of the predefined fields that contain the keyword
886
    // or all the users who have entered the keyword in a free-form field
887
    $sql = "SELECT
888
                user.user_id as col0,
889
                user.official_code as col1,
890
                user.lastname as col2,
891
                user.firstname as col3,
892
                user.email as col4,
893
                user.active as col5,
894
                user.user_id as col6
895
            FROM $table_user user, $table_user_field_values user_values, $tableExtraField e
896
            WHERE
897
                user.user_id = user_values.item_id AND
898
                user_values.field_id = e.id AND
899
                e.extra_field_type = $extraFieldType AND
900
                (value LIKE '%".$keyword."%'".$profiling_field_options_exact_values_sql.")";
901
    $result = Database::query($sql);
902
    $additional_users = [];
903
    while ($profiled_users = Database::fetch_array($result)) {
904
        $additional_users[$profiled_users['col0']] = $profiled_users;
905
    }
906
907
    return $additional_users;
908
}
909
910
/**
911
 * This function displays a dropdown list with all the additional user
912
 * profile fields defined by the platform administrator in
913
 * platform administration > profiling.
914
 * Only the fields that have predefined fields are usefull for such a filter.
915
 */
916
function display_extra_profile_fields_filter()
917
{
918
    // getting all the additional user profile fields
919
    $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
920
    $return = '<option value="">'.get_lang('SelectFilter').'</option>';
921
922
    // looping through the additional user profile fields
923
    foreach ($extra as $id => $field_details) {
924
        // $field_details[2] contains the type of the additional user profile field
925
        switch ($field_details[2]) {
926
            // text fields cannot be used as a filter
927
            case ExtraFieldModel::FIELD_TYPE_TEXT:
928
                break;
929
            // text area fields cannot be used as a filter
930
            case ExtraFieldModel::FIELD_TYPE_TEXTAREA:
931
                break;
932
            case ExtraFieldModel::FIELD_TYPE_RADIO:
933
            case ExtraFieldModel::FIELD_TYPE_SELECT:
934
            case ExtraFieldModel::FIELD_TYPE_SELECT_MULTIPLE:
935
                $return .= '<optgroup label="'.$field_details[3].'">';
936
                foreach ($field_details[9] as $option_id => $option_details) {
937
                    if (isset($_GET['subscribe_user_filter_value']) &&
938
                        $_GET['subscribe_user_filter_value'] == $field_details[0].'*'.$option_details[1]
939
                    ) {
940
                        $selected = 'selected="selected"';
941
                    } else {
942
                        $selected = false;
943
                    }
944
                    $return .= '<option value="'.$field_details[0].'*'.$option_details[1].'" '.$selected.'>'.$option_details[2].'</option>';
945
                }
946
                $return .= '</optgroup>';
947
                break;
948
        }
949
    }
950
951
    $html = '<form class="form-inline" id="subscribe_user_filter" name="subscribe_user_filter" method="get" action="'.api_get_self().'?'.api_get_cidreq().'">';
952
    $html .= '<input type="hidden" name="type" id="type" value="'.Security::remove_XSS($_REQUEST['type']).'" />';
953
    $html .= '<select name="subscribe_user_filter_value" id="subscribe_user_filter_value">'.$return.'</select>';
954
    $html .= '<button type="submit" name="submit_filter" id="submit_filter" value="" class="search">'.get_lang('Filter').'</button>';
955
    $html .= '</form>';
956
957
    return $html;
958
}
959