Passed
Push — 1.11.x ( 1cf311...245f02 )
by Angel Fernando Quiroz
08:24
created

TrackingCourseLog::protectIfNotAllowed()   B

Complexity

Conditions 11

Size

Total Lines 53
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 27
c 0
b 0
f 0
dl 0
loc 53
rs 7.3166
cc 11
nop 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
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
6
use Chamilo\CoreBundle\Entity\ExtraField as EntityExtraField;
7
use ChamiloSession as Session;
8
9
class TrackingCourseLog
10
{
11
    const HIDE_COURSE_REPORT_GRAPH_SHOWN = 0;
12
    const HIDE_COURSE_REPORT_GRAPH_HIDDEN = 1;
13
    const HIDE_COURSE_REPORT_GRAPH_CLICK_SHOW = 2;
14
15
    /**
16
     * @return mixed
17
     */
18
    public static function countItemResources()
19
    {
20
        $sessionId = api_get_session_id();
21
        $courseId = api_get_course_int_id();
22
23
        $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
24
        $tableUser = Database::get_main_table(TABLE_MAIN_USER);
25
26
        $sql = "SELECT count(tool) AS total_number_of_items
27
                FROM $tableItemProperty track_resource, $tableUser user
28
                WHERE
29
                    track_resource.c_id = $courseId AND
30
                    track_resource.insert_user_id = user.user_id AND
31
                    session_id ".(empty($sessionId) ? ' IS NULL ' : " = $sessionId ");
32
33
        if (isset($_GET['keyword'])) {
34
            $keyword = Database::escape_string(trim($_GET['keyword']));
35
            $sql .= " AND (
36
                        user.username LIKE '%".$keyword."%' OR
37
                        lastedit_type LIKE '%".$keyword."%' OR
38
                        tool LIKE '%".$keyword."%'
39
                    )";
40
        }
41
42
        $sql .= " AND tool IN (
43
                    'document',
44
                    'learnpath',
45
                    'quiz',
46
                    'glossary',
47
                    'link',
48
                    'course_description',
49
                    'announcement',
50
                    'thematic',
51
                    'thematic_advance',
52
                    'thematic_plan'
53
                )";
54
        $res = Database::query($sql);
55
        $obj = Database::fetch_object($res);
56
57
        return $obj->total_number_of_items;
58
    }
59
60
    public static function getItemResourcesData($from, $numberOfItems, $column, $direction): array
61
    {
62
        $sessionId = api_get_session_id();
63
        $courseId = api_get_course_int_id();
64
65
        $tableItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
66
        $tableUser = Database::get_main_table(TABLE_MAIN_USER);
67
        $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
68
        $column = (int) $column;
69
        $direction = !in_array(strtolower(trim($direction)), ['asc', 'desc']) ? 'asc' : $direction;
70
71
        $sql = "SELECT
72
                    tool as col0,
73
                    lastedit_type as col1,
74
                    ref as ref,
75
                    user.username as col3,
76
                    insert_date as col6,
77
                    visibility as col7,
78
                    user.user_id as user_id
79
                FROM $tableItemProperty track_resource, $tableUser user
80
                WHERE
81
                  track_resource.c_id = $courseId AND
82
                  track_resource.insert_user_id = user.user_id AND
83
                  session_id ".(empty($sessionId) ? ' IS NULL ' : " = $sessionId ");
84
85
        if (isset($_GET['keyword'])) {
86
            $keyword = Database::escape_string(trim($_GET['keyword']));
87
            $sql .= " AND (
88
                        user.username LIKE '%".$keyword."%' OR
89
                        lastedit_type LIKE '%".$keyword."%' OR
90
                        tool LIKE '%".$keyword."%'
91
                     ) ";
92
        }
93
94
        $sql .= " AND tool IN (
95
                    'document',
96
                    'learnpath',
97
                    'quiz',
98
                    'glossary',
99
                    'link',
100
                    'course_description',
101
                    'announcement',
102
                    'thematic',
103
                    'thematic_advance',
104
                    'thematic_plan'
105
                )";
106
107
        if ($column == 0) {
108
            $column = '0';
109
        }
110
        if ($column != '' && $direction != '') {
111
            if ($column != 2 && $column != 4) {
112
                $sql .= " ORDER BY col$column $direction";
113
            }
114
        } else {
115
            $sql .= " ORDER BY col6 DESC ";
116
        }
117
118
        $from = intval($from);
119
        if ($from) {
120
            $numberOfItems = intval($numberOfItems);
121
            $sql .= " LIMIT $from, $numberOfItems ";
122
        }
123
124
        $res = Database::query($sql);
125
        $resources = [];
126
        $thematicTools = ['thematic', 'thematic_advance', 'thematic_plan'];
