Issues (2128)

main/admin/statistics/index.php (2 issues)

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * This tool show global Statistics on general platform events.
7
 */
8
$cidReset = true;
9
10
require_once __DIR__.'/../../inc/global.inc.php';
11
api_protect_admin_script(true);
12
13
$interbreadcrumb[] = ['url' => '../index.php', 'name' => get_lang('PlatformAdmin')];
14
15
$report = $_REQUEST['report'] ?? '';
16
$sessionDuration = isset($_GET['session_duration']) ? (int) $_GET['session_duration'] : '';
17
$validated = false;
18
$sessionStatusAllowed = api_get_configuration_value('allow_session_status');
19
$invoicingMonth = isset($_GET['invoicing_month']) ? (int) $_GET['invoicing_month'] : '';
20
$invoicingYear = isset($_GET['invoicing_year']) ? (int) $_GET['invoicing_year'] : '';
21
$tool_name = get_lang('Statistics');
22
if (api_is_platform_admin()) {
23
    $tools = [
24
        get_lang('Courses') => [
25
            'report=courses' => get_lang('CountCours'),
26
            'report=tools' => get_lang('PlatformToolAccess'),
27
            'report=courselastvisit' => get_lang('LastAccess'),
28
            'report=coursebylanguage' => get_lang('CountCourseByLanguage'),
29
        ],
30
        get_lang('Users') => [
31
            'report=users' => get_lang('CountUsers'),
32
            'report=recentlogins' => get_lang('Logins'),
33
            'report=logins&amp;type=month' => get_lang('Logins').' ('.get_lang('PeriodMonth').')',
34
            'report=logins&amp;type=day' => get_lang('Logins').' ('.get_lang('PeriodDay').')',
35
            'report=logins&amp;type=hour' => get_lang('Logins').' ('.get_lang('PeriodHour').')',
36
            'report=pictures' => get_lang('CountUsers').' ('.get_lang('UserPicture').')',
37
            'report=logins_by_date' => get_lang('LoginsByDate'),
38
            'report=no_login_users' => get_lang('StatsUsersDidNotLoginInLastPeriods'),
39
            'report=zombies' => get_lang('Zombies'),
40
            'report=users_active' => get_lang('UserStats'),
41
            'report=users_online' => get_lang('UsersOnline'),
42
            'report=invoicing' => get_lang('InvoicingByAccessUrl'),
43
            'report=duplicated_users' => get_lang('DuplicatedUsers'),
44
            'report=duplicated_users_by_mail' => get_lang('DuplicatedUsersByMail'),
45
        ],
46
        get_lang('System') => [
47
            'report=activities' => get_lang('ImportantActivities'),
48
            'report=user_session' => get_lang('PortalUserSessionStats'),
49
            'report=courses_usage' => get_lang('CoursesUsage'),
50
            'report=quarterly_report' => get_lang('QuarterlyReport'),
51
        ],
52
        get_lang('Social') => [
53
            'report=messagereceived' => get_lang('MessagesReceived'),
54
            'report=messagesent' => get_lang('MessagesSent'),
55
            'report=friends' => get_lang('CountFriends'),
56
        ],
57
        get_lang('Session') => [
58
            'report=session_by_date' => get_lang('SessionsByDate'),
59
        ],
60
    ];
61
62
    if ('true' === api_get_plugin_setting('lti_provider', 'enabled')) {
63
        $tools[get_lang('Users')]['report=lti_tool_lp'] = get_lang('LearningPathLTI');
64
    }
65
} elseif (api_is_session_admin()) {
66
    $tools = [
67
        get_lang('Session') => [
68
            'report=session_by_date' => get_lang('SessionsByDate'),
69
        ],
70
    ];
71
}
72
73
// Get list of allowed reports based on role
74
$allowedReports = [];
75
foreach ($tools as $section => $items) {
76
    foreach ($items as $key => $label) {
77
        if (preg_match('/report=([a-zA-Z0-9_]+)/', $key, $matches)) {
78
            $allowedReports[] = $matches[1];
79
        }
80
    }
81
}
82
83
// Ensure current report is valid for this user, or default to first available
84
if (!in_array($report, $allowedReports)) {
85
    $report = reset($allowedReports);
86
}
87
88
if (
89
in_array(
90
    $report,
91
    ['recentlogins', 'tools', 'courses', 'coursebylanguage', 'users', 'users_active', 'session_by_date']
92
)
93
) {
94
    $htmlHeadXtra[] = api_get_js('chartjs/Chart.min.js');
95
    $htmlHeadXtra[] = api_get_asset('chartjs-plugin-labels/build/chartjs-plugin-labels.min.js');
96
97
    // Prepare variables for the JS charts
98
    $url = $reportName = $reportType = '';
99
    switch ($report) {
100
        case 'recentlogins':
101
            $url = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=recent_logins&session_duration='
102
                .$sessionDuration;
103
            $reportName = '';
104
            $reportType = 'line';
105
            $reportOptions = '';
106
            $htmlHeadXtra[] = Statistics::getJSChartTemplate($url, $reportType, $reportOptions);
107
            break;
108
        case 'tools':
109
            $url = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=tools_usage';
110
            $reportName = 'PlatformToolAccess';
111
            $reportType = 'pie';
112
            $reportOptions = '
113
                legend: {
114
                    position: "left"
115
                },
116
                title: {
117
                    text: "'.get_lang($reportName).'",
118
                    display: true
119
                },
120
                cutoutPercentage: 25
121
                ';
122
            $htmlHeadXtra[] = Statistics::getJSChartTemplate($url, $reportType, $reportOptions);
123
            break;
124
        case 'courses':
125
            $url = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=courses';
126
            $reportName = 'CountCours';
127
            $reportType = 'pie';
128
            $reportOptions = '
129
                legend: {
130
                    position: "left"
131
                },
132
                title: {
133
                    text: "'.get_lang($reportName).'",
134
                    display: true
135
                },
136
                cutoutPercentage: 25
137
                ';
138
            $htmlHeadXtra[] = Statistics::getJSChartTemplate($url, $reportType, $reportOptions);
139
            break;
140
        case 'coursebylanguage':
141
            $url = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?a=courses_by_language';
142
            $reportName = 'CountCourseByLanguage';
143
            $reportType = 'pie';
144
            $reportOptions = '
145
                legend: {
146
                    position: "left"
147
                },
148
                title: {
149
                    text: "'.get_lang($reportName).'",
150
                    display: true
151
                },
152
                cutoutPercentage: 25
153
                ';
154
            $htmlHeadXtra[] = Statistics::getJSChartTemplate($url, $reportType, $reportOptions);
155
            break;
156
        case 'users':
157
            $invisible = isset($_GET['count_invisible_courses']) ? intval($_GET['count_invisible_courses']) : null;
158
            $urlBase = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?';
159
            $url1 = $urlBase.'a=users&count_invisible='.$invisible;
160
            $url2 = $urlBase.'a=users_teachers&count_invisible='.$invisible;
161
            $url3 = $urlBase.'a=users_students&count_invisible='.$invisible;
162
            $reportName1 = get_lang('NumberOfUsers');
163
            $reportName2 = get_lang('Teachers');
164
            $reportName3 = get_lang('Students');
165
            $reportType = 'pie';
166
            $reportOptions = '
167
                legend: {
168
                    position: "left"
169
                },
170
                title: {
171
                    text: "%s",
172
                    display: true
173
                },
174
                cutoutPercentage: 25
175
                ';
176
            $reportOptions1 = sprintf($reportOptions, $reportName1);
177
            $reportOptions2 = sprintf($reportOptions, $reportName2);
178
            $reportOptions3 = sprintf($reportOptions, $reportName3);
179
            $htmlHeadXtra[] = Statistics::getJSChartTemplate(
180
                $url1,
181
                $reportType,
182
                $reportOptions1,
183
                'canvas1'
184
            );
185
            $htmlHeadXtra[] = Statistics::getJSChartTemplate(
186
                $url2,
187
                $reportType,
188
                $reportOptions2,
189
                'canvas2'
190
            );
191
            $htmlHeadXtra[] = Statistics::getJSChartTemplate(
192
                $url3,
193
                $reportType,
194
                $reportOptions3,
195
                'canvas3'
196
            );
197
            break;
198
        case 'users_active':
199
            $form = new FormValidator('users_active', 'get', api_get_self().'?report=users_active');
200
            $form->addDateRangePicker(
201
                'daterange',
202
                get_lang('DateRange'),
203
                true,
204
                ['format' => 'YYYY-MM-DD', 'timePicker' => 'false', 'validate_format' => 'Y-m-d']
205
            );
206
207
            $form->addHidden('report', 'users_active');
208
            $form->addButtonFilter(get_lang('Search'));
209
210
            $validated = $form->validate() || isset($_REQUEST['daterange']);
211
212
            $urlBase = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?';
213
            $dateStart = '';
214
            $dateEnd = '';
215
            if ($validated) {
216
                $values = $_REQUEST;
217
                $form->setDefaults(['daterange' => Security::remove_XSS($values['daterange'])]);
218
                $dateStart = Security::remove_XSS($values['daterange_start']);
219
                $dateEnd = Security::remove_XSS($values['daterange_end']);
220
            }
221
222
            $reportType = 'pie';
223
            $reportOptions = '
224
                legend: {
225
                    position: "left"
226
                },
227
                title: {
228
                    text: "%s",
229
                    display: true
230
                },
231
                cutoutPercentage: 25
232
                ';
233
234
            $reportName1 = get_lang('UsersCreatedInTheSelectedPeriod');
235
            $reportName2 = get_lang('UsersByStatus');
236
            $reportName3 = get_lang('UsersByLanguage');
237
            $reportName4 = get_lang('UsersByTargetLanguage');
238
            $reportName5 = get_lang('UsersByCareer');
239
            $reportName6 = get_lang('UsersByContract');
240
            $reportName7 = get_lang('UsersByCertificate');
241
            $reportName8 = get_lang('UsersByAge');
242
243
            //$url1 = $urlBase.'a=users_active&filter=active&date_start='.$dateStart.'&date_end='.$dateEnd;
244
            $url2 = $urlBase.'a=users_active&filter=status&date_start='.$dateStart.'&date_end='.$dateEnd;
245
            $url3 = $urlBase.'a=users_active&filter=language&date_start='.$dateStart.'&date_end='.$dateEnd;
246
            $url4 = $urlBase.'a=users_active&filter=language_cible&date_start='.$dateStart.'&date_end='.$dateEnd;
247
            $url5 = $urlBase.'a=users_active&filter=career&date_start='.$dateStart.'&date_end='.$dateEnd;
248
            $url6 = $urlBase.'a=users_active&filter=contract&date_start='.$dateStart.'&date_end='.$dateEnd;
249
            $url7 = $urlBase.'a=users_active&filter=certificate&date_start='.$dateStart.'&date_end='.$dateEnd;
250
            $url8 = $urlBase.'a=users_active&filter=age&date_start='.$dateStart.'&date_end='.$dateEnd;
251
252
            $reportOptions1 = sprintf($reportOptions, $reportName1);
253
            $reportOptions2 = sprintf($reportOptions, $reportName2);
254
            $reportOptions3 = sprintf($reportOptions, $reportName3);
255
            $reportOptions4 = sprintf($reportOptions, $reportName4);
256
            $reportOptions5 = sprintf($reportOptions, $reportName5);
257
            $reportOptions6 = sprintf($reportOptions, $reportName6);
258
            $reportOptions7 = sprintf($reportOptions, $reportName7);
259
            $reportOptions8 = sprintf($reportOptions, $reportName8);
260
261
            break;
262
        case 'session_by_date':
263
            $form = new FormValidator('session_by_date', 'get');
264
            $form->addDateRangePicker(
265
                'range',
266
                get_lang('DateRange'),
267
                true,
268
                ['format' => 'YYYY-MM-DD', 'timePicker' => 'false', 'validate_format' => 'Y-m-d']
269
            );
270
271
            if ($sessionStatusAllowed) {
272
                $options = SessionManager::getStatusList();
273
                $form->addSelect('status_id', get_lang('SessionStatus'), $options, ['placeholder' => get_lang('All')]);
274
            }
275
276
            $form->addHidden('report', 'session_by_date');
277
            $form->addButtonSearch(get_lang('Search'));
278
279
            $validated = $form->validate() || isset($_REQUEST['range']);
280
            if ($validated) {
281
                $values = $form->getSubmitValues();
282
                $urlBase = api_get_path(WEB_CODE_PATH).'inc/ajax/statistics.ajax.php?';
283
                $dateStart = null;
284
                $dateEnd = null;
285
286
                if (isset($values['range_start'])) {
287
                    $dateStart = Security::remove_XSS($values['range_start']);
288
                }
289
                if (isset($values['range_end'])) {
290
                    $dateEnd = Security::remove_XSS($values['range_end']);
291
                }
292
293
                if (isset($_REQUEST['range_start'])) {
294
                    $dateStart = Security::remove_XSS($_REQUEST['range_start']);
295
                }
296
297
                if (isset($_REQUEST['range_end'])) {
298
                    $dateEnd = Security::remove_XSS($_REQUEST['range_end']);
299
                }
300
301
                $statusId = isset($_REQUEST['status_id']) ? (int) $_REQUEST['status_id'] : 0;
302
303
                $conditions = "&date_start=$dateStart&date_end=$dateEnd&status=$statusId";
304
305
                $url1 = $urlBase.'a=session_by_date&filter=category'.$conditions;
306
                $url2 = $urlBase.'a=session_by_date&filter=language'.$conditions;
307
                $url3 = $urlBase.'a=session_by_date&filter=status'.$conditions;
308
                $url4 = $urlBase.'a=session_by_date&filter=course_in_session'.$conditions;
309
310
                $reportName1 = get_lang('SessionsPerCategory');
311
                $reportName2 = get_lang('SessionsPerLanguage');
312
                $reportName3 = get_lang('SessionsPerStatus');
313
                $reportName4 = get_lang('CourseInSession');
314
315
                $reportType = 'pie';
316
                $reportOptions = '
317
                    legend: {
318
                        position: "left"
319
                    },
320
                    title: {
321
                        text: "%s",
322
                        display: true
323
                    },
324
                    cutoutPercentage: 25
325
                ';
326
                $reportOptions1 = sprintf($reportOptions, $reportName1);
327
                $reportOptions2 = sprintf($reportOptions, $reportName2);
328
                $reportOptions3 = sprintf($reportOptions, $reportName3);
329
330
                $htmlHeadXtra[] = Statistics::getJSChartTemplate(
331
                    $url1,
332
                    $reportType,
333
                    $reportOptions1,
334
                    'canvas1'
335
                );
336
                $htmlHeadXtra[] = Statistics::getJSChartTemplate(
337
                    $url2,
338
                    $reportType,
339
                    $reportOptions2,
340
                    'canvas2'
341
                );
342
343
                if ($sessionStatusAllowed) {
344
                    $htmlHeadXtra[] = Statistics::getJSChartTemplate(
345
                        $url3,
346
                        $reportType,
347
                        $reportOptions3,
348
                        'canvas3'
349
                    );
350
                }
351
352
                $reportOptions = '
353
                    legend: {
354
                        position: "left"
355
                    },
356
                    title: {
357
                        text: "'.$reportName4.'",
358
                        display: true
359
                    },
360
                    responsive: true,
361
                    animation: {
362
                      animateScale: true,
363
                      animateRotate: true
364
                    },
365
                    cutoutPercentage: 25,
366
                    tooltips: {
367
                        callbacks: {
368
                            label: function(tooltipItem, data) {
369
                                var dataset = data.datasets[tooltipItem.datasetIndex];
370
                                var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
371
                                    return previousValue + currentValue;
372
                                });
373
374
                                var label = data.labels[tooltipItem.datasetIndex];
375
                                var currentValue = dataset.data[tooltipItem.index];
376
                                var percentage = Math.floor(((currentValue/total) * 100)+0.5);
377
378
                                return label + " " + percentage + "%";
379
                            }
380
                        }
381
                    }
382
                ';
383
384
                $htmlHeadXtra[] = Statistics::getJSChartTemplate(
385
                    $url4,
386
                    $reportType,
387
                    $reportOptions,
388
                    'canvas4'
389
                );
390
            }
