MySpace::check_user_in_array()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 2
dl 0
loc 14
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\Session as SessionEntity;
5
use Chamilo\CoreBundle\Entity\User;
6
use Chamilo\CoreBundle\Framework\Container;
7
use ChamiloSession as Session;
8
use CpChart\Cache as pCache;
9
use CpChart\Data as pData;
10
use CpChart\Image as pImage;
11
12
/**
13
 * Class MySpace.
14
 */
15
class MySpace
16
{
17
    /**
18
     * Generate the list of admin actions to be shown
19
     * @return array
20
     */
21
    public static function generateAdminActionLinks(): array
22
    {
23
        $actions = [
24
            [
25
                'url' => api_get_path(WEB_CODE_PATH).'my_space/admin_view.php?display=coaches',
26
                'content' => get_lang('Trainers Overview'),
27
            ],
28
            [
29
                'url' => api_get_path(WEB_CODE_PATH).'my_space/admin_view.php?display=user',
30
                'content' => get_lang('User overview'),
31
            ],
32
            [
33
                'url' => api_get_path(WEB_CODE_PATH).'my_space/admin_view.php?display=session',
34
                'content' => get_lang('Sessions overview'),
35
            ],
36
            [
37
                'url' => api_get_path(WEB_CODE_PATH).'my_space/admin_view.php?display=course',
38
                'content' => get_lang('Courses overview'),
39
            ],
40
            [
41
                'url' => api_get_path(WEB_CODE_PATH).'tracking/question_course_report.php?view=admin',
42
                'content' => get_lang('Learning paths exercises results list'),
43
            ],
44
            [
45
                'url' => api_get_path(WEB_CODE_PATH).'tracking/course_session_report.php?view=admin',
46
                'content' => get_lang('Results of learning paths exercises by session'),
47
            ],
48
            [
49
                'url' => api_get_path(WEB_CODE_PATH).'my_space/admin_view.php?display=accessoverview',
50
                'content' => get_lang('Accesses by user overview').' ('.get_lang('Beta').')',
51
            ],
52
            [
53
                'url' => api_get_path(WEB_CODE_PATH).'my_space/exercise_category_report.php',
54
                'content' => get_lang('Exercise report by category for all sessions'),
55
            ],
56
            [
57
                'url' => api_get_path(WEB_CODE_PATH).'my_space/survey_report.php',
58
                'content' => get_lang('Surveys report'),
59
            ],
60
            [
61
                'url' => api_get_path(WEB_CODE_PATH).'my_space/tc_report.php',
62
                'content' => get_lang("Student's superior follow up"),
63
            ],
64
            [
65
                'url' => api_get_path(WEB_CODE_PATH).'my_space/ti_report.php',
66
                'content' => get_lang('General Coaches planning'),
67
            ],
68
            [
69
                'url' => api_get_path(WEB_CODE_PATH).'my_space/question_stats_global.php',
70
                'content' => get_lang('Question stats'),
71
            ],
72
            [
73
                'url' => api_get_path(WEB_CODE_PATH).'my_space/question_stats_global_detail.php',
74
                'content' => get_lang('Detailed questions stats'),
75
            ],
76
        ];
77
78
        $field = new ExtraField('user');
79
        $companyField = $field->get_handler_field_info_by_field_variable('company');
80
        if (!empty($companyField)) {
81
            $actions[] =
82
                [
83
                    'url' => api_get_path(WEB_CODE_PATH).'my_space/admin_view.php?display=company',
84
                    'content' => get_lang('User by organization'),
85
                ];
86
        }
87
        $field = new ExtraField('lp');
88
        $authorsField = $field->get_handler_field_info_by_field_variable('authors');
89
        if (!empty($authorsField)) {
90
            $actions[] =
91
                [
92
                    'url' => api_get_path(WEB_CODE_PATH).'my_space/admin_view.php?display=learningPath',
93
                    'content' => get_lang('Learning path by author'),
94
                ];
95
        }
96
        $field = new ExtraField('lp_item');
97
        $authorsItemField = $field->get_handler_field_info_by_field_variable('authorlpitem');
98
        if (!empty($authorsItemField)) {
99
            $actions[] =
100
                [
101
                    'url' => api_get_path(WEB_CODE_PATH).'my_space/admin_view.php?display=learningPathByItem',
102
                    'content' => get_lang('LP item by author'),
103
                ];
104
        }
105
        return $actions;
106
    }
107
108
    /**
109
     * @return string
110
     */
111
    public static function getTopMenu()
112
    {
113
        $menuItems = [];
114
        $menuItems[] = Display::url(
115
            Display::getMdiIcon('chart-box', 'ch-tool-icon', null, 32, get_lang('View my progress')),
116
            api_get_path(WEB_CODE_PATH).'auth/my_progress.php'
117
        );
118
        $menuItems[] = Display::url(
119
            Display::getMdiIcon('human-male-board', 'ch-tool-icon', null, 32, get_lang('Trainer View')),
120
            api_get_path(WEB_CODE_PATH).'my_space/index.php?view=teacher'
121
        );
122
        $menuItems[] = Display::url(
123
            Display::getMdiIcon('star', 'ch-tool-icon', null, 32, get_lang('Admin view')),
124
            '#'
125
        );
126
        $menuItems[] = Display::url(
127
            Display::getMdiIcon('order-bool-ascending-variant', 'ch-tool-icon', null, 32, get_lang('Exam tracking')),
128
            api_get_path(WEB_CODE_PATH).'tracking/exams.php'
129
        );
130
131
        return Display::toolbarAction('myspace', $menuItems);
132
    }
133
134
    /**
135
     * This function serves exporting data in CSV format.
136
     *
137
     * @param array  $header    the header labels
138
     * @param array  $data      the data array
139
     * @param string $file_name the name of the file which contains exported data
140
     *
141
     * @return string mixed             Returns a message (string) if an error occurred
142
     */
143
    public function export_csv($header, $data, $file_name = 'export.csv')
144
    {
145
        $archive_path = api_get_path(SYS_ARCHIVE_PATH);
146
        $archive_url = api_get_path(WEB_CODE_PATH).'course_info/download.php?archive_path=&archive=';
147
        $message = '';
148
        if (!$open = fopen($archive_path.$file_name, 'w+')) {
149
            $message = get_lang('Could not open');
150
        } else {
151
            $info = '';
152
153
            foreach ($header as $value) {
154
                $info .= $value.';';
155
            }
156
            $info .= "\r\n";
157
158
            foreach ($data as $row) {
159
                foreach ($row as $value) {
160
                    $info .= $value.';';
161
                }
162
                $info .= "\r\n";
163
            }
164
165
            fwrite($open, $info);
166
            fclose($open);
167
            @chmod($file_name, api_get_permissions_for_new_files());
168
169
            header("Location:".$archive_url.$file_name);
170
            exit;
171
        }
172
173
        return $message;
174
    }
175
176
    /**
177
     * Gets the connections to a course as an array of login and logout time.
178
     *
179
     * @param int   $userId     User id
180
     * @param array $courseInfo
181
     * @param int   $sessionId  Session id (optional, default = 0)
182
     *
183
     * @return array Connections
184
     */
185
    public static function get_connections_to_course(
186
        $userId,
187
        $courseInfo,
188
        $sessionId = 0
189
    ) {
190
        $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
191
192
        // protect data
193
        $userId = (int) $userId;
194
        $courseId = (int) $courseInfo['real_id'];
195
        $sessionId = (int) $sessionId;
196
        $sessionCondition = api_get_session_condition($sessionId);
197
198
        $sql = 'SELECT login_course_date, logout_course_date
199
                FROM '.$table.'
200
                WHERE
201
                    user_id = '.$userId.' AND
202
                    c_id = '.$courseId.'
203
                    '.$sessionCondition.'
204
                ORDER BY login_course_date ASC';
205
        $rs = Database::query($sql);
206
        $connections = [];
207
208
        while ($row = Database::fetch_array($rs)) {
209
            $connections[] = [
210
                'login' => $row['login_course_date'],
211
                'logout' => $row['logout_course_date'],
212
            ];
213
        }
214
215
        return $connections;
216
    }
217
218
    /**
219
     * @param $user_id
220
     * @param $course_list
221
     * @param int $session_id
222
     *
223
     * @return array|bool
224
     */
225
    public static function get_connections_from_course_list(
226
        $user_id,
227
        $course_list,
228
        $session_id = 0
229
    ) {
230
        // Database table definitions
231
        $tbl_track_course = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
232
        if (empty($course_list)) {
233
            return false;
234
        }
235
236
        // protect data
237
        $user_id = (int) $user_id;
238
        $session_id = (int) $session_id;
239
        $new_course_list = [];
240
        foreach ($course_list as $course_item) {
241
            $courseInfo = api_get_course_info($course_item['code']);
242
            if ($courseInfo) {
243
                $courseId = $courseInfo['real_id'];
244
                $new_course_list[] = '"'.$courseId.'"';
245
            }
246
        }
247
        $course_list = implode(', ', $new_course_list);
248
249
        if (empty($course_list)) {
250
            return false;
251
        }
252
        $sql = 'SELECT login_course_date, logout_course_date, c_id
253
                FROM '.$tbl_track_course.'
254
                WHERE
255
                    user_id = '.$user_id.' AND
256
                    c_id IN ('.$course_list.') AND
257
                    session_id = '.$session_id.'
258
                ORDER BY login_course_date ASC';
259
        $rs = Database::query($sql);
260
        $connections = [];
261
262
        while ($row = Database::fetch_array($rs)) {
263
            $timestamp_login_date = api_strtotime($row['login_course_date'], 'UTC');
264
            $timestamp_logout_date = api_strtotime($row['logout_course_date'], 'UTC');
265
            $connections[] = [
266
                'login' => $timestamp_login_date,
267
                'logout' => $timestamp_logout_date,
268
                'c_id' => $row['c_id'],
269
            ];
270
        }
271
272
        return $connections;
273
    }
274
275
    /**
276
     * Creates a small table in the last column of the table with the user overview.
277
     *
278
     * @return array List course
279
     */
280
    public static function returnCourseTracking(User $user)
281
    {
282
        $userId = $user->getId();
283
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
284
        // getting all the courses of the user
285
        $sql = "SELECT * FROM $tbl_course_user
286
                WHERE
287
                    user_id = $userId AND
288
                    relation_type <> ".COURSE_RELATION_TYPE_RRHH;
289
        $result = Database::query($sql);
290
291
        $list = [];
292
293
        while ($row = Database::fetch_array($result)) {
294
            $course = api_get_course_entity($row['c_id']);
295
296
            if (null === $course) {
297
                continue;
298
            }
299
300
            $courseId = $course->getId();
301
            $courseCode = $course->getCode();
302
303
            $avg_score = Tracking::get_avg_student_score($userId, $course);
304
            if (is_numeric($avg_score)) {
305
                $avg_score = round($avg_score, 2);
306
            } else {
307
                $avg_score = '-';
308
            }
309
310
            // Student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
311
            $exercisesResults = self::exercises_results($userId, $courseCode);
312
313
            $resultToString = '';
314
            if (!is_null($exercisesResults['percentage'])) {
315
                $resultToString =
316
                    $exercisesResults['score_obtained'].'/'.$exercisesResults['score_possible'].
317
                    ' ( '.$exercisesResults['percentage'].'% )';
318
            }
319
320
            $item = [
321
                'code' => $courseCode,
322
                'real_id' => $courseId,
323
                'title' => $course->getTitle(),
324
                'category' => '',
325
                //'category' => $courseInfo['categoryName'], // @todo show categories instead of 1 category
326
                //'image_small' => $courseInfo['course_image'],
327
                //'image_large' => $courseInfo['course_image_large'],
328
                'time_spent' => api_time_to_hms(Tracking::get_time_spent_on_the_course($userId, $courseId)),
329
                'student_progress' => round(Tracking::get_avg_student_progress($userId, $course)),
330
                'student_score' => $avg_score,
331
                'student_message' => Container::getForumPostRepository()->countUserForumPosts($user, $course),
332
                'student_assignments' => Container::getStudentPublicationRepository()->countUserPublications($user, $course),
333
                'student_exercises' => $resultToString,
334
                'questions_answered' => $exercisesResults['questions_answered'],
335
                'last_connection' => Tracking::get_last_connection_date_on_the_course(
336
                    $userId,
337
                    ['real_id' => $courseId]
338
                ),
339
            ];
340
            $list[] = $item;
341
        }
342
343
        return $list;
344
    }
345
346
    /**
347
     * Display a sortable table that contains an overview off all the
348
     * reporting progress of all users and all courses the user is subscribed to.
349
     *
350
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
351
     *          Alex Aragon <[email protected]>, BeezNest, Perú
352
     *
353
     * @version Chamilo 1.11.8
354
     *
355
     * @since April 2019
356
     */
357
    public static function returnTrackingUserOverviewFilter($userId)
358
    {
359
        $tpl = new Template('', false, false, false, false, false, false);
360
        $user = api_get_user_entity($userId);
361
        $url = Container::getIllustrationRepository()->getIllustrationUrl($user);
362
363
        $item = [
364
            'id' => $user->getId(),
365
            'code_user' => $user->getOfficialCode(),
366
            'complete_name' => UserManager::formatUserFullName($user),
367
            'username' => $user->getUsername(),
368
            'course' => self::returnCourseTracking($user),
369
            'avatar' => $url,
370
        ];
371
372
        $tpl->assign('item', $item);
373
        $templateName = $tpl->get_template('my_space/partials/tracking_user_overview.tpl');
374
375
        return $tpl->fetch($templateName);
376
    }
377
378
    /**
379
     * Display a sortable table that contains an overview off all the
380
     * reporting progress of all users and all courses the user is subscribed to.
381
     *
382
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
383
     *         Alex Aragon <[email protected]>, BeezNest, Perú
384
     *
385
     * @version Chamilo 1.11.8
386
     *
387
     * @since October 2008, Update April 2019
388
     */
389
    public static function display_tracking_user_overview()
390
    {
391
        self::display_user_overview_export_options();
392
393
        $params = ['view' => 'admin', 'display' => 'user'];
394
        $table = new SortableTable(
395
            'tracking_user_overview',
396
            ['MySpace', 'get_number_of_users_tracking_overview'],
397
            ['MySpace', 'get_user_data_tracking_overview'],
398
            0,
399
            20,
400
            'ASC',
401
            null, [
402
                'class' => 'table table-transparent',
403
            ]
404
        );
405
        $table->additional_parameters = $params;
406
407
        $table->set_column_filter(0, ['MySpace', 'returnTrackingUserOverviewFilter']);
408
        $tableContent = $table->return_table();
409
        $tpl = new Template('', false, false, false, false, false, false);
410
        $tpl->assign('table', $tableContent);
411
        $templateName = $tpl->get_template('my_space/user_summary.tpl');
412
        echo $tpl->fetch($templateName);
413
    }
414
415
    /**
416
     * @param $export_csv
417
     */
418
    public static function display_tracking_coach_overview($export_csv)
419
    {
420
        if ($export_csv) {
421
            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
422
        } else {
423
            $is_western_name_order = api_is_western_name_order();
424
        }
425
        $sort_by_first_name = api_sort_by_first_name();
426
427
        if (isset($_GET['tracking_list_coaches_column'])) {
428
            $tracking_column = (int) $_GET['tracking_list_coaches_column'];
429
        } else {
430
            $tracking_column = ($is_western_name_order xor $sort_by_first_name) ? 1 : 0;
431
        }
432
433
        $tracking_direction = (isset($_GET['tracking_list_coaches_direction']) && in_array(strtoupper($_GET['tracking_list_coaches_direction']), ['ASC', 'DESC', 'ASCENDING', 'DESCENDING', '0', '1'])) ? $_GET['tracking_list_coaches_direction'] : 'DESC';
434
        // Prepare array for column order - when impossible, use some of user names.
435
        if ($is_western_name_order) {
436
            $order = [
437
                0 => 'firstname',
438
                1 => 'lastname',
439
                2 => $sort_by_first_name ? 'firstname' : 'lastname',
440
                3 => 'login_date',
441
                4 => $sort_by_first_name ? 'firstname' : 'lastname',
442
                5 => $sort_by_first_name ? 'firstname' : 'lastname',
443
            ];
444
        } else {
445
            $order = [
446
                0 => 'lastname',
447
                1 => 'firstname',
448
                2 => $sort_by_first_name ? 'firstname' : 'lastname',
449
                3 => 'login_date',
450
                4 => $sort_by_first_name ? 'firstname' : 'lastname',
451
                5 => $sort_by_first_name ? 'firstname' : 'lastname',
452
            ];
453
        }
454
        $table = new SortableTable(
455
            'tracking_list_coaches_myspace',
456
            null,
457
            null,
458
            ($is_western_name_order xor $sort_by_first_name) ? 1 : 0
459
        );
460
        $parameters['view'] = 'admin';
461
        $table->set_additional_parameters($parameters);
462
        if ($is_western_name_order) {
463
            $table->set_header(0, get_lang('First name'), true);
464
            $table->set_header(1, get_lang('Last name'), true);
465
        } else {
466
            $table->set_header(0, get_lang('Last name'), true);
467
            $table->set_header(1, get_lang('First name'), true);
468
        }
469
        $table->set_header(2, get_lang('Time spent in portal'), false);
470
        $table->set_header(3, get_lang('Latest login'), false);
471
        $table->set_header(4, get_lang('Learners'), false);
472
        $table->set_header(5, get_lang('Courses'), false);
473
        $table->set_header(6, get_lang('Number of sessions'), false);
474
        $table->set_header(7, get_lang('Course sessions'), false);
475
476
        if ($is_western_name_order) {
477
            $csv_header[] = [
478
                get_lang('First name'),
479
                get_lang('Last name'),
480
                get_lang('Time spent in portal'),
481
                get_lang('Latest login'),
482
                get_lang('Learners'),
483
                get_lang('Courses'),
484
                get_lang('Number of sessions'),
485
            ];
486
        } else {
487
            $csv_header[] = [
488
                get_lang('Last name'),
489
                get_lang('First name'),
490
                get_lang('Time spent in portal'),
491
                get_lang('Latest login'),
492
                get_lang('Learners'),
493
                get_lang('Courses'),
494
                get_lang('Number of sessions'),
495
            ];
496
        }
497
498
        $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
499
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
500
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
501
        $tblSessionRelUser = Database::get_main_table(TABLE_MAIN_SESSION_USER);
502
503
        $sqlCoachs = "SELECT DISTINCT
504
                        scu.user_id as id_coach,
505
                        u.id as user_id,
506
                        lastname,
507
                        firstname,
508
                        MAX(login_date) as login_date
509
                        FROM $tbl_user u, $tbl_session_course_user scu, $tbl_track_login
510
                        WHERE
511
                            u.active <> ".USER_SOFT_DELETED." AND scu.user_id = u.id AND scu.status=".SessionEntity::COURSE_COACH." AND login_user_id=u.id
512
                        GROUP BY user_id ";
513
514
        if (api_is_multiple_url_enabled()) {
515
            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
516
            $access_url_id = api_get_current_access_url_id();
517
            if (-1 != $access_url_id) {
518
                $sqlCoachs = "SELECT DISTINCT
519
                                    scu.user_id as id_coach,
520
                                    u.id as user_id,
521
                                    lastname,
522
                                    firstname,
523
                                    MAX(login_date) as login_date
524
                                FROM $tbl_user u,
525
                                $tbl_session_course_user scu,
526
                                $tbl_track_login ,
527
                                $tbl_session_rel_access_url session_rel_url
528
                                WHERE
529
                                    scu.user_id = u.id AND
530
                                    scu.status = ".SessionEntity::COURSE_COACH." AND
531
                                    login_user_id = u.id AND
532
                                    access_url_id = $access_url_id AND
533
                                    session_rel_url.session_id = scu.session_id
534
                                GROUP BY u.id";
535
            }
536
        }
537
        if (!empty($order[$tracking_column])) {
538
            $sqlCoachs .= " ORDER BY `".$order[$tracking_column]."` ".$tracking_direction;
539
        }
540
541
        $result_coaches = Database::query($sqlCoachs);
542
        $global_coaches = [];
543
        while ($coach = Database::fetch_array($result_coaches)) {
544
            $global_coaches[$coach['user_id']] = $coach;
545
        }
546
547
        $sql_session_coach = "SELECT u.id AS user_id, u.lastname, u.firstname, MAX(tel.login_date) AS login_date
548
                                FROM $tbl_user u
549
                                INNER JOIN $tbl_track_login tel
550
                                ON tel.login_user_id = u.id
551
                                INNER JOIN $tblSessionRelUser sru
552
                                ON (u.id = sru.user_id AND sru.relation_type = ".SessionEntity::GENERAL_COACH.")
553
                                GROUP BY u.id
554
                                ORDER BY login_date $tracking_direction";
555
556
        if (api_is_multiple_url_enabled()) {
557
            $tbl_session_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
558
            $access_url_id = api_get_current_access_url_id();
559
            if (-1 != $access_url_id) {
560
                $sql_session_coach = "SELECT u.id AS user_id, u.lastname, u.firstname, MAX(tel.login_date) AS login_date
561
                    FROM $tbl_user u
562
                    INNER JOIN $tbl_track_login  tel
563
                    ON tel.login_user_id = u.id
564
                    INNER JOIN $tblSessionRelUser sru
565
                    ON (u.id = sru.user_id AND sru.relation_type = ".SessionEntity::GENERAL_COACH.")
566
                    INNER JOIN $tbl_session_rel_access_url aurs
567
                    ON sru.session_id = aurs.session_id
568
                    WHERE aurs.access_url_id = $access_url_id
569
                    GROUP BY u.id
570
					ORDER BY login_date $tracking_direction";
571
            }
572
        }
573
574
        $result_sessions_coach = Database::query($sql_session_coach);
575
        //$total_no_coaches += Database::num_rows($result_sessions_coach);
576
        while ($coach = Database::fetch_array($result_sessions_coach)) {
577
            $global_coaches[$coach['user_id']] = $coach;
578
        }
579
580
        $all_datas = [];
581
        foreach ($global_coaches as $id_coach => $coaches) {
582
            $time_on_platform = api_time_to_hms(
583
                Tracking::get_time_spent_on_the_platform($coaches['user_id'])
584
            );
585
            $last_connection = Tracking::get_last_connection_date(
586
                $coaches['user_id']
587
            );
588
            $nb_students = count(
589
                Tracking::get_student_followed_by_coach($coaches['user_id'])
590
            );
591
            $nb_courses = count(
592
                Tracking::get_courses_followed_by_coach($coaches['user_id'])
593
            );
594
            $nb_sessions = count(
595
                Tracking::get_sessions_coached_by_user($coaches['user_id'])
596
            );
597
598
            $table_row = [];
599
            if ($is_western_name_order) {
600
                $table_row[] = $coaches['firstname'];
601
                $table_row[] = $coaches['lastname'];
602
            } else {
603
                $table_row[] = $coaches['lastname'];
604
                $table_row[] = $coaches['firstname'];
605
            }
606
            $table_row[] = $time_on_platform;
607
            $table_row[] = $last_connection;
608
            $table_row[] = $nb_students;
609
            $table_row[] = $nb_courses;
610
            $table_row[] = $nb_sessions;
611
            $table_row[] = '<a href="session.php?id_coach='.$coaches['user_id'].'">
612
                '.Display::getMdiIcon('arrow-left-bold-box', 'ch-tool-icon', null, 22, get_lang('Details')).'
613
            </a>';
614
            $all_datas[] = $table_row;
615
616
            if ($is_western_name_order) {
617
                $csv_content[] = [
618
                    api_html_entity_decode($coaches['firstname'], ENT_QUOTES),
619
                    api_html_entity_decode($coaches['lastname'], ENT_QUOTES),
620
                    $time_on_platform,
621
                    $last_connection,
622
                    $nb_students,
623
                    $nb_courses,
624
                    $nb_sessions,
625
                ];
626
            } else {
627
                $csv_content[] = [
628
                    api_html_entity_decode($coaches['lastname'], ENT_QUOTES),
629
                    api_html_entity_decode($coaches['firstname'], ENT_QUOTES),
630
                    $time_on_platform,
631
                    $last_connection,
632
                    $nb_students,
633
                    $nb_courses,
634
                    $nb_sessions,
635
                ];
636
            }
637
        }
638
639
        if (3 != $tracking_column) {
640
            if ('DESC' === $tracking_direction) {
641
                usort($all_datas, ['MySpace', 'rsort_users']);
642
            } else {
643
                usort($all_datas, ['MySpace', 'sort_users']);
644
            }
645
        }
646
647
        if ($export_csv && 3 != $tracking_column) {
648
            usort($csv_content, 'sort_users');
649
        }
650
        if ($export_csv) {
651
            $csv_content = array_merge($csv_header, $csv_content);
652
        }
653
654
        foreach ($all_datas as $row) {
655
            $table->addRow($row, 'align="right"');
656
        }
657
        $table->display();
658
    }
659
660
    public static function sort_users($a, $b)
661
    {
662
        $tracking = Session::read('tracking_column', 0);
663
664
        return api_strcmp(
665
            trim(api_strtolower($a[$tracking])),
666
            trim(api_strtolower($b[$tracking]))
667
        );
668
    }
669
670
    public static function rsort_users($a, $b)
671
    {
672
        $tracking = Session::read('tracking_column', 0);
673
674
        return api_strcmp(
675
            trim(api_strtolower($b[$tracking])),
676
            trim(api_strtolower($a[$tracking]))
677
        );
678
    }
679
680
    /**
681
     * Displays a form with all the additionally defined user fields of the profile
682
     * and give you the opportunity to include these in the CSV export.
683
     *
684
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
685
     *
686
     * @version 1.8.6
687
     *
688
     * @since November 2008
689
     */
690
    public static function display_user_overview_export_options()
691
    {
692
        $message = '';
693
        $defaults = [];
694
        // include the user manager and formvalidator library
695
        if (isset($_GET['export']) && 'options' == $_GET['export']) {
696
            // get all the defined extra fields
697
            $extrafields = UserManager::get_extra_fields(
698
                0,
699
                50,
700
                5,
701
                'ASC',
702
                false,
703
                1
704
            );
705
706
            // creating the form with all the defined extra fields
707
            $form = new FormValidator(
708
                'exportextrafields',
709
                'post',
710
                api_get_self()."?view=".Security::remove_XSS($_GET['view']).'&display='.Security::remove_XSS($_GET['display']).'&export='.Security::remove_XSS($_GET['export'])
711
            );
712
713
            if (is_array($extrafields) && count($extrafields) > 0) {
714
                foreach ($extrafields as $key => $extra) {
715
                    $form->addElement('checkbox', 'extra_export_field'.$extra[0], '', $extra[3]);
716
                }
717
                $form->addButtonSave(get_lang('Validate'), 'submit');
718
719
                // setting the default values for the form that contains all the extra fields
720
                $exportFields = Session::read('additional_export_fields');
721
                if (is_array($exportFields)) {
722
                    foreach ($exportFields as $key => $value) {
723
                        $defaults['extra_export_field'.$value] = 1;
724
                    }
725
                }
726
                $form->setDefaults($defaults);
727
            } else {
728
                $form->addElement('html', Display::return_message(get_lang('There are not extra fields available'), 'warning'));
729
            }
730
731
            if ($form->validate()) {
732
                // exporting the form values
733
                $values = $form->exportValues();
734
735
                // re-initialising the session that contains the additional fields that need to be exported
736
                Session::write('additional_export_fields', []);
737
738
                // adding the fields that are checked to the session
739
                $message = '';
740
                $additionalExportFields = [];
741
                foreach ($values as $field_ids => $value) {
742
                    if (1 == $value && strstr($field_ids, 'extra_export_field')) {
743
                        $additionalExportFields[] = str_replace('extra_export_field', '', $field_ids);
744
                    }
745
                }
746
                Session::write('additional_export_fields', $additionalExportFields);
747
748
                // adding the fields that will be also exported to a message string
749
                $additionalExportFields = Session::read('additional_export_fields');
750
                if (is_array($additionalExportFields)) {
751
                    foreach ($additionalExportFields as $key => $extra_field_export) {
752
                        $message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
753
                    }
754
                }
755
756
                // Displaying a feedback message
757
                if (!empty($additionalExportFields)) {
758
                    echo Display::return_message(
759
                        get_lang('The following fields will also be exported').': <br /><ul>'.$message.'</ul>',
760
                        'confirm',
761
                        false
762
                    );
763
                } else {
764
                    echo Display::return_message(
765
                        get_lang('No additional fields will be exported'),
766
                        'confirm',
767
                        false
768
                    );
769
                }
770
            } else {
771
                $form->display();
772
            }
773
        } else {
774
            $additionalExportFields = Session::read('additional_export_fields');
775
            if (!empty($additionalExportFields)) {
776
                // get all the defined extra fields
777
                $extrafields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
778
779
                foreach ($additionalExportFields as $key => $extra_field_export) {
780
                    $message .= '<li>'.$extrafields[$extra_field_export][3].'</li>';
781
                }
782
783
                echo Display::return_message(
784
                    get_lang('The following fields will also be exported').': <br /><ul>'.$message.'</ul>',
785
                    'normal',
786
                    false
787
                );
788
            }
789
        }
790
    }
791
792
    /**
793
     * Export to cvs a list of users who were enrolled in the lessons.
794
     * It is necessary that in the extra field, a company is defined.
795
     *
796
     * @param string|null $startDate
797
     * @param string|null $endDate
798
     *
799
     * @return array
800
     */
801
    public static function exportCompanyResumeCsv($startDate, $endDate)
802
    {
803
        $companys = self::getCompanyLearnpathSubscription($startDate, $endDate);
804
        $csv_content = [];
805
        // Printing table
806
        $total = 0;
807
        $displayText = get_lang('Company');
808
        // the first line of the csv file with the column headers
809
        $csv_row = [];
810
        $csv_row[] = $displayText;
811
812
        $csv_row[] = get_lang('Subscribed users count');
813
        $csv_content[] = $csv_row;
814
815
        foreach ($companys as $entity => $student) {
816
            $csv_row = [];
817
            // user official code
818
            $csv_row[] = $entity;
819
            $csv_row[] = count($student);
820
            $total += count($student);
821
            $csv_content[] = $csv_row;
822
        }
823
824
        $csv_row = [];
825
        // user official code
826
        $csv_row[] = get_lang('General total');
827
        $csv_row[] = $total;
828
        $csv_content[] = $csv_row;
829
        Export::arrayToCsv($csv_content, 'reporting_company_resume');
830
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
831
    }
832
833
    /**
834
     * Displays a list as a table of users who were enrolled in the lessons.
835
     * It is necessary that in the extra field, a company is defined.
836
     *
837
     * @param string|null $startDate
838
     * @param string|null $endDate
839
     */
840
    public static function displayResumeCompany(
841
        $startDate = null,
842
        $endDate = null
843
    ) {
844
        $companys = self::getCompanyLearnpathSubscription($startDate, $endDate);
845
        $tableHtml = '';
846
        // Printing table
847
        $total = 0;
848
        $table = '<div class="table-responsive"><table class="table table-hover table-striped table-bordered data_table">';
849
850
        $displayText = get_lang('Company');
851
        $table .= "<thead><tr><th class=\"th-header\">$displayText</th><th class=\"th-header\"> ".get_lang('Subscribed users count')." </th></tr></thead><tbody>";
852
853
        foreach ($companys as $entity => $student) {
854
            $table .= "<tr><td>$entity</td><td>".count($student)."</td></tr>";
855
            $total += count($student);
856
        }
857
        $table .= "<tr><td>".get_lang('General total')."</td><td>$total</td></tr>";
858
        $table .= '</tbody></table></div>';
859
860
        if (!empty($startDate) or !empty($endDate)) {
861
            $tableHtml = $table;
862
        }
863
864
        $form = new FormValidator('searchDate', 'get');
865
        $form->addHidden('display', 'company');
866
        $today = new DateTime();
867
        if (empty($startDate)) {
868
            $startDate = api_get_local_time($today->modify('first day of this month')->format('Y-m-d'));
869
        }
870
        if (empty($endDate)) {
871
            $endDate = api_get_local_time($today->modify('last day of this month')->format('Y-m-d'));
872
        }
873
        $form->addDatePicker(
874
            'startDate',
875
            get_lang('Start date'),
876
            [
877
                'value' => $startDate,
878
            ]);
879
        $form->addDatePicker(
880
            'endDate',
881
            get_lang('End date'),
882
            [
883
                'value' => $endDate,
884
            ]);
885
        $form->addButtonSearch(get_lang('Search'));
886
        if (0 != count($companys)) {
887
            $form
888
                ->addButton(
889
                    'export_csv',
890
                    get_lang('CSV export'),
891
                    'check',
892
                    'primary',
893
                    null,
894
                    null,
895
                    [
896
                    ]
897
                );
898
        }
899
900
        $tableContent = $form->returnForm();
901
        $tableContent .= $tableHtml;
902
        // $tableContent .= $table->return_table();
903
904
        $tpl = new Template('', false, false, false, false, false, false);
905
        $tpl->assign('table', $tableContent);
906
        $templateName = $tpl->get_template('my_space/course_summary.tpl');
907
        $tpl->display($templateName);
908
    }
909
910
    /**
911
     *  Displays a list as a table of teachers who are set authors by a extra_field authors.
912
     *
913
     * @param string|null $startDate
914
     * @param string|null $endDate
915
     * @param bool        $csv
916
     */
917
    public static function displayResumeLP(
918
        $startDate = null,
919
        $endDate = null,
920
        $csv = false
921
    ) {
922
        $tableHtml = '';
923
        $tblExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
924
        $tblExtraFieldValue = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
925
        $tblCourse = Database::get_main_table(TABLE_MAIN_COURSE);
926
        $query = "
927
        SELECT
928
            item_id AS lp_id,
929
            REPLACE (s.value, ';', ',') AS users_id
930
        FROM
931
            $tblExtraFieldValue s
932
        INNER JOIN $tblExtraField sf ON (s.field_id = sf.id)
933
        WHERE
934
            field_id IN (
935
                SELECT
936
                    id
937
                FROM
938
                    $tblExtraField
939
                WHERE
940
                    variable = 'authors'
941
            )
942
        AND sf.item_type = ".ExtraField::FIELD_TYPE_DATE."
943
        AND (s.value != '' OR s.value IS NOT NULL)
944
";
945
        $queryResult = Database::query($query);
946
        $data = [];
947
        while ($row = Database::fetch_assoc($queryResult)) {
948
            $lp_id = (int) $row['lp_id'];
949
            $registeredUsers = self::getCompanyLearnpathSubscription($startDate, $endDate, $lp_id);
950
            if (!empty($registeredUsers)) {
951
                $lpInfo = [];
952
                $teacherList = [];
953
                $teachersId = explode(',', trim($row['users_id'], ","));
954
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
955
                $query = "
956
            SELECT $lp_table.*,
957
                   $tblCourse.title as courseTitle,
958
                   $tblCourse.code as courseCode
959
            FROM
960
                $lp_table
961
            INNER JOIN $tblCourse ON $tblCourse.id = $lp_table.c_id
962
            WHERE
963
                $lp_table.iid = $lp_id
964
                ";
965
                $res = Database::query($query);
966
                if (Database::num_rows($res)) {
967
                    $lpInfo = Database::fetch_array($res);
968
                }
969
                $studentUsers = [];
970
                for ($i = 0; $i < count($registeredUsers); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
971
                    $studentUsers[] = api_get_user_info($registeredUsers[$i]);
972
                }
973
                $teacherList = [];
974
                for ($i = 0; $i < count($teachersId); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
975
                    $teacherId = $teachersId[$i];
976
                    $teacher = api_get_user_info($teacherId);
977
                    $data[$teacher['complete_name']][$lpInfo['name']] = [
978
                        'students' => count($studentUsers),
979
                        'studentList' => $studentUsers,
980
                        'lpInfo' => $lpInfo,
981
                    ];
982
                    $teacherList[] = $teacher;
983
                }
984
            }
985
        }
986
        if (false == $csv) {
987
            $table = "<div class='table-responsive'>".
988
                "<table class='table table-hover table-striped table-bordered data_table'>".
989
                "<thead>".
990
                "<tr>".
991
                "<th class=\"th-header\">".get_lang('Author')."</th>".
992
                "<th class=\"th-header\">".get_lang('Learning path list')."</th>".
993
                "<th class=\"th-header\">".get_lang('Subscribed users count')."</th>".
994
                "<th class=\"th-header\">".get_lang('Learner list')."</th>".
995
                "</tr>".
996
                "</thead>".
997
                "<tbody>";
998
            $index = 0;
999
            //icons for show and hode
1000
            $iconAdd = Display::getMdiIcon('plus', 'ch-tool-icon', null, 22, get_lang('Show/Hide'));
1001
            $iconRemove = Display::getMdiIcon('delete', 'ch-tool-icon', null, 22, get_lang('Show/Hide'));
1002
            $teacherNameTemp = '';
1003
            foreach ($data as $teacherName => $reportData) {
1004
                $lpCount = 0;
1005
                $totalStudent = 0;
1006
                foreach ($reportData as $lpName => $row) {
1007
                    $hiddenField = 'student_show_'.$index;
1008
                    $hiddenFieldLink = 'student_show_'.$index.'_';
1009
                    $printTeacherName = ($teacherName == $teacherNameTemp) ? '' : $teacherName;
1010
                    $lpInfo = $row['lpInfo'];
1011
                    $teacherNameTemp = $teacherName;
1012
                    $table .=
1013
                        "<tr>".
1014
                        "<td>$printTeacherName</td>".
1015
                        "<td>$lpName</td>".
1016
                        "<td>".$row['students']."</td>".
1017
                        "<td>".
1018
                        "<a href='#!' id='$hiddenFieldLink' onclick='showHideStudent(\"$hiddenField\")'>".
1019
                        "<div class='icon_add'>$iconAdd</div>".
1020
                        "<div class='icon_remove hidden'>$iconRemove</div>".
1021
                        "</a>".
1022
                        "<div id='$hiddenField' class='hidden'>";
1023
                    foreach ($row['studentList'] as $student) {
1024
                        $reportLink = Display::url(
1025
                            Display::getMdiIcon('chart-box', 'ch-tool-icon', null, 22, get_lang('Statistics')),
1026
                            api_get_path(WEB_CODE_PATH).'my_space/myStudents.php?details=true&student='.
1027
                            $student['id']
1028
                            .'&id_session='.$lpInfo['session_id']
1029
                            .'&course='.$lpInfo['courseCode']
1030
                        );
1031
                        $table .= "$reportLink ".$student['complete_name']."<br>";
1032
                        $totalStudent++;
1033
                    }
1034
                    $index++;
1035
                    $lpCount++;
1036
                    $table .= "</div>".
1037
                        "</td>".
1038
                        "</tr>";
1039
                }
1040
                $table .=
1041
                    "<tr>".
1042
                    "<td></td>".
1043
                    "<td><strong>".get_lang('Total learning paths')." $lpCount</strong></td>".
1044
                    "<td><strong>$totalStudent</strong></td>".
1045
                    "<td></td>".
1046
                    "</tr>";
1047
            }
1048
            $table .= "</tbody>".
1049
                "</table>".
1050
                "</div>";
1051
            if (!empty($startDate) or !empty($endDate)) {
1052
                $tableHtml = $table;
1053
            }
1054
1055
            $form = new FormValidator('searchDate', 'get');
1056
            $form->addHidden('display', 'learningPath');
1057
            $today = new DateTime();
1058
            if (empty($startDate)) {
1059
                $startDate = $today->modify('first day of this month')->format('Y-m-d');
1060
            }
1061
            if (empty($endDate)) {
1062
                $endDate = $today->modify('last day of this month')->format('Y-m-d');
1063
            }
1064
            $form->addDatePicker(
1065
                'startDate',
1066
                get_lang('Start date'),
1067
                [
1068
                    'value' => $startDate,
1069
                ]);
1070
            $form->addDatePicker(
1071
                'endDate',
1072
                get_lang('End date'),
1073
                [
1074
                    'value' => $endDate,
1075
                ]);
1076
            $form->addButtonSearch(get_lang('Search'));
1077
            if (0 != count($data)) {
1078
                $form
1079
                    ->addButton(
1080
                        'export_csv',
1081
                        get_lang('CSV export'),
1082
                        'check',
1083
                        'primary',
1084
                        null,
1085
                        null,
1086
                        [
1087
                        ]
1088
                    );
1089
            }
1090
            $tableContent = $form->returnForm();
1091
            $tableContent .= $tableHtml;
1092
            $tpl = new Template('', false, false, false, false, false, false);
1093
            $tpl->assign('table', $tableContent);
1094
            $templateName = $tpl->get_template('my_space/course_summary.tpl');
1095
            $tpl->display($templateName);
1096
        } else {
1097
            $csv_content = [];
1098
            $csv_row = [];
1099
            $csv_row[] = get_lang('Author');
1100
            $csv_row[] = get_lang('Learning path list');
1101
            $csv_row[] = get_lang('Subscribed users count');
1102
            $csv_row[] = get_lang('Learner list');
1103
            $csv_content[] = $csv_row;
1104
            foreach ($data as $teacherName => $reportData) {
1105
                foreach ($reportData as $lpName => $row) {
1106
                    $csv_row = [];
1107
                    $csv_row[] = $teacherName;
1108
                    $csv_row[] = $lpName;
1109
                    $csv_row[] = $row['students'];
1110
                    $studentsName = '';
1111
                    foreach ($row['studentList'] as $student) {
1112
                        $studentsName .= $student['complete_name']." / ";
1113
                    }
1114
                    $csv_row[] = trim($studentsName, " / ");
1115
                    $csv_content[] = $csv_row;
1116
                }
1117
            }
1118
            Export::arrayToCsv($csv_content, 'reporting_lp_by_authors');
1119
        }
1120
    }
1121
1122
    /**
1123
     *  Displays a list as a table of teachers who are set authors of lp's item by a extra_field authors.
1124
     *
1125
     * @param string|null $startDate
1126
     * @param string|null $endDate
1127
     * @param bool        $csv
1128
     */
1129
    public static function displayResumeLpByItem(
1130
        $startDate = null,
1131
        $endDate = null,
1132
        $csv = false
1133
    ) {
1134
        $tableHtml = '';
1135
        $table = '';
1136
        $tblExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
1137
        $tblExtraFieldValue = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
1138
        $extraFieldLpByAutorName = 'authorlpitem';
1139
        $extraFieldLpPrice = 'price';
1140
1141
        $queryExtraFieldPrice = "SELECT id  ".
1142
            " FROM $tblExtraField ".
1143
            " WHERE variable = '$extraFieldLpPrice'";
1144
        $queryExtraFieldValue = "SELECT id ".
1145
            " FROM $tblExtraField ".
1146
            " WHERE variable = '$extraFieldLpByAutorName'";
1147
1148
        // search items of lp
1149
        $cLpItemsQuery = "select item_id as lp_item_id ".
1150
            " from $tblExtraFieldValue ".
1151
            " where field_id IN ( $queryExtraFieldValue ) ".
1152
            " group by lp_item_id";
1153
        $queryResult = Database::query($cLpItemsQuery);
1154
        $cLpItems = [];
1155
        while ($row = Database::fetch_assoc($queryResult)) {
1156
            $cLpItems[] = (int) $row['lp_item_id'];
1157
        }
1158
        if (0 == count($cLpItems)) {
1159
            $tableContent = "<div class='table-responsive'>".
1160
                "<table class='table table-hover table-striped table-bordered data_table'>".
1161
                "<thead>".
1162
                "<tr>".
1163
                "<th class=\"th-header\">".get_lang('No data available')."</th>".
1164
                "</tr>".
1165
                "</thead>".
1166
                "</tbody>".
1167
                "</tbody>".
1168
                "</table>".
1169
                "</div>";
1170
            $tableHtml = $tableContent;
1171
        } else {
1172
            $cLpItems = implode(',', $cLpItems);
1173
            // search by price
1174
            $cLpItemsPriceQuery = "select value as price, item_id as lp_item_id ".
1175
                " from $tblExtraFieldValue ".
1176
                " where field_id IN ( $queryExtraFieldPrice ) and item_id in ($cLpItems)";
1177
            $queryResult = Database::query($cLpItemsPriceQuery);
1178
            $lpItemPrice = [];
1179
            while ($row = Database::fetch_assoc($queryResult)) {
1180
                $lpItemPrice[$row['lp_item_id']] = $row['price'];
1181
            }
1182
            // search authors of lp
1183
            $autorsStr = '';
1184
            $autorsQuery = "select value as users_id ".
1185
                " from $tblExtraFieldValue ".
1186
                " where field_id IN ( $queryExtraFieldValue ) ".
1187
                " group by users_id ";
1188
            $queryResult = Database::query($autorsQuery);
1189
            while ($row = Database::fetch_assoc($queryResult)) {
1190
                $autorsStr .= " ".str_replace(';', ' ', $row['users_id']);
1191
                $autorsStr = trim($autorsStr);
1192
            }
1193
            $autorsStr = str_replace(' ', ',', $autorsStr);
1194
1195
            //search autors detailed
1196
            $authors = [];
1197
            if (!empty($autorsStr)) {
1198
                $autorsStr = explode(',', $autorsStr);
1199
                foreach ($autorsStr as $item) {
1200
                    $authors[$item] = api_get_user_info($item);
1201
                }
1202
            }
1203
            unset($autorsStr);
1204
1205
            //search info of lp's items
1206
            $cLpItemsData = [];
1207
            if (!empty($cLpItems)) {
1208
                $query = "select * ".
1209
                    " from c_lp_item ".
1210
                    " where iid in ($cLpItems)";
1211
                $queryResult = Database::query($query);
1212
                while ($row = Database::fetch_assoc($queryResult)) {
1213
                    $row['price'] = isset($lpItemPrice[$row['iid']]) ? $lpItemPrice[$row['iid']] : 0;
1214
                    $cLpItemsData[$row['iid']] = $row;
1215
                }
1216
            }
1217
1218
            $query = "select item_id as lp_item_id ,value as users_id ".
1219
                " from $tblExtraFieldValue ".
1220
                " where field_id IN ( $queryExtraFieldValue )";
1221
            $queryResult = Database::query($query);
1222
            $printData = [];
1223
            while ($row = Database::fetch_assoc($queryResult)) {
1224
                $cLpItem = (int) $row['lp_item_id'];
1225
                // get full lp data
1226
                $cLpItemData = isset($cLpItemsData[$cLpItem]) ? $cLpItemsData[$cLpItem] : [];
1227
                $authorData = $row['users_id'];
1228
                if (!empty($authorData)) {
1229
                    if (false === strpos($authorData, ";")) {
1230
                        $printData[(int) $authorData][$cLpItem] = $cLpItemData;
1231
                    } else {
1232
                        foreach (explode(';', $authorData) as $item) {
1233
                            $printData[$item][$cLpItem] = $cLpItemData;
1234
                        }
1235
                    }
1236
                }
1237
            }
1238
            $index = 0;
1239
        }
1240
        if (false == $csv) {
1241
            if (empty($tableHtml)) {
1242
                $table .= "<div class='table-responsive'>".
1243
                    "<table class='table table-hover table-striped table-bordered data_table'>".
1244
                    "<thead>".
1245
                    "<tr>".
1246
                    "<th class=\"th-header\">".get_lang('Author')."</th>".
1247
                    "<th class=\"th-header\">".get_lang('Content list')."</th>".
1248
                    "<th class=\"th-header\">".get_lang('Tariff')."</th>".
1249
                    "<th class=\"th-header\">".get_lang('Subscribed users count')."</th>".
1250
                    "<th class=\"th-header\">".get_lang('To invoice')."</th>".
1251
                    "<th class=\"th-header\">".get_lang('Learner list')."</th>".
1252
                    "</tr>".
1253
                    "</thead>".
1254
                    "<tbody>";
1255
                //Icon Constant
1256
                $iconAdd = Display::getMdiIcon('plus', 'ch-tool-icon', null, 22, get_lang('Show/Hide'));
1257
                $iconRemove = Display::getMdiIcon('delete', 'ch-tool-icon', null, 22, get_lang('Show/Hide'));
1258
1259
                $lastAuthor = '';
1260
                $total = 0;
1261
                foreach ($printData as $authorId => $lpItemData) {
1262
                    $autor = $authors[$authorId];
1263
                    $totalSudent = 0;
1264
                    foreach ($lpItemData as $lpItemId => $lpitem) {
1265
                        $title = $lpitem['title'];
1266
                        $price = $lpitem['price'];
1267
                        $hide = "class='author_$authorId hidden' ";
1268
                        if ($lastAuthor != $autor) {
1269
                            $table .= "<tr>";
1270
                            $table .= "<td>".$autor['complete_name'].
1271
                                "</td>";
1272
                        } else {
1273
                            $table .= "<tr $hide >";
1274
                            $table .= "<td></td>";
1275
                        }
1276
1277
                        $hiddenField = 'student_show_'.$index;
1278
                        $hiddenFieldLink = 'student_show_'.$index.'_';
1279
                        if ($lastAuthor != $autor) {
1280
                            $table .= "<td>$title".
1281
                                "</td>";
1282
                        } else {
1283
                            $table .= "<td>$title</td>";
1284
                        }
1285
                        $table .= "<td>$price</td>";
1286
                        $registeredUsers = self::getCompanyLearnpathSubscription($startDate, $endDate, $lpitem['lp_id'], true);
1287
                        $studenRegister = count($registeredUsers);
1288
                        $table .= "<td>$studenRegister</td>";
1289
                        $facturar = ($studenRegister * $price);
1290
                        $table .= "<td>$facturar</td>";
1291
                        $total += $facturar;
1292
                        $totalSudent += $studenRegister;
1293
                        if (0 != $studenRegister) {
1294
                            $table .= "<td>".
1295
                                "<a href='#!' id='$hiddenFieldLink' onclick='showHideStudent(\"$hiddenField\")'>".
1296
                                "<div class='icon_add'>$iconAdd</div>".
1297
                                "<div class='icon_remove hidden'>$iconRemove</div>".
1298
                                "</a>".
1299
                                "<div id='$hiddenField' class='hidden'>";
1300
                            for ($i = 0; $i < $studenRegister; $i++) {
1301
                                $tempStudent = api_get_user_info($registeredUsers[$i]['id']);
1302
                                $table .= $tempStudent['complete_name']." (".$registeredUsers[$i]['company'].")<br>";
1303
                            }
1304
                            $index++;
1305
                            $table .= "</div>".
1306
                                "</td>";
1307
                        } else {
1308
                            $table .= "<td></td>";
1309
                        }
1310
                        $table .= "</tr>";
1311
                        $lastAuthor = $autor;
1312
                    }
1313
                    //footer
1314
                    $table .= "<tr><th class=\"th-header\"></th>".
1315
                        "<th class=\"th-header\">".
1316
                        "<a href='#!' id='$hiddenFieldLink' onclick='ShowMoreAuthor(\"$authorId\")'>".
1317
                        "<div class='icon_add_author_$authorId'>$iconAdd</div>".
1318
                        "<div class='icon_remove_author_$authorId hidden'>$iconRemove</div>".
1319
                        "</a>"."</th>".
1320
                        "<th class=\"th-header\"></th>".
1321
                        "<th class=\"th-header\">$totalSudent</th>".
1322
                        "<th class=\"th-header\">$total</th>".
1323
                        "<th class=\"th-header\"></tr>";
1324
                    $total = 0;
1325
                }
1326
                $table .= "</tbody>".
1327
                    "</table>".
1328
                    "</div>";
1329
                $tableHtml = $table;
1330
            }
1331
1332
            $form = new FormValidator('searchDate', 'get');
1333
            $form->addHidden('display', 'learningPathByItem');
1334
            $today = new DateTime();
1335
            if (empty($startDate)) {
1336
                $startDate = $today->modify('first day of this month')->format('Y-m-d');
1337
            }
1338
            if (empty($endDate)) {
1339
                $endDate = $today->modify('last day of this month')->format('Y-m-d');
1340
            }
1341
            $form->addDatePicker(
1342
                'startDate',
1343
                get_lang('Start date'),
1344
                [
1345
                    'value' => $startDate,
1346
                ]);
1347
            $form->addDatePicker(
1348
                'endDate',
1349
                get_lang('End date'),
1350
                [
1351
                    'value' => $endDate,
1352
                ]);
1353
            $form->addButtonSearch(get_lang('Search'));
1354
1355
            if (0 != count($printData)) {
1356
                $form
1357
                    ->addButton(
1358
                        'export_csv',
1359
                        get_lang('CSV export'),
1360
                        'check',
1361
                        'primary',
1362
                        null,
1363
                        null,
1364
                        [
1365
                        ]
1366
                    );
1367
            }
1368
            $tableContent = $form->returnForm();
1369
            $tableContent .= $tableHtml;
1370
            $tpl = new Template('', false, false, false, false, false, false);
1371
            $tpl->assign('table', $tableContent);
1372
            $templateName = $tpl->get_template('my_space/course_summary.tpl');
1373
            $tpl->display($templateName);
1374
        } else {
1375
            $csv_content = [];
1376
            $csv_row = [];
1377
1378
            $csv_row[] = get_lang('Author');
1379
            $csv_row[] = get_lang('Content list');
1380
            $csv_row[] = get_lang('Tariff');
1381
            $csv_row[] = get_lang('Subscribed users count');
1382
            $csv_row[] = get_lang('To invoice');
1383
            $csv_row[] = get_lang('Learner list');
1384
            $csv_content[] = $csv_row;
1385
            foreach ($printData as $authorId => $lpItemData) {
1386
                $autor = $authors[$authorId];
1387
                foreach ($lpItemData as $lpItemId => $lpitem) {
1388
                    $title = $lpitem['title'];
1389
                    $price = $lpitem['price'];
1390
1391
                    $csv_row = [];
1392
                    $csv_row[] = $autor['complete_name'];
1393
                    $csv_row[] = $title;
1394
                    $csv_row[] = $price;
1395
                    $registeredUsers = self::getCompanyLearnpathSubscription($startDate, $endDate, $lpitem['lp_id'], true);
1396
                    $studenRegister = count($registeredUsers);
1397
                    $csv_row[] = $studenRegister;
1398
                    $facturar = ($studenRegister * $price);
1399
                    $csv_row[] = $facturar;
1400
                    $totalStudent += $studenRegister;
1401
                    if (0 != $studenRegister) {
1402
                        $studentsName = '';
1403
                        for ($i = 0; $i < $studenRegister; $i++) {
1404
                            $tempStudent = api_get_user_info($registeredUsers[$i]['id']);
1405
                            $studentsName .= $tempStudent['complete_name']." (".$registeredUsers[$i]['company'].") / ";
1406
1407
                            $totalStudent++;
1408
                        }
1409
                        $csv_row[] = trim($studentsName, " / ");
1410
                        $csv_content[] = $csv_row;
1411
                        $index++;
1412
                        $lpCount++;
1413
                    }
1414
                }
1415
            }
1416
            Export::arrayToCsv($csv_content, 'reporting_lp_by_authors');
1417
        }
1418
    }
1419
1420
    /**
1421
     * Display a sortable table that contains an overview of all the reporting progress of all courses.
1422
     */
1423
    public static function display_tracking_course_overview()
1424
    {
1425
        $params = ['view' => 'admin', 'display' => 'courseoverview'];
1426
        $table = new SortableTable(
1427
            'tracking_session_overview',
1428
            ['MySpace', 'get_total_number_courses'],
1429
            ['MySpace', 'get_course_data_tracking_overview'],
1430
            1,
1431
            20,
1432
            'ASC',
1433
            null, [
1434
                'class' => 'table table-transparent',
1435
            ]
1436
        );
1437
        $table->additional_parameters = $params;
1438
        $table->set_column_filter(0, ['MySpace', 'course_tracking_filter']);
1439
        $tableContent = $table->return_table();
1440
1441
        $tpl = new Template('', false, false, false, false, false, false);
1442
        $tpl->assign('table', $tableContent);
1443
        $templateName = $tpl->get_template('my_space/course_summary.tpl');
1444
        $tpl->display($templateName);
1445
    }
1446
1447
    /**
1448
     * Get the total number of courses.
1449
     *
1450
     * @return int Total number of courses
1451
     */
1452
    public static function get_total_number_courses()
1453
    {
1454
        return CourseManager::count_courses(api_get_current_access_url_id());
1455
    }
1456
1457
    /**
1458
     * Get data for the courses.
1459
     *
1460
     * @param int    $from        Inferior limit
1461
     * @param int    $numberItems Number of items to select
1462
     * @param string $column      Column to order on
1463
     * @param string $direction   Order direction
1464
     *
1465
     * @return array Results
1466
     */
1467
    public static function get_course_data_tracking_overview(
1468
        $from,
1469
        $numberItems,
1470
        $column,
1471
        $direction
1472
    ) {
1473
        switch ($column) {
1474
            default:
1475
            case 1:
1476
                $column = 'title';
1477
                break;
1478
        }
1479
        $courses = CourseManager::get_courses_list(
1480
            $from,
1481
            $numberItems,
1482
            $column,
1483
            $direction,
1484
             -1,
1485
            '',
1486
            api_get_current_access_url_id()
1487
        );
1488
1489
        $list = [];
1490
        foreach ($courses as $course) {
1491
            $list[] = [
1492
                '0' => $course['real_id'],
1493
                'col0' => $course['real_id'],
1494
            ];
1495
        }
1496
1497
        return $list;
1498
    }
1499
1500
    /**
1501
     * Fills in course reporting data.
1502
     *
1503
     * @param int course code
1504
     * @param array $url_params additional url parameters
1505
     * @param array $row        the row information (the other columns)
1506
     *
1507
     * @return string html code
1508
     */
1509
    public static function course_tracking_filter($course_code, $url_params, $row)
1510
    {
1511
        $courseId = $row[0];
1512
        $course = api_get_course_entity($courseId);
1513
        $courseCode = $course->getCode();
1514
1515
        $tpl = new Template('', false, false, false, false, false, false);
1516
        $data = null;
1517
1518
        $time_spent = 0;
1519
        $progress = 0;
1520
        $nb_progress_lp = 0;
1521
        $score = 0;
1522
        $nb_score_lp = 0;
1523
        $nb_messages = 0;
1524
        $nb_assignments = 0;
1525
        $last_login_date = false;
1526
        $total_score_obtained = 0;
1527
        $total_score_possible = 0;
1528
        $total_questions_answered = 0;
1529
1530
        $courseId = $course->getId();
1531
        $courseCode = $course->getCode();
1532
        $courseRelUsers = $course->getUsers();
1533
        foreach ($courseRelUsers as $courseRelUser) {
1534
            $user = $courseRelUser->getUser();
1535
            $userId = $user->getId();
1536
1537
            // get time spent in the course and session
1538
            $time_spent += Tracking::get_time_spent_on_the_course(
1539
                $userId,
1540
                $courseId
1541
            );
1542
            $progress_tmp = Tracking::get_avg_student_progress(
1543
                $userId,
1544
                $course,
1545
                [],
1546
                null,
1547
                true
1548
            );
1549
            if ($progress_tmp) {
1550
                $progress += $progress_tmp[0];
1551
                $nb_progress_lp += $progress_tmp[1];
1552
            }
1553
            $score_tmp = Tracking::get_avg_student_score(
1554
                $userId,
1555
                $course,
1556
                [],
1557
                null,
1558
                true
1559
            );
1560
            if (is_array($score_tmp)) {
1561
                $score += $score_tmp[0];
1562
                $nb_score_lp += $score_tmp[1];
1563
            }
1564
1565
            //$nb_messages += Container::getForumPostRepository($user, $course);
1566
            //$nb_assignments += Container::getStudentPublicationRepository($user, $course);
1567
1568
            $last_login_date_tmp = Tracking::get_last_connection_date_on_the_course(
1569
                $userId,
1570
                ['real_id' => $courseId],
1571
                null,
1572
                false
1573
            );
1574
            if (false != $last_login_date_tmp &&
1575
                false == $last_login_date
1576
            ) { // TODO: To be cleaned
1577
                $last_login_date = $last_login_date_tmp;
1578
            } elseif (false != $last_login_date_tmp && false != $last_login_date) {
1579
                // TODO: Repeated previous condition. To be cleaned.
1580
                // Find the max and assign it to first_login_date
1581
                if (strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
1582
                    $last_login_date = $last_login_date_tmp;
1583
                }
1584
            }
1585
1586
            $exercise_results_tmp = self::exercises_results($userId, $courseCode);
1587
            $total_score_obtained += $exercise_results_tmp['score_obtained'];
1588
            $total_score_possible += $exercise_results_tmp['score_possible'];
1589
            $total_questions_answered += $exercise_results_tmp['questions_answered'];
1590
        }
1591
        if ($nb_progress_lp > 0) {
1592
            $avg_progress = round($progress / $nb_progress_lp, 2);
1593
        } else {
1594
            $avg_progress = 0;
1595
        }
1596
        if ($nb_score_lp > 0) {
1597
            $avg_score = round($score / $nb_score_lp, 2);
1598
        } else {
1599
            $avg_score = '-';
1600
        }
1601
        if ($last_login_date) {
1602
            $last_login_date = api_convert_and_format_date(
1603
                $last_login_date,
1604
                DATE_FORMAT_SHORT,
1605
                date_default_timezone_get()
1606
            );
1607
        } else {
1608
            $last_login_date = '-';
1609
        }
1610
        if ($total_score_possible > 0) {
1611
            $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
1612
        } else {
1613
            $total_score_percentage = 0;
1614
        }
1615
        if ($total_score_percentage > 0) {
1616
            $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
1617
        } else {
1618
            $total_score = '-';
1619
        }
1620
1621
        $data = [
1622
            'time_spent' => api_time_to_hms($time_spent),
1623
            'avg_progress' => $avg_progress,
1624
            'avg_score' => $avg_score,
1625
            'number_message' => $nb_messages,
1626
            'number_assignments' => $nb_assignments,
1627
            'total_score' => $total_score,
1628
            'questions_answered' => $total_questions_answered,
1629
            'last_login' => $last_login_date,
1630
        ];
1631
1632
        $tpl->assign('data', $data);
1633
        $tpl->assign('course', $course);
1634
        $layout = $tpl->get_template('my_space/partials/tracking_course_overview.html.twig');
1635
1636
        return $tpl->fetch($layout);
1637
    }
1638
1639
    /**
1640
     * This function exports the table that we see in display_tracking_course_overview().
1641
     */
1642
    public static function export_tracking_course_overview()
1643
    {
1644
        // database table definition
1645
        $tbl_course_rel_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1646
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1647
1648
        // the values of the sortable table
1649
        if ($_GET['tracking_course_overview_page_nr']) {
1650
            $from = $_GET['tracking_course_overview_page_nr'];
1651
        } else {
1652
            $from = 0;
1653
        }
1654
        if ($_GET['tracking_course_overview_column']) {
1655
            $orderby = $_GET['tracking_course_overview_column'];
1656
        } else {
1657
            $orderby = 0;
1658
        }
1659
1660
        if ($_GET['tracking_course_overview_direction']) {
1661
            $direction = $_GET['tracking_course_overview_direction'];
1662
        } else {
1663
            $direction = 'ASC';
1664
        }
1665
1666
        $course_data = self::get_course_data_tracking_overview(
1667
            $from,
1668
            1000,
1669
            $orderby,
1670
            $direction
1671
        );
1672
1673
        $csv_content = [];
1674
1675
        // the first line of the csv file with the column headers
1676
        $csv_row = [];
1677
        $csv_row[] = get_lang('Course');
1678
        $csv_row[] = get_lang('Time');
1679
        $csv_row[] = get_lang('Progress');
1680
        $csv_row[] = get_lang('Average score in learning paths');
1681
        $csv_row[] = get_lang('Total number of messages');
1682
        $csv_row[] = get_lang('Total number of assignments');
1683
        $csv_row[] = get_lang('Total score obtained for tests');
1684
        $csv_row[] = get_lang('Total possible score for tests');
1685
        $csv_row[] = get_lang('Number of tests answered');
1686
        $csv_row[] = get_lang('Total score percentage for tests');
1687
        $csv_row[] = get_lang('Latest login');
1688
        $csv_content[] = $csv_row;
1689
1690
        // the other lines (the data)
1691
        foreach ($course_data as $key => $course) {
1692
            $courseId = $course[0];
1693
            $course = api_get_course_entity($courseId);
1694
            $courseCode = $course->getCode();
1695
            $course_title = $course->getTitle();
1696
1697
            $csv_row = [];
1698
            $csv_row[] = $course_title;
1699
1700
            $time_spent = 0;
1701
            $progress = 0;
1702
            $nb_progress_lp = 0;
1703
            $score = 0;
1704
            $nb_score_lp = 0;
1705
            $nb_messages = 0;
1706
            $nb_assignments = 0;
1707
            $last_login_date = false;
1708
            $total_score_obtained = 0;
1709
            $total_score_possible = 0;
1710
            $total_questions_answered = 0;
1711
1712
            $courseRelUsers = $course->getUsers();
1713
            foreach ($courseRelUsers as $courseRelUser) {
1714
                $user = $courseRelUser->getUser();
1715
                $userId = $user->getId();
1716
1717
                // get time spent in the course and session
1718
                $time_spent += Tracking::get_time_spent_on_the_course(
1719
                    $userId,
1720
                    $courseId
1721
                );
1722
                $progress_tmp = Tracking::get_avg_student_progress(
1723
                    $userId,
1724
                    $course,
1725
                    [],
1726
                    null,
1727
                    true
1728
                );
1729
                $progress += $progress_tmp[0];
1730
                $nb_progress_lp += $progress_tmp[1];
1731
                $score_tmp = Tracking::get_avg_student_score(
1732
                    $userId,
1733
                    $course,
1734
                    [],
1735
                    null,
1736
                    true
1737
                );
1738
                if (is_array($score_tmp)) {
1739
                    $score += $score_tmp[0];
1740
                    $nb_score_lp += $score_tmp[1];
1741
                }
1742
                $nb_messages += Container::getForumPostRepository()->countUserForumPosts($user, $course);
1743
                $nb_assignments += Container::getStudentPublicationRepository()->countUserPublications($user, $course);
1744
1745
                $last_login_date_tmp = Tracking::get_last_connection_date_on_the_course(
1746
                    $userId,
1747
                    ['real_id' => $courseId],
1748
                    null,
1749
                    false
1750
                );
1751
1752
                if (false != $last_login_date_tmp && false == $last_login_date) {
1753
                    $last_login_date = $last_login_date_tmp;
1754
                    // TODO: Repeated previous condition. To be cleaned.
1755
                    // Find the max and assign it to first_login_date
1756
                    if (strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
1757
                        $last_login_date = $last_login_date_tmp;
1758
                    }
1759
                }
1760
1761
                $exercise_results_tmp = self::exercises_results($userId, $courseCode);
1762
                $total_score_obtained += $exercise_results_tmp['score_obtained'];
1763
                $total_score_possible += $exercise_results_tmp['score_possible'];
1764
                $total_questions_answered += $exercise_results_tmp['questions_answered'];
1765
            }
1766
            if ($nb_progress_lp > 0) {
1767
                $avg_progress = round($progress / $nb_progress_lp, 2);
1768
            } else {
1769
                $avg_progress = 0;
1770
            }
1771
            if ($nb_score_lp > 0) {
1772
                $avg_score = round($score / $nb_score_lp, 2);
1773
            } else {
1774
                $avg_score = '-';
1775
            }
1776
            if ($last_login_date) {
1777
                $last_login_date = api_convert_and_format_date(
1778
                    $last_login_date,
1779
                    DATE_FORMAT_SHORT,
1780
                    date_default_timezone_get()
1781
                );
1782
            } else {
1783
                $last_login_date = '-';
1784
            }
1785
            if ($total_score_possible > 0) {
1786
                $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
1787
            } else {
1788
                $total_score_percentage = 0;
1789
            }
1790
            // time spent in the course
1791
            $csv_row[] = api_time_to_hms($time_spent);
1792
            // student progress in course
1793
            $csv_row[] = $avg_progress;
1794
            // student score
1795
            $csv_row[] = $avg_score;
1796
            // student messages
1797
            $csv_row[] = $nb_messages;
1798
            // student assignments
1799
            $csv_row[] = $nb_assignments;
1800
            // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
1801
            $csv_row[] = $total_score_obtained;
1802
            $csv_row[] = $total_score_possible;
1803
            $csv_row[] = $total_questions_answered;
1804
            $csv_row[] = $total_score_percentage;
1805
            // last connection
1806
            $csv_row[] = $last_login_date;
1807
            $csv_content[] = $csv_row;
1808
        }
1809
        Export::arrayToCsv($csv_content, 'reporting_course_overview');
1810
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1811
    }
1812
1813
    /**
1814
     * Display a sortable table that contains an overview of all the reporting
1815
     * progress of all sessions and all courses the user is subscribed to.
1816
     *
1817
     * @author Guillaume Viguier <[email protected]>
1818
     */
1819
    public static function display_tracking_session_overview()
1820
    {
1821
        $head = '<table style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
1822
        $head .= '<tr>';
1823
        $head .= '<th width="155px" style="border-left:0;border-bottom:0"><span>'.get_lang('Course').'</span></th>';
1824
        $head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('Time'), 6, true).'</span></th>';
1825
        $head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('Progress'), 6, true).'</span></th>';