127
        while ($row = Database::fetch_array($res)) {
128
            $ref = $row['ref'];
129
            $tableName = self::getToolNameTable($row['col0']);
130
            $tableTool = Database::get_course_table($tableName['table_name']);
131
132
            $id = $tableName['id_tool'];
133
            $recorset = false;
134
135
            if (in_array($row['col0'], ['thematic_plan', 'thematic_advance'])) {
136
                $tblThematic = Database::get_course_table(TABLE_THEMATIC);
137
                $sql = "SELECT thematic_id FROM $tableTool
138
                        WHERE c_id = $courseId AND id = $ref";
139
                $rsThematic = Database::query($sql);
140
                if (Database::num_rows($rsThematic)) {
141
                    $rowThematic = Database::fetch_array($rsThematic);
142
                    $thematicId = $rowThematic['thematic_id'];
143
144
                    $sql = "SELECT session.id, session.name, user.username
145
                            FROM $tblThematic t, $tableSession session, $tableUser user
146
                            WHERE
147
                              t.c_id = $courseId AND
148
                              t.session_id = session.id AND
149
                              session.id_coach = user.user_id AND
150
                              t.id = $thematicId";
151
                    $recorset = Database::query($sql);
152
                }
153
            } else {
154
                $sql = "SELECT session.id, session.name, user.username
155
                          FROM $tableTool tool, $tableSession session, $tableUser user
156
                          WHERE
157
                              tool.c_id = $courseId AND
158
                              tool.session_id = session.id AND
159
                              session.id_coach = user.user_id AND
160
                              tool.$id = $ref";
161
                $recorset = Database::query($sql);
162
            }
163
164
            if (!empty($recorset)) {
165
                $obj = Database::fetch_object($recorset);
166
167
                $nameSession = '';
168
                $coachName = '';
169
                if (!empty($obj)) {
170
                    $nameSession = $obj->name;
171
                    $coachName = $obj->username;
172
                }
173
174
                $urlTool = api_get_path(WEB_CODE_PATH).$tableName['link_tool'];
175
176
                if ($row['col6'] != 2) {
177
                    if (in_array($row['col0'], $thematicTools)) {
178
                        $expThematicTool = explode('_', $row['col0']);
179
                        $thematicTooltitle = '';
180
                        if (is_array($expThematicTool)) {
181
                            foreach ($expThematicTool as $exp) {
182
                                $thematicTooltitle .= api_ucfirst($exp);
183
                            }
184
                        } else {
185
                            $thematicTooltitle = api_ucfirst($row['col0']);
186
                        }
187
188
                        $row[0] = '<a href="'.$urlTool.'?'.api_get_cidreq().'&action=thematic_details">'.get_lang(
189
                                $thematicTooltitle
190
                            ).'</a>';
191
                    } else {
192
                        $row[0] = '<a href="'.$urlTool.'?'.api_get_cidreq().'">'.get_lang(
193
                                'Tool'.api_ucfirst($row['col0'])
194
                            ).'</a>';
195
                    }
196
                } else {
197
                    $row[0] = api_ucfirst($row['col0']);
198
                }
199
                $row[1] = get_lang($row[1]);
200
                $row[6] = api_convert_and_format_date($row['col6'], null, date_default_timezone_get());
201
                $row[5] = '';
202
                //@todo Improve this code please
203
                switch ($tableName['table_name']) {
204
                    case 'document':
205
                        $sql = "SELECT tool.title as title FROM $tableTool tool
206
                                WHERE c_id = $courseId AND id = $ref";
207
                        $rsDocument = Database::query($sql);
208
                        $objDocument = Database::fetch_object($rsDocument);
209
                        if ($objDocument) {
210
                            $row[5] = $objDocument->title;
211
                        }
212
                        break;
213
                    case 'quiz':
214
                    case 'course_description':
215
                    case 'announcement':
216
                        $sql = "SELECT title FROM $tableTool
217
                                WHERE c_id = $courseId AND id = $ref";
218
                        $rsDocument = Database::query($sql);
219
                        $objDocument = Database::fetch_object($rsDocument);
220
                        if ($objDocument) {
221
                            $row[5] = $objDocument->title;
222
                        }
223
                        break;
224
                    case 'glossary':
225
                        $sql = "SELECT name FROM $tableTool
226
                                WHERE c_id = $courseId AND glossary_id = $ref";
227
                        $rsDocument = Database::query($sql);
228
                        $objDocument = Database::fetch_object($rsDocument);
229
                        if ($objDocument) {
230
                            $row[5] = $objDocument->name;
231
                        }
232
                        break;
233
                    case 'lp':
234
                        $sql = "SELECT name
235
                                FROM $tableTool WHERE c_id = $courseId AND id = $ref";
236
                        $rsDocument = Database::query($sql);
237
                        $objDocument = Database::fetch_object($rsDocument);
238
                        $row[5] = $objDocument->name;
239
                        break;
240
                    case 'thematic_plan':
241
                    case 'thematic':
242
                        $rs = Database::query("SELECT title FROM $tableTool WHERE c_id = $courseId AND id = $ref");
243
                        if (Database::num_rows($rs) > 0) {
244
                            $obj = Database::fetch_object($rs);
245
                            if ($obj) {
246
                                $row[5] = $obj->title;
247
                            }
248
                        }
249
                        break;
250
                    case 'thematic_advance':
251
                        $rs = Database::query("SELECT content FROM $tableTool WHERE c_id = $courseId AND id = $ref");
252
                        if (Database::num_rows($rs) > 0) {
253
                            $obj = Database::fetch_object($rs);
254
                            if ($obj) {
255
                                $row[5] = $obj->content;
256
                            }
257
                        }
258
                        break;
259
                    default:
260
                        break;
261
                }
262
263
                $row2 = $nameSession;
264
                if (!empty($coachName)) {
265
                    $row2 .= '<br />'.get_lang('Coach').': '.$coachName;
266
                }
267
                $row[2] = $row2;
268
                if (!empty($row['col3'])) {
269
                    $userInfo = api_get_user_info($row['user_id']);
270
                    $row['col3'] = Display::url(
271
                        $row['col3'],
272
                        $userInfo['profile_url']
273
                    );
274
                    $row[3] = $row['col3'];
275
276
                    $ip = Tracking::get_ip_from_user_event(
277
                        $row['user_id'],
278
                        $row['col6'],
279
                        true
280
                    );
281
                    if (empty($ip)) {
282
                        $ip = get_lang('Unknown');
283
                    }
284
                    $row[4] = $ip;
285
                }
286
287
                $resources[] = $row;
288
            }
289
        }
290
291
        return $resources;
292
    }
293
294
    public static function getToolNameTable(string $tool): array
295
    {
296
        $linkTool = '';
297
        $idTool = '';
298
299
        switch ($tool) {
300
            case 'document':
301
                $tableName = TABLE_DOCUMENT;
302
                $linkTool = 'document/document.php';
303
                $idTool = 'id';
304
                break;
305
            case 'learnpath':
306
                $tableName = TABLE_LP_MAIN;
307
                $linkTool = 'lp/lp_controller.php';
308
                $idTool = 'id';
309
                break;
310
            case 'quiz':
311
                $tableName = TABLE_QUIZ_TEST;
312
                $linkTool = 'exercise/exercise.php';
313
                $idTool = 'iid';
314
                break;
315
            case 'glossary':
316
                $tableName = TABLE_GLOSSARY;
317
                $linkTool = 'glossary/index.php';
318
                $idTool = 'glossary_id';
319
                break;
320
            case 'link':
321
                $tableName = TABLE_LINK;
322
                $linkTool = 'link/link.php';
323
                $idTool = 'id';
324
                break;
325
            case 'course_description':
326
                $tableName = TABLE_COURSE_DESCRIPTION;
327
                $linkTool = 'course_description/';
328
                $idTool = 'id';
329
                break;
330
            case 'announcement':
331
                $tableName = TABLE_ANNOUNCEMENT;
332
                $linkTool = 'announcements/announcements.php';
333
                $idTool = 'id';
334
                break;
335
            case 'thematic':
336
                $tableName = TABLE_THEMATIC;
337
                $linkTool = 'course_progress/index.php';
338
                $idTool = 'id';
339
                break;
340
            case 'thematic_advance':
341
                $tableName = TABLE_THEMATIC_ADVANCE;
342
                $linkTool = 'course_progress/index.php';
343
                $idTool = 'id';
344
                break;
345
            case 'thematic_plan':
346
                $tableName = TABLE_THEMATIC_PLAN;
347
                $linkTool = 'course_progress/index.php';
348
                $idTool = 'id';
349
                break;
350
            default:
351
                $tableName = $tool;
352
                break;
353
        }
354
355
        return [
356
            'table_name' => $tableName,
357
            'link_tool' => $linkTool,
358
            'id_tool' => $idTool,
359
        ];
360
    }
