getReport()   F
last analyzed

Complexity

Conditions 33
Paths > 20000

Size

Total Lines 233
Code Lines 164

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 33
eloc 164
c 1
b 0
f 0
nc 1533224
nop 4
dl 0
loc 233
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
require_once __DIR__.'/../inc/global.inc.php';
6
7
api_block_anonymous_users();
8
9
$is_allowedToTrack = api_is_platform_admin(true, true) ||
10
    api_is_teacher() || api_is_course_tutor() || api_is_student_boss();
11
12
if (!$is_allowedToTrack) {
13
    api_not_allowed(true);
14
    exit;
15
}
16
17
// the section (for the tabs)
18
$this_section = SECTION_TRACKING;
19
$quote_simple = "'";
20
21
$userId = isset($_REQUEST['user_id']) ? (int) $_REQUEST['user_id'] : 0;
22
$userInfo = api_get_user_info($userId);
23
if (empty($userInfo)) {
24
    api_not_allowed(true);
25
}
26
27
/**
28
 * @param string $dateTime
29
 * @param bool   $showTime
30
 *
31
 * @return string
32
 */
33
function customDate($dateTime, $showTime = false)
34
{
35
    $format = 'd/m/Y';
36
    if ($showTime) {
37
        $format = 'd/m/Y H:i:s';
38
    }
39
    $dateTime = api_get_local_time(
40
        $dateTime,
41
        null,
42
        null,
43
        true,
44
        false,
45
        true,
46
        $format
47
    );
48
49
    return $dateTime;
50
}
51
52
$sessions = SessionManager::getSessionsFollowedByUser(
53
    $userId,
54
    null,
55
    null,
56
    null,
57
    false,
58
    false,
59
    false,
60
    'ORDER BY s.access_end_date'
61
);
62
63
$startDate = '';
64
$endDate = '';
65
if (!empty($sessions)) {
66
    foreach ($sessions as $session) {
67
        $startDate = customDate($session['access_start_date']);
68
        $endDate = customDate($session['access_end_date']);
69
    }
70
}
71
72
$form = new FormValidator(
73
    'myform',
74
    'get',
75
    api_get_self().'?user_id='.$userId,
76
    null,
77
    ['id' => 'myform']
78
);
79
$form->addElement('text', 'from', get_lang('From'), ['placeholder' => get_lang('DateFormatddmmyyyy')]);
80
$form->addElement('text', 'to', get_lang('Until'), ['placeholder' => get_lang('DateFormatddmmyyyy')]);
81
$form->addHidden('user_id', $userId);
82
$form->addRule('from', get_lang('ThisFieldIsRequired'), 'required');
83
$form->addRule('from', get_lang('ThisFieldIsRequired').' dd/mm/yyyy', 'callback', 'validateDate');
84
$form->addRule('to', get_lang('ThisFieldIsRequired'), 'required');
85
$form->addRule('to', get_lang('ThisFieldIsRequired').' dd/mm/yyyy', 'callback', 'validateDate');
86
$form->addButtonSearch(get_lang('GenerateReport'));
87
88
/**
89
 * @param string $value
90
 *
91
 * @return bool
92
 */