391
            break;
392
    }
393
}
394
395
if ('user_session' === $report) {
396
    $htmlHeadXtra[] = api_get_jqgrid_js();
397
}
398
399
if (isset($_GET['export'])) {
400
    ob_start();
401
}
402
403
$course_categories = Statistics::getCourseCategories();
404
$content = '';
405
406
switch ($report) {
407
    case 'courses_usage':
408
        $form = new FormValidator('courses_usage', 'get');
409
        $nextElement = 0;
410
        $currentPage = 0;
411
        $start = 0;
412
        $pagged = 10;
413
        $coursesList = [];
414
        $op = [];
415
        $today = new DateTime();
416
        $reportPost = $_POST['report'] ?? null;
417
        $endDate = $today->format('Y-m-d');
418
        $pag = 0;
419
        $fechas = [
420
            'day' => $today->setTimestamp(strtotime('-1 day'))->format('Y-m-d'),
421
            'week' => $today->setTimestamp(strtotime('-1 week'))->format('Y-m-d'),
422
            'month' => $today->setTimestamp(strtotime('-1 month'))->format('Y-m-d'),
423
            '6month' => $today->setTimestamp(strtotime('-6 month'))->format('Y-m-d'),
424
            'year' => $today->setTimestamp(strtotime('-1 year'))->format('Y-m-d'),
425
            '2year' => $today->setTimestamp(strtotime('-2 year'))->format('Y-m-d'),
426
            'total' => null,
427
        ];
428
        $courses = CourseManager::get_course_list();
429
        $coursesTotal = count($courses);
430
        if (0 < $coursesTotal) {
431
            $start = isset($_GET['start']) ? (int) ($_GET['start']) : 0;
432
        }
433
434
        $start = abs($start);
435
436
        $termina = ($start + $pagged) < $pagged ? $pagged : $start + $pagged;
437
        foreach ($courses as $course) {
438
            $courseId = $course['id'];
439
            $sessions = 0;
440
            $courseTotal = 0;
441
            $visit = 0;
442
            $indexCourseList = count($coursesList);
443
            $item = [];
444
            if ($indexCourseList >= $start && $indexCourseList < $termina) {
445
                foreach ($fechas as $index => $date) {
446
                    $startDate = $date;
447
                    $courseTotal = count(CourseManager::getAccessCourse(
448
                        $courseId,
449
                        0,
450
                        0,
451
                        $startDate,
452
                        $endDate
453
                    ));
454
                    $sessions = count(CourseManager::getAccessCourse(
455
                        $courseId,
456
                        1,
457
                        0,
458
                        $startDate,
459
                        $endDate
460
                    ));
461
                    $visit = count(CourseManager::getAccessCourse(
462
                        $courseId,
463
                        3,
464
                        0,
465
                        $startDate,
466
                        $endDate
467
                    ));
468
                    $temp = [
469
                        'start' => $startDate,
470
                        'course' => $visit,
471
                        'course_id' => $course['id'],
472
                        'session' => $sessions,
473
                        'count' => $sessions + $courseTotal,
474
                    ];
475
                    $item[$index] = $temp;
476
                }
477
                $coursesList[$indexCourseList] = [
478
                    $course['title'],
479
                    $item['day']['count'],
480
                    $item['week']['count'],
481
                    $item['month']['count'],
482
                    $item['6month']['count'],
483
                    $item['year']['count'],
484
                    $item['2year']['count'],
485
                    $courseTotal,
486
                    $sessions,
487
                    $item['total']['count'],
488
                ];
489
                if (0 == $nextElement) {
490
                    $nextElement = $indexCourseList;
491
                }
492
                $op[] = $coursesList[$indexCourseList];
493
            } else {
494
                $coursesList[$indexCourseList] = null;
495
            }
496
            if ($indexCourseList >= ($termina)) {
497
                break;
498
            }
499
500
            if (1 == count($coursesList) % $pagged) {
501
                $currentPage++;
502
            }
503
        }
504
        $headerName = [
505
            [get_lang('Course'), false],
506
            [get_lang('Today'), false],
507
            [get_lang('ThisWeek'), false],
508
            [get_lang('ThisMonth'), false],
509
            ["6 ".get_lang('MinMonths'), false],
510
            ["1 ".get_lang('Year'), false],
511
            ["2 ".get_lang('Years'), false],
512
            [get_lang('NumAccess')." (".get_lang('Course').")", false],
513
            [get_lang('NumAccess')." (".get_lang('Session').")", false],
514
            [get_lang('AbsoluteTotal')." (".get_lang('Visited').")", false],
515
        ];
516
        $query_vars = [];
517
        $query_vars['start'] = $nextElement;
518
        $query_vars['report'] = 'courses_usage';
519
        $paging_options = [];
520
        $paging_options['per_page'] = $pagged;
521
        $nextCourseIndex = ($start + $pagged);
522
        $previousCourseIndex = ($start - 10) < 0 ? 0 : ($start - 10);
523
524
        $pag = (int) ($coursesTotal / $pagged);
525
        if ($pag < ($coursesTotal / $pagged)) {
526
            $pag++;
527
        }
528
529
        $nextLink = Display::url(
530
            Display::return_icon(
531
                'action_next.png',
532
                get_lang('NextPage'),
533
                [],
534
                ICON_SIZE_MEDIUM
535
            ),
536
            api_get_self()."?&start=$nextCourseIndex&report=courses_usage",
537
            ['class' => 'btn']
538
        );
539
540
        $previousLink = Display::url(
541
            Display::return_icon(
542
                'action_prev.png',
543
                get_lang('PreviousPage'),
544
                [],
545
                ICON_SIZE_MEDIUM
546
            ),
547
            api_get_self()."?&start=$previousCourseIndex&report=courses_usage",
548
            ['class' => 'btn']
549
        );
550
        $table = Display::return_sortable_table(
551
            $headerName,
552
            $op,
553
            'ASC',
554
            $paging_options,
555
            $query_vars);
556
557
        $form->addHtml(
558
            $table
559
        );
560
        $html = "<div class='col-md-12 row'><div class='col-md-6'>&nbsp;</div><div class='col-md-6'>";
561
        $html .= ($pag > 1) ? $currentPage." / ".$pag : '';
562
        $html .= ($previousCourseIndex > 1) ? $previousLink : '';
563
        $html .= ($nextCourseIndex < $coursesTotal) ? $nextLink : '';
564
        $html .= '</div>';
565
        $form->addHtml($html);
566
        $content = $form->returnForm();
567
568
        break;
569
    case 'session_by_date':
570
        $sessions = [];
571
        if ($validated) {
572
            $values = $form->getSubmitValues();
573
            $first = DateTime::createFromFormat('Y-m-d', $dateStart);
574
            $second = DateTime::createFromFormat('Y-m-d', $dateEnd);
575
            $numberOfWeeks = 0;
576
            if ($first) {
577
                $numberOfWeeks = floor($first->diff($second)->days / 7);
578
            }
579
580
            $statusCondition = '';
581
            if (!empty($statusId)) {
582
                $statusCondition .= " AND status = $statusId ";
583
            }
584
585
            $start = Database::escape_string($dateStart);
586
            $end = Database::escape_string($dateEnd);
587
588
            // User count
589
            $tableSession = Database::get_main_table(TABLE_MAIN_SESSION);
590
            $sql = "SELECT * FROM $tableSession
591
                    WHERE
592
                        (display_start_date BETWEEN '$start' AND '$end' OR
593
                        display_end_date BETWEEN '$start' AND '$end')
594
                        $statusCondition
595
                    ";
596
            $result = Database::query($sql);
597
598
            $sessionCount = 0;
599
            $numberUsers = 0;
600
            while ($row = Database::fetch_array($result, 'ASSOC')) {
601
                $sessions[] = $row;
602
                $numberUsers += $row['nbr_users'];
603
                $sessionCount++;
604
            }
605
606
            // Coach
607
            $sql = "SELECT count(DISTINCT(id_coach)) count FROM $tableSession
608
                    WHERE
609
                        (display_start_date BETWEEN '$start' AND '$end' OR
610
                        display_end_date BETWEEN '$start' AND '$end')
611
                        $statusCondition
612
                     ";
613
            $result = Database::query($sql);
614
            $row = Database::fetch_array($result);
615
            $uniqueCoaches = $row['count'];
616
617
            // Categories
618
            $sql = "SELECT count(id) count, session_category_id FROM $tableSession
619
                    WHERE
620
                        (display_start_date BETWEEN '$start' AND '$end' OR
621
                        display_end_date BETWEEN '$start' AND '$end')
622
                        $statusCondition;
623
                    GROUP BY session_category_id
624
                    ";
625
626
            $result = Database::query($sql);
627
            $sessionPerCategories = [];
628
            while ($row = Database::fetch_array($result)) {
629
                $sessionPerCategories[$row['session_category_id']] = $row['count'];
630
            }
631
632
            $sessionAverage = 0;
633
            $averageUser = 0;
634
            $averageCoach = 0;
635
            if (!empty($numberOfWeeks)) {
636
                $sessionAverage = api_number_format($sessionCount / $numberOfWeeks, 2);
637
            }
638
            if (!empty($sessionCount)) {
639
                $averageUser = api_number_format($numberUsers / $sessionCount, 2);
640
            }
641
            if (!empty($uniqueCoaches)) {
642
                $averageCoach = api_number_format($sessionCount / $uniqueCoaches, 2);
643
            }
644
645
            $courseSessions = [];
646
            if (!empty($sessions)) {
647
                foreach ($sessions as $session) {
648
                    $courseList = SessionManager::getCoursesInSession($session['id']);
649
                    foreach ($courseList as $courseId) {
650
                        if (!isset($courseSessions[$courseId])) {
651
                            $courseSessions[$courseId] = 0;
652
                        }
653
                        $courseSessions[$courseId]++;
654
                    }
655
                }
656
            }
657
658
            $content .= Display::page_subheader2(get_lang('UsersReportByCourseInSessions'));
659
660
            $tableCourse = new HTML_Table(['class' => 'table table-responsive']);
661
            $headers = [
662
                get_lang('Course'),
663
                get_lang('CountOfSessions'),
664
                get_lang('UsersReport'),
665
            ];
666
667
            $row = 0;
668
            $column = 0;
669
            foreach ($headers as $header) {
670
                $tableCourse->setHeaderContents($row, $column, $header);
671
                $column++;
672
            }
673
            $row++;
674
675
            if (!empty($courseSessions)) {
676
                $dateStart = null;
677
                $dateEnd = null;
678
                if (isset($_REQUEST['range_start'])) {
679
                    $dateStart = Security::remove_XSS($_REQUEST['range_start']);
680
                }
681
                if (isset($_REQUEST['range_end'])) {
682
                    $dateEnd = Security::remove_XSS($_REQUEST['range_end']);
683
                }
684
                $conditions = "&date_start=$dateStart&date_end=$dateEnd";
685
                arsort($courseSessions);
686
                foreach ($courseSessions as $courseId => $count) {
687
                    $courseInfo = api_get_course_info_by_id($courseId);
688
                    $tableCourse->setCellContents($row, 0, $courseInfo['name']);
689
                    $tableCourse->setCellContents($row, 1, $count);
690
                    $exportLink = api_get_self().'?report=session_by_date&course_id='.$courseId.'&action=export_users'.$conditions;
691
                    $urlExport = Display::url(
692
                        Display::return_icon('excel.png', get_lang('UsersReport')),
693
                        $exportLink
694
                    );
695
                    $tableCourse->setCellContents($row, 2, $urlExport);
696
                    $row++;
697
                }
698
            }
699
700
            $content .= $tableCourse->toHtml();
701
702
            $content .= Display::page_subheader2(get_lang('GeneralStats'));
703
704
            $table = new HTML_Table(['class' => 'table table-responsive']);
705
            $row = 0;
706
            $table->setCellContents($row, 0, get_lang('Weeks'));
707
            $table->setCellContents($row, 1, $numberOfWeeks);
708
            $row++;
709
710
            $table->setCellContents($row, 0, get_lang('SessionCount'));
711
            $table->setCellContents($row, 1, $sessionCount);
712
            $row++;
713
714
            $table->setCellContents($row, 0, get_lang('SessionsPerWeek'));
715
            $table->setCellContents($row, 1, $sessionAverage);
716
            $row++;
717
718
            $table->setCellContents($row, 0, get_lang('AverageUserPerSession'));
719
            $table->setCellContents($row, 1, $averageUser);
720
            $row++;
721
722
            $table->setCellContents($row, 0, get_lang('AverageSessionPerGeneralCoach'));
723
            $table->setCellContents($row, 1, $averageCoach);
724
            $row++;
725
726
            $content .= $table->toHtml();
727
728
            $content .= '<div class="row">';
729
            $content .= '<div class="col-md-4"><h4 class="page-header" id="canvas1_title"></h4><div id="canvas1_table"></div></div>';
730
            $content .= '<div class="col-md-4"><h4 class="page-header" id="canvas2_title"></h4><div id="canvas2_table"></div></div>';
731
732
            if ($sessionStatusAllowed) {
733
                $content .= '<div class="col-md-4"><h4 class="page-header" id="canvas3_title"></h4><div id="canvas3_table"></div></div>';
734
            }
735
            $content .= '</div>';
736
737
            $content .= '<div class="row">';
738
            $content .= '<div class="col-md-4"><canvas id="canvas1" style="margin-bottom: 20px"></canvas></div>';
739
            $content .= '<div class="col-md-4"><canvas id="canvas2" style="margin-bottom: 20px"></canvas></div>';
740
741
            if ($sessionStatusAllowed) {
742
                $content .= '<div class="col-md-4"><canvas id="canvas3" style="margin-bottom: 20px"></canvas></div>';
743
            }
744
            $content .= '</div>';
745
746
            $content .= '<div class="row">';
747
            $content .= '<div class="col-md-12"><canvas id="canvas4" style="margin-bottom: 20px"></canvas></div>';
748
            $content .= '</div>';
749
        }
750
751
        $table = new HTML_Table(['class' => 'table table-responsive']);
752
        $headers = [
753
            get_lang('Name'),
754
            get_lang('StartDate'),
755
            get_lang('EndDate'),
756
            get_lang('Language'),
757
        ];
758
        if ($sessionStatusAllowed) {
759
            $headers[] = get_lang('Status');
760
        }
761
        $headers[] = get_lang('NumberOfStudents');
762
        $row = 0;
763
        $column = 0;
764
        foreach ($headers as $header) {
765
            $table->setHeaderContents($row, $column, $header);
766
            $column++;
767
        }
768
        $row++;
769
770
        foreach ($sessions as $session) {
771
            $courseList = SessionManager::getCoursesInSession($session['id']);
772
            $table->setCellContents($row, 0, $session['name']);
773
            $table->setCellContents($row, 1, api_get_local_time($session['display_start_date']));
774
            $table->setCellContents($row, 2, api_get_local_time($session['display_end_date']));
775
776
            // Get first language.
777
            $language = '';
778
            $courses = SessionManager::getCoursesInSession($session['id']);
779
            if (!empty($courses)) {
780
                $courseId = $courses[0];
781
                $courseInfo = api_get_course_info_by_id($courseId);
782
                $language = $courseInfo['language'];
783
                $language = get_lang(ucfirst(str_replace(2, '', $language)));
784
            }
785
            $table->setCellContents($row, 3, $language);
786
787
            if ($sessionStatusAllowed) {
788
                $table->setCellContents($row, 4, SessionManager::getStatusLabel($session['status']));
789
            }
790
            $studentsCount = SessionManager::get_users_by_session($session['id'], 0, true);
791
            $table->setCellContents($row, 5, $studentsCount);
792
            $row++;
793
        }
794
795
        $content .= $table->toHtml();
796
797
        if (isset($_REQUEST['action']) && 'export_users' === $_REQUEST['action'] && isset($_REQUEST['course_id'])) {
798
            $courseId = intval($_REQUEST['course_id']);
799
            $startDate = isset($_REQUEST['date_start']) ? Database::escape_string($_REQUEST['date_start']) : null;
800
            $endDate = isset($_REQUEST['date_end']) ? Database::escape_string($_REQUEST['date_end']) : null;
801
802
            Statistics::exportUserReportByCourseSession($courseId, $startDate, $endDate);
803
            exit;
804
        }
805
806
        if (isset($_REQUEST['action']) && 'export' === $_REQUEST['action']) {
807
            $data = $table->toArray();
808
            Export::arrayToXls($data);
809
            exit;
810
        }
811
812
        $link = '';
813
        if ($validated) {
814
            $url = api_get_self().'?report=session_by_date&action=export';
815
            if (!empty($values)) {
816
                foreach ($values as $index => $value) {
817
                    $url .= '&'.$index.'='.$value;
818
                }
819
            }
820
            $link = Display::url(
821
                Display::return_icon('excel.png').'&nbsp;'.get_lang('ExportAsXLS'),
822
                $url,
823
                ['class' => 'btn btn-default']
824
            );
825
        }
826
827
        $content = $form->returnForm().$content.$link;
828
829
        break;
830
    case 'user_session':
831
        $form = new FormValidator('user_session', 'get');
832
        $form->addDateRangePicker('range', get_lang('DateRange'));
833
        $form->addHidden('report', 'user_session');
834
        $form->addButtonSearch(get_lang('Search'));
835
836
        $date = new DateTime('now');
837
        $startDate = $date->format('Y-m-d').' 00:00:00';
838
        $endDate = $date->format('Y-m-d').' 23:59:59';
839
        $start = $startDate;
840
        $end = $endDate;
841
842
        if ($form->validate()) {
843
            $values = $form->getSubmitValues();
844
            $start = $values['range_start'];
845
            $end = $values['range_end'];
846
        }
847
        $content .= $form->returnForm();
848
849
        $url = api_get_path(WEB_AJAX_PATH).'statistics.ajax.php?a=get_user_session&start='.$start.'&end='.$end;
850
        $columns = [
851
            'URL',
852
            get_lang('Session'),
853
            get_lang('Course'),
854
            get_lang('CountUsers'),
855
        ];
856
857
        $columnModel = [
858
            [
859
                'name' => 'url',
860
                'index' => 'url',
861
                'width' => '120',
862
                'align' => 'left',
863
            ],
864
            [
865
                'name' => 'session',
866
                'index' => 'session',
867
                'width' => '180',
868
                'align' => 'left',
869
                'sortable' => 'false',
870
            ],
871
            [
872
                'name' => 'course',
873
                'index' => 'course',
874
                'width' => '100',
875
                'align' => 'left',
876
                'sortable' => 'false',
877
            ],
878
            [
879
                'name' => 'count',
880
                'index' => 'count',
881
                'width' => '50',
882
                'align' => 'left',
883
                'sortable' => 'false',
884
            ],
885
        ];
886
        $extraParams['autowidth'] = 'true'; //use the width of the parent
887
        $extraParams['height'] = 'auto'; //use the width of the parent
888
        $actionLinks = '';
889
890
        $content .= '
891
        <script>
892
            $(function() {
893
                '.Display::grid_js(
894
                'user_session_grid',
895
                $url,
896
                $columns,
897
                $columnModel,
898
                $extraParams,
899
                [],
900
                $actionLinks,
901
                true
902
            ).';
903
904
                jQuery("#user_session_grid").jqGrid("navGrid","#user_session_grid_pager",{
905
                    view:false,
906
                    edit:false,
907
                    add:false,
908
                    del:false,
909
                    search:false,
910
                    excel:true
911
                });
912
913
                jQuery("#user_session_grid").jqGrid("navButtonAdd","#user_session_grid_pager", {
914
                    caption:"",
915
                    onClickButton : function () {
916
                        jQuery("#user_session_grid").jqGrid("excelExport",{"url":"'.$url.'&export_format=xls"});
917
                    }
918
                });
919
            });