361
362
    public static function displayAdditionalProfileFields(array $exclude = []): string
363
    {
364
        // getting all the extra profile fields that are defined by the platform administrator
365
        $extraFields = UserManager::get_extra_fields(0, 50);
366
367
        // creating the form
368
        $return = '<form action="courseLog.php" method="get" name="additional_profile_field_form" id="additional_profile_field_form">';
369
370
        // the select field with the additional user profile fields, this is where we select the field of which we want to see
371
        // the information the users have entered or selected.
372
        $return .= '<select class="chzn-select" name="additional_profile_field[]" multiple>';
373
        $return .= '<option value="-">'.get_lang('SelectFieldToAdd').'</option>';
374
        $extraFieldsToShow = 0;
375
        foreach ($extraFields as $field) {
376
            // exclude extra profile fields by id
377
            if (in_array($field[3], $exclude)) {
378
                continue;
379
            }
380
            // show only extra fields that are visible + and can be filtered, added by J.Montoya
381
            if ($field[6] == 1 && $field[8] == 1) {
382
                if (isset($_GET['additional_profile_field']) && $field[0] == $_GET['additional_profile_field']) {
383
                    $selected = 'selected="selected"';
384
                } else {
385
                    $selected = '';
386
                }
387
                $extraFieldsToShow++;
388
                $return .= '<option value="'.$field[0].'" '.$selected.'>'.$field[3].'</option>';
389
            }
390
        }
391
        $return .= '</select>';
392
393
        // the form elements for the $_GET parameters (because the form is passed through GET
394
        foreach ($_GET as $key => $value) {
395
            if ($key != 'additional_profile_field') {
396
                $return .= '<input type="hidden" name="'.Security::remove_XSS($key).'" value="'.Security::remove_XSS(
397
                        $value
398
                    ).'" />';
399
            }
400
        }
401
        // the submit button
402
        $return .= '<button class="save" type="submit">'.get_lang('AddAdditionalProfileField').'</button>';
403
        $return .= '</form>';
404
405
        return $extraFieldsToShow > 0 ? $return : '';
406
    }
407
408
    /**
409
     * This function gets all the information of a certrain ($field_id)
410
     * additional profile field for a specific list of users is more efficent
411
     * than get_addtional_profile_information_of_field() function
412
     * It gets the information of all the users so that it can be displayed
413
     * in the sortable table or in the csv or xls export.
414
     *
415
     * @param int   field id
416
     * @param array list of user ids
417
     *
418
     * @author     Julio Montoya <[email protected]>
419
     *
420
     * @since      Nov 2009
421
     *
422
     * @version    1.8.6.2
423
     */
424
    public static function getAdditionalProfileInformationOfFieldByUser($fieldId, $users): array
425
    {
426
        // Database table definition
427
        $tableUser = Database::get_main_table(TABLE_MAIN_USER);
428
        $tableUserFieldValues = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
429
        $extraField = Database::get_main_table(TABLE_EXTRA_FIELD);
430
        $resultExtraField = UserManager::get_extra_field_information($fieldId);
431
        $return = [];
432
        if (!empty($users)) {
433
            if ($resultExtraField['field_type'] == UserManager::USER_FIELD_TYPE_TAG) {
434
                foreach ($users as $user_id) {
435
                    $userResult = UserManager::get_user_tags($user_id, $fieldId);
436
                    $tagList = [];
437
                    foreach ($userResult as $item) {
438
                        $tagList[] = $item['tag'];
439
                    }
440
                    $return[$user_id][] = implode(', ', $tagList);
441
                }
442
            } else {
443
                $newUserArray = [];
444
                foreach ($users as $user_id) {
445
                    $newUserArray[] = "'".$user_id."'";
446
                }
447
                $users = implode(',', $newUserArray);
448
                $extraFieldType = EntityExtraField::USER_FIELD_TYPE;
449
                // Selecting only the necessary information NOT ALL the user list
450
                $sql = "SELECT user.user_id, v.value
451
                        FROM $tableUser user
452
                        INNER JOIN $tableUserFieldValues v
453
                        ON (user.user_id = v.item_id)
454
                        INNER JOIN $extraField f
455
                        ON (f.id = v.field_id)
456
                        WHERE
457
                            f.extra_field_type = $extraFieldType AND
458
                            v.field_id=".intval($fieldId)." AND
459
                            user.user_id IN ($users)";
460
461
                $result = Database::query($sql);
462
                while ($row = Database::fetch_array($result)) {
463
                    // get option value for field type double select by id
464
                    if (!empty($row['value'])) {
465
                        if ($resultExtraField['field_type'] ==
466
                            ExtraField::FIELD_TYPE_DOUBLE_SELECT
467
                        ) {
468
                            $idDoubleSelect = explode(';', $row['value']);
469
                            if (is_array($idDoubleSelect)) {
470
                                $value1 = $resultExtraField['options'][$idDoubleSelect[0]]['option_value'];
471
                                $value2 = $resultExtraField['options'][$idDoubleSelect[1]]['option_value'];
472
                                $row['value'] = ($value1.';'.$value2);
473
                            }
474
                        }
475
476
                        if ($resultExtraField['field_type'] == ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD) {
477
                            $parsedValue = explode('::', $row['value']);
478
479
                            if ($parsedValue) {
480
                                $value1 = $resultExtraField['options'][$parsedValue[0]]['display_text'];
481
                                $value2 = $parsedValue[1];
482
483
                                $row['value'] = "$value1: $value2";
484
                            }
485
                        }
486
487
                        if ($resultExtraField['field_type'] == ExtraField::FIELD_TYPE_TRIPLE_SELECT) {
488
                            [$level1, $level2, $level3] = explode(';', $row['value']);
489
490
                            $row['value'] = $resultExtraField['options'][$level1]['display_text'].' / ';
491
                            $row['value'] .= $resultExtraField['options'][$level2]['display_text'].' / ';
492
                            $row['value'] .= $resultExtraField['options'][$level3]['display_text'];
493
                        }
494
                    }
495
                    // get other value from extra field
496
                    $return[$row['user_id']][] = $row['value'];
497
                }
498
            }
499
        }
500
501
        return $return;
502
    }