1826
        $head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('Average score in learning paths'), 6, true).'</span></th>';
1827
        $head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('Total number of messages'), 6, true).'</span></th>';
1828
        $head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('Total number of assignments'), 6, true).'</span></th>';
1829
        $head .= '<th width="105px" style="border-bottom:0"><span>'.get_lang('Total score obtained for tests').'</span></th>';
1830
        $head .= '<th style="padding:0;border-bottom:0"><span>'.cut(get_lang('Number of tests answered'), 6, true).'</span></th>';
1831
        $head .= '<th style="padding:0;border-bottom:0;border-right:0;"><span>'.get_lang('Latest login').'</span></th>';
1832
        $head .= '</tr></table>';
1833
1834
        $params = ['view' => 'admin', 'display' => 'sessionoverview'];
1835
        $table = new SortableTable(
1836
            'tracking_session_overview',
1837
            ['MySpace', 'get_total_number_sessions'],
1838
            ['MySpace', 'get_session_data_tracking_overview'],
1839
            1
1840
        );
1841
        $table->additional_parameters = $params;
1842
1843
        $table->set_header(0, '', false, null, ['style' => 'display: none']);
1844
        $table->set_header(
1845
            1,
1846
            get_lang('Session'),
1847
            true,
1848
            ['style' => 'font-size:8pt'],
1849
            ['style' => 'font-size:8pt']
1850
        );