920
        </script>';
921
922
        $content .= Display::grid_html('user_session_grid');
923
924
        break;
925
    case 'courses':
926
        $content .= '<canvas class="col-md-12" id="canvas" height="300px" style="margin-bottom: 20px"></canvas>';
927
        // total amount of courses
928
        $courses = [];
929
        foreach ($course_categories as $code => $name) {
930
            $courses[$name] = Statistics::countCourses($code);
931
        }
932
        // courses for each course category
933
        $content .= Statistics::printStats(get_lang('CountCours'), $courses);
934
        break;
935
    case 'tools':
936
        $content .= '<canvas class="col-md-12" id="canvas" height="300px" style="margin-bottom: 20px"></canvas>';
937
        $content .= Statistics::printToolStats();
938
        break;
939
    case 'coursebylanguage':
940
        $content .= '<canvas class="col-md-12" id="canvas" height="300px" style="margin-bottom: 20px"></canvas>';
941
        $result = Statistics::printCourseByLanguageStats();
942
        $content .= Statistics::printStats(get_lang('CountCourseByLanguage'), $result);
943
        break;
944
    case 'courselastvisit':
945
        $content .= Statistics::printCourseLastVisit();
946
        break;
947
    case 'invoicing':
948
        if (!empty($invoicingMonth)) {
949
            $invoicingMonth = sprintf("%02d", $invoicingMonth);
950
            $currentMonth = $invoicingYear.'-'.$invoicingMonth;
951
            $lastMonth = date("Y-m", mktime(0, 0, 0, $invoicingMonth, 0, $invoicingYear));
952
        } else {
953
            $currentMonth = date("Y-m");
954
            $lastMonth = date("Y-m", strtotime('-1 month'));
955
            $invoicingMonth = date('m');
956
            $invoicingYear = date('Y');
957
        }