503
504
    /**
505
     * Get number of users for sortable with pagination.
506
     */
507
    public static function getNumberOfUsers(array $conditions): array
508
    {
509
        $conditions['get_count'] = true;
510
511
        return self::getUserData(0, 0, 0, '', $conditions);
512
    }
513
514
    /**
515
     * Get data for users list in sortable with pagination.
516
     */
517
    public static function getUserData(
518
        $from,
519
        $numberOfItems,
520
        $column,
521
        $direction,
522
        array $conditions = []
523
    ): array {
524
        global $user_ids, $course_code, $export_csv, $session_id;
525
        $includeInvitedUsers = $conditions['include_invited_users']; // include the invited users
526
        $getCount = $conditions['get_count'] ?? false;
527
528
        $csvContent = [];
529
        $course_code = $course_code ? Database::escape_string($course_code) : api_get_course_id();
530
        $tblUser = Database::get_main_table(TABLE_MAIN_USER);
531
        $tblUrlRelUser = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
532
        $accessUrlId = api_get_current_access_url_id();
533
534
        // get all users data from a course for sortable with limit
535
        if (is_array($user_ids) && !empty($user_ids)) {
536
            $user_ids = array_map('intval', $user_ids);
537
            $conditionUser = " WHERE user.id IN (".implode(',', $user_ids).") ";
538
        } else {
539
            $user_ids = (int) $user_ids;
540
            $conditionUser = " WHERE user.id = $user_ids ";
541
        }
542
543
        if (!empty($_GET['user_keyword'])) {
544
            $keyword = trim(Database::escape_string($_GET['user_keyword']));
545
            $conditionUser .= " AND (
546
                user.firstname LIKE '%".$keyword."%' OR
547
                user.lastname LIKE '%".$keyword."%'  OR
548
                user.username LIKE '%".$keyword."%'  OR
549
                user.email LIKE '%".$keyword."%'
550
             ) ";
551
        }
552
553
        $urlTable = '';
554
        $urlCondition = '';
555
        if (api_is_multiple_url_enabled()) {
556
            $urlTable = " INNER JOIN $tblUrlRelUser as url_users ON (user.id = url_users.user_id)";
557
            $urlCondition = " AND access_url_id = '$accessUrlId'";
558
        }
559
560
        $invitedUsersCondition = '';
561
        if (!$includeInvitedUsers) {
562
            $invitedUsersCondition = " AND user.status != ".INVITEE;
563
        }
564
565
        $select = '
566
                SELECT user.id as user_id,
567
                    user.official_code  as col0,
568
                    user.lastname       as col1,
569
                    user.firstname      as col2,
570
                    user.username       as col3,
571
                    user.email          as col4';
572
        if ($getCount) {
573
            $select = ' SELECT COUNT(distinct(user.id)) as count ';
574
        }
575
576
        $sqlInjectJoins = '';
577
        $where = 'AND 1 = 1 ';
578
        $sqlInjectWhere = '';
579
        if (!empty($conditions)) {
580
            if (isset($conditions['inject_joins'])) {
581
                $sqlInjectJoins = $conditions['inject_joins'];
582
            }
583
            if (isset($conditions['where'])) {
584
                $where = $conditions['where'];
585
            }
586
            if (isset($conditions['inject_where'])) {
587
                $sqlInjectWhere = $conditions['inject_where'];
588
            }
589
            $injectExtraFields = !empty($conditions['inject_extra_fields']) ? $conditions['inject_extra_fields'] : 1;
590
            $injectExtraFields = rtrim($injectExtraFields, ', ');
591
            if (false === $getCount) {
592
                $select .= " , $injectExtraFields";
593
            }
594
        }
595
596
        $sql = "$select
597
                FROM $tblUser as user
598
                $urlTable
599
                $sqlInjectJoins
600
                $conditionUser
601
                $urlCondition
602
                $invitedUsersCondition
603
                $where
604
                $sqlInjectWhere
605
                ";
606
607
        if (!in_array($direction, ['ASC', 'DESC'])) {
608
            $direction = 'ASC';
609
        }
610
611
        $column = $column <= 2 ? (int) $column : 0;
612
        $from = (int) $from;
613
        $numberOfItems = (int) $numberOfItems;
614
615
        if ($getCount) {
616
            $res = Database::query($sql);
617
            $row = Database::fetch_array($res);
618
619
            return $row['count'];
620
        }
621
622
        $sortByFirstName = api_sort_by_first_name();
623
624
        if ($sortByFirstName) {
625
            if ($column == 1) {
626
                $column = 2;
627
            } elseif ($column == 2) {
628
                $column = 1;
629
            }
630
        }
631
632
        $sql .= " ORDER BY col$column $direction ";
633
        $sql .= " LIMIT $from, $numberOfItems";
634
635
        $res = Database::query($sql);
636
        $users = [];
637
638
        $courseInfo = api_get_course_info($course_code);
639
        $courseId = $courseInfo['real_id'];
640
        $courseCode = $courseInfo['code'];
641
642
        $totalSurveys = 0;
643
        $totalExercises = ExerciseLib::get_all_exercises(
644
            $courseInfo,
645
            $session_id,
646
            false,
647
            null,
648
            false,
649
            3
650
        );
651
652
        if (empty($session_id)) {
653
            $surveyUserList = [];
654
            $surveyList = SurveyManager::get_surveys($course_code, $session_id);
655
            if ($surveyList) {
656
                $totalSurveys = count($surveyList);
657
                foreach ($surveyList as $survey) {
658
                    $userList = SurveyManager::get_people_who_filled_survey(
659
                        $survey['survey_id'],
660
                        false,
661
                        $courseId
662
                    );
663
664
                    foreach ($userList as $user_id) {
665
                        isset($surveyUserList[$user_id]) ? $surveyUserList[$user_id]++ : $surveyUserList[$user_id] = 1;
666
                    }
667
                }
668
            }
669
        }
670
671
        $urlBase = api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?details=true&cidReq='.$courseCode.
672
            '&course='.$course_code.'&origin=tracking_course&id_session='.$session_id;
673
674
        Session::write('user_id_list', []);
675
        $userIdList = [];
676
677
        $addExerciseOption = api_get_configuration_value('add_exercise_best_attempt_in_report');
678
        $exerciseResultsToCheck = [];
679
        if (!empty($addExerciseOption) && isset($addExerciseOption['courses']) &&
680
            isset($addExerciseOption['courses'][$courseCode])
681
        ) {
682
            foreach ($addExerciseOption['courses'][$courseCode] as $exerciseId) {
683
                $exercise = new Exercise();
684
                $exercise->read($exerciseId);
685
                if ($exercise->iid) {
686
                    $exerciseResultsToCheck[] = $exercise;
687
                }
688
            }
689
        }