1851
        $table->set_header(
1852
            2,
1853
            $head,
1854
            false,
1855
            ['style' => 'width:90%;border:0;padding:0;font-size:7.5pt;'],
1856
            ['style' => 'width:90%;padding:0;font-size:7.5pt;']
1857
        );
1858
        $table->set_column_filter(2, ['MySpace', 'session_tracking_filter']);
1859
        $table->display();
1860
    }
1861
1862
    /**
1863
     * Get the total number of sessions.
1864
     *
1865
     * @return int Total number of sessions
1866
     */
1867
    public static function get_total_number_sessions()
1868
    {
1869
        return SessionManager::count_sessions(api_get_current_access_url_id());
1870
    }
1871
1872
    /**
1873
     * Get data for the sessions.
1874
     *
1875
     * @param int    $from        Inferior limit
1876
     * @param int    $numberItems Number of items to select
1877
     * @param string $column      Column to order on
1878
     * @param string $direction   Order direction
1879
     *
1880
     * @return array Results
1881
     */
1882
    public static function get_session_data_tracking_overview(
1883
        $from,
1884
        $numberItems,
1885
        $column,
1886
        $direction
1887
    ) {
1888
        $from = (int) $from;
1889
        $numberItems = (int) $numberItems;
1890
        $direction = Database::escape_string($direction);
1891
        $columnName = 'name';
1892
        if (1 === $column) {
1893
            $columnName = 'id';
1894
        }
1895
1896
        $options = [
1897
            'order' => " $columnName $direction",
1898
            'limit' => " $from,$numberItems",
1899
        ];
1900
        $sessions = SessionManager::formatSessionsAdminForGrid($options);
1901
        $list = [];
1902
        foreach ($sessions as $session) {
1903
            $list[] = [
1904
                '0' => $session['id'],
1905
                'col0' => $session['id'],
1906
                '1' => strip_tags($session['name']),
1907
                'col1' => strip_tags($session['name']),
1908
            ];
1909
        }
1910
1911
        return $list;
1912
    }