958
        $content .= Statistics::printInvoicingByAccessUrl($currentMonth, $lastMonth, $invoicingMonth, $invoicingYear);
959
        break;
960
    case 'users_active':
961
        $content = '';
962
        if ($validated) {
963
            $startDate = $values['daterange_start'];
964
            $endDate = $values['daterange_end'];
965
966
            $graph = '<div class="row">';
967
            $graph .= '<div class="col-md-4"><canvas id="canvas1" style="margin-bottom: 20px"></canvas></div>';
968
            $graph .= '<div class="col-md-4"><canvas id="canvas2" style="margin-bottom: 20px"></canvas></div>';
969
            $graph .= '<div class="col-md-4"><canvas id="canvas3" style="margin-bottom: 20px"></canvas></div>';
970
            $graph .= '</div>';
971
972
            $graph .= '<div class="row">';
973
            $graph .= '<div class="col-md-6"><canvas id="canvas4" style="margin-bottom: 20px"></canvas></div>';
974
            $graph .= '<div class="col-md-6"><canvas id="canvas8" style="margin-bottom: 20px"></canvas></div>';
975
            $graph .= '</div>';
976
977
            $graph .= '<div class="row">';
978
            $graph .= '<div class="col-md-6"><canvas id="canvas5" style="margin-bottom: 20px"></canvas></div>';
979
            $graph .= '<div class="col-md-6"><canvas id="canvas6" style="margin-bottom: 20px"></canvas></div>';
980
            $graph .= '</div>';
981
982
            $graph .= '<div class="row">';
983
            $graph .= '<div class="col-md-6"><canvas id="canvas7" style="margin-bottom: 20px"></canvas></div>';
984
            $graph .= '</div>';
985
986
            $conditions = [];
987
            $extraConditions = '';
988
            if (!empty($startDate) && !empty($endDate)) {
989
                // $extraConditions is already cleaned inside the function getUserListExtraConditions
990
                $extraConditions .= " AND registration_date BETWEEN '$startDate' AND '$endDate' ";
991
            }
992
993
            $totalCount = UserManager::getUserListExtraConditions(
994
                $conditions,
995
                [],
996
                false,
997
                false,
998
                null,
999
                $extraConditions,
1000
                true
1001
            );
1002
1003
            $pagination = 10;
1004
            $table = new SortableTableFromArray(
1005
                [],
1006
                0,
1007
                $pagination,
1008
                'table_users_active',
1009
                null,
1010
                'table_users_active'
1011
            );
1012
1013
            $table->actionButtons = [
1014
                'export' => [
1015
                    'label' => get_lang('ExportAsXLS'),
1016
                    'icon' => Display::return_icon('excel.png'),
1017
                ],
1018
            ];
1019
1020
            $first = ($table->page_nr - 1) * $pagination;
1021
            $limit = $table->page_nr * $pagination;
1022
1023
            $data = [];
1024
            $headers = [
1025
                get_lang('FirstName'),
1026
                get_lang('LastName'),
1027
                get_lang('RegistrationDate'),
1028
                get_lang('UserNativeLanguage'),
1029
                get_lang('LangueCible'),
1030
                get_lang('ApprenticeshipContract'),
1031
                get_lang('UserResidenceCountry'),
1032
                get_lang('Career'),
1033
                get_lang('Status'),
1034
                get_lang('Active'),
1035
                get_lang('Certificate'),
1036
                get_lang('UserBirthday'),
1037
            ];
1038
1039
            if (isset($_REQUEST['action_table']) && 'export' === $_REQUEST['action_table']) {
1040
                $first = 0;
1041
                $limit = $totalCount;
1042
                $data[] = $headers;
1043
            }
1044
1045
            if (isset($_REQUEST['table_users_active_per_page'])) {
1046
                $limit = (int) $_REQUEST['table_users_active_per_page'];
1047
            }
1048
1049
            $users = UserManager::getUserListExtraConditions(
1050
                $conditions,
1051
                [],
1052
                $first,
1053
                $limit,
1054
                null,
1055
                $extraConditions
1056
            );
1057
1058
            $extraFieldValueUser = new ExtraFieldValue('user');
1059
            foreach ($users as $user) {
1060
                $userId = $user['user_id'];
1061
                $userInfo = api_get_user_info($userId);
1062
1063
                $extraDataList = $extraFieldValueUser->getAllValuesByItem($userId);
1064
                $extraFields = [];
1065
                foreach ($extraDataList as $extraData) {
1066
                    $extraFields[$extraData['variable']] = $extraData['value'];
1067
                }
1068
1069
                $certificate = GradebookUtils::get_certificate_by_user_id(0, $userId);
1070
                $language = $extraFields['langue_cible'] ?? '';
1071
                //$contract = isset($extraFields['termactivated']) ? $extraFields['termactivated'] : '';
1072
                $contract = false;
1073
                $legalAccept = $extraFieldValueUser->get_values_by_handler_and_field_variable($userId, 'legal_accept');
1074
                if ($legalAccept && !empty($legalAccept['value'])) {
1075
                    list($legalId, $legalLanguageId, $legalTime) = explode(':', $legalAccept['value']);
1076
                    if ($legalId) {
1077
                        $contract = true;
1078
                    }
1079
                }
1080
1081
                $residence = $extraFields['terms_paysresidence'] ?? '';
1082
                $career = $extraFields['filiere_user'] ?? '';
1083
                $birthDate = $extraFields['terms_datedenaissance'] ?? '';
1084
1085
                $userLanguage = '';
1086
                if (!empty($user['language'])) {
1087
                    $userLanguage = get_lang(ucfirst(str_replace(2, '', $user['language'])));
1088
                }
1089
1090
                $languageTarget = '';
1091
                if (!empty($language)) {
1092
                    $languageTarget = get_lang(ucfirst(str_replace(2, '', strtolower($language))));
1093
                }
1094
1095
                $item = [];
1096
                $item[] = $user['firstname'];
1097
                $item[] = $user['lastname'];
1098
                $item[] = api_get_local_time($user['registration_date']);
1099
                $item[] = $userLanguage;
1100
                $item[] = $languageTarget;
1101
                $item[] = $contract ? get_lang('Yes') : get_lang('No');
1102
                $item[] = $residence;
1103
                $item[] = $career;
1104
                $item[] = $userInfo['icon_status_label'];
1105
                $item[] = 1 == $user['active'] ? get_lang('Yes') : get_lang('No');
1106
                $item[] = $certificate ? get_lang('Yes') : get_lang('No');
1107
                $item[] = $birthDate;
1108
                $data[] = $item;
1109
            }
1110
1111
            if (isset($_REQUEST['action_table']) && 'export' === $_REQUEST['action_table']) {
1112
                Export::arrayToXls($data);
1113
                exit;
1114
            }
1115
1116
            $table->total_number_of_items = $totalCount;
1117
            $table->table_data = $data;
1118
            unset($values['submit']);
1119
            $table->set_additional_parameters($values);
1120
            $table->handlePagination = true;
1121
1122
            $row = 0;
1123
            $column = 0;
1124
            foreach ($headers as $header) {
1125
                $table->set_header($column, $header, false);
1126
                $column++;
1127
            }
1128
1129
            $studentCount = UserManager::getUserListExtraConditions(
1130
                ['status' => STUDENT],
1131
                null,
1132
                null,
1133
                null,
1134
                null,
1135
                null,
1136
                true
1137
            );
1138
            $content .= $table->return_table();
1139
1140
            $conditions = ['active' => 1];
1141
            $active = UserManager::getUserListExtraConditions(
1142
                $conditions,
1143
                [],
1144
                false,
1145
                false,
1146
                null,
1147
                $extraConditions,
1148
                true
1149
            );
1150
            $conditions = ['active' => 0];
1151
            $noActive = UserManager::getUserListExtraConditions(
1152
                $conditions,
1153
                [],
1154
                false,
1155
                false,
1156
                null,
1157
                $extraConditions,
1158
                true
1159
            );
1160
1161
            $all = [
1162
                get_lang('Active') => $active,
1163
                get_lang('Inactive') => $noActive,
1164
            ];
1165
1166
            $data = Statistics::buildJsChartData($all, $reportName1);
1167
            $htmlHeadXtra[] = Statistics::getJSChartTemplateWithData(
1168
                $data['chart'],
1169
                'pie',
1170
                $reportOptions1,
1171
                'canvas1'
1172
            );
1173
1174
            $scoreDisplay = ScoreDisplay::instance();
1175
            $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
1176
            $headers = [
1177
                get_lang('Name'),
1178
                get_lang('Count'),
1179
                get_lang('Percentage'),
1180
            ];
1181
            $row = 0;
1182
            $column = 0;
1183
            foreach ($headers as $header) {
1184
                $table->setHeaderContents($row, $column, $header);
1185
                $column++;
1186
            }
1187
1188
            $row++;
1189
            $table->setCellContents($row, 0, get_lang('Total'));
1190
            $table->setCellContents($row, 1, $totalCount);
1191
            $table->setCellContents($row, 2, '100 %');
1192
1193
            $row++;
1194
            $total = 0;
1195
            foreach ($all as $name => $value) {
1196
                $total += $value;
1197
            }
1198
            foreach ($all as $name => $value) {
1199
                $percentage = $scoreDisplay->display_score([$value, $total], SCORE_PERCENT);
1200
                $table->setCellContents($row, 0, $name);
1201
                $table->setCellContents($row, 1, $value);
1202
                $table->setCellContents($row, 2, $percentage);
1203
                $row++;
1204
            }
1205
            $extraTables = Display::page_subheader2($reportName1).$table->toHtml();
1206
1207
            // graph 2
1208
            $extraFieldValueUser = new ExtraField('user');
1209
            $extraField = $extraFieldValueUser->get_handler_field_info_by_field_variable('statusocial');
1210
1211
            if ($extraField) {
1212
                $users = UserManager::getUserListExtraConditions(
1213
                    [],
1214
                    [],
1215
                    false,
1216
                    false,
1217
                    null,
1218
                    $extraConditions
1219
                );
1220
1221
                $userIdList = array_column($users, 'user_id');
1222
                $userIdListToString = implode("', '", $userIdList);
1223
1224
                $all = [];
1225
                $total = count($users);
1226
                $usersFound = 0;
1227
1228
                $extraFieldOption = new ExtraFieldOption('user');
1229
                foreach ($extraField['options'] as $item) {
1230
                    $value = Database::escape_string($item['option_value']);
1231
                    $count = 0;
1232
                    $sql = "SELECT count(id) count
1233
                            FROM $extraFieldValueUser->table_field_values
1234
                            WHERE
1235
                            value = '$value' AND
1236
                            item_id IN ('$userIdListToString') AND
1237
                            field_id = ".$extraField['id'];
1238
                    $query = Database::query($sql);
1239
                    $result = Database::fetch_array($query);
1240
                    $count = $result['count'];
1241
                    $usersFound += $count;
1242
1243
                    $option = $extraFieldOption->get($item['id']);
1244
                    $item['display_text'] = $option['display_text'];
1245
                    $all[$item['display_text']] = $count;
1246
                }
1247
                $all[get_lang('N/A')] = $total - $usersFound;
1248
1249
                $data = Statistics::buildJsChartData($all, $reportName2);
1250
                $htmlHeadXtra[] = Statistics::getJSChartTemplateWithData(
1251
                    $data['chart'],
1252
                    'pie',
1253
                    $reportOptions2,
1254
                    'canvas2'
1255
                );
1256
                $extraTables .= $data['table'];
1257
            }
1258
1259
            // graph 3
1260
            $languages = api_get_languages();
1261
            $all = [];
1262
            foreach ($languages['folder'] as $language) {
1263
                $conditions = ['language' => $language];
1264
                $key = $language;
1265
                if ('2' === substr($language, -1)) {
1266
                    $key = str_replace(2, '', $language);
1267
                }
1268
1269
                $key = get_lang(ucfirst($key));
1270
                if (!isset($all[$key])) {
1271
                    $all[$key] = 0;
1272
                }
1273
                $all[$key] += UserManager::getUserListExtraConditions(
1274
                    $conditions,
1275
                    [],
1276
                    false,
1277
                    false,
1278
                    null,
1279
                    $extraConditions,
1280
                    true
1281
                );
1282
            }
1283
1284
            $data = Statistics::buildJsChartData($all, $reportName3);
1285
            $htmlHeadXtra[] = Statistics::getJSChartTemplateWithData(
1286
                $data['chart'],
1287
                'pie',
1288
                $reportOptions3,
1289
                'canvas3'
1290
            );
1291
            $extraTables .= $data['table'];
1292
1293
            // graph 4
1294
            $extraFieldValueUser = new ExtraField('user');
1295
            $extraField = $extraFieldValueUser->get_handler_field_info_by_field_variable('langue_cible');
1296
            if ($extraField) {
1297
                $users = UserManager::getUserListExtraConditions(
1298
                    [],
1299
                    [],
1300
                    false,
1301
                    false,
1302
                    null,
1303
                    $extraConditions
1304
                );
1305
1306
                $userIdList = array_column($users, 'user_id');
1307
                $userIdListToString = implode("', '", $userIdList);
1308
1309
                $all = [];
1310
                $total = count($users);
1311
                $usersFound = 0;
1312
                foreach ($extraField['options'] as $item) {
1313
                    $value = Database::escape_string($item['option_value']);
1314
                    $count = 0;
1315
                    $sql = "SELECT count(id) count
1316
                            FROM $extraFieldValueUser->table_field_values
1317
                            WHERE
1318
                            value = '$value' AND
1319
                            item_id IN ('$userIdListToString') AND
1320
                            field_id = ".$extraField['id'];
1321
                    $query = Database::query($sql);
1322
                    $result = Database::fetch_array($query);
1323
                    $count = $result['count'];
1324
                    $usersFound += $count;
1325
1326
                    $item['display_text'] = get_lang(ucfirst(str_replace('2', '', strtolower($item['display_text']))));
1327
                    $all[$item['display_text']] = $count;
1328
                }
1329
                $all[get_lang('N/A')] = $total - $usersFound;
1330
1331
                $data = Statistics::buildJsChartData($all, $reportName4);
1332
                $htmlHeadXtra[] = Statistics::getJSChartTemplateWithData(
1333
                    $data['chart'],
1334
                    'pie',
1335
                    $reportOptions4,
1336
                    'canvas4'
1337
                );
1338
                $extraTables .= $data['table'];
1339
            }
1340
1341
            // Graph Age
1342
            $extraFieldValueUser = new ExtraField('user');
1343
            $extraField = $extraFieldValueUser->get_handler_field_info_by_field_variable('terms_datedenaissance');
1344
            if ($extraField) {
1345
                $users = UserManager::getUserListExtraConditions(
1346
                    [],
1347
                    [],
1348
                    false,
1349
                    false,
1350
                    null,
1351
                    $extraConditions
1352
                );
1353
1354
                $userIdList = array_column($users, 'user_id');
1355
                $userIdListToString = implode("', '", $userIdList);
1356
1357
                $all = [];
1358
                $total = count($users);
1359
1360
                $sql = "SELECT value
1361
                        FROM $extraFieldValueUser->table_field_values
1362
                        WHERE
1363
                        item_id IN ('$userIdListToString') AND
1364
                        field_id = ".$extraField['id'];
1365
                $query = Database::query($sql);
1366
                $usersFound = 0;
1367
                $now = new DateTime();
1368
                $all = [
1369
                    //get_lang('N/A') => 0,
1370
                    '16-17' => 0,
1371
                    '18-25' => 0,
1372
                    '26-30' => 0,
1373
                ];
1374
1375
                while ($row = Database::fetch_array($query)) {
1376
                    $usersFound++;
1377
                    if (!empty($row['value'])) {
1378
                        $validDate = DateTime::createFromFormat('Y-m-d', $row['value']);
1379
                        $validDate = $validDate && $validDate->format('Y-m-d') === $row['value'];
1380
                        if ($validDate) {
1381
                            $date1 = new DateTime($row['value']);
1382
                            $interval = $now->diff($date1);
1383
                            $years = $interval->y;
1384
1385
                            if ($years >= 16 && $years <= 17) {
1386
                                $all['16-17']++;
1387
                            }
1388
                            if ($years >= 18 && $years <= 25) {
1389
                                $all['18-25']++;
1390
                            }
1391
                            if ($years >= 26 && $years <= 30) {
1392
                                $all['26-30']++;
1393
                            }
1394
                        }
1395
                    }
1396
                }
1397
1398
                $data = Statistics::buildJsChartData($all, $reportName8);
1399
                $htmlHeadXtra[] = Statistics::getJSChartTemplateWithData(
1400
                    $data['chart'],
1401
                    'pie',
1402
                    $reportOptions8,
1403
                    'canvas8'
1404
                );
1405
                $extraTables .= $data['table'];
1406
            }
1407
1408
            // graph 5
1409
            $extraFieldValueUser = new ExtraField('user');
1410
            $extraField = $extraFieldValueUser->get_handler_field_info_by_field_variable('filiere_user');
1411
            if ($extraField) {
1412
                $all = [];
1413
                $users = UserManager::getUserListExtraConditions(
1414
                    [],
1415
                    [],
1416
                    false,
1417
                    false,
1418
                    null,
1419
                    $extraConditions
1420
                );
1421
1422
                $userIdList = array_column($users, 'user_id');
1423
                $userIdListToString = implode("', '", $userIdList);
1424
                $usersFound = 0;
1425
1426
                $total = count($users);
1427
                $extraFieldOption = new ExtraFieldOption('user');
1428
                foreach ($extraField['options'] as $item) {
1429
                    $value = Database::escape_string($item['option_value']);
1430
                    $count = 0;
1431
                    $sql = "SELECT count(id) count
1432
                            FROM $extraFieldValueUser->table_field_values
1433
                            WHERE
1434
                            value = '$value' AND
1435
                            item_id IN ('$userIdListToString') AND
1436
                            field_id = ".$extraField['id'];
1437
                    $query = Database::query($sql);
1438
                    $result = Database::fetch_array($query);
1439
                    $count = $result['count'];
1440
                    $option = $extraFieldOption->get($item['id']);
1441
                    $item['display_text'] = $option['display_text'];
1442
                    $all[$item['display_text']] = $count;
1443
                    $usersFound += $count;
1444
                }
1445
1446
                $all[get_lang('N/A')] = $total - $usersFound;
1447
1448
                $data = Statistics::buildJsChartData($all, $reportName5);
1449
                $htmlHeadXtra[] = Statistics::getJSChartTemplateWithData(
1450
                    $data['chart'],
1451
                    'pie',
1452
                    $reportOptions5,
1453
                    'canvas5'
1454
                );
1455
                $extraTables .= $data['table'];
1456
            }
1457
1458
            // graph 6
1459
            $extraFieldValueUser = new ExtraField('user');
1460
            $extraField = $extraFieldValueUser->get_handler_field_info_by_field_variable('termactivated');
1461
            if ($extraField) {
1462
                $users = UserManager::getUserListExtraConditions(
1463
                    [],
1464
                    [],
1465
                    false,
1466
                    false,
1467
                    null,
1468
                    $extraConditions
1469
                );
1470
1471
                $userIdList = array_column($users, 'user_id');
1472
                $userIdListToString = implode("', '", $userIdList);
1473
1474
                $all = [];
1475
                $total = count($users);
1476
                $sql = "SELECT count(id) count
1477
                        FROM $extraFieldValueUser->table_field_values
1478
                        WHERE
1479
                        value = 1 AND
1480
                        item_id IN ('$userIdListToString') AND
1481
                        field_id = ".$extraField['id'];
1482
                $query = Database::query($sql);
1483
                $result = Database::fetch_array($query);
1484
                $count = $result['count'];
1485
1486
                $all[get_lang('Yes')] = $count;
1487
                $all[get_lang('No')] = $total - $count;
1488
1489
                $data = Statistics::buildJsChartData($all, $reportName6);
1490
                $htmlHeadXtra[] = Statistics::getJSChartTemplateWithData(
1491
                    $data['chart'],
1492
                    'pie',
1493
                    $reportOptions6,
1494
                    'canvas6'
1495
                );
1496
                $extraTables .= $data['table'];
1497
            }
1498
1499
            // Graph 7
1500
            $extraFieldValueUser = new ExtraField('user');
1501
            $extraField = $extraFieldValueUser->get_handler_field_info_by_field_variable('langue_cible');
1502
            if ($extraField) {
1503
                $users = UserManager::getUserListExtraConditions(
1504
                    [],
1505
                    [],
1506
                    false,
1507
                    false,
1508
                    null,
1509
                    $extraConditions
1510
                );
1511
1512
                $total = count($users);
1513
                $userIdList = array_column($users, 'user_id');
1514
                $certificateCount = 0;
1515
                foreach ($userIdList as $userId) {
1516
                    $certificate = GradebookUtils::get_certificate_by_user_id(
1517
                        0,
1518
                        $userId
1519
                    );
1520
1521
                    if (!empty($certificate)) {
1522
                        $certificateCount++;
1523
                    }
1524
                }
1525
1526
                $all[get_lang('Yes')] = $certificateCount;
1527
                $all[get_lang('No')] = $total - $certificateCount;
1528
1529
                $data = Statistics::buildJsChartData($all, $reportName7);
1530
                $htmlHeadXtra[] = Statistics::getJSChartTemplateWithData(
1531
                    $data['chart'],
1532
                    'pie',
1533
                    $reportOptions7,
1534
                    'canvas7'
1535
                );
1536
                $extraTables .= $data['table'];
1537
            }
1538
1539
            $header = Display::page_subheader2(get_lang('TotalNumberOfStudents').': '.$studentCount);
1540
            $content = $header.$extraTables.$graph.$content;
1541
        }