690
691
        $lpShowMaxProgress = api_get_configuration_value('lp_show_max_progress_instead_of_average');
692
        if (api_get_configuration_value('lp_show_max_progress_or_average_enable_course_level_redefinition')) {
693
            $lpShowProgressCourseSetting = api_get_course_setting('lp_show_max_or_average_progress', $courseInfo, true);
694
            if (in_array($lpShowProgressCourseSetting, ['max', 'average'])) {
695
                $lpShowMaxProgress = ('max' === $lpShowProgressCourseSetting);
696
            }
697
        }
698
699
        while ($user = Database::fetch_array($res, 'ASSOC')) {
700
            $userIdList[] = $user['user_id'];
701
            $user['official_code'] = $user['col0'];
702
            $user['username'] = $user['col3'];
703
            $user['time'] = api_time_to_hms(
704
                Tracking::get_time_spent_on_the_course(
705
                    $user['user_id'],
706
                    $courseId,
707
                    $session_id
708
                )
709
            );
710
711
            $avgStudentScore = Tracking::get_avg_student_score(
712
                $user['user_id'],
713
                $course_code,
714
                [],
715
                $session_id
716
            );
717
718
            $averageBestScore = Tracking::get_avg_student_score(
719
                $user['user_id'],
720
                $course_code,
721
                [],
722
                $session_id,
723
                false,
724
                false,
725
                true
726
            );
727
728
            $avgStudentProgress = Tracking::get_avg_student_progress(
729
                $user['user_id'],
730
                $course_code,
731
                [],
732
                $session_id,
733
                false,
734
                false,
735
                $lpShowMaxProgress
736
            );
737
738
            if (empty($avgStudentProgress)) {
739
                $avgStudentProgress = 0;
740
            }
741
            $user['average_progress'] = $avgStudentProgress.'%';
742
743
            $totalUserExercise = Tracking::get_exercise_student_progress(
744
                $totalExercises,
745
                $user['user_id'],
746
                $courseId,
747
                $session_id
748
            );
749
750
            $user['exercise_progress'] = $totalUserExercise;
751
752
            $totalUserExercise = Tracking::get_exercise_student_average_best_attempt(
753
                $totalExercises,
754
                $user['user_id'],
755
                $courseId,
756
                $session_id
757
            );
758
759
            $user['exercise_average_best_attempt'] = $totalUserExercise;
760
761
            if (is_numeric($avgStudentScore)) {
762
                $user['student_score'] = $avgStudentScore.'%';
763
            } else {
764
                $user['student_score'] = $avgStudentScore;
765
            }
766
767
            if (is_numeric($averageBestScore)) {
768
                $user['student_score_best'] = $averageBestScore.'%';
769
            } else {
770
                $user['student_score_best'] = $averageBestScore;
771
            }
772
773
            $exerciseResults = [];
774
            if (!empty($exerciseResultsToCheck)) {
775
                foreach ($exerciseResultsToCheck as $exercise) {
776
                    $bestExerciseResult = Event::get_best_attempt_exercise_results_per_user(
777
                        $user['user_id'],
778
                        $exercise->iid,
779
                        $courseId,
780
                        $session_id,
781
                        false
782
                    );
783
784
                    $best = null;
785
                    if ($bestExerciseResult) {
786
                        $best = $bestExerciseResult['exe_result'] / $bestExerciseResult['exe_weighting'];
787
                        $best = round($best, 2) * 100;
788
                        $best .= '%';
789
                    }
790
                    $exerciseResults['exercise_'.$exercise->iid] = $best;
791
                }
792
            }
793
794
            $user['count_assignments'] = Tracking::count_student_assignments(
795
                $user['user_id'],
796
                $course_code,
797
                $session_id
798
            );
799
            $user['count_messages'] = Tracking::count_student_messages(
800
                $user['user_id'],
801
                $course_code,
802
                $session_id
803
            );
804
            $user['first_connection'] = Tracking::get_first_connection_date_on_the_course(
805
                $user['user_id'],
806
                $courseId,
807
                $session_id,
808
                false === $export_csv
809
            );
810
811
            $user['last_connection'] = Tracking::get_last_connection_date_on_the_course(
812
                $user['user_id'],
813
                $courseInfo,
814
                $session_id,
815
                false === $export_csv
816
            );
817
818
            if ($export_csv) {
819
                if (!empty($user['first_connection'])) {
820
                    $user['first_connection'] = api_get_local_time($user['first_connection']);
821
                } else {
822
                    $user['first_connection'] = '-';
823
                }
824
                if (!empty($user['last_connection'])) {
825
                    $user['last_connection'] = api_get_local_time($user['last_connection']);
826
                } else {
827
                    $user['last_connection'] = '-';
828
                }
829
            }
830
831
            if (empty($session_id)) {
832
                $user['survey'] = ($surveyUserList[$user['user_id']] ?? 0).' / '.$totalSurveys;
833
            }
834
835
            $url = $urlBase.'&student='.$user['user_id'];
836
837
            $user['link'] = '<center><a href="'.$url.'">
838
                            '.Display::return_icon('2rightarrow.png', get_lang('Details')).'
839
                             </a></center>';
840
841
            // store columns in array $users
842
            $userRow = [];
843
            $userRow['official_code'] = $user['official_code']; //0
844
            if ($sortByFirstName) {
845
                $userRow['firstname'] = $user['col2'];
846
                $userRow['lastname'] = $user['col1'];
847
            } else {
848
                $userRow['lastname'] = $user['col1'];
849
                $userRow['firstname'] = $user['col2'];
850
            }
851
            $userRow['username'] = $user['username'];
852
            $userRow['time'] = $user['time'];
853
            $userRow['average_progress'] = $user['average_progress'];
854
            $userRow['exercise_progress'] = $user['exercise_progress'];
855
            $userRow['exercise_average_best_attempt'] = $user['exercise_average_best_attempt'];
856
            $userRow['student_score'] = $user['student_score'];
857
            $userRow['student_score_best'] = $user['student_score_best'];
858
            if (!empty($exerciseResults)) {
859
                foreach ($exerciseResults as $exerciseId => $bestResult) {
860
                    $userRow[$exerciseId] = $bestResult;
861
                }
862
            }
863
864
            $userRow['count_assignments'] = $user['count_assignments'];
865
            $userRow['count_messages'] = $user['count_messages'];
866
867
            $userGroupManager = new UserGroup();
868
            if ($export_csv) {
869
                $userRow['classes'] = implode(
870
                    ',',
871
                    $userGroupManager->getNameListByUser($user['user_id'], UserGroup::NORMAL_CLASS)
872
                );
873
            } else {
874
                $userRow['classes'] = $userGroupManager->getLabelsFromNameList(
875
                    $user['user_id'],
876
                    UserGroup::NORMAL_CLASS
877
                );
878
            }
879
880
            if (empty($session_id)) {
881
                $userRow['survey'] = $user['survey'];
882
            } else {
883
                $userSession = SessionManager::getUserSession($user['user_id'], $session_id);
884
                $userRow['registered_at'] = '';
885
                if ($userSession) {
886
                    $userRow['registered_at'] = api_get_local_time($userSession['registered_at']);
887
                }
888
            }
889
890
            $userRow['first_connection'] = $user['first_connection'];
891
            $userRow['last_connection'] = $user['last_connection'];
892
893
            // we need to display an additional profile field
894
            if (isset($_GET['additional_profile_field'])) {
895
                $data = Session::read('additional_user_profile_info');
896
897
                $extraFieldInfo = Session::read('extra_field_info');
898
                foreach ($_GET['additional_profile_field'] as $fieldId) {
899
                    if (isset($data[$fieldId]) && isset($data[$fieldId][$user['user_id']])) {
900
                        if (is_array($data[$fieldId][$user['user_id']])) {
901
                            $userRow[$extraFieldInfo[$fieldId]['variable']] = implode(
902
                                ', ',
903
                                $data[$fieldId][$user['user_id']]
904
                            );
905
                        } else {
906
                            $userRow[$extraFieldInfo[$fieldId]['variable']] = $data[$fieldId][$user['user_id']];
907
                        }
908
                    } else {
909
                        $userRow[$extraFieldInfo[$fieldId]['variable']] = '';
910
                    }
911
                }
912
            }
913
914
            $data = Session::read('default_additional_user_profile_info');
915
            $defaultExtraFieldInfo = Session::read('default_extra_field_info');
916
            if (isset($defaultExtraFieldInfo) && isset($data)) {
917
                foreach ($data as $key => $val) {
918
                    if (isset($val[$user['user_id']])) {
919
                        if (is_array($val[$user['user_id']])) {
920
                            $userRow[$defaultExtraFieldInfo[$key]['variable']] = implode(
921
                                ', ',
922
                                $val[$user['user_id']]
923
                            );
924
                        } else {
925
                            $userRow[$defaultExtraFieldInfo[$key]['variable']] = $val[$user['user_id']];
926
                        }
927
                    } else {
928
                        $userRow[$defaultExtraFieldInfo[$key]['variable']] = '';
929
                    }
930
                }
931
            }
932
933
            if (api_get_setting('show_email_addresses') === 'true') {
934
                $userRow['email'] = $user['col4'];
935
            }
936
937
            $userRow['link'] = $user['link'];
938
939
            if ($export_csv) {
940
                unset($userRow['link']);
941
                $csvContent[] = $userRow;
942
            }
943
            $users[] = array_values($userRow);
944
        }