1913
1914
    /**
1915
     * Fills in session reporting data.
1916
     *
1917
     * @param int   $session_id the id of the user
1918
     * @param array $url_params additonal url parameters
1919
     * @param array $row        the row information (the other columns)
1920
     *
1921
     * @return string html code
1922
     */
1923
    public static function session_tracking_filter($session_id, $url_params, $row)
1924
    {
1925
        $sessionId = $row[0];
1926
        $session = api_get_session_entity($sessionId);
1927
        // the table header
1928
        $return = '<table
1929
            class="data_table"
1930
            style="width: 100%;border:0;padding:0;border-collapse:collapse;table-layout: fixed">';
1931
1932
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1933
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1934
        $sessionRelCourses = $session->getCourses();
1935
        foreach ($sessionRelCourses as $sessionRelCourse) {
1936
            $course = $sessionRelCourse->getCourse();
1937
            $courseId = $course->getId();
1938
            $courseCode = $course->getCode();
1939
            $return .= '<tr>';
1940
            $return .= '<td>'.$course->getTitle().'</td>';
1941
            //$users = Container::getSessionRepository()->getUsersByCourse($session, $course, $url);
1942
1943
            // get the users in the course
1944
            $sql = "SELECT u.id as user_id
1945
                    FROM $tbl_user AS u
1946
                    INNER JOIN $tbl_session_rel_course_rel_user AS scu
1947
                    ON u.id = scu.user_id
1948
                    WHERE u.active <> ".USER_SOFT_DELETED." AND scu.session_id = '".$session_id."' AND scu.c_id = '".$courseId."'";
1949
            $result_users = Database::query($sql);
1950
            $time_spent = 0;
1951
            $progress = 0;
1952
            $nb_progress_lp = 0;
1953
            $score = 0;
1954
            $nb_score_lp = 0;
1955
            $nb_messages = 0;
1956
            $nb_assignments = 0;
1957
            $last_login_date = false;
1958
            $total_score_obtained = 0;
1959
            $total_score_possible = 0;
1960
            $total_questions_answered = 0;
1961
            while ($row_user = Database::fetch_object($result_users)) {
1962
                $user = api_get_user_entity($row_user->user_id);
1963
                // get time spent in the course and session
1964
                $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $courseId, $session_id);
1965
                $progress_tmp = Tracking::get_avg_student_progress(
1966
                    $row_user->user_id,
1967
                    $course,
1968
                    [],
1969
                    $session_id,
1970
                    true
1971
                );
1972
                $progress += $progress_tmp[0];
1973
                $nb_progress_lp += $progress_tmp[1];
1974
                $score_tmp = Tracking::get_avg_student_score($row_user->user_id, $course, [], $session_id, true);
1975
                if (is_array($score_tmp)) {
1976
                    $score += $score_tmp[0];
1977
                    $nb_score_lp += $score_tmp[1];
1978
                }
1979
                $nb_messages += Container::getForumPostRepository()->countUserForumPosts($user, $course, $session);
1980
                $nb_assignments += Container::getStudentPublicationRepository()->countUserPublications(
1981
                    $user,
1982
                    $course,
1983
                    $session
1984
                );
1985
                $last_login_date_tmp = Tracking::get_last_connection_date_on_the_course(
1986
                    $row_user->user_id,
1987
                    ['real_id' => $courseId],
1988
                    $session_id,
1989
                    false
1990
                );
1991
                if (false != $last_login_date_tmp && false == $last_login_date) {
1992
                    // TODO: To be cleaned.
1993
                    $last_login_date = $last_login_date_tmp;
1994
                } elseif (false != $last_login_date_tmp && false != $last_login_date) {
1995
                    // TODO: Repeated previous condition! To be cleaned.
1996
                    // Find the max and assign it to first_login_date
1997
                    if (strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
1998
                        $last_login_date = $last_login_date_tmp;
1999
                    }
2000
                }
2001
2002
                $exercise_results_tmp = self::exercises_results($row_user->user_id, $courseCode, $session_id);
2003
                $total_score_obtained += $exercise_results_tmp['score_obtained'];
2004
                $total_score_possible += $exercise_results_tmp['score_possible'];
2005
                $total_questions_answered += $exercise_results_tmp['questions_answered'];
2006
            }
2007
            if ($nb_progress_lp > 0) {
2008
                $avg_progress = round($progress / $nb_progress_lp, 2);
2009
            } else {
2010
                $avg_progress = 0;
2011
            }
2012
            if ($nb_score_lp > 0) {
2013
                $avg_score = round($score / $nb_score_lp, 2);
2014
            } else {
2015
                $avg_score = '-';
2016
            }
2017
            if ($last_login_date) {
2018
                $last_login_date = api_convert_and_format_date(
2019
                    $last_login_date,
2020
                    DATE_FORMAT_SHORT,
2021
                    date_default_timezone_get()
2022
                );
2023
            } else {
2024
                $last_login_date = '-';
2025
            }
2026
            if ($total_score_possible > 0) {
2027
                $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
2028
            } else {
2029
                $total_score_percentage = 0;
2030
            }
2031
            if ($total_score_percentage > 0) {
2032
                $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
2033
            } else {
2034
                $total_score = '-';
2035
            }
2036
            // time spent in the course
2037
            $return .= '    <td><div>'.api_time_to_hms($time_spent).'</div></td>';
2038
            // student progress in course
2039
            $return .= '    <td><div>'.$avg_progress.'</div></td>';
2040
            // student score
2041
            $return .= '    <td><div>'.$avg_score.'</div></td>';
2042
            // student messages
2043
            $return .= '    <td><div>'.$nb_messages.'</div></td>';
2044
            // student assignments
2045
            $return .= '    <td><div>'.$nb_assignments.'</div></td>';
2046
            // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
2047
            $return .= '<td width="105px;">'.$total_score.'</td>';
2048
            $return .= '<td>'.$total_questions_answered.'</td>';
2049
            // last connection
2050
            $return .= '    <td><div>'.$last_login_date.'</div></td>';
2051
            $return .= '<tr>';
2052
        }