1542
1543
        $content = $form->returnForm().$content;
1544
1545
        break;
1546
    case 'users_online':
1547
        $table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
1548
        $intervals = [3, 5, 30, 120];
1549
        $counts = [];
1550
        foreach ($intervals as $minutes) {
1551
            $sql = "SELECT count(distinct(user_id))
1552
                FROM $table WHERE
1553
                tms > DATE_SUB(UTC_TIMESTAMP(), INTERVAL '$minutes' MINUTE)";
1554
            $query = Database::query($sql);
1555
            $counts[$minutes] = 0;
1556
            if (Database::num_rows($query) > 0) {
1557
                $row = Database::fetch_array($query);
1558
                $counts[$minutes] = $row[0];
1559
            }
1560
        }
1561
        $content = '<div class="pull-left">'.get_lang('UsersOnline').'</div>
1562
        <div class="pull-right">'.api_get_local_time().'</div>
1563
        <hr />
1564
        <div class="tracking-course-summary">
1565
            <div class="row">
1566
                <div class="col-lg-3 col-sm-3">
1567
                    <div class="panel panel-default tracking tracking-exercise">
1568
                        <div class="panel-body">
1569
                            <span class="tracking-icon">
1570
                                <i class="fa fa-thermometer-4" aria-hidden="true"></i>