945
946
        if ($export_csv) {
947
            Session::write('csv_content', $csvContent);
948
        }
949
950
        Session::erase('additional_user_profile_info');
951
        Session::erase('extra_field_info');
952
        Session::erase('default_additional_user_profile_info');
953
        Session::erase('default_extra_field_info');
954
        Session::write('user_id_list', $userIdList);
955
956
        return $users;
957
    }
958
959
    /**
960
     * Get data for users list in sortable with pagination.
961
     */
962
    public static function getTotalTimeReport(
963
        $from,
964
        $numberOfItems,
965
        $column,
966
        $direction,
967
        bool $includeInvitedUsers = false
968
    ): array {
969
        global $user_ids, $course_code, $export_csv, $session_id;
970
971
        $course_code = Database::escape_string($course_code);
972
        $tblUser = Database::get_main_table(TABLE_MAIN_USER);
973
        $tblUrlRelUser = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
974
        $accessUrlId = api_get_current_access_url_id();
975
976
        // get all users data from a course for sortable with limit
977
        if (is_array($user_ids)) {
978
            $user_ids = array_map('intval', $user_ids);
979
            $conditionUser = " WHERE user.user_id IN (".implode(',', $user_ids).") ";
980
        } else {
981
            $user_ids = intval($user_ids);
982
            $conditionUser = " WHERE user.user_id = $user_ids ";
983
        }
984
985
        $urlTable = null;
986
        $urlCondition = null;
987
        if (api_is_multiple_url_enabled()) {
988
            $urlTable = ", ".$tblUrlRelUser." as url_users";
989
            $urlCondition = " AND user.user_id = url_users.user_id AND access_url_id='$accessUrlId'";
990
        }
991
992
        $invitedUsersCondition = '';
993
        if (!$includeInvitedUsers) {
994
            $invitedUsersCondition = " AND user.status != ".INVITEE;
995
        }
996
997
        $sql = "SELECT  user.user_id as user_id,
998
                    user.official_code  as col0,
999
                    user.lastname       as col1,
1000
                    user.firstname      as col2,
1001
                    user.username       as col3
1002
                FROM $tblUser as user $urlTable
1003
                $conditionUser $urlCondition $invitedUsersCondition";
1004
1005
        if (!in_array($direction, ['ASC', 'DESC'])) {
1006
            $direction = 'ASC';
1007
        }
1008
1009
        $column = (int) $column;
1010
        $from = (int) $from;
1011
        $numberOfItems = (int) $numberOfItems;
1012
1013
        $sql .= " ORDER BY col$column $direction ";
1014
        $sql .= " LIMIT $from,$numberOfItems";
1015
1016
        $res = Database::query($sql);
1017
        $users = [];
1018
1019
        $sortByFirstName = api_sort_by_first_name();
1020
        $courseInfo = api_get_course_info($course_code);
1021
        $courseId = $courseInfo['real_id'];
1022
1023
        while ($user = Database::fetch_array($res, 'ASSOC')) {
1024
            $user['official_code'] = $user['col0'];
1025
            $user['lastname'] = $user['col1'];
1026
            $user['firstname'] = $user['col2'];
1027
            $user['username'] = $user['col3'];
1028
1029
            $totalCourseTime = Tracking::get_time_spent_on_the_course(
1030
                $user['user_id'],
1031
                $courseId,
1032
                $session_id
1033
            );
1034
1035
            $user['time'] = api_time_to_hms($totalCourseTime);
1036
            $totalLpTime = Tracking::get_time_spent_in_lp(
1037
                $user['user_id'],
1038
                $course_code,
1039
                [],
1040
                $session_id
1041
            );
1042
1043
            $warning = '';
1044
            if ($totalLpTime > $totalCourseTime) {
1045
                $warning = '&nbsp;'.Display::label(get_lang('TimeDifference'), 'danger');
1046
            }
1047
1048
            $user['total_lp_time'] = api_time_to_hms($totalLpTime).$warning;
1049
1050
            $user['first_connection'] = Tracking::get_first_connection_date_on_the_course(
1051
                $user['user_id'],
1052
                $courseId,
1053
                $session_id
1054
            );
1055
            $user['last_connection'] = Tracking::get_last_connection_date_on_the_course(
1056
                $user['user_id'],
1057
                $courseInfo,
1058
                $session_id,
1059
                $export_csv === false
1060
            );
1061
1062
            $user['link'] = '<center>
1063
                             <a href="../mySpace/myStudents.php?student='.$user['user_id'].'&details=true&course='.$course_code.'&origin=tracking_course&id_session='.$session_id.'">
1064
                             '.Display::return_icon('2rightarrow.png', get_lang('Details')).'
1065
                             </a>
1066
                         </center>';
1067
1068
            // store columns in array $users
1069
            $userRow = [];
1070
            $userRow['official_code'] = $user['official_code']; //0
1071
            if ($sortByFirstName) {
1072
                $userRow['firstname'] = $user['firstname'];
1073
                $userRow['lastname'] = $user['lastname'];
1074
            } else {
1075
                $userRow['lastname'] = $user['lastname'];
1076
                $userRow['firstname'] = $user['firstname'];
1077
            }
1078
            $userRow['username'] = $user['username'];
1079
            $userRow['time'] = $user['time'];
1080
            $userRow['total_lp_time'] = $user['total_lp_time'];
1081
            $userRow['first_connection'] = $user['first_connection'];
1082
            $userRow['last_connection'] = $user['last_connection'];
1083
1084
            $userRow['link'] = $user['link'];
1085
            $users[] = array_values($userRow);
1086
        }
1087
1088
        return $users;
1089
    }