2053
        $return .= '</table>';
2054
2055
        return $return;
2056
    }
2057
2058
    /**
2059
     * This function exports the table that we see in display_tracking_session_overview().
2060
     */
2061
    public static function export_tracking_session_overview()
2062
    {
2063
        // database table definition
2064
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2065
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
2066
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2067
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2068
2069
        // the values of the sortable table
2070
        $from = 0;
2071
        if ($_GET['tracking_session_overview_page_nr']) {
2072
            $from = $_GET['tracking_session_overview_page_nr'];
2073
        }
2074
2075
        $orderby = 0;
2076
        if ($_GET['tracking_session_overview_column']) {
2077
            $orderby = $_GET['tracking_session_overview_column'];
2078
        }
2079
2080
        $direction = 'ASC';
2081
        if ($_GET['tracking_session_overview_direction']) {
2082
            $direction = $_GET['tracking_session_overview_direction'];
2083
        }
2084
2085
        $session_data = self::get_session_data_tracking_overview($from, 1000, $orderby, $direction);
2086
2087
        $csv_content = [];
2088
2089
        // the first line of the csv file with the column headers
2090
        $csv_row = [];
2091
        $csv_row[] = get_lang('Session');
2092
        $csv_row[] = get_lang('Course');
2093
        $csv_row[] = get_lang('Time');
2094
        $csv_row[] = get_lang('Progress');
2095
        $csv_row[] = get_lang('Average score in learning paths');
2096
        $csv_row[] = get_lang('Total number of messages');
2097
        $csv_row[] = get_lang('Total number of assignments');
2098
        $csv_row[] = get_lang('Total score obtained for tests');
2099
        $csv_row[] = get_lang('Total possible score for tests');
2100
        $csv_row[] = get_lang('Number of tests answered');
2101
        $csv_row[] = get_lang('Total score percentage for tests');
2102
        $csv_row[] = get_lang('Latest login');
2103
        $csv_content[] = $csv_row;
2104
2105
        // the other lines (the data)
2106
        foreach ($session_data as $session) {
2107
            $session_id = $session[0];
2108
            $session_title = $session[1];
2109
2110
            // getting all the courses of the session
2111
            $sql = "SELECT * FROM $tbl_course AS c
2112
                    INNER JOIN $tbl_session_rel_course AS sc
2113
                    ON sc.c_id = c.id
2114
                    WHERE sc.session_id = '".$session_id."';";
2115
            $result = Database::query($sql);
2116
            while ($row = Database::fetch_object($result)) {
2117
                $courseId = $row->c_id;
2118
                $courseInfo = ['real_id' => $courseId];
2119
                $course = api_get_course_entity($courseId);
2120
                $csv_row = [];
2121
                $csv_row[] = $session_title;
2122
                $csv_row[] = $row->title;
2123
                // get the users in the course
2124
                $sql = "SELECT scu.user_id
2125
                        FROM $tbl_user AS u
2126
                        INNER JOIN $tbl_session_rel_course_rel_user AS scu
2127
                        ON u.id = scu.user_id
2128
                        WHERE u.active <> ".USER_SOFT_DELETED." AND scu.session_id = '".$session_id."' AND scu.c_id = '".$courseId."'";
2129
                $result_users = Database::query($sql);
2130
                $time_spent = 0;
2131
                $progress = 0;
2132
                $nb_progress_lp = 0;
2133
                $score = 0;
2134
                $nb_score_lp = 0;
2135
                $nb_messages = 0;
2136
                $nb_assignments = 0;
2137
                $last_login_date = false;
2138
                $total_score_obtained = 0;
2139
                $total_score_possible = 0;
2140
                $total_questions_answered = 0;
2141
                while ($row_user = Database::fetch_object($result_users)) {
2142
                    // get time spent in the course and session
2143
                    $time_spent += Tracking::get_time_spent_on_the_course($row_user->user_id, $courseId, $session_id);
2144
                    $progress_tmp = Tracking::get_avg_student_progress(
2145
                        $row_user->user_id,
2146
                        $row->code,
2147
                        [],
2148
                        $session_id,
2149
                        true
2150
                    );
2151
                    $progress += $progress_tmp[0];
2152
                    $nb_progress_lp += $progress_tmp[1];
2153
                    $score_tmp = Tracking::get_avg_student_score(
2154
                        $row_user->user_id,
2155
                        $course,
2156
                        [],
2157
                        $session_id,
2158
                        true
2159
                    );
2160
                    if (is_array($score_tmp)) {
2161
                        $score += $score_tmp[0];
2162
                        $nb_score_lp += $score_tmp[1];
2163
                    }
2164
                    $nb_messages += Tracking::count_student_messages(
2165
                        $row_user->user_id,
2166
                        $row->code,
2167
                        $session_id
2168
                    );
2169
2170
                    $nb_assignments += Tracking::count_student_assignments(
2171
                        $row_user->user_id,
2172
                        $row->code,
2173
                        $session_id
2174
                    );
2175
2176
                    $last_login_date_tmp = Tracking:: get_last_connection_date_on_the_course(
2177
                        $row_user->user_id,
2178
                        $courseInfo,
2179
                        $session_id,
2180
                        false
2181
                    );
2182
                    if (false != $last_login_date_tmp && false == $last_login_date) {
2183
                        // TODO: To be cleaned.
2184
                        $last_login_date = $last_login_date_tmp;
2185
                    } elseif (false != $last_login_date_tmp && false == $last_login_date) {
2186
                        // TODO: Repeated previous condition. To be cleaned.
2187
                        // Find the max and assign it to first_login_date
2188
                        if (strtotime($last_login_date_tmp) > strtotime($last_login_date)) {
2189
                            $last_login_date = $last_login_date_tmp;
2190
                        }
2191
                    }
2192
2193
                    $exercise_results_tmp = self::exercises_results($row_user->user_id, $row->code, $session_id);
2194
                    $total_score_obtained += $exercise_results_tmp['score_obtained'];
2195
                    $total_score_possible += $exercise_results_tmp['score_possible'];
2196
                    $total_questions_answered += $exercise_results_tmp['questions_answered'];
2197
                }
2198
                if ($nb_progress_lp > 0) {
2199
                    $avg_progress = round($progress / $nb_progress_lp, 2);
2200
                } else {
2201
                    $avg_progress = 0;
2202
                }
2203
                if ($nb_score_lp > 0) {
2204
                    $avg_score = round($score / $nb_score_lp, 2);
2205
                } else {
2206
                    $avg_score = '-';
2207
                }
2208
                if ($last_login_date) {
2209
                    $last_login_date = api_convert_and_format_date(
2210
                        $last_login_date,
2211
                        DATE_FORMAT_SHORT,
2212
                        date_default_timezone_get()
2213
                    );
2214
                } else {
2215
                    $last_login_date = '-';
2216
                }
2217
                if ($total_score_possible > 0) {
2218
                    $total_score_percentage = round($total_score_obtained / $total_score_possible * 100, 2);
2219
                } else {
2220
                    $total_score_percentage = 0;
2221
                }
2222
                if ($total_score_percentage > 0) {
2223
                    $total_score = $total_score_obtained.'/'.$total_score_possible.' ('.$total_score_percentage.' %)';
2224
                } else {
2225
                    $total_score = '-';
2226
                }
2227
                // time spent in the course
2228
                $csv_row[] = api_time_to_hms($time_spent);
2229
                // student progress in course
2230
                $csv_row[] = $avg_progress;
2231
                // student score
2232
                $csv_row[] = $avg_score;
2233
                // student messages
2234
                $csv_row[] = $nb_messages;
2235
                // student assignments
2236
                $csv_row[] = $nb_assignments;
2237
                // student exercises results (obtained score, maximum score, number of exercises answered, score percentage)
2238
                $csv_row[] = $total_score_obtained;
2239
                $csv_row[] = $total_score_possible;
2240
                $csv_row[] = $total_questions_answered;
2241
                $csv_row[] = $total_score_percentage;
2242
                // last connection
2243
                $csv_row[] = $last_login_date;
2244
                $csv_content[] = $csv_row;
2245
            }
2246
        }
2247
        Export::arrayToCsv($csv_content, 'reporting_session_overview');
2248
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2249
    }
2250
2251
    /**
2252
     * Get general information about the exercise performance of the user
2253
     * the total obtained score (all the score on all the questions)
2254
     * the maximum score that could be obtained
2255
     * the number of questions answered
2256
     * the success percentage.
2257
     *
2258
     * @param int    $user_id     the id of the user
2259
     * @param string $course_code the course code
2260
     * @param int    $session_id
2261
     *
2262
     * @return array
2263
     *
2264
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
2265
     *
2266
     * @version Dokeos 1.8.6
2267
     *
2268
     * @since November 2008
2269
     */
2270
    public static function exercises_results($user_id, $course_code, $session_id = 0)
2271
    {
2272
        $user_id = (int) $user_id;
2273
        $courseId = api_get_course_int_id($course_code);
2274
        $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCISES);
2275
        $sessionCondition = api_get_session_condition($session_id);
2276
        $sql = "SELECT score, max_score
2277
                FROM $table
2278
                WHERE
2279
                    c_id = $courseId AND
2280
                    exe_user_id = $user_id
2281
                    $sessionCondition
2282
                    ";
2283
2284
        $result = Database::query($sql);
2285
        $score_obtained = 0;
2286
        $score_possible = 0;
2287
        $questions_answered = 0;
2288
        while ($row = Database::fetch_array($result)) {
2289
            $score_obtained += $row['score'];
2290
            $score_possible += $row['max_score'];
2291
            $questions_answered++;
2292
        }
2293
2294
        $percentage = null;
2295
        if (0 != $score_possible) {
2296
            $percentage = round(($score_obtained / $score_possible * 100), 2);
2297
        }
2298
2299
        return [
2300
            'score_obtained' => $score_obtained,
2301
            'score_possible' => $score_possible,
2302
            'questions_answered' => $questions_answered,
2303
            'percentage' => $percentage,
2304
        ];
2305
    }
2306
2307
    /**
2308
     * This function exports the table that we see in display_tracking_user_overview().
2309
     *
2310
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
2311
     *
2312
     * @version Dokeos 1.8.6
2313
     *
2314
     * @since October 2008
2315
     */
2316
    public static function export_tracking_user_overview()