1571
                            </span>
1572
                            <div class="tracking-info">
1573
                                <div class="tracking-text">'.get_lang('UsersOnline').' (3\')</div>
1574
                                <div class="tracking-number">'.getOnlineUsersCount(3).'</div>
1575
                            </div>
1576
                        </div>
1577
                    </div>
1578
                </div>
1579
                <div class="col-lg-3 col-sm-3">
1580
                    <div class="panel panel-default tracking tracking-certificate">
1581
                        <div class="panel-body">
1582
                            <span class="tracking-icon">
1583
                                <i class="fa fa-thermometer-3" aria-hidden="true"></i>
1584
                            </span>
1585
                            <div class="tracking-info">
1586
                                <div class="tracking-text">'.get_lang('UsersOnline').' (5\')</div>
1587
                                <div class="tracking-number">'.getOnlineUsersCount(5).'</div>
1588
                            </div>
1589
                        </div>
1590
                    </div>
1591
                </div>
1592
                <div class="col-lg-3 col-sm-3">
1593
                    <div class="panel panel-default tracking tracking-lessons">
1594
                        <div class="panel-body">
1595
                            <span class="tracking-icon">
1596
                                <i class="fa fa-thermometer-2" aria-hidden="true"></i>
1597
                            </span>
1598
                            <div class="tracking-info">
1599
                                <div class="tracking-text">'.get_lang('UsersOnline').' (30\')</div>
1600
                                <div class="tracking-number">'.getOnlineUsersCount(30).'</div>
1601
                            </div>
1602
                        </div>
1603
                    </div>
1604
                </div>
1605
                <div class="col-lg-3 col-sm-3">
1606
                    <div class="panel panel-default tracking tracking-student">
1607
                        <div class="panel-body">
1608
                            <span class="tracking-icon">
1609
                                <i class="fa fa-thermometer-1" aria-hidden="true"></i>
1610
                            </span>
1611
                            <div class="tracking-info">
1612
                                <div class="tracking-text">'.get_lang('UsersOnline').' (120\')</div>
1613
                                <div class="tracking-number">'.getOnlineUsersCount(120).'</div>
1614
                            </div>
1615
                        </div>
1616
                    </div>
1617
                </div>
1618
            </div>
1619
        <div class="pull-left">'.get_lang('UsersActiveInATest').'</div>
1620
        <hr />
1621
        <div class="row">
1622
            <div class="col-lg-3 col-sm-3">
1623
                <div class="panel panel-default tracking tracking-exercise">
1624
                    <div class="panel-body">
1625
                        <span class="tracking-icon">
1626
                            <i class="fa fa-thermometer-4" aria-hidden="true"></i>
1627
                        </span>
1628
                        <div class="tracking-info">
1629
                            <div class="tracking-text">(3\')</div>
1630
                            <div class="tracking-number">'.$counts[3].'</div>
1631
                        </div>
1632
                    </div>
1633
                </div>
1634
            </div>
1635
            <div class="col-lg-3 col-sm-3">
1636
                <div class="panel panel-default tracking tracking-certificate">
1637
                    <div class="panel-body">
1638
                        <span class="tracking-icon">
1639
                            <i class="fa fa-thermometer-3" aria-hidden="true"></i>
1640
                        </span>
1641
                        <div class="tracking-info">
1642
                            <div class="tracking-text">(5\')</div>
1643
                            <div class="tracking-number">'.$counts[5].'</div>
1644
                        </div>
1645
                    </div>
1646
                </div>
1647
            </div>
1648
            <div class="col-lg-3 col-sm-3">
1649
                <div class="panel panel-default tracking tracking-lessons">
1650
                    <div class="panel-body">
1651
                        <span class="tracking-icon">
1652
                            <i class="fa fa-thermometer-2" aria-hidden="true"></i>
1653
                        </span>
1654
                        <div class="tracking-info">
1655
                            <div class="tracking-text">(30\')</div>
1656
                            <div class="tracking-number">'.$counts[30].'</div>
1657
                        </div>
1658
                    </div>
1659
                </div>
1660
            </div>
1661
             <div class="col-lg-3 col-sm-3">
1662
                <div class="panel panel-default tracking tracking-student">
1663
                    <div class="panel-body">
1664
                        <span class="tracking-icon">
1665
                            <i class="fa fa-thermometer-1" aria-hidden="true"></i>
1666
                        </span>
1667
                        <div class="tracking-info">
1668
                            <div class="tracking-text">(120\')</div>
1669
                            <div class="tracking-number">'.$counts[120].'</div>
1670
                        </div>
1671
                    </div>
1672
                </div>
1673
            </div>
1674
1675
        </div>';
1676
        break;
1677
    case 'users':
1678
        $content .= '<div class="row">';
1679
        $content .= '<div class="col-md-4"><canvas id="canvas1" style="margin-bottom: 20px"></canvas></div>';
1680
        $content .= '<div class="col-md-4"><canvas id="canvas2" style="margin-bottom: 20px"></canvas></div>';
1681
        $content .= '<div class="col-md-4"><canvas id="canvas3" style="margin-bottom: 20px"></canvas></div>';
1682
1683
        $content .= '</div>';
1684
        // total amount of users
1685
        $teachers = $students = [];
1686
        $countInvisible = isset($_GET['count_invisible_courses']) ? intval($_GET['count_invisible_courses']) : null;
1687
        $content .= Statistics::printStats(
1688
            get_lang('NumberOfUsers'),
1689
            [
1690
                get_lang('Teachers') => Statistics::countUsers(COURSEMANAGER, null, $countInvisible),
1691
                get_lang('Students') => Statistics::countUsers(STUDENT, null, $countInvisible),
1692
            ]
1693
        );
1694
        foreach ($course_categories as $code => $name) {
1695
            $name = str_replace(get_lang('Department'), '', $name);
1696
            $teachers[$name] = Statistics::countUsers(COURSEMANAGER, $code, $countInvisible);
1697
            $students[$name] = Statistics::countUsers(STUDENT, $code, $countInvisible);
1698
        }
1699
        // docents for each course category
1700
        $content .= Statistics::printStats(get_lang('Teachers'), $teachers);
1701
        // students for each course category
1702
        $content .= Statistics::printStats(get_lang('Students'), $students);
1703
        break;
1704
    case 'recentlogins':
1705
        $content .= '<h2>'.sprintf(get_lang('LastXDays'), '31').'</h2>';
1706
        $form = new FormValidator(
1707
            'session_time',
1708
            'get',
1709
            api_get_self().'?report=recentlogins&session_duration='.$sessionDuration
1710
        );
1711
        $sessionTimeList = ['', 5 => 5, 15 => 15, 30 => 30, 60 => 60];
1712
        $form->addSelect('session_duration', [get_lang('SessionMinDuration'), get_lang('Minutes')], $sessionTimeList);
1713
        $form->addButtonSend(get_lang('Filter'));
1714
        $form->addHidden('report', 'recentlogins');
1715
        $content .= $form->returnForm();
1716
1717
        $content .= '<canvas class="col-md-12" id="canvas" height="200px" style="margin-bottom: 20px"></canvas>';
1718
        $content .= Statistics::printRecentLoginStats(false, $sessionDuration);
1719
        $content .= Statistics::printRecentLoginStats(true, $sessionDuration);
1720
        break;
1721
    case 'logins':
1722
        $content .= Statistics::printLoginStats($_GET['type']);
1723
        break;
1724
    case 'pictures':
1725
        $content .= Statistics::printUserPicturesStats();
1726
        break;
1727
    case 'no_login_users':
1728
        $content .= Statistics::printUsersNotLoggedInStats();
1729
        break;
1730
    case 'zombies':
1731
        $content .= ZombieReport::create(['report' => 'zombies'])->display(true);
1732
        break;
1733
    case 'activities':
1734
        $content .= Statistics::printActivitiesStats();
1735
        break;
1736
    case 'messagesent':
1737
        $messages_sent = Statistics::getMessages('sent');
1738
        $content .= Statistics::printStats(get_lang('MessagesSent'), $messages_sent);
1739
        break;
1740
    case 'messagereceived':
1741
        $messages_received = Statistics::getMessages('received');
1742
        $content .= Statistics::printStats(get_lang('MessagesReceived'), $messages_received);
1743
        break;
1744
    case 'friends':
1745
        // total amount of friends
1746
        $friends = Statistics::getFriends();
1747
        $content .= Statistics::printStats(get_lang('CountFriends'), $friends);
1748
        break;
1749
    case 'logins_by_date':
1750
        $content .= Statistics::printLoginsByDate();
1751
        break;
1752
    case 'lti_tool_lp':
1753
        $content .= Statistics::printLtiLearningPath();
1754
        break;
1755
    case 'quarterly_report':
1756
1757
        $htmlHeadXtra[] = '<script>
1758
                function loadReportQuarterlyUsers () {
1759
                    $("#tracking-report-quarterly-users")
1760
                        .html(\'<p><span class="fa fa-spinner fa-spin fa-2x" aria-hidden="true"></span></p>\')
1761
                        .load(_p.web_ajax + "statistics.ajax.php?a=report_quarterly_users");
1762
            }</script>';
1763
        $htmlHeadXtra[] = '<script>
1764
                function loadReportQuarterlyCourses () {
1765
                    $("#tracking-report-quarterly-courses")
1766
                        .html(\'<p><span class="fa fa-spinner fa-spin fa-2x" aria-hidden="true"></span></p>\')
1767
                        .load(_p.web_ajax + "statistics.ajax.php?a=report_quarterly_courses");
1768
            }</script>';
1769
1770
        $htmlHeadXtra[] = '<script>
1771
                function loadReportQuarterlyHoursOfTraining () {
1772
                    $("#tracking-report-quarterly-hours-of-training")
1773
                        .html(\'<p><span class="fa fa-spinner fa-spin fa-2x" aria-hidden="true"></span></p>\')
1774
                        .load(_p.web_ajax + "statistics.ajax.php?a=report_quarterly_hours_of_training");
1775
            }</script>';
1776
1777
        $htmlHeadXtra[] = '<script>
1778
                function loadReportQuarterlyCertificatesGenerated () {
1779
                    $("#tracking-report-quarterly-number-of-certificates-generated")
1780
                        .html(\'<p><span class="fa fa-spinner fa-spin fa-2x" aria-hidden="true"></span></p>\')
1781
                        .load(_p.web_ajax + "statistics.ajax.php?a=report_quarterly_number_of_certificates_generated");
1782
            }</script>';
1783
1784
        $htmlHeadXtra[] = '<script>
1785
                function loadReportQuarterlySessionsByDuration () {
1786
                    $("#tracking-report-quarterly-sessions-by-duration")
1787
                        .html(\'<p><span class="fa fa-spinner fa-spin fa-2x" aria-hidden="true"></span></p>\')
1788
                        .load(_p.web_ajax + "statistics.ajax.php?a=report_quarterly_sessions_by_duration");
1789
            }</script>';
1790
1791
        $htmlHeadXtra[] = '<script>
1792
                function loadReportQuarterlyCoursesAndSessions () {
1793
                    $("#tracking-report-quarterly-courses-and-sessions")
1794
                        .html(\'<p><span class="fa fa-spinner fa-spin fa-2x" aria-hidden="true"></span></p>\')
1795
                        .load(_p.web_ajax + "statistics.ajax.php?a=report_quarterly_courses_and_sessions");
1796
            }</script>';
1797
1798
        if (api_get_current_access_url_id() === 1) {
1799
            $htmlHeadXtra[] = '<script>
1800
                function loadReportQuarterlyTotalDiskUsage () {
1801
                    $("#tracking-report-quarterly-total-disk-usage")
1802
                        .html(\'<p><span class="fa fa-spinner fa-spin fa-2x" aria-hidden="true"></span></p>\')
1803
                        .load(_p.web_ajax + "statistics.ajax.php?a=report_quarterly_total_disk_usage");
1804
            }</script>';
1805
        }
1806
1807
        $content .= Display::tag('H4', get_lang('ReportQuarterlyUsers'), ['style' => 'margin-bottom: 25px;']);
1808
        $content .= Display::url(
1809
            get_lang('Show'),
1810
            'javascript://',
1811
            ['onclick' => 'loadReportQuarterlyUsers();', 'class' => 'btn btn-default']
1812
        );
1813
        $content .= Display::div('', ['id' => 'tracking-report-quarterly-users', 'style' => 'margin: 30px;']);
1814
1815
        $content .= Display::tag('H4', get_lang('ReportQuarterlyCourses'), ['style' => 'margin-bottom: 25px;']);
1816
        $content .= Display::url(
1817
            get_lang('Show'),
1818
            'javascript://',
1819
            ['onclick' => 'loadReportQuarterlyCourses();', 'class' => 'btn btn-default']
1820
        );
1821
        $content .= Display::div('', ['id' => 'tracking-report-quarterly-courses', 'style' => 'margin: 30px;']);
1822
1823
        $content .= Display::tag('H4', get_lang('ReportQuarterlyHoursOfTraining'), ['style' => 'margin-bottom: 25px;']);
1824
        $content .= Display::url(
1825
            get_lang('Show'),
1826
            'javascript://',
1827
            ['onclick' => 'loadReportQuarterlyHoursOfTraining();', 'class' => 'btn btn-default']
1828
        );
1829
        $content .= Display::div(
1830
            '',
1831
            [
1832
                'id' => 'tracking-report-quarterly-hours-of-training',
1833
                'style' => 'margin: 30px;',
1834
            ]
1835
        );
1836
        $content .= Display::tag(
1837
            'H4',
1838
            get_lang('ReportQuarterlyNumberOfCertificatesGenerated'),
1839
            ['style' => 'margin-bottom: 25px;']
1840
        );
1841
        $content .= Display::url(
1842
            get_lang('Show'),
1843
            'javascript://',
1844
            ['onclick' => 'loadReportQuarterlyCertificatesGenerated();', 'class' => 'btn btn-default']
1845
        );
1846
        $content .= Display::div(
1847
            '',
1848
            ['id' => 'tracking-report-quarterly-number-of-certificates-generated', 'style' => 'margin: 30px;']
1849
        );
1850
        $content .= Display::tag(
1851
            'H4',
1852
            get_lang('ReportQuarterlySessionsByDuration'),
1853
            ['style' => 'margin-bottom: 25px;']
1854
        );
1855
        $content .= Display::url(
1856
            get_lang('Show'),
1857
            'javascript://',
1858
            ['onclick' => 'loadReportQuarterlySessionsByDuration();', 'class' => 'btn btn-default']
1859
        );
1860
        $content .= Display::div(
1861
            '',
1862
            ['id' => 'tracking-report-quarterly-sessions-by-duration', 'style' => 'margin: 30px;']
1863
        );
1864
        $content .= Display::tag(
1865
            'H4',
1866
            get_lang('ReportQuarterlyCoursesAndSessions'),
1867
            ['style' => 'margin-bottom: 25px;']
1868
        );
1869
        $content .= Display::url(
1870
            get_lang('Show'),
1871
            'javascript://',
1872
            ['onclick' => 'loadReportQuarterlyCoursesAndSessions();', 'class' => 'btn btn-default']
1873
        );
1874
        $content .= Display::div(
1875
            '',
1876
            [
1877
                'id' => 'tracking-report-quarterly-courses-and-sessions',
1878
                'style' => 'margin: 30px;',
1879
            ]
1880
        );
1881
1882
        if (api_get_current_access_url_id() === 1) {
1883
            $content .= Display::tag(
1884
                'H4',
1885
                get_lang('ReportQuarterlyTotalDiskUsage'),
1886
                ['style' => 'margin-bottom: 25px;']
1887
            );
1888
            $content .= Display::url(
1889
                get_lang('Show'),
1890
                'javascript://',
1891
                ['onclick' => 'loadReportQuarterlyTotalDiskUsage();', 'class' => 'btn btn-default']
1892
            );
1893
            $content .= Display::div(
1894
                '',
1895
                [
1896
                    'id' => 'tracking-report-quarterly-total-disk-usage',
1897
                    'style' => 'margin: 30px;',
1898
                ]
1899
            );
1900
        }
1901
1902
        break;
1903
    case 'duplicated_users':
1904
        $interbreadcrumb[] = [
1905
            'name' => $tool_name,
1906
            'url' => 'index.php',
1907
        ];
1908
1909
        $additionalExtraFieldsInfo = TrackingCourseLog::getAdditionalProfileExtraFields();
1910
1911
        $frmFields = TrackingCourseLog::displayAdditionalProfileFields([], api_get_self());
1912
        $table = Statistics::returnDuplicatedUsersTable('name', $additionalExtraFieldsInfo);
1913
1914
        if (isset($_GET['action_table'])) {
1915
            $data = $table->toArray(true, true);
1916
1917
            if ('export_excel' === $_GET['action_table']) {
1918
                Export::arrayToXls($data);
1919
            } elseif ('export_csv' === $_GET['action_table']) {
1920
                Export::arrayToCsv($data);
1921
            }
1922
1923
            exit;
1924
        }
1925
1926
        $htmlHeadXtra[] = '<script>'.UserManager::getScriptFunctionForActiveFilter().'</script>';
1927
1928
        $content .= Display::page_subheader2(get_lang('DuplicatedUsers'));
1929
        $content .= Display::return_message(get_lang('ThisReportOnlyListsUsersThatHaveTheSameFirstnameAndLastname'));
1930
1931
        $content .= $frmFields;
1932
        $content .= $table->return_table();
1933
        break;
1934
    case 'duplicated_users_by_mail':
1935
        $interbreadcrumb[] = [
1936
            'name' => $tool_name,
1937
            'url' => 'index.php',
1938
        ];
1939
1940
        $additionalExtraFieldsInfo = TrackingCourseLog::getAdditionalProfileExtraFields();
1941
1942
        $frmFields = TrackingCourseLog::displayAdditionalProfileFields([], api_get_self());
1943
        $table = Statistics::returnDuplicatedUsersTable('email', $additionalExtraFieldsInfo);
1944
1945
        if (isset($_GET['action_table'])) {
1946
            $data = $table->toArray(true, true);
1947
1948
            if ('export_excel' === $_GET['action_table']) {
1949
                Export::arrayToXls($data);
1950
            } elseif ('export_csv' === $_GET['action_table']) {
1951
                Export::arrayToCsv($data);
1952
            }
1953
1954
            exit;
1955
        }
1956
1957
        $htmlHeadXtra[] = '<script>'.UserManager::getScriptFunctionForActiveFilter().'</script>';
1958
1959
        $content .= Display::page_subheader2(get_lang('DuplicatedUsersByMail'));
1960
        $content .= Display::return_message(get_lang('ThisReportOnlyListsUsersThatHaveTheSameEmail'));
1961
1962
        $content .= $frmFields;
1963
        $content .= $table->return_table();
1964
        break;
1965
}
1966
1967
Display::display_header($tool_name);
1968
echo Display::page_header($tool_name);
1969
echo '<table><tr>';
1970
foreach ($tools as $section => $items) {
0 ignored issues
show
Comprehensibility Bug introduced by
$section is overwriting a variable from outer foreach loop.
Loading history...
Comprehensibility Bug introduced by
$items is overwriting a variable from outer foreach loop.
Loading history...
1971
    echo '<td style="vertical-align:top;">';
1972
    echo '<h3>'.$section.'</h3>';
1973
    echo '<ul>';
1974
    foreach ($items as $key => $value) {
1975
        echo '<li><a href="index.php?'.$key.'">'.$value.'</a></li>';
1976
    }
1977
    echo '</ul>';
1978
    echo '</td>';
1979
}
1980
echo '</tr></table>';
1981
1982
//@todo: spaces between elements should be handled in the css, br should be removed if only there for presentation
1983
echo '<br/><br/>';
1984
1985
echo $content;
1986
1987
Display::display_footer();
1988
1989
if (isset($_GET['export'])) {
1990
    ob_end_clean();
1991
}
1992