1090
1091
    public static function actionsLeft($current, $sessionId = 0): string
1092
    {
1093
        $usersLink = Display::url(
1094
            Display::return_icon('user.png', get_lang('StudentsTracking'), [], ICON_SIZE_MEDIUM),
1095
            'courseLog.php?'.api_get_cidreq(true, false)
1096
        );
1097
1098
        $groupsLink = Display::url(
1099
            Display::return_icon('group.png', get_lang('GroupReporting'), [], ICON_SIZE_MEDIUM),
1100
            'course_log_groups.php?'.api_get_cidreq()
1101
        );
1102
1103
        $resourcesLink = Display::url(
1104
            Display::return_icon('tools.png', get_lang('ResourcesTracking'), [], ICON_SIZE_MEDIUM),
1105
            'course_log_resources.php?'.api_get_cidreq(true, false)
1106
        );
1107
1108
        $courseLink = Display::url(
1109
            Display::return_icon('course.png', get_lang('CourseTracking'), [], ICON_SIZE_MEDIUM),
1110
            'course_log_tools.php?'.api_get_cidreq(true, false)
1111
        );
1112
1113
        $examLink = Display::url(
1114
            Display::return_icon('quiz.png', get_lang('ExamTracking'), [], ICON_SIZE_MEDIUM),
1115
            api_get_path(WEB_CODE_PATH).'tracking/exams.php?'.api_get_cidreq()
1116
        );
1117
1118
        $eventsLink = Display::url(
1119
            Display::return_icon('security.png', get_lang('EventsReport'), [], ICON_SIZE_MEDIUM),
1120
            api_get_path(WEB_CODE_PATH).'tracking/course_log_events.php?'.api_get_cidreq()
1121
        );
1122
1123
        $lpLink = Display::url(
1124
            Display::return_icon('scorms.png', get_lang('CourseLearningPathsGenericStats'), [], ICON_SIZE_MEDIUM),
1125
            api_get_path(WEB_CODE_PATH).'tracking/lp_report.php?'.api_get_cidreq()
1126
        );
1127
1128
        $attendanceLink = '';
1129
        if (!empty($sessionId)) {
1130
            $attendanceLink = Display::url(
1131
                Display::return_icon('attendance_list.png', get_lang('Logins'), '', ICON_SIZE_MEDIUM),
1132
                api_get_path(WEB_CODE_PATH).'attendance/index.php?'.api_get_cidreq().'&action=calendar_logins'
1133
            );
1134
        }
1135
1136
        switch ($current) {
1137
            case 'users':
1138
                $usersLink = Display::url(
1139
                    Display::return_icon(
1140
                        'user_na.png',
1141
                        get_lang('StudentsTracking'),
1142
                        [],
1143
                        ICON_SIZE_MEDIUM
1144
                    ),
1145
                    '#'
1146
                );
1147
                break;
1148
            case 'groups':
1149
                $groupsLink = Display::url(
1150
                    Display::return_icon('group_na.png', get_lang('GroupReporting'), [], ICON_SIZE_MEDIUM),
1151
                    '#'
1152
                );
1153
                break;
1154
            case 'courses':
1155
                $courseLink = Display::url(
1156
                    Display::return_icon('course_na.png', get_lang('CourseTracking'), [], ICON_SIZE_MEDIUM),
1157
                    '#'
1158
                );
1159
                break;
1160
            case 'resources':
1161
                $resourcesLink = Display::url(
1162
                    Display::return_icon(
1163
                        'tools_na.png',
1164
                        get_lang('ResourcesTracking'),
1165
                        [],
1166
                        ICON_SIZE_MEDIUM
1167
                    ),
1168
                    '#'
1169
                );
1170
                break;
1171
            case 'exams':
1172
                $examLink = Display::url(
1173
                    Display::return_icon('quiz_na.png', get_lang('ExamTracking'), [], ICON_SIZE_MEDIUM),
1174
                    '#'
1175
                );
1176
                break;
1177
            case 'logs':
1178
                $eventsLink = Display::url(
1179
                    Display::return_icon('security_na.png', get_lang('EventsReport'), [], ICON_SIZE_MEDIUM),
1180
                    '#'
1181
                );
1182
                break;
1183
            case 'attendance':
1184
                if (!empty($sessionId)) {
1185
                    $attendanceLink = Display::url(
1186
                        Display::return_icon('attendance_list.png', get_lang('Logins'), '', ICON_SIZE_MEDIUM),
1187
                        '#'
1188
                    );
1189
                }
1190
                break;
1191
            case 'lp':
1192
                $lpLink = Display::url(
1193
                    Display::return_icon(
1194
                        'scorms_na.png',
1195
                        get_lang('CourseLearningPathsGenericStats'),
1196
                        [],
1197
                        ICON_SIZE_MEDIUM
1198
                    ),
1199
                    '#'
1200
                );
1201
                break;
1202
        }
1203
1204
        $items = [
1205
            $usersLink,
1206
            $groupsLink,
1207
            $courseLink,
1208
            $resourcesLink,
1209
            $examLink,
1210
            $eventsLink,
1211
            $lpLink,
1212
            $attendanceLink,
1213
        ];
1214
1215
        return implode('', $items).'&nbsp;';
1216
    }