2317
    {
2318
        // database table definitions
2319
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
2320
        $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
2321
2322
        // the values of the sortable table
2323
        if ($_GET['tracking_user_overview_page_nr']) {
2324
            $from = $_GET['tracking_user_overview_page_nr'];
2325
        } else {
2326
            $from = 0;
2327
        }
2328
        if ($_GET['tracking_user_overview_column']) {
2329
            $orderby = $_GET['tracking_user_overview_column'];
2330
        } else {
2331
            $orderby = 0;
2332
        }
2333
        if ($is_western_name_order != api_is_western_name_order() && (1 == $orderby || 2 == $orderby)) {
2334
            // Swapping the sorting column if name order for export is different than the common name order.
2335
            $orderby = 3 - $orderby;
2336
        }
2337
        if ($_GET['tracking_user_overview_direction']) {
2338
            $direction = $_GET['tracking_user_overview_direction'];
2339
        } else {
2340
            $direction = 'ASC';
2341
        }
2342
2343
        $user_data = self::get_user_data_tracking_overview(
2344
            $from,
2345
            1000,
2346
            $orderby,
2347
            $direction
2348
        );
2349
2350
        // the first line of the csv file with the column headers
2351
        $csv_row = [];
2352
        $csv_row[] = get_lang('Code');
2353
        if ($is_western_name_order) {
2354
            $csv_row[] = get_lang('First name');
2355
            $csv_row[] = get_lang('Last name');
2356
        } else {
2357
            $csv_row[] = get_lang('Last name');
2358
            $csv_row[] = get_lang('First name');
2359
        }
2360
        $csv_row[] = get_lang('Login');
2361
        $csv_row[] = get_lang('Code');
2362
2363
        // the additional user defined fields (only those that were selected to be exported)
2364
        $fields = UserManager::get_extra_fields(0, 50, 5, 'ASC');
2365
2366
        $additionalExportFields = Session::read('additional_export_fields');
2367
2368
        if (is_array($additionalExportFields)) {
2369
            foreach ($additionalExportFields as $key => $extra_field_export) {
2370
                $csv_row[] = $fields[$extra_field_export][3];
2371
                $field_names_to_be_exported[] = 'extra_'.$fields[$extra_field_export][1];
2372
            }
2373
        }
2374
        $csv_row[] = get_lang('Time');
2375
        $csv_row[] = get_lang('Progress');
2376
        $csv_row[] = get_lang('Average score in learning paths');
2377
        $csv_row[] = get_lang('Tests score');
2378
        $csv_row[] = get_lang('Messages per learner');
2379
        $csv_row[] = get_lang('Assignments');
2380
        $csv_row[] = get_lang('Total score obtained for tests');
2381
        $csv_row[] = get_lang('Total possible score for tests');
2382
        $csv_row[] = get_lang('Number of tests answered');
2383
        $csv_row[] = get_lang('Total score percentage for tests');
2384
        $csv_row[] = get_lang('First connection');
2385
        $csv_row[] = get_lang('Latest login');
2386
        $csv_content[] = $csv_row;
2387
2388
        // the other lines (the data)
2389
        foreach ($user_data as $user) {
2390
            // getting all the courses of the user
2391
            $sql = "SELECT * FROM $tbl_course_user
2392
                    WHERE user_id = '".intval($user[4])."' AND relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
2393
            $result = Database::query($sql);
2394
            while ($row = Database::fetch_row($result)) {
2395
                $course = api_get_course_entity($row['c_id']);
2396
                $courseId = $course->getId();
2397
                $courseCode = $course->getCode();
2398
2399
                $csv_row = [];
2400
                // user official code
2401
                $csv_row[] = $user[0];
2402
                // user first|last name
2403
                $csv_row[] = $user[1];
2404
                // user last|first name
2405
                $csv_row[] = $user[2];
2406
                // user login name
2407
                $csv_row[] = $user[3];
2408
                // course code
2409
                $csv_row[] = $row[0];
2410
                // the additional defined user fields
2411
                $extra_fields = self::get_user_overview_export_extra_fields($user[4]);
2412
2413
                if (is_array($field_names_to_be_exported)) {
2414
                    foreach ($field_names_to_be_exported as $key => $extra_field_export) {
2415
                        $csv_row[] = $extra_fields[$extra_field_export];
2416
                    }
2417
                }
2418
                // time spent in the course
2419
                $csv_row[] = api_time_to_hms(Tracking::get_time_spent_on_the_course($user[4], $courseId));
2420
                // student progress in course
2421
                $csv_row[] = round(Tracking::get_avg_student_progress($user[4], $course), 2);
2422
                // student score
2423
                $csv_row[] = round(Tracking::get_avg_student_score($user[4], $course), 2);
2424
                // student tes score
2425
                $csv_row[] = round(Tracking::get_avg_student_exercise_score($user[4], $courseCode), 2);
2426
                // student messages
2427
                //$csv_row[] = Tracking::count_student_messages($user[4], $row[0]);
2428
                // student assignments
2429
                //$csv_row[] = Tracking::count_student_assignments($user[4], $row[0]);
2430
                // student exercises results
2431
                $exercises_results = self::exercises_results($user[4], $row[0]);
2432
                $csv_row[] = $exercises_results['score_obtained'];
2433
                $csv_row[] = $exercises_results['score_possible'];
2434
                $csv_row[] = $exercises_results['questions_answered'];
2435
                $csv_row[] = $exercises_results['percentage'];
2436
                // first connection
2437
                $csv_row[] = Tracking::get_first_connection_date_on_the_course($user[4], $courseId);
2438
                // last connection
2439
                $csv_row[] = strip_tags(Tracking::get_last_connection_date_on_the_course($user[4], $courseInfo));
2440
2441
                $csv_content[] = $csv_row;
2442
            }
2443
        }
2444
        Export::arrayToCsv($csv_content, 'reporting_user_overview');
2445
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2446
    }
2447
2448
    /**
2449
     * Get data for courses list in sortable with pagination.
2450
     *
2451
     * @return array
2452
     */
2453
    public static function get_course_data($from, $number_of_items, $column, $direction)
2454
    {
2455
        global $courses, $csv_content, $charset, $session_id;
2456
2457
        // definition database tables
2458
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
2459
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
2460
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2461
2462
        $course_data = [];
2463
        $courses_code = array_keys($courses);
2464
2465
        foreach ($courses_code as &$code) {
2466
            $code = "'$code'";
2467
        }
2468
2469
        // get all courses with limit
2470
        $sql = "SELECT course.code as col1, course.title as col2
2471
                FROM $tbl_course course
2472
                WHERE course.code IN (".implode(',', $courses_code).")";
2473
2474
        if (!in_array($direction, ['ASC', 'DESC'])) {
2475
            $direction = 'ASC';
2476
        }
2477
2478
        $column = (int) $column;
2479
        $from = (int) $from;
2480
        $number_of_items = (int) $number_of_items;
2481
        $sql .= " ORDER BY col$column $direction ";
2482
        $sql .= " LIMIT $from,$number_of_items";
2483
2484
        $res = Database::query($sql);
2485
        while ($row_course = Database::fetch_row($res)) {
2486
            $course_code = $row_course[0];
2487
            $courseInfo = api_get_course_info($course_code);
2488
            $courseId = $courseInfo['real_id'];
2489
            $avg_assignments_in_course = $avg_messages_in_course = $nb_students_in_course = $avg_progress_in_course = $avg_score_in_course = $avg_time_spent_in_course = $avg_score_in_exercise = 0;
2490
2491
            // students directly subscribed to the course
2492
            if (empty($session_id)) {
2493
                $sql = "SELECT user_id
2494
                        FROM $tbl_course_user as course_rel_user
2495
                        WHERE
2496
                            course_rel_user.status='5' AND
2497
                            course_rel_user.c_id = '$courseId'";
2498
            } else {
2499
                $sql = "SELECT user_id FROM $tbl_session_course_user srcu
2500
                        WHERE
2501
                            c_id = '$courseId' AND
2502
                            session_id = '$session_id' AND
2503
                            status = ".SessionEntity::STUDENT;
2504
            }
2505
            $rs = Database::query($sql);
2506
            $users = [];
2507
            while ($row = Database::fetch_array($rs)) {
2508
                $users[] = $row['user_id'];
2509
            }
2510
2511
            if (count($users) > 0) {
2512
                $nb_students_in_course = count($users);
2513
                $avg_assignments_in_course = Tracking::count_student_assignments($users, $course_code, $session_id);
2514
                $avg_messages_in_course = Tracking::count_student_messages($users, $course_code, $session_id);
2515
                $avg_progress_in_course = Tracking::get_avg_student_progress($users, $course_code, [], $session_id);
2516
                $avg_score_in_course = Tracking::get_avg_student_score($users, $course_code, [], $session_id);
2517
                $avg_score_in_exercise = Tracking::get_avg_student_exercise_score($users, $course_code, 0, $session_id);
2518
                $avg_time_spent_in_course = Tracking::get_time_spent_on_the_course(
2519
                    $users,
2520
                    $courseInfo['real_id'],
2521
                    $session_id
2522
                );
2523
2524
                $avg_progress_in_course = round($avg_progress_in_course / $nb_students_in_course, 2);
2525
                if (is_numeric($avg_score_in_course)) {
2526
                    $avg_score_in_course = round($avg_score_in_course / $nb_students_in_course, 2);
2527
                }
2528
                $avg_time_spent_in_course = api_time_to_hms($avg_time_spent_in_course / $nb_students_in_course);
2529
            } else {
2530
                $avg_time_spent_in_course = null;
2531
                $avg_progress_in_course = null;
2532
                $avg_score_in_course = null;
2533
                $avg_score_in_exercise = null;
2534
                $avg_messages_in_course = null;
2535
                $avg_assignments_in_course = null;
2536
            }
2537
            $table_row = [];
2538
            $table_row[] = $row_course[1];
2539
            $table_row[] = $nb_students_in_course;
2540
            $table_row[] = $avg_time_spent_in_course;
2541
            $table_row[] = is_null($avg_progress_in_course) ? '' : $avg_progress_in_course.'%';
2542
            $table_row[] = is_null($avg_score_in_course) ? '' : $avg_score_in_course.'%';
2543
            $table_row[] = is_null($avg_score_in_exercise) ? '' : $avg_score_in_exercise.'%';
2544
            $table_row[] = $avg_messages_in_course;
2545
            $table_row[] = $avg_assignments_in_course;
2546
2547
            //set the "from" value to know if I access the Reporting by the chamilo tab or the course link
2548
            $table_row[] = '<center><a href="../../tracking/courseLog.php?cidReq='.$course_code.'&from=myspace&id_session='.$session_id.'">
2549
                             '.Display::getMdiIcon('fast-forward-outline', 'ch-tool-icon', null, 22, get_lang('Details')).'
2550
                             </a>
2551
                            </center>';
2552
2553
            $scoreInCourse = null;
2554
            if (null !== $avg_score_in_course) {
2555
                if (is_numeric($avg_score_in_course)) {
2556
                    $scoreInCourse = $avg_score_in_course.'%';
2557
                } else {
2558
                    $scoreInCourse = $avg_score_in_course;
2559
                }
2560
            }
2561
2562
            $csv_content[] = [
2563
                api_html_entity_decode($row_course[1], ENT_QUOTES, $charset),
2564
                $nb_students_in_course,
2565
                $avg_time_spent_in_course,
2566
                is_null($avg_progress_in_course) ? null : $avg_progress_in_course.'%',
2567
                $scoreInCourse,
2568
                is_null($avg_score_in_exercise) ? null : $avg_score_in_exercise.'%',
2569
                $avg_messages_in_course,
2570
                $avg_assignments_in_course,
2571
            ];
2572
            $course_data[] = $table_row;
2573
        }
2574
2575
        return $course_data;
2576
    }
2577
2578
    /**
2579
     * Get the number of users of the platform.
2580
     *
2581
     * @return int
2582
     */
2583
    public static function get_number_of_users_tracking_overview()
2584
    {
2585
        return UserManager::get_number_of_users(0, api_get_current_access_url_id());
2586
    }
2587
2588
    /**
2589
     * Get all the data for the sortable table of the reporting progress of
2590
     * all users and all the courses the user is subscribed to.
2591
     *
2592
     * @param int    $from
2593
     * @param int    $numberItems
2594
     * @param int    $column
2595
     * @param string $direction
2596
     *
2597
     * @return array
2598
     */
2599
    public static function get_user_data_tracking_overview($from, $numberItems, $column, $direction)
2600
    {
2601
        $isWestern = api_is_western_name_order();
2602
2603
        switch ($column) {
2604
            case '0':
2605
                $column = $isWestern ? 'firstname' : 'lastname';
2606
                break;
2607
        }
2608
2609
        $order = [
2610
            " `$column` $direction",
2611
        ];
2612
        $userList = UserManager::get_user_list([], $order, $from, $numberItems);
2613
        $return = [];
2614
        foreach ($userList as $user) {
2615
            $return[] = [
2616
                '0' => $user['user_id'],
2617
                'col0' => $user['user_id'],
2618
            ];
2619
        }
2620
2621
        return $return;
2622
    }
2623
2624
    /**
2625
     * Get all information that the user with user_id = $user_data has
2626
     * entered in the additionally defined profile fields.
2627
     *
2628
     * @param int $user_id the id of the user
2629
     *
2630
     * @return array
2631
     *
2632
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
2633
     *
2634
     * @version Dokeos 1.8.6
2635
     *
2636
     * @since November 2008
2637
     */
2638
    public static function get_user_overview_export_extra_fields($user_id)
2639
    {
2640
        // include the user manager
2641
        $data = UserManager::get_extra_user_data($user_id, true);
2642
2643
        return $data;
2644
    }
2645
2646
    /**
2647
     * Checks if a username exist in the DB otherwise it create a "double"
2648
     * i.e. if we look into for jmontoya but the user's name already exist we create the user jmontoya2
2649
     * the return array will be array(username=>'jmontoya', sufix='2').
2650
     *
2651
     * @param string firstname
2652
     * @param string lastname
2653
     * @param string username
2654
     *
2655
     * @return array with the username, the sufix
2656
     *
2657
     * @author Julio Montoya
2658
     */
2659
    public static function make_username($firstname, $lastname, $username, $language = null, $encoding = null)
2660
    {
2661
        // if username exist
2662
        if (!UserManager::is_username_available($username) || empty($username)) {
2663
            $i = 0;
2664
            while (1) {
2665
                if (0 == $i) {
2666
                    $sufix = '';
2667
                } else {
2668
                    $sufix = $i;
2669
                }
2670
                $desired_username = UserManager::create_username(
2671
                    $firstname,
2672
                    $lastname
2673
                );
2674
                if (UserManager::is_username_available($desired_username.$sufix)) {
2675
                    break;
2676
                } else {
2677
                    $i++;
2678
                }
2679
            }
2680
            $username_array = ['username' => $desired_username, 'sufix' => $sufix];
2681
2682
            return $username_array;
2683
        } else {
2684
            $username_array = ['username' => $username, 'sufix' => ''];
2685
2686
            return $username_array;
2687
        }
2688
    }
2689
2690
    /**
2691
     * Checks if there are repeted users in a given array.
2692
     *
2693
     * @param array $usernames  list of the usernames in the uploaded file
2694
     * @param array $user_array $user_array['username'] and $user_array['sufix']
2695
     *                          where suffix is the number part in a login i.e -> jmontoya2
2696
     *
2697
     * @return array with the $usernames array and the $user_array array
2698
     *
2699
     * @author Julio Montoya
2700
     */
2701
    public static function check_user_in_array($usernames, $user_array)
2702
    {
2703
        $user_list = array_keys($usernames);
2704
        $username = $user_array['username'].$user_array['sufix'];
2705
2706
        if (in_array($username, $user_list)) {
2707
            $user_array['sufix'] += $usernames[$username];
2708
            $usernames[$username]++;
2709
        } else {
2710
            $usernames[$username] = 1;
2711
        }
2712
        $result_array = [$usernames, $user_array];
2713
2714
        return $result_array;
2715
    }
2716
2717
    /**
2718
     * Checks whether a username has been already subscribed in a session.
2719
     *
2720
     * @param string $username    a given username
2721
     * @param array  $course_list the array with the course list id
2722
     * @param int    $id_session  the session id
2723
     *
2724
     * @return int 0 if the user is not subscribed otherwise it returns the user_id of the given username
2725
     *
2726
     * @author Julio Montoya
2727
     */
2728
    public static function user_available_in_session($username, $course_list, $id_session)
2729
    {
2730
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
2731
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2732
        $id_session = (int) $id_session;
2733
        $username = Database::escape_string($username);
2734
        foreach ($course_list as $courseId) {
2735
            $courseId = (int) $courseId;
2736
            $sql = " SELECT u.id as user_id FROM $tbl_session_rel_course_rel_user rel
2737
                     INNER JOIN $table_user u
2738
                     ON (rel.user_id = u.id)
2739
                     WHERE
2740
                        rel.session_id='$id_session' AND
2741
                        u.status='5' AND
2742
                        u.username ='$username' AND
2743
                        rel.c_id='$courseId'";
2744
            $rs = Database::query($sql);
2745
            if (Database::num_rows($rs) > 0) {
2746
                return Database::result($rs, 0, 0);
2747
            }
2748
        }
2749
2750
        return 0;
2751
    }
2752
2753
    /**
2754
     * This function checks whether some users in the uploaded file
2755
     * repeated and creates unique usernames if necesary.
2756
     * A case: Within the file there is an user repeted twice (Julio Montoya / Julio Montoya)
2757
     * and the username fields are empty.
2758
     * Then, this function would create unique usernames based on the first and the last name.
2759
     * Two users wiould be created - jmontoya and jmontoya2.
2760
     * Of course, if in the database there is a user with the name jmontoya,
2761
     * the newly created two users registered would be jmontoya2 and jmontoya3.
2762
     *
2763
     * @param $users list of users
2764
     *
2765
     * @return array
2766
     *
2767
     * @author Julio Montoya Armas
2768
     */
2769
    public static function check_all_usernames($users, $course_list, $id_session)
2770
    {
2771
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
2772
        $usernames = [];
2773
        $new_users = [];
2774
        foreach ($users as $index => $user) {
2775
            $desired_username = [];
2776
            if (empty($user['UserName'])) {
2777
                $desired_username = self::make_username($user['FirstName'], $user['LastName'], '');
2778
                $pre_username = $desired_username['username'].$desired_username['sufix'];
2779
                $user['UserName'] = $pre_username;
2780
                $user['create'] = '1';
2781
            } else {
2782
                if (UserManager::is_username_available($user['UserName'])) {
2783
                    $desired_username = self::make_username($user['FirstName'], $user['LastName'], $user['UserName']);
2784
                    $user['UserName'] = $desired_username['username'].$desired_username['sufix'];
2785
                    $user['create'] = '1';
2786
                } else {
2787
                    $is_session_avail = self::user_available_in_session($user['UserName'], $course_list, $id_session);
2788
                    if (0 == $is_session_avail) {
2789
                        $user_name = $user['UserName'];
2790
                        $sql_select = "SELECT user_id FROM $table_user WHERE username ='$user_name' ";
2791
                        $rs = Database::query($sql_select);
2792
                        $user['create'] = Database::result($rs, 0, 0);
2793
                    } else {
2794
                        $user['create'] = $is_session_avail;
2795
                    }
2796
                }
2797
            }
2798
            // Usernames is the current list of users in the file.
2799
            $result_array = self::check_user_in_array($usernames, $desired_username);
2800
            $usernames = $result_array[0];
2801
            $desired_username = $result_array[1];
2802
            $user['UserName'] = $desired_username['username'].$desired_username['sufix'];
2803
            $new_users[] = $user;
2804
        }
2805
2806
        return $new_users;
2807
    }
2808
2809
    /**
2810
     * This functions checks whether there are users that are already
2811
     * registered in the DB by different creator than the current coach.
2812
     *
2813
     * @param array $users
2814
     *
2815
     * @return array
2816
     *
2817
     * @author Julio Montoya Armas
2818
     */
2819
    public static function get_user_creator($users)
2820
    {
2821
        $errors = [];
2822
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
2823
        foreach ($users as $index => $user) {
2824
            $username = Database::escape_string($user['UserName']);
2825
            $sql = "SELECT creator_id FROM $table_user WHERE username='$username' ";
2826
2827
            $rs = Database::query($sql);
2828
            $creator_id = Database::result($rs, 0, 0);
2829
            // check if we are the creators or not
2830
            if ('' != $creator_id) {
2831
                if ($creator_id != api_get_user_id()) {
2832
                    $user['error'] = get_lang('User already register by other coach.');
2833
                    $errors[] = $user;
2834
                }
2835
            }
2836
        }
2837
2838
        return $errors;
2839
    }
2840
2841
    /**
2842
     * Validates imported data.
2843
     *
2844
     * @param array $users list of users
2845
     */