93
function validateDate($value)
94
{
95
    $value = DateTime::createFromFormat('d/m/Y', $value);
96
97
    if ($value === false) {
98
        return false;
99
    }
100
101
    return true;
102
}
103
104
function getReport($userId, $from, $to, $addTime = false)
105
{
106
    $sessionCategories = UserManager::get_sessions_by_category($userId, false, true, true);
107
    $report = [];
108
    $minLogin = 0;
109
    $maxLogin = 0;
110
    $totalDuration = 0;
111
112
    foreach ($sessionCategories as $category) {
113
        foreach ($category['sessions'] as $session) {
114
            $sessionId = $session['session_id'];
115
            $courseList = $session['courses'];
116
            foreach ($courseList as $course) {
117
                $courseInfo = api_get_course_info_by_id($course['real_id']);
118
                $result = MySpace::get_connections_to_course_by_date(
119
                    $userId,
120
                    $courseInfo,
121
                    $sessionId,
122
                    $from,
123
                    $to
124
                );
125
126
                $partialMinLogin = 0;
127
                $partialMaxLogin = 0;
128
                $partialDuration = 0;
129
130
                foreach ($result as $item) {
131
                    $record = [
132
                        customDate($item['login'], true),
133
                        customDate($item['logout'], true),
134
                        api_format_time($item['duration'], 'lang'),
135
                    ];
136
137
                    $totalDuration += $item['duration'];
138
139
                    if (empty($minLogin)) {
140
                        $minLogin = api_strtotime($item['login'], 'UTC');
141
                    }
142
                    if ($minLogin > api_strtotime($item['login'], 'UTC')) {
143
                        $minLogin = api_strtotime($item['login'], 'UTC');
144
                    }
145
                    if (api_strtotime($item['logout']) > $maxLogin) {
146
                        $maxLogin = api_strtotime($item['logout'], 'UTC');
147
                    }
148
149
                    // Partials
150
                    $partialDuration += $item['duration'];
151
                    if (empty($partialMinLogin)) {
152
                        $partialMinLogin = api_strtotime($item['login'], 'UTC');
153
                    }
154
                    if ($partialMinLogin > api_strtotime($item['login'], 'UTC')) {
155
                        $partialMinLogin = api_strtotime($item['login'], 'UTC');
156
                    }
157
                    if (api_strtotime($item['logout'], 'UTC') > $partialMaxLogin) {
158
                        $partialMaxLogin = api_strtotime($item['logout'], 'UTC');
159
                    }
160
161
                    $report[$sessionId]['courses'][$course['real_id']][] = $record;
162
                    $report[$sessionId]['name'][$course['real_id']] = $courseInfo['title'].'&nbsp; ('.$session['session_name'].')';
163
                }
164
165
                if (!empty($result)) {
166
                    $record = [
167
                        customDate($partialMinLogin, true),
168
                        customDate($partialMaxLogin, true),
169
                        api_format_time($partialDuration, 'lang'),
170
                    ];
171
                    $report[$sessionId]['courses'][$course['real_id']][] = $record;
172
                    $report[$sessionId]['name'][$course['real_id']] = $courseInfo['title'].'&nbsp; ('.$session['session_name'].')';
173
                }
174
            }
175
        }
176
    }
177
178
    $courses = CourseManager::returnCourses($userId);
179
    $courses = array_merge($courses['in_category'], $courses['not_category']);
180
181
    if ($addTime) {
182
        $fromFirst = api_get_local_time($from.' 00:00:00');
183
        $toEnd = api_get_local_time($from.' 23:59:59');
184
185
        $from = api_get_utc_datetime($fromFirst);
186
        $to = api_get_utc_datetime($toEnd);
187
    }
188
189
    foreach ($courses as $course) {
190
        $result = MySpace::get_connections_to_course_by_date(
191
            $userId,
192
            $course,
193
            0,
194
            $from,
195
            $to
196
        );
197
        $partialMinLogin = 0;
198
        $partialMaxLogin = 0;
199
        $partialDuration = 0;
200
201
        foreach ($result as $item) {
202
            $record = [
203
                customDate($item['login'], true),
204
                customDate($item['logout'], true),
205
                api_format_time($item['duration'], 'lang'),
206
            ];
207
            $report[0]['courses'][$course['course_id']][] = $record;
208
            $report[0]['name'][$course['course_id']] = $course['title'];
209
210
            $totalDuration += $item['duration'];
211
212
            if (empty($minLogin)) {
213
                $minLogin = api_strtotime($item['login'], 'UTC');
214
            }
215
            if ($minLogin > api_strtotime($item['login'], 'UTC')) {
216
                $minLogin = api_strtotime($item['login'], 'UTC');
217
            }
218
            if (api_strtotime($item['logout'], 'UTC') > $maxLogin) {
219
                $maxLogin = api_strtotime($item['logout'], 'UTC');
220
            }
221
222
            // Partials
223
            $partialDuration += $item['duration'];
224
            if (empty($partialMinLogin)) {
225
                $partialMinLogin = api_strtotime($item['login'], 'UTC');
226
            }
227
            if ($partialMinLogin > api_strtotime($item['login'], 'UTC')) {
228
                $partialMinLogin = api_strtotime($item['login'], 'UTC');
229
            }
230
            if (api_strtotime($item['logout'], 'UTC') > $partialMaxLogin) {
231
                $partialMaxLogin = api_strtotime($item['logout'], 'UTC');
232
            }
233
        }
234
235
        if (!empty($result)) {
236
            $record = [
237
                customDate($partialMinLogin, true),
238
                customDate($partialMaxLogin, true),
239
                api_format_time($partialDuration, 'lang'),
240
            ];
241
242
            $report[0]['courses'][$course['course_id']][] = $record;
243
            $report[0]['name'][$course['course_id']] = $course['title'];
244
        }
245
    }
246
247
    $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
248
    $headers = [
249
        get_lang('MinStartDate'),
250
        get_lang('MaxEndDate'),
251
        get_lang('TotalDuration'),
252
    ];
253
    $row = 0;
254
    $column = 0;
255
    foreach ($headers as $header) {
256
        $table->setHeaderContents($row, $column, $header);
257
        $column++;
258
    }
259
    $row++;
260
    $column = 0;
261
    $table->setCellContents($row, $column++, customDate($minLogin));
262
    $table->setCellContents($row, $column++, customDate($maxLogin));
263
    $table->setRowAttributes($row, ['style' => 'font-weight:bold']);
264
    $table->setCellContents($row, $column++, api_format_time($totalDuration, 'lang'));
265
266
    $first = $table->toHtml();
267
268
    $courseSessionTable = '';
269
    $courseSessionTableData = [];
270
    $iconCourse = Display::return_icon('course.png', null, [], ICON_SIZE_SMALL);
271
    foreach ($report as $sessionId => $data) {
272
        foreach ($data['courses'] as $courseId => $courseData) {
273
            if (empty($courseData)) {
274
                continue;
275
            }
276
            $courseSessionTable .= '<div class="data-title">'.Display::page_subheader3(
277
                    $iconCourse.$data['name'][$courseId]
278
                ).'</div>';
279
            $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
280
            $headers = [
281
                get_lang('StartDate'),
282
                get_lang('EndDate'),
283
                get_lang('Duration'),
284
            ];
285
            $row = 0;
286
            $column = 0;
287
            foreach ($headers as $header) {
288
                $table->setHeaderContents($row, $column, $header);
289
                $column++;
290
            }
291
            $row++;
292
            $countData = count($courseData);
293
            foreach ($courseData as $record) {
294
                $column = 0;
295
                foreach ($record as $item) {
296
                    $table->setCellContents($row, $column++, $item);
297
                    if ($row == $countData) {
298
                        $courseSessionTableData[$data['name'][$courseId]] = $item;
299
                        $table->setRowAttributes($row, ['style' => 'font-weight:bold']);
300
                    }
301
                }
302
                $row++;
303
            }
304
            $courseSessionTable .= $table->toHtml();
305
        }
306
    }
307
    $totalCourseSessionTable = '';
308
    if ($courseSessionTableData) {
309
        $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
310
        $headers = [
311
            get_lang('Course'),
312
            get_lang('TotalDuration'),
313
        ];
314
        $row = 0;
315
        $column = 0;
316
        foreach ($headers as $header) {
317
            $table->setHeaderContents($row, $column, $header);
318
            $column++;
319
        }
320
        $row++;
321
        foreach ($courseSessionTableData as $name => $duration) {
322
            $column = 0;
323
            $table->setCellContents($row, $column++, $name);
324
            $table->setCellContents($row, $column++, $duration);
325
            $row++;
326
        }
327
        $totalCourseSessionTable = $table->toHtml();
328
    }
329
330
    $result = [];
331
    $result['first'] = $first;
332
    $result['second'] = $courseSessionTable;
333
    $result['third'] = $totalCourseSessionTable;
334
    $result['total'] = $totalDuration;
335
336
    return $result;
337
}
338
339
if ($form->validate()) {
340
    $values = $form->getSubmitValues();
341
    $from = $values['from'];
342
    $to = $values['to'];
343
344
    $from = DateTime::createFromFormat('d/m/Y', $from);
345
    $to = DateTime::createFromFormat('d/m/Y', $to);
346
347
    $from = api_get_utc_datetime($from->format('Y-m-d'));
348
    $to = api_get_utc_datetime($to->format('Y-m-d'));
349
    $title = Display::page_subheader3(sprintf(get_lang('ExtractionFromX'), api_get_local_time()));
350
    $result = getReport($userId, $from, $to);
351
352
    $first = $result['first'];
353
    $courseSessionTable = $result['second'];
354
    $totalCourseSessionTable = $result['third'];
355
356
    $tpl = new Template('', false, false, false, true, false, false);
357
    $tpl->assign('title', get_lang('RealisationCertificate'));
358
    $tpl->assign('student', $userInfo['complete_name']);
359
    $tpl->assign('table_progress', $title.$first.$totalCourseSessionTable.'<pagebreak>'.$courseSessionTable);
360
361
    $content = $tpl->fetch($tpl->get_template('my_space/pdf_export_student.tpl'));
362
363
    $params = [
364
        'pdf_title' => get_lang('Resume'),
365
        'course_info' => '',
366
        'pdf_date' => '',
367
        'student_info' => $userInfo,
368
        'show_grade_generated_date' => true,
369
        'show_real_course_teachers' => false,
370
        'show_teacher_as_myself' => false,
371
        'orientation' => 'P',
372
    ];
373
374
    $pdfName = api_strtoupper($userInfo['lastname'].'_'.$userInfo['firstname']).'_'.api_get_local_time();
375
    @$pdf = new PDF('A4', $params['orientation'], $params);
376
    @$pdf->setBackground($tpl->theme);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for setBackground(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

376
    /** @scrutinizer ignore-unhandled */ @$pdf->setBackground($tpl->theme);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
377
    @$pdf->content_to_pdf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for content_to_pdf(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

377
    /** @scrutinizer ignore-unhandled */ @$pdf->content_to_pdf(

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
378
        $content,
379
        '',
380
        $pdfName,
381
        null,
382
        'D',
383
        false,
384
        null,
385
        false,
386
        true,
387
        false
388
    );
389
    exit;
390
}
391
392
$interbreadcrumb[] = ['url' => '#', 'name' => get_lang('AccessDetails')];
393
$userInfo = api_get_user_info($userId);
394
395
$form->setDefaults(['from' => $startDate, 'to' => $endDate]);
396
397
$formByDay = new FormValidator(
398
    'by_day',
399
    'get',
400
    api_get_self().'?user_id='.$userId,
401
    null,
402
    ['id' => 'by_day']
403
);
404
$formByDay->addElement('text', 'from', get_lang('From'), ['placeholder' => get_lang('DateFormatddmmyyyy')]);
405
$formByDay->addElement('text', 'to', get_lang('Until'), ['placeholder' => get_lang('DateFormatddmmyyyy')]);
406
$formByDay->addCheckBox('reduced', null, get_lang('ReducedReport'));
407
$formByDay->addHidden('user_id', $userId);
408
$formByDay->addRule('from', get_lang('ThisFieldIsRequired'), 'required');
409
$formByDay->addRule('from', get_lang('ThisFieldIsRequired').' dd/mm/yyyy', 'callback', 'validateDate');
410
$formByDay->addRule('to', get_lang('ThisFieldIsRequired'), 'required');
411
$formByDay->addRule('to', get_lang('ThisFieldIsRequired').' dd/mm/yyyy', 'callback', 'validateDate');
412
$formByDay->addButtonSearch(get_lang('GenerateReport'));
413
414
if ($formByDay->validate()) {
415
    $from = $formByDay->getSubmitValue('from');
416
    $to = $formByDay->getSubmitValue('to');
417
    $reduced = !empty($formByDay->getSubmitValue('reduced'));
418
419
    $fromObject = DateTime::createFromFormat('d/m/Y', $from);
420
    $toObject = DateTime::createFromFormat('d/m/Y', $to);
421
422
    $from = api_get_utc_datetime($fromObject->format('Y-m-d').' 00:00:00');
423
    $to = api_get_utc_datetime($toObject->format('Y-m-d').' 23:59:59');
424
425
    $list = Tracking::get_time_spent_on_the_platform($userId, 'wide', $from, $to, true);
426
    $newList = [];
427
    foreach ($list as $item) {
428
        $key = substr($item['login_date'], 0, 10);
429
430
        $dateLogout = substr($item['logout_date'], 0, 10);
431
        if ($dateLogout > $key) {
432
            $itemLogoutOriginal = $item['logout_date'];
433
            $fromItemObject = DateTime::createFromFormat('Y-m-d H:i:s', $item['login_date'], new DateTimeZone('UTC'));
434
            $toItemObject = DateTime::createFromFormat('Y-m-d H:i:s', $item['logout_date'], new DateTimeZone('UTC'));
435
            $item['logout_date'] = api_get_utc_datetime($key.' 23:59:59');
436
437
            $period = new DatePeriod(
438
                $fromItemObject,
439
                new DateInterval('P1D'),
440
                $toItemObject
441
            );
442
443
            $counter = 1;
444
            $itemKey = null;
445
            foreach ($period as $value) {
446
                $dateToCheck = api_get_utc_datetime($value->format('Y-m-d').' 00:00:01');
447
                $end = api_get_utc_datetime($value->format('Y-m-d').' 23:59:59');
448
                if ($counter === 1) {
449
                    $dateToCheck = $item['login_date'];
450
                }
451
                $itemKey = substr($value->format('Y-m-d'), 0, 10);
452
453
                if (isset($newList[$itemKey])) {
454
                    if ($newList[$itemKey]['login_date']) {
455
                        $dateToCheck = $newList[$itemKey]['login_date'];
456
                    }
457
                }
458
459
                $newList[$itemKey] = [
460
                    'login_date' => $dateToCheck,
461
                    'logout_date' => $end,
462
                    'diff' => 0,
463
                ];
464
465
                $counter++;
466
            }
467
468
            if (!empty($itemKey) && isset($newList[$itemKey])) {
469
                if (
470
                    substr(api_get_local_time($newList[$itemKey]['login_date']), 0, 10) ===
471
                    substr(api_get_local_time($itemLogoutOriginal), 0, 10)
472
                ) {
473
                    $newList[$itemKey]['logout_date'] = $itemLogoutOriginal;
474
                }
475
            }
476
        }
477
478
        if (!isset($newList[$key])) {
479
            $newList[$key] = [
480
                'login_date' => $item['login_date'],
481
                'logout_date' => $item['logout_date'],
482
                'diff' => 0,
483
            ];
484
        } else {
485
            $newList[$key] = [
486
                'login_date' => $newList[$key]['login_date'],
487
                'logout_date' => $item['logout_date'],
488
                'diff' => 0,
489
            ];
490
        }
491
    }
492
493
    if (!empty($newList)) {
494
        foreach ($newList as &$item) {
495
            $item['diff'] = api_strtotime($item['logout_date']) - api_strtotime($item['login_date']);
496
        }
497
    }
498
499
    $period = new DatePeriod(
500
        $fromObject,
501
        new DateInterval('P1D'),
502
        $toObject
503
    );
504
505
    $tableList = '';
506
    foreach ($period as $value) {
507
        $dateToCheck = $value->format('Y-m-d');
508
        $data = isset($newList[$dateToCheck]) ? $newList[$dateToCheck] : [];
509
510
        if (empty($data)) {
511
            continue;
512
        }
513
514
        $table = new HTML_Table(['class' => ' table_print']);
515
        $headers = [
516
            get_lang('FirstLogin'),
517
            get_lang('LastConnection'),
518
            get_lang('Total'),
519
        ];
520
521
        $row = 0;
522
        $column = 0;
523
        foreach ($headers as $header) {
524
            $table->setHeaderContents($row, $column, $header);
525
            $column++;
526
        }
527
528
        $row = 1;
529
        $column = 0;
530
        $table->setCellContents($row, $column++, customDate($data['login_date'], true));
531
        $table->setCellContents($row, $column++, customDate($data['logout_date'], true));
532
        $table->setCellContents($row, $column, api_format_time($data['diff'], 'lang'));
533
534
        $result = getReport($userId, $dateToCheck, $dateToCheck, true);
535
        $first = $result['first'];
536
        $courseSessionTable = $result['second'];
537
        $totalCourseSessionTable = $result['third'];
538
        $total = $result['total'];
539
        $iconCalendar = Display::return_icon('calendar.png', null, [], ICON_SIZE_SMALL);
540
        $tableList .= '<div class="date-calendar">'.Display::page_subheader2(
541
                $iconCalendar.get_lang('Date').': '.$dateToCheck
542
            ).'</div>';
543
        $tableList .= $table->toHtml();
544
        if (!$reduced && !empty($total)) {
545
            $diff = get_lang('NotInCourse').' '.api_format_time($data['diff'] - $total, 'lang');
546
            $tableList .= $courseSessionTable;
547
            $tableList .= $totalCourseSessionTable;
548
            $tableList .= '<div style="text-align: center;">'.Display::page_subheader3($diff).'</div>';
549
        }
550
    }
551
552
    $tpl = new Template('', false, false, false, true, false, false);
553
    $tpl->assign('title', get_lang('RealisationCertificate'));
554
    $tpl->assign('student', $userInfo['complete_name']);
555
    $totalTable = Display::page_subheader3(sprintf(get_lang('ExtractionFromX'), api_get_local_time()));
556
    $tpl->assign('table_progress', $totalTable.$tableList);
557
558
    $content = $tpl->fetch($tpl->get_template('my_space/pdf_export_student.tpl'));
559
560
    $params = [
561
        'pdf_title' => get_lang('Resume'),
562
        'course_info' => '',
563
        'pdf_date' => '',
564
        'student_info' => $userInfo,
565
        'show_grade_generated_date' => true,
566
        'show_real_course_teachers' => false,
567
        'show_teacher_as_myself' => false,
568
        'orientation' => 'P',
569
    ];
570
    $pdfName = api_strtoupper($userInfo['lastname'].'_'.$userInfo['firstname']).'_'.api_get_local_time();
571
    @$pdf = new PDF('A4', $params['orientation'], $params);
572
    @$pdf->setBackground($tpl->theme, true);
573
    @$pdf->content_to_pdf(
574
        $content,
575
        '',
576
        $pdfName,
577
        null,
578
        'D',
579
        false,
580
        null,
581
        false,
582
        true,
583
        false
584
    );
585
    exit;
586
}
587
588
$formByDay->setDefaults(['from' => $startDate, 'to' => $endDate]);
589
590
Display::display_header('');
591
echo Display::page_header(get_lang('CertificateOfAchievement'), get_lang('CertificateOfAchievementHelp'));
592
echo Display::page_subheader(
593
    get_lang('User').': '.$userInfo['complete_name']
594
);
595
596
echo Display::tabs(
597
    [get_lang('CertificateOfAchievement'), get_lang('CertificateOfAchievementByDay')],
598
    [$form->returnForm(), $formByDay->returnForm()]
599
);
600
601
Display::display_footer();
602