1217
1218
    public static function getTeachersOrCoachesHtmlHeader(
1219
        string $courseCode,
1220
        int $cId,
1221
        int $sessionId,
1222
        bool $addLinkToPrfile
1223
    ): string {
1224
        $html = '';
1225
1226
        $teacherList = CourseManager::getTeacherListFromCourseCodeToString(
1227
            $courseCode,
1228
            ',',
1229
            $addLinkToPrfile,
1230
            true
1231
        );
1232
1233
        if (!empty($teacherList)) {
1234
            $html .= Display::page_subheader2(get_lang('Teachers'));
1235
            $html .= $teacherList;
1236
        }
1237
1238
        if (!empty($sessionId)) {
1239
            $coaches = CourseManager::get_coachs_from_course_to_string(
1240
                $sessionId,
1241
                $cId,
1242
                ',',
1243
                $addLinkToPrfile,
1244
                true
1245
            );
1246
1247
            if (!empty($coaches)) {
1248
                $html .= Display::page_subheader2(get_lang('Coaches'));
1249
                $html .= $coaches;
1250
            }
1251
        }
1252
1253
        return $html;
1254
    }
1255
1256
    /**
1257
     * @return float|string
1258
     */
1259
    public static function calcBestScoreAverageNotInLP(
1260
        array $exerciseList,
1261
        array $usersInGroup,
1262
        int $cId,
1263
        int $sessionId = 0,
1264
        bool $returnFormatted = false
1265
    ) {
1266
        if (empty($exerciseList) || empty($usersInGroup)) {
1267
            return 0;
1268
        }
1269
1270
        $bestScoreAverageNotInLP = 0;
1271
1272
        foreach ($exerciseList as $exerciseData) {
1273
            foreach ($usersInGroup as $userId) {
1274
                $results = Event::get_best_exercise_results_by_user(
1275
                    $exerciseData['iid'],
1276
                    $cId,
1277
                    $sessionId,
1278
                    $userId
1279
                );
1280
1281
                $scores = array_map(
1282
                    function (array $result) {
1283
                        return empty($result['exe_weighting']) ? 0 : $result['exe_result'] / $result['exe_weighting'];
1284
                    },
1285
                    $results
1286
                );
1287
1288
                $bestScoreAverageNotInLP += $scores ? max($scores) : 0;
1289
            }
1290
        }
1291
1292
        $rounded = round(
1293
            $bestScoreAverageNotInLP / count($exerciseList) * 100 / count($usersInGroup),
1294
            2
1295
        );
1296
1297
        if ($returnFormatted) {
1298
            return sprintf(get_lang('XPercent'), $rounded);
1299
        }
1300
1301
        return $rounded;
1302
    }
1303
1304
    public static function protectIfNotAllowed()
1305
    {
1306
        $courseInfo = api_get_course_info();
1307
1308
        if (empty($courseInfo)) {
1309
            api_not_allowed(true);
1310
        }
1311
1312
        $sessionId = api_get_session_id();
1313
        $isAllowedToTrack = Tracking::isAllowToTrack($sessionId);
1314
1315
        if (!$isAllowedToTrack) {
1316
            api_not_allowed(true);
1317
        }
1318
1319
        $courseCode = $courseInfo['code'];
1320
1321
        // If the user is an HR director (drh)
1322
        if (!api_is_drh()) {
1323
            return;
1324
        }
1325
1326
        // Blocking course for drh
1327
        if (api_drh_can_access_all_session_content()) {
1328
            // If the drh has been configured to be allowed to see all session content, give him access to the session courses
1329
            $coursesFromSession = SessionManager::getAllCoursesFollowedByUser(api_get_user_id(), null);
1330
            $coursesFromSessionCodeList = [];
1331
1332
            if (!empty($coursesFromSession)) {
1333
                foreach ($coursesFromSession as $course) {
1334
                    $coursesFromSessionCodeList[$course['code']] = $course['code'];
1335
                }
1336
            }
1337
1338
            $coursesFollowedList = CourseManager::get_courses_followed_by_drh(api_get_user_id());
1339
1340
            if (!empty($coursesFollowedList)) {
1341
                $coursesFollowedList = array_keys($coursesFollowedList);
1342
            }
1343
1344
            if (!in_array($courseCode, $coursesFollowedList)
1345
                && !in_array($courseCode, $coursesFromSessionCodeList)
1346
            ) {
1347
                api_not_allowed(true);
1348
            }
1349
        } else {
1350
            // If the drh has *not* been configured to be allowed to see all session content,
1351
            // then check if he has also been given access to the corresponding courses
1352
            $coursesFollowedList = CourseManager::get_courses_followed_by_drh(api_get_user_id());
1353
            $coursesFollowedList = array_keys($coursesFollowedList);
1354
1355
            if (!in_array($courseCode, $coursesFollowedList)) {
1356
                api_not_allowed(true);
1357
            }
1358
        }
1359
    }
1360
1361
    public static function returnCourseGraphicalReport(array $conditions)
1362
    {
1363
1364
    }
1365
1366
    /**
1367
     * count the number of students in this course (used for SortableTable)
1368
     * Deprecated.
1369
     */
1370
    public function countStudentInCourse(): int
1371
    {
1372
        global $nbStudents;
1373
1374
        return $nbStudents;
1375
    }
1376
1377
    public function sortUsers($a, $b): int
1378
    {
1379
        $tracking = Session::read('tracking_column');
1380
1381
        return strcmp(
1382
            trim(api_strtolower($a[$tracking])),
1383
            trim(api_strtolower($b[$tracking]))
1384
        );
1385
    }
1386
1387
    public function sortUsersDesc($a, $b): int
1388
    {
1389
        $tracking = Session::read('tracking_column');
1390
1391
        return strcmp(
1392
            trim(api_strtolower($b[$tracking])),
1393
            trim(api_strtolower($a[$tracking]))
1394
        );
1395
    }
1396
}
1397