2846
    public static function validate_data($users, $id_session = null)
2847
    {
2848
        $errors = [];
2849
        $new_users = [];
2850
        foreach ($users as $index => $user) {
2851
            // 1. Check whether mandatory fields are set.
2852
            $mandatory_fields = ['LastName', 'FirstName'];
2853
            if ('true' == api_get_setting('registration', 'email')) {
2854
                $mandatory_fields[] = 'Email';
2855
            }
2856
2857
            foreach ($mandatory_fields as $key => $field) {
2858
                if (!isset($user[$field]) || 0 == strlen($user[$field])) {
2859
                    $user['error'] = get_lang($field.'Mandatory');
2860
                    $errors[] = $user;
2861
                }
2862
            }
2863
            // 2. Check whether the username is too long.
2864
            if (UserManager::is_username_too_long($user['UserName'])) {
2865
                $user['error'] = get_lang('This login is too long');
2866
                $errors[] = $user;
2867
            }
2868
2869
            $user['UserName'] = trim($user['UserName']);
2870
2871
            if (empty($user['UserName'])) {
2872
                $user['UserName'] = UserManager::create_username($user['FirstName'], $user['LastName']);
2873
            }
2874
            $new_users[] = $user;
2875
        }
2876
        $results = ['errors' => $errors, 'users' => $new_users];
2877
2878
        return $results;
2879
    }
2880
2881
    /**
2882
     * Adds missing user-information (which isn't required, like password, etc).
2883
     */
2884
    public static function complete_missing_data($user)
2885
    {
2886
        // 1. Generate a password if it is necessary.
2887
        if (!isset($user['Password']) || 0 == strlen($user['Password'])) {
2888
            $user['Password'] = api_generate_password();
2889
        }
2890
2891
        return $user;
2892
    }
2893
2894
    /**
2895
     * Saves imported data.
2896
     */
2897
    public static function save_data($users, $course_list, $id_session)
2898
    {
2899
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
2900
        $tbl_session_rel_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
2901
        $tbl_session_rel_course_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
2902
        $tbl_session_rel_user = Database::get_main_table(TABLE_MAIN_SESSION_USER);
2903
2904
        $id_session = (int) $id_session;
2905
        $sendMail = $_POST['sendMail'] ? 1 : 0;
2906
2907
        // Adding users to the platform.
2908
        $new_users = [];
2909
        foreach ($users as $index => $user) {
2910
            $user = self::complete_missing_data($user);
2911
            // coach only will registered users
2912
            $default_status = STUDENT;
2913
            if (COURSEMANAGER == $user['create']) {
2914
                $user['id'] = UserManager:: create_user(
2915
                    $user['FirstName'],
2916
                    $user['LastName'],
2917
                    $default_status,
2918
                    $user['Email'],
2919
                    $user['UserName'],
2920
                    $user['Password'],
2921
                    $user['OfficialCode'],
2922
                    api_get_setting('PlatformLanguage'),
2923
                    $user['PhoneNumber']
2924
                );
2925
                $user['added_at_platform'] = 1;
2926
            } else {
2927
                $user['id'] = $user['create'];
2928
                $user['added_at_platform'] = 0;
2929
            }
2930
            $new_users[] = $user;
2931
        }
2932
        // Update user list.
2933
        $users = $new_users;
2934
2935
        // Inserting users.
2936
        SessionManager::insertUsersInCourses(
2937
            array_column($users, 'id'),
2938
            $course_list,
2939
            $id_session
2940
        );
2941
2942
        array_walk(
2943
            $users,
2944
            function (array &$user) {
2945
                $user['added_at_session'] = 1;
2946
            }
2947
        );
2948
2949
        $registered_users = get_lang('File imported').'<br /> Import file results : <br />';
2950
        // Sending emails.
2951
        $addedto = '';
2952
        if ($sendMail) {
2953
            foreach ($users as $index => $user) {
2954
                $emailsubject = '['.api_get_setting('siteName').'] '.get_lang('Your registration on').' '.api_get_setting('siteName');
2955
                $emailbody = get_lang('Dear').' '.
2956
                    api_get_person_name($user['First name'], $user['Last name']).",\n\n".
2957
                    get_lang('You are registered to')." ".api_get_setting('siteName')." ".get_lang('with the following settings:')."\n\n".
2958
                    get_lang('Username')." : $user[UserName]\n".
2959
                    get_lang('Pass')." : $user[Password]\n\n".
2960
                    get_lang('The address of')." ".api_get_setting('siteName')." ".get_lang('is')." : ".api_get_path(WEB_PATH)." \n\n".
2961
                    get_lang('In case of trouble, contact us.')."\n\n".
2962
                    get_lang('Sincerely').",\n\n".
2963
                    api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'))."\n".
2964
                    get_lang('Administrator')." ".api_get_setting('siteName')."\nT. ".
2965
                    api_get_setting('administratorTelephone')."\n".get_lang('E-mail')." : ".api_get_setting('emailAdministrator');
2966
2967
                api_mail_html(
2968
                    api_get_person_name($user['First name'], $user['Last name'], null, PERSON_NAME_EMAIL_ADDRESS),
2969
                    $user['e-mail'],
2970
                    $emailsubject,
2971
                    $emailbody
2972
                );
2973
                $userInfo = api_get_user_info($user['id']);
2974
2975
                if ((1 == $user['added_at_platform'] && 1 == $user['added_at_session']) || 1 == $user['added_at_session']) {
2976
                    if (1 == $user['added_at_platform']) {
2977
                        $addedto = get_lang('User created in portal');
2978
                    } else {
2979
                        $addedto = '          ';
2980
                    }
2981
2982
                    if (1 == $user['added_at_session']) {
2983
                        $addedto .= get_lang('User added into the session');
2984
                    }
2985
                } else {
2986
                    $addedto = get_lang('User not added.');
2987
                }
2988
2989
                $registered_users .= UserManager::getUserProfileLink($userInfo).' - '.$addedto.'<br />';
2990
            }
2991
        } else {
2992
            foreach ($users as $index => $user) {
2993
                $userInfo = api_get_user_info($user['id']);
2994
                if ((1 == $user['added_at_platform'] && 1 == $user['added_at_session']) || 1 == $user['added_at_session']) {
2995
                    if (1 == $user['added_at_platform']) {
2996
                        $addedto = get_lang('User created in portal');
2997
                    } else {
2998
                        $addedto = '          ';
2999
                    }
3000
3001
                    if (1 == $user['added_at_session']) {
3002
                        $addedto .= ' '.get_lang('User added into the session');
3003
                    }
3004
                } else {
3005
                    $addedto = get_lang('User not added.');
3006
                }
3007
                $registered_users .= "<a href=\"../user/userInfo.php?uInfo=".$user['id']."\">".
3008
                    Security::remove_XSS($userInfo['complete_user_name'])."</a> - ".$addedto.'<br />';
3009
            }
3010
        }
3011
        Display::addFlash(Display::return_message($registered_users, 'normal', false));
3012
        header('Location: course.php?id_session='.$id_session);
3013
        exit;
3014
    }
3015
3016
    /**
3017
     * Reads CSV-file.
3018
     *
3019
     * @param string $file Path to the CSV-file
3020
     *
3021
     * @return array All userinformation read from the file
3022
     */
3023
    public static function parse_csv_data($file)
3024
    {
3025
        $users = Import::csvToArray($file);
3026
        foreach ($users as $index => $user) {
3027
            if (isset($user['Courses'])) {
3028
                $user['Courses'] = explode('|', trim($user['Courses']));
3029
            }
3030
            $users[$index] = $user;
3031
        }
3032
3033
        return $users;
3034
    }
3035
3036
    /**
3037
     * Reads XML-file.
3038
     *
3039
     * @param string $file Path to the XML-file
3040
     *
3041
     * @return array All userinformation read from the file
3042
     */
3043
    public static function parse_xml_data($file)
3044
    {
3045
        $crawler = new \Symfony\Component\DomCrawler\Crawler();
3046
        $crawler->addXmlContent(file_get_contents($file));
3047
        $crawler = $crawler->filter('Contacts > Contact ');
3048
        $array = [];
3049
        foreach ($crawler as $domElement) {
3050
            $row = [];
3051
            foreach ($domElement->childNodes as $node) {
3052
                if ('#text' != $node->nodeName) {
3053
                    $row[$node->nodeName] = $node->nodeValue;
3054
                }
3055
            }
3056
            if (!empty($row)) {
3057
                $array[] = $row;
3058
            }
3059
        }
3060
3061
        return $array;
3062
    }
3063
3064
    /**
3065
     * @param int $courseId
3066
     * @param int $sessionId
3067
     * @param int $studentId
3068
     */
3069
    public static function displayTrackingAccessOverView(
3070
        $courseId,
3071
        $sessionId,
3072
        $studentId,
3073
        $perPage = 20,
3074
        $dates = null
3075
    ) {
3076
        $courseId = (int) $courseId;
3077
        $sessionId = (int) $sessionId;
3078
        $studentId = (int) $studentId;
3079
3080
        $courseList = [];
3081
        $sessionList = [];
3082
        $studentList = [];
3083
3084
        if (!empty($courseId)) {
3085
            $course = api_get_course_entity($courseId);
3086
            if ($course) {
3087
                $courseList[$course->getId()] = $course->getTitle();
3088
            }
3089
        }
3090
3091
        if (!empty($sessionId)) {
3092
            $session = api_get_session_entity($sessionId);
3093
            if ($session) {
3094
                $sessionList[$session->getId()] = $session->getTitle();
3095
            }
3096
        }
3097
3098
        if (!empty($studentId)) {
3099
            $student = api_get_user_entity($studentId);
3100
            if ($student) {
3101
                $studentList[$student->getId()] = UserManager::formatUserFullName($student);
3102
            }
3103
        }
3104
3105
        $form = new FormValidator('access_overview', 'GET');
3106
        $form->addElement(
3107
            'select_ajax',
3108
            'course_id',
3109
            get_lang('Search courses'),
3110
            $courseList,
3111
            [
3112
                'url' => api_get_path(WEB_AJAX_PATH).'course.ajax.php?'.http_build_query([
3113
                    'a' => 'search_course_by_session_all',
3114
                    'session_id' => $sessionId,
3115
                    'course_id' => $courseId,
3116
                ]),
3117
            ]
3118
        );
3119
3120
        $form->addElement(
3121
            'select_ajax',
3122
            'session_id',
3123
            get_lang('Search sessions'),
3124
            $sessionList,
3125
            [
3126
                'url_function' => "
3127
                    function () {
3128
                        var params = $.param({
3129
                            a: 'search_session_by_course',
3130
                            course_id: $('#access_overview_course_id').val() || 0
3131
                        });
3132
3133
                        return '".api_get_path(WEB_AJAX_PATH)."session.ajax.php?' + params;
3134
                    }
3135
                ",
3136
            ]
3137
        );
3138
3139
        $form->addSelect(
3140
            'profile',
3141
            get_lang('Profile'),
3142
            [
3143
                '' => get_lang('Select'),
3144
                STUDENT => get_lang('Learner'),
3145
                COURSEMANAGER => get_lang('Teacher'),
3146
                DRH => get_lang('Human Resources Manager'),
3147
            ],
3148
            ['id' => 'profile']
3149
        );
3150
3151
        $form->addElement(
3152
            'select_ajax',
3153
            'student_id',
3154
            get_lang('Search users'),
3155
            $studentList,
3156
            [
3157
                'placeholder' => get_lang('All'),
3158
                'url_function' => "
3159
                    function () {
3160
                        var params = $.param({
3161
                            a: 'search_user_by_course',
3162
                            session_id: $('#access_overview_session_id').val(),
3163
                            course_id: $('#access_overview_course_id').val()
3164
                        });
3165
3166
                        return '".api_get_path(WEB_AJAX_PATH)."course.ajax.php?' + params;
3167
                    }
3168
                ",
3169
            ]
3170
        );
3171
        $form->addDateRangePicker(
3172
            'date',
3173
            get_lang('Date range'),
3174
            true,
3175
            [
3176
                'id' => 'date_range',
3177
                'format' => 'YYYY-MM-DD HH:mm',
3178
                'timePicker' => 'true',
3179
            ]
3180
        );
3181
        $form->addHidden('display', 'accessoverview');
3182
        $form->addRule('course_id', get_lang('Required'), 'required');
3183
        $form->addRule('profile', get_lang('Required'), 'required');
3184
        $form->addButton('submit', get_lang('Generate'), 'gear', 'primary');
3185
3186
        $table = null;
3187
        if (!empty($dates)) {
3188
            $table = new SortableTable(
3189
                'tracking_access_overview',
3190
                ['MySpace', 'getNumberOfTrackAccessOverview'],
3191
                ['MySpace', 'getUserDataAccessTrackingOverview'],
3192
                0,
3193
                $perPage
3194
            );
3195
            $table->set_additional_parameters(
3196
                [
3197
                    'course_id' => $courseId,
3198
                    'session_id' => $sessionId,
3199
                    'student_id' => $studentId,
3200
                    'date' => $dates,
3201
                    'tracking_access_overview_per_page' => $perPage,
3202
                    'display' => 'accessoverview',
3203
                ]
3204
            );
3205
            $table->set_header(0, get_lang('Login date'), true);
3206
            $table->set_header(1, get_lang('Username'), true);
3207
            if (api_is_western_name_order()) {
3208
                $table->set_header(2, get_lang('First name'), true);
3209
                $table->set_header(3, get_lang('Last name'), true);
3210
            } else {
3211
                $table->set_header(2, get_lang('Last name'), true);
3212
                $table->set_header(3, get_lang('First name'), true);
3213
            }
3214
            $table->set_header(4, get_lang('IP'), false);
3215
            $table->set_header(5, get_lang('Time connected (hh:mm)'), false);
3216
        }
3217
3218
        $template = new Template(
3219
            null,
3220
            false,
3221
            false,
3222
            false,
3223
            false,
3224
            false,
3225
            false
3226
        );
3227
        $template->assign('form', $form->returnForm());
3228
        $template->assign('table', $table ? $table->return_table() : null);
3229
3230
        echo $template->fetch(
3231
            $template->get_template('my_space/accessoverview.tpl')
3232
        );
3233
    }
3234
3235
    /**
3236
     * @return int
3237
     */
3238
    public static function getNumberOfTrackAccessOverview()
3239
    {
3240
        $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
3241
        $sql = "SELECT COUNT(course_access_id) count FROM $table";
3242
        $result = Database::query($sql);
3243
        $row = Database::fetch_assoc($result);
3244
3245
        if ($row) {
3246
            return $row['count'];
3247
        }
3248
3249
        return 0;
3250
    }
3251
3252
    /**
3253
     * @param $from
3254
     * @param $numberItems
3255
     * @param $column
3256
     * @param $orderDirection
3257
     *
3258
     * @return array
3259
     */
3260
    public static function getUserDataAccessTrackingOverview(
3261
        $from,
3262
        $numberItems,
3263
        $column,
3264
        $orderDirection
3265
    ) {
3266
        $from = (int) $from;
3267
        $numberItems = (int) $numberItems;
3268
        $column = (int) $column;
3269
        $orderDirection = Database::escape_string($orderDirection);
3270
        $orderDirection = !in_array(strtolower(trim($orderDirection)), ['asc', 'desc']) ? 'asc' : $orderDirection;
3271
3272
        $user = Database::get_main_table(TABLE_MAIN_USER);
3273
        $course = Database::get_main_table(TABLE_MAIN_COURSE);
3274
        $track_e_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
3275
        $trackCourseAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
3276
3277
        global $export_csv;
3278
        $is_western_name_order = api_is_western_name_order();
3279
        if ($export_csv) {
3280
            $is_western_name_order = api_is_western_name_order(PERSON_NAME_DATA_EXPORT);
3281
        }
3282
3283
        //TODO add course name
3284
        $sql = "SELECT
3285
                a.login_course_date as col0,
3286
                u.username as col1,
3287
                ".(
3288
                    $is_western_name_order ? "
3289
                        u.firstname AS col2,
3290
                        u.lastname AS col3,
3291
                    " : "
3292
                        u.lastname AS col2,
3293
                        u.firstname AS col3,
3294
                "
3295
        )."
3296
                a.login_course_date,
3297
                a.logout_course_date,
3298
                c.title,
3299
                c.code,
3300
                u.id as user_id,
3301
                user_ip
3302
            FROM $trackCourseAccess a
3303
            INNER JOIN $user u
3304
            ON a.user_id = u.id
3305
            INNER JOIN $course c
3306
            ON a.c_id = c.id
3307
            WHERE 1=1 ";
3308
3309
        $sql = self::getDataAccessTrackingFilters($sql);
3310
3311
        $sql .= " ORDER BY col$column $orderDirection ";
3312
        $sql .= " LIMIT $from,$numberItems";
3313
3314
        $result = Database::query($sql);
3315
3316
        $data = [];
3317
        while ($user = Database::fetch_assoc($result)) {
3318
            $data[] = $user;
3319
        }
3320
3321
        $return = [];
3322
        //TODO: Dont use numeric index
3323
        foreach ($data as $key => $info) {
3324
            $return[] = [
3325
                api_get_local_time($info['login_course_date']),
3326
                $info['col1'],
3327
                $info['col2'],
3328
                $info['col3'],
3329
                $info['user_ip'],
3330
                gmdate('H:i:s', strtotime($info['logout_course_date']) - strtotime($info['login_course_date'])),
3331
            ];
3332
        }
3333
3334
        return $return;
3335
    }
3336
3337
    /**
3338
     * Gets the connections to a course as an array of login and logout time.
3339
     *
3340
     * @param int    $user_id
3341
     * @param array  $course_info
3342
     * @param int    $sessionId
3343
     * @param string $start_date
3344
     * @param string $end_date
3345
     * @param bool   $addUserIp
3346
     *
3347
     * @author  Jorge Frisancho Jibaja
3348
     * @author  Julio Montoya <[email protected]> fixing the function
3349
     *
3350
     * @version OCT-22- 2010
3351
     *
3352
     * @return array
3353
     */
3354
    public static function get_connections_to_course_by_date(
3355
        $user_id,
3356
        $course_info,
3357
        $sessionId,
3358
        $start_date,
3359
        $end_date,
3360
        $addUserIp = false
3361
    ) {
3362
        $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
3363
        $user_id = (int) $user_id;
3364
        $connections = [];
3365
        if (!empty($course_info)) {
3366
            $courseId = (int) $course_info['real_id'];
3367
            $end_date = self::add_day_to($end_date);
3368
3369
            $start_date = Database::escape_string($start_date);
3370
            $end_date = Database::escape_string($end_date);
3371
            $sessionCondition = api_get_session_condition($sessionId);
3372
            $sql = "SELECT
3373
                        login_course_date,
3374
                        logout_course_date,
3375
                        TIMESTAMPDIFF(SECOND, login_course_date, logout_course_date) duration,
3376
                        user_ip
3377
                    FROM $table
3378
                    WHERE
3379
                        user_id = $user_id AND
3380
                        c_id = $courseId AND
3381
                        login_course_date BETWEEN '$start_date' AND '$end_date' AND
3382
                        logout_course_date BETWEEN '$start_date' AND '$end_date'
3383
                        $sessionCondition
3384
                    ORDER BY login_course_date ASC";
3385
            $rs = Database::query($sql);
3386
3387
            while ($row = Database::fetch_array($rs)) {
3388
                $item = [
3389
                    'login' => $row['login_course_date'],
3390
                    'logout' => $row['logout_course_date'],
3391
                    'duration' => $row['duration'],
3392
                ];
3393
                if ($addUserIp) {
3394
                    $item['user_ip'] = $row['user_ip'];
3395
                }
3396
                $connections[] = $item;
3397
            }
3398
        }
3399
3400
        return $connections;
3401
    }
3402
3403
    /**
3404
     * @param int   $user_id
3405
     * @param array $course_info
3406
     * @param int   $sessionId
3407
     * @param null  $start_date
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $start_date is correct as it would always require null to be passed?
Loading history...
3408
     * @param null  $end_date
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $end_date is correct as it would always require null to be passed?
Loading history...
3409
     *
3410
     * @return array
3411
     */
3412
    public static function getStats($user_id, $course_info, $sessionId, $start_date = null, $end_date = null)
3413
    {
3414
        $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
3415
        $result = [];
3416
        if (!empty($course_info)) {
3417
            $stringStartDate = '';
3418
            $stringEndDate = '';
3419
            if (null != $start_date && null != $end_date) {
3420
                $end_date = self::add_day_to($end_date);
3421
3422
                $start_date = Database::escape_string($start_date);
3423
                $end_date = Database::escape_string($end_date);
3424
3425
                $stringStartDate = "AND login_course_date BETWEEN '$start_date' AND '$end_date'";
3426
                $stringEndDate = "AND logout_course_date BETWEEN '$start_date' AND '$end_date'";
3427
            }
3428
            $user_id = (int) $user_id;
3429
            $courseId = (int) $course_info['real_id'];
3430
            $sessionCondition = api_get_session_condition($sessionId);
3431
            $sql = "SELECT
3432
                SEC_TO_TIME(AVG(time_to_sec(timediff(logout_course_date,login_course_date)))) as avrg,
3433
                SEC_TO_TIME(SUM(time_to_sec(timediff(logout_course_date,login_course_date)))) as total,
3434
                count(user_id) as times
3435
                FROM $table
3436
                WHERE
3437
                    user_id = $user_id AND
3438
                    c_id = $courseId $stringStartDate $stringEndDate
3439
                    $sessionCondition
3440
                ORDER BY login_course_date ASC";
3441
3442
            $rs = Database::query($sql);
3443
            if ($row = Database::fetch_array($rs)) {
3444
                $foo_avg = $row['avrg'];
3445
                $foo_total = $row['total'];
3446
                $foo_times = $row['times'];
3447
                $result = [
3448
                'avg' => $foo_avg,
3449
                'total' => $foo_total,
3450
                'times' => $foo_times,
3451
            ];
3452
            }
3453
        }
3454
3455
        return $result;
3456
    }
3457
3458
    public static function add_day_to($end_date)
3459
    {
3460
        $foo_date = strtotime($end_date);
3461
        $foo_date = strtotime(' +1 day', $foo_date);
3462
        $foo_date = date('Y-m-d', $foo_date);
3463
3464
        return $foo_date;
3465
    }
3466
3467
    /**
3468
     * This function draw the graphic to be displayed on the user view as an image.
3469
     *
3470
     * @param array  $sql_result
3471
     * @param string $start_date
3472
     * @param string $end_date
3473
     * @param string $type
3474
     *
3475
     * @author Jorge Frisancho Jibaja
3476
     *
3477
     * @version OCT-22- 2010
3478
     *
3479
     * @return string
3480
     */
3481
    public static function grapher($sql_result, $start_date, $end_date, $type = '')
3482
    {
3483
        if (empty($start_date)) {
3484
            $start_date = '';
3485
        }
3486
        if (empty($end_date)) {
3487
            $end_date = '';
3488
        }
3489
        if ('' == $type) {
3490
            $type = 'day';
3491
        }
3492
        $main_year = $main_month_year = $main_day = [];
3493
3494
        $period = new DatePeriod(
3495
        new DateTime($start_date),
3496
        new DateInterval('P1D'),
3497
        new DateTime($end_date)
3498
    );
3499
3500
        foreach ($period as $date) {
3501
            $main_day[$date->format('d-m-Y')] = 0;
3502
        }
3503
3504
        $period = new DatePeriod(
3505
        new DateTime($start_date),
3506
        new DateInterval('P1M'),
3507
        new DateTime($end_date)
3508
    );
3509
3510
        foreach ($period as $date) {
3511
            $main_month_year[$date->format('m-Y')] = 0;
3512
        }
3513
3514
        $i = 0;
3515
        if (is_array($sql_result) && count($sql_result) > 0) {
3516
            foreach ($sql_result as $key => $data) {
3517
                $login = api_strtotime($data['login']);
3518
                $logout = api_strtotime($data['logout']);
3519
                //creating the main array
3520
                if (isset($main_month_year[date('m-Y', $login)])) {
3521
                    $main_month_year[date('m-Y', $login)] += (float) ($logout - $login) / 60;
3522
                }
3523
                if (isset($main_day[date('d-m-Y', $login)])) {
3524
                    $main_day[date('d-m-Y', $login)] += (float) ($logout - $login) / 60;
3525
                }
3526
                if ($i > 500) {
3527
                    break;
3528
                }
3529
                $i++;
3530
            }
3531
            switch ($type) {
3532
            case 'day':
3533
                $main_date = $main_day;
3534
                break;
3535
            case 'month':
3536
                $main_date = $main_month_year;
3537
                break;
3538
            case 'year':
3539
                $main_date = $main_year;
3540
                break;
3541
        }
3542
3543
            $labels = array_keys($main_date);
3544
            if (1 == count($main_date)) {
3545
                $labels = $labels[0];
3546
                $main_date = $main_date[$labels];
3547
            }
3548
3549
            /* Create and populate the pData object */
3550
            $myData = new pData();
3551
            $myData->addPoints($main_date, 'Serie1');
3552
            if (1 != count($main_date)) {
3553
                $myData->addPoints($labels, 'Labels');
3554
                $myData->setSerieDescription('Labels', 'Months');
3555
                $myData->setAbscissa('Labels');
3556
            }
3557
            $myData->setSerieWeight('Serie1', 1);
3558
            $myData->setSerieDescription('Serie1', get_lang('My results'));
3559
            $myData->setAxisName(0, get_lang('Minutes'));
3560
            $myData->loadPalette(api_get_path(SYS_CODE_PATH).'palettes/pchart/default.color', true);
3561
3562
            // Cache definition
3563
            $cachePath = api_get_path(SYS_ARCHIVE_PATH);
3564
            $myCache = new pCache(['CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)]);
3565
            $chartHash = $myCache->getHash($myData);
3566
3567
            if ($myCache->isInCache($chartHash)) {
3568
                //if we already created the img
3569
                $imgPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
3570
                $myCache->saveFromCache($chartHash, $imgPath);
3571
                $imgPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
3572
            } else {
3573
                /* Define width, height and angle */
3574
                $mainWidth = 760;
3575
                $mainHeight = 230;
3576
                $angle = 50;
3577
3578
                /* Create the pChart object */
3579
                $myPicture = new pImage($mainWidth, $mainHeight, $myData);
3580
3581
                /* Turn of Antialiasing */
3582
                $myPicture->Antialias = false;
3583
                /* Draw the background */
3584
                $settings = ["R" => 255, "G" => 255, "B" => 255];
3585
                $myPicture->drawFilledRectangle(0, 0, $mainWidth, $mainHeight, $settings);
3586
3587
                /* Add a border to the picture */
3588
                $myPicture->drawRectangle(
3589
                0,
3590
                0,
3591
                $mainWidth - 1,
3592
                $mainHeight - 1,
3593
                ["R" => 0, "G" => 0, "B" => 0]
3594
            );
3595
3596
                /* Set the default font */
3597
                $myPicture->setFontProperties(
3598
                [
3599
                    "FontName" => api_get_path(SYS_FONTS_PATH).'opensans/OpenSans-Regular.ttf',
3600
                    "FontSize" => 10, ]
3601
            );
3602
                /* Write the chart title */
3603
                $myPicture->drawText(
3604
                $mainWidth / 2,
3605
                30,
3606
                get_lang('Time spent in the course'),
3607
                [
3608
                    "FontSize" => 12,
3609
                    "Align" => TEXT_ALIGN_BOTTOMMIDDLE,
3610
                ]
3611
            );
3612
3613
                /* Set the default font */
3614
                $myPicture->setFontProperties(
3615
                [
3616
                    "FontName" => api_get_path(SYS_FONTS_PATH).'opensans/OpenSans-Regular.ttf',
3617
                    "FontSize" => 8,
3618
                ]
3619
            );
3620
3621
                /* Define the chart area */
3622
                $myPicture->setGraphArea(50, 40, $mainWidth - 40, $mainHeight - 80);
3623
3624
                /* Draw the scale */
3625
                $scaleSettings = [
3626
                'XMargin' => 10,
3627
                'YMargin' => 10,
3628
                'Floating' => true,
3629
                'GridR' => 200,
3630
                'GridG' => 200,
3631
                'GridB' => 200,
3632
                'DrawSubTicks' => true,
3633
                'CycleBackground' => true,
3634
                'LabelRotation' => $angle,
3635
                'Mode' => SCALE_MODE_ADDALL_START0,
3636
            ];
3637
                $myPicture->drawScale($scaleSettings);
3638
3639
                /* Turn on Antialiasing */
3640
                $myPicture->Antialias = true;
3641
3642
                /* Enable shadow computing */
3643
                $myPicture->setShadow(
3644
                true,
3645
                [
3646
                    "X" => 1,
3647
                    "Y" => 1,
3648
                    "R" => 0,
3649
                    "G" => 0,
3650
                    "B" => 0,
3651
                    "Alpha" => 10,
3652
                ]
3653
            );
3654
3655
                /* Draw the line chart */
3656
                $myPicture->setFontProperties(
3657
                [
3658
                    "FontName" => api_get_path(SYS_FONTS_PATH).'opensans/OpenSans-Regular.ttf',
3659
                    "FontSize" => 10,
3660
                ]
3661
            );
3662
                $myPicture->drawSplineChart();
3663
                $myPicture->drawPlotChart(
3664
                [
3665
                    "DisplayValues" => true,
3666
                    "PlotBorder" => true,
3667
                    "BorderSize" => 1,
3668
                    "Surrounding" => -60,
3669
                    "BorderAlpha" => 80,
3670
                ]
3671
            );
3672
3673
                /* Do NOT Write the chart legend */
3674
3675
                /* Write and save into cache */
3676
                $myCache->writeToCache($chartHash, $myPicture);
3677
                $imgPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
3678
                $myCache->saveFromCache($chartHash, $imgPath);
3679
                $imgPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
3680
            }
3681
3682
            return '<img src="'.$imgPath.'">';
3683
        } else {
3684
            return api_convert_encoding(
3685
                '<div id="messages" class="warning-message">'.get_lang('Graphic not available').'</div>',
3686
            'UTF-8'
3687
        );
3688
        }
3689
    }
3690
3691
    /**
3692
     * Gets a list of users who were enrolled in the lessons.
3693
     * It is necessary that in the extra field, a company is defined.
3694
     *
3695
     *  if lpId is different to 0, this search by lp id too
3696
     *
3697
     * @param string|null $startDate
3698
     * @param string|null $endDate
3699
     * @param int         $lpId
3700
     * @param bool        $whitCompany
3701
     *
3702
     * @return array
3703
     */
3704
    protected static function getCompanyLearnpathSubscription(
3705
        $startDate = null,
3706
        $endDate = null,
3707
        $lpId = 0,
3708
        $whitCompany = false
3709
    ) {
3710
        $tblItemProperty = Database::get_course_table(TABLE_ITEM_PROPERTY);
3711
        $tblLp = Database::get_course_table(TABLE_LP_MAIN);
3712
        $tblExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
3713
        $tblExtraFieldValue = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
3714
3715
        $whereCondition = '';
3716
3717
        //Validating dates
3718
        if (!empty($startDate)) {
3719
            $startDate = new DateTime($startDate);
3720
        }
3721
        if (!empty($endDate)) {
3722
            $endDate = new DateTime($endDate);
3723
        }
3724
        if (!empty($startDate) and !empty($endDate)) {
3725
            if ($startDate > $endDate) {
3726
                $dateTemp = $endDate;
3727
                $endDate = $startDate;
3728
                $startDate = $dateTemp;
3729
                unset($dateTemp);
3730
            }
3731
        }
3732
3733
        // Settings condition and parametter GET to right date
3734
        if (!empty($startDate)) {
3735
            $startDate = api_get_utc_datetime($startDate->setTime(0, 0, 0)->format('Y-m-d H:i:s'));
3736
            $_GET['startDate'] = $startDate;
3737
            $whereCondition .= "
3738
            AND $tblItemProperty.lastedit_date >= '$startDate' ";
3739
        }
3740
        if (!empty($endDate)) {
3741
            $endDate = api_get_utc_datetime($endDate->setTime(23, 59, 59)->format('Y-m-d H:i:s'));
3742
            $_GET['endDate'] = $endDate;
3743
            $whereCondition .= "
3744
            AND $tblItemProperty.lastedit_date <= '$endDate' ";
3745
        }
3746
        if (0 != $lpId) {
3747
            $whereCondition .= "
3748
            AND c_item_property.ref = $lpId ";
3749
        }
3750
3751
        $companys = [];
3752
        if (!empty($startDate) or !empty($endDate)) {
3753
            // get Compnay data
3754
            $selectToCompany = " (
3755
            SELECT
3756
                value
3757
            FROM
3758
                $tblExtraFieldValue
3759
            WHERE
3760
                field_id IN (
3761
                    SELECT
3762
                        id
3763
                    FROM
3764
                        $tblExtraField
3765
                    WHERE
3766
                        variable = 'company'
3767
                )
3768
            AND item_id = $tblItemProperty.to_user_id
3769
            ) ";
3770
            $query = "
3771
            SELECT
3772
                * ,
3773
                 $selectToCompany  as company,
3774
                    (
3775
                    SELECT
3776
                        name
3777
                    FROM
3778
                        $tblLp
3779
                    WHERE
3780
                    $tblLp.iid = c_item_property.ref
3781
                 ) as name_lp
3782
            FROM
3783
                $tblItemProperty
3784
            WHERE
3785
                c_id IN (
3786
                    SELECT
3787
                        c_id
3788
                    FROM
3789
                        ".TABLE_MAIN_COURSE_USER."
3790
                    WHERE
3791
                        STATUS = 5
3792
                )
3793
                AND lastedit_type = 'LearnpathSubscription'
3794
3795
                ";
3796
            // -- AND $selectToCompany IS NOT NULL
3797
            if (strlen($whereCondition) > 2) {
3798
                $query .= $whereCondition;
3799
            }
3800
            $queryResult = Database::query($query);
3801
            while ($row = Database::fetch_assoc($queryResult)) {
3802
                // $courseId = (int)$row['c_id'];
3803
                $studentId = (int) $row['to_user_id'];
3804
                $company = isset($row['company']) ? $row['company'] : '';
3805
                if ('' == $company) {
3806
                    $company = get_lang('No organization');
3807
                }
3808
                // $lpId = $row['ref'];
3809
                if (0 != $lpId && 0 != $studentId) {
3810
                    if (true == $whitCompany) {
3811
                        $companys[] = [
3812
                            'id' => $studentId,
3813
                            'company' => $company,
3814
                        ];
3815
                    } else {
3816
                        $companys[] = $studentId;
3817
                    }
3818
                } else {
3819
                    $companys[$company][] = $studentId;
3820
                    $companys[$company] = array_unique($companys[$company]);
3821
                }
3822
            }
3823
        }
3824
3825
        return $companys;
3826
    }
3827
3828
    private static function getDataAccessTrackingFilters($sql)
3829
    {
3830
        if (isset($_GET['course_id']) && !empty($_GET['course_id'])) {
3831
            $courseId = (int) $_GET['course_id'];
3832
            $sql .= " AND c.id = ".$courseId;
3833
        }
3834
3835
        if (isset($_GET['session_id']) && !empty($_GET['session_id'])) {
3836
            $sessionId = (int) $_GET['session_id'];
3837
            $sql .= " AND a.session_id = ".$sessionId;
3838
        }
3839
3840
        if (isset($_GET['student_id']) && !empty($_GET['student_id'])) {
3841
            $userId = (int) $_GET['student_id'];
3842
            $sql .= " AND u.id = ".$userId;
3843
        }
3844
3845
        $sql .= " AND u.status <> ".ANONYMOUS;
3846
3847
        if (isset($_GET['date']) && !empty($_GET['date'])) {
3848
            $dateRangePicker = new DateRangePicker('date', '', ['timePicker' => 'true']);
3849
            $dates = $dateRangePicker->parseDateRange($_GET['date']);
3850
            if (isset($dates['start']) && !empty($dates['start'])) {
3851
                $dates['start'] = Database::escape_string(api_get_utc_datetime($dates['start']));
3852
                $sql .= " AND login_course_date >= '".$dates['start']."'";
3853
            }
3854
            if (isset($dates['end']) && !empty($dates['end'])) {
3855
                $dates['end'] = Database::escape_string(api_get_utc_datetime($dates['end']));
3856
                $sql .= " AND logout_course_date <= '".$dates['end']."'";
3857
            }
3858
        }
3859
3860
        return $sql;
3861
    }
3862
}
3863