Passed
Push — 1.11.x ( 698351...64ff3f )
by Angel Fernando Quiroz
10:36
created

generateHtmlForCourse()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 4
nop 4
dl 0
loc 28
rs 9.3888
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CLpCategory;
6
use Symfony\Component\HttpFoundation\Request as HttpRequest;
7
8
require_once __DIR__.'/../inc/global.inc.php';
9
require_once '../work/work.lib.php';
10
11
api_block_anonymous_users(false);
12
13
$allowedToTrackUser = api_is_platform_admin(true, true) ||
14
    api_is_allowed_to_edit(null, true) ||
15
    api_is_session_admin() ||
16
    api_is_drh() ||
17
    api_is_student_boss() ||
18
    api_is_course_admin() ||
19
    api_is_teacher();
20
21
if (!$allowedToTrackUser) {
22
    api_not_allowed();
23
}
24
25
$httpRequest = HttpRequest::createFromGlobals();
26
27
$studentInfo = api_get_user_info($httpRequest->query->getInt('student'));
28
29
if (empty($studentInfo)) {
30
    api_not_allowed();
31
}
32
33
function getCoursesInSession(int $studentId): array
34
{
35
    $coursesInSessions = [];
36
37
    $courseRelUser = Database::select(
38
        'c_id',
39
        Database::get_main_table(TABLE_MAIN_COURSE_USER),
40
        [
41
            'where' => [
42
                'relation_type <> ? AND user_id = ?' => [COURSE_RELATION_TYPE_RRHH, $studentId],
43
            ],
44
        ]
45
    );
46
    $sessionRelCourseRelUser = Database::select(
47
        ['session_id', 'c_id'],
48
        Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER),
49
        [
50
            'where' => [
51
                'user_id = ?' => $studentId,
52
            ],
53
        ]
54
    );
55
56
    foreach ($courseRelUser as $row) {
57
        $coursesInSessions[0][] = $row['c_id'];
58
    }
59
60
    foreach ($sessionRelCourseRelUser as $row) {
61
        $coursesInSessions[$row['session_id']][] = $row['c_id'];
62
    }
63
64
    return $coursesInSessions;
65
}
66
67
function generateForm(int $studentId, array $coursesInSessions): FormValidator
68
{
69
    $form = new FormValidator(
70
        'frm_export',
71
        'post',
72
        api_get_self()."?student=$studentId",
73
        '',
74
        [],
75
        FormValidator::LAYOUT_BOX
76
    );
77
78
    foreach ($coursesInSessions as $sId => $courses) {
79
        if (empty($courses)) {
80
            continue;
81
        }
82
83
        if ($sId) {
84
            $sessionInfo = api_get_session_info($sId);
85
86
            $dateSession = empty($sessionInfo['duration'])
87
                ? '('.SessionManager::parseSessionDates($sessionInfo, true)['display'].')'
88
                : '';
89
90
            $fieldTitle = $sessionInfo['name'].PHP_EOL.Display::tag('small', $dateSession);
91
        } else {
92
            $fieldTitle = get_lang('Courses');
93
        }
94
95
        $options = [];
96
97
        foreach ($courses as $courseId) {
98
            $courseInfoItem = api_get_course_info_by_id($courseId);
99
100
            if (empty($sessionInfo)) {
101
                $isSubscribed = CourseManager::is_user_subscribed_in_course(
102
                    $studentId,
103
                    $courseInfoItem['code']
104
                );
105
            } else {
106
                $isSubscribed = CourseManager::is_user_subscribed_in_course(
107
                    $studentId,
108
                    $courseInfoItem['code'],
109
                    true,
110
                    $sId
111
                );
112
            }
113
114
            if (!$isSubscribed) {
115
                continue;
116
            }
117
118
            $options[$sId.'_'.$courseId] = $courseInfoItem['title'];
119
        }
120
121
        $form->addCheckBoxGroup("sc", $fieldTitle, $options, ['checked' => 'checked']);
122
    }
123
124
    $form->addButtonExport(get_lang('ExportToPDF'));
125
126
    return $form;
127
}
128
129
function generateHtmlForLearningPaths(int $studentId, array $courseInfo, int $sessionId): string
130
{
131
    $student = api_get_user_entity($studentId);
132
133
    $html = Display::page_subheader2(get_lang('ToolLearnpath'));
134
135
    $columnHeaders = [];
136
    $columnHeaders['lp'] = get_lang('LearningPath');
137
    $columnHeaders['time'] = get_lang('Time');
138
    $columnHeaders['best_score'] = get_lang('BestScore');
139
    $columnHeaders['latest_attempt_avg_score'] = get_lang('LatestAttemptAverageScore');
140
    $columnHeaders['progress'] = get_lang('Progress');
141
    $columnHeaders['last_connection'] = get_lang('LastConnexion');
142
143
    $trackingColumns = api_get_configuration_value('tracking_columns');
144
145
    if (isset($trackingColumns['my_students_lp'])) {
146
        foreach ($columnHeaders as $key => $value) {
147
            if (!isset($trackingColumns['my_progress_lp'][$key]) || $trackingColumns['my_students_lp'][$key] == false) {
148
                unset($columnHeaders[$key]);
149
            }
150
        }
151
    }
152
153
    if (true === api_get_configuration_value('student_follow_page_add_LP_subscription_info')) {
154
        $columnHeaders['student_follow_page_add_LP_subscription_info'] = get_lang('Unlock');
155
    }
156
157
    if (true === api_get_configuration_value('student_follow_page_add_LP_acquisition_info')) {
158
        $columnHeaders['student_follow_page_add_LP_acquisition_info'] = get_lang('Acquisition');
159
    }
160
161
    $columnHeadersKeys = array_keys($columnHeaders);
162
163
    $hideInvisibleViews = api_get_configuration_value('student_follow_page_add_LP_invisible_checkbox');
164
165
    $timeCourse = Tracking::minimumTimeAvailable($sessionId, $courseInfo['real_id'])
166
        ? Tracking::getCalculateTime($student->getId(), $courseInfo['real_id'], $sessionId)
167
        : null;
168
169
    $lpCategories = learnpath::getCategories($courseInfo['real_id'], true);
170
171
    /** @var CLpCategory $item */
172
    foreach ($lpCategories as $item) {
173
        $categoryId = $item->getId();
174
175
        if (!learnpath::categoryIsVisibleForStudent($item, $student, $courseInfo['real_id'], $sessionId)) {
176
            continue;
177
        }
178
179
        $lpList = new LearnpathList(
180
            $student->getId(),
181
            $courseInfo,
182
            $sessionId,
183
            null,
184
            false,
185
            $categoryId,
186
            false,
187
            false,
188
            false
189
        );
190
191
        $flatList = $lpList->get_flat_list();
192
193
        if (count($lpCategories) > 1) {
194
            $html .= Display::page_subheader3($item->getName());
195
        }
196
197
        $lpTable = [$columnHeaders];
198
199
        foreach ($flatList as $learnpath) {
200
            $lpId = $learnpath['lp_old_id'];
201
202
            if ($hideInvisibleViews
203
                && !StudentFollowPage::isViewVisible($lpId, $student->getId(), $courseInfo['real_id'], $sessionId)
204
            ) {
205
                continue;
206
            }
207
208
            $contentToExport = [];
209
210
            if (in_array('lp', $columnHeadersKeys)) {
211
                $contentToExport[] = api_html_entity_decode(stripslashes($learnpath['lp_name']), ENT_QUOTES);
212
            }
213
214
            if (in_array('time', $columnHeadersKeys)) {
215
                // Get time in lp
216
                if (!empty($timeCourse)) {
217
                    $lpTime = $timeCourse[TOOL_LEARNPATH] ?? 0;
218
                    $totalTime = isset($lpTime[$lpId]) ? (int) $lpTime[$lpId] : 0;
219
                } else {
220
                    $totalTime = Tracking::get_time_spent_in_lp(
221
                        $student->getId(),
222
                        $courseInfo['code'],
223
                        [$lpId],
224
                        $sessionId
225
                    );
226
                }
227
228
                $contentToExport[] = api_time_to_hms($totalTime);
229
            }
230
231
            if (in_array('best_score', $columnHeadersKeys)) {
232
                $bestScore = Tracking::get_avg_student_score(
233
                    $student->getId(),
234
                    $courseInfo['code'],
235
                    [$lpId],
236
                    $sessionId,
237
                    false,
238
                    false,
239
                    true
240
                );
241
242
                $contentToExport[] = empty($bestScore) ? '' : "$bestScore %";
243
            }
244
245
            if (in_array('latest_attempt_avg_score', $columnHeadersKeys)) {
246
                $scoreLatest = Tracking::get_avg_student_score(
247
                    $student->getId(),
248
                    $courseInfo['code'],
249
                    [$lpId],
250
                    $sessionId,
251
                    false,
252
                    true
253
                );
254
255
                if (isset($scoreLatest) && is_numeric($scoreLatest)) {
256
                    $scoreLatest = "$scoreLatest %";
257
                }
258
259
                $contentToExport[] = $scoreLatest;
260
            }
261
262
            if (in_array('progress', $columnHeadersKeys)) {
263
                $progress = Tracking::get_avg_student_progress(
264
                    $student->getId(),
265
                    $courseInfo['code'],
266
                    [$lpId],
267
                    $sessionId
268
                );
269
270
                $contentToExport[] = is_numeric($progress) ? "$progress %" : '0 %';
271
            }
272
273
            if (in_array('last_connection', $columnHeadersKeys)) {
274
                // Get last connection time in lp
275
                $startTime = Tracking::get_last_connection_time_in_lp(
276
                    $student->getId(),
277
                    $courseInfo['code'],
278
                    $lpId,
279
                    $sessionId
280
                );
281
282
                $contentToExport[] = empty($startTime)
283
                    ? '-'
284
                    : api_convert_and_format_date($startTime, DATE_TIME_FORMAT_LONG);
285
            }
286
287
            if (in_array('student_follow_page_add_LP_subscription_info', $columnHeadersKeys)) {
288
                $lpSubscription = StudentFollowPage::getLpSubscription(
289
                    $learnpath,
290
                    $student->getId(),
291
                    $courseInfo['real_id'],
292
                    $sessionId
293
                );
294
                $contentToExport[] = strip_tags(str_replace('<br>', "\n", $lpSubscription));
295
            }
296
297
            if (in_array('student_follow_page_add_LP_acquisition_info', $columnHeadersKeys)) {
298
                $lpAcquisition = StudentFollowPage::getLpAcquisition(
299
                    $learnpath,
300
                    $student->getId(),
301
                    $courseInfo['real_id'],
302
                    $sessionId
303
                );
304
                $contentToExport[] = strip_tags(str_replace('<br>', "\n", $lpAcquisition));
305
            }
306
307
            $lpTable[] = $contentToExport;
308
        }
309
310
        $html .= Export::convert_array_to_html($lpTable);
311
    }
312
313
    return $html;
314
}
315
316
function generateHtmlForQuizzes(int $studentId, array $courseInfo, int $sessionId): string
317
{
318
    $html = Display::page_subheader2(get_lang('ToolQuiz'));
319
320
    $columnHeaders = [];
321
    $columnHeaders[] = get_lang('Exercises');
322
    $columnHeaders[] = get_lang('LearningPath');
323
    $columnHeaders[] = get_lang('AvgCourseScore');
324
    $columnHeaders[] = get_lang('Attempts');
325
326
    $taskTable = [$columnHeaders];
327
328
    $tblQuiz = Database::get_course_table(TABLE_QUIZ_TEST);
329
    $sessionCondition = api_get_session_condition($sessionId, true, true, 'quiz.session_id');
330
331
    $sql = "SELECT quiz.title, id
332
        FROM $tblQuiz AS quiz
333
        WHERE
334
            quiz.c_id = ".$courseInfo['real_id']."
335
            AND active IN (0, 1)
336
            $sessionCondition
337
        ORDER BY quiz.title ASC";
338
    $resultExercices = Database::query($sql);
339
340
    if (Database::num_rows($resultExercices) > 0) {
341
        while ($exercices = Database::fetch_array($resultExercices)) {
342
            $exerciseId = (int) $exercices['id'];
343
            $countAttempts = Tracking::count_student_exercise_attempts(
344
                $studentId,
345
                $courseInfo['real_id'],
346
                $exerciseId,
347
                0,
348
                0,
349
                $sessionId,
350
                2
351
            );
352
            $scorePercentage = Tracking::get_avg_student_exercise_score(
353
                $studentId,
354
                $courseInfo['code'],
355
                $exerciseId,
356
                $sessionId
357
            );
358
359
            $lpName = '-';
360
361
            if (!isset($scorePercentage) && $countAttempts > 0) {
362
                $lpScores = Tracking::get_avg_student_exercise_score(
363
                    $studentId,
364
                    $courseInfo['code'],
365
                    $exerciseId,
366
                    $sessionId,
367
                    2,
368
                    1
369
                );
370
                $scorePercentage = $lpScores[0];
371
                $lpName = $lpScores[1];
372
            }
373
374
            $lpName = !empty($lpName) ? $lpName : get_lang('NoLearnpath');
375
376
            $contentToExport = [];
377
            $contentToExport[] = Exercise::get_formated_title_variable($exercices['title']);
378
            $contentToExport[] = empty($lpName) ? '-' : $lpName;
379
            $contentToExport[] = $countAttempts > 0 ? sprintf(get_lang('XPercent'), $scorePercentage) : '-';
380
            $contentToExport[] = $countAttempts;
381
382
            $taskTable[] = $contentToExport;
383
        }
384
385
        $html .= Export::convert_array_to_html($taskTable);
386
    }
387
388
    return $html;
389
}
390
391
function generateHtmlForTasks(int $studentId, array $courseInfo, int $sessionId): string
392
{
393
    $columnHeaders = [];
394
    $columnHeaders[] = get_lang('Tasks');
395
    $columnHeaders[] = get_lang('DocumentNumber');
396
    $columnHeaders[] = get_lang('Note');
397
    $columnHeaders[] = get_lang('HandedOut');
398
    $columnHeaders[] = get_lang('HandOutDateLimit');
399
    $columnHeaders[] = get_lang('ConsideredWorkingTime');
400
401
    $workingTime = api_get_configuration_value('considered_working_time');
402
403
    $userWorks = getWorkPerUser($studentId, $courseInfo['real_id'], $sessionId);
404
405
    $taskTable = [$columnHeaders];
406
407
    foreach ($userWorks as $work) {
408
        $work = $work['work'];
409
410
        foreach ($work->user_results as $key => $results) {
411
            $documentNumber = $key + 1;
412
413
            $contentToExport = [];
414
415
            $contentToExport[] = $work->title;
416
            $contentToExport[] = $documentNumber;
417
            $contentToExport[] = !empty($results['qualification']) ? $results['qualification'] : '-';
418
            $contentToExport[] = api_convert_and_format_date($results['sent_date_from_db']).PHP_EOL
419
                .$results['expiry_note'];
420
421
            $assignment = get_work_assignment_by_id($work->id, $courseInfo['real_id']);
422
423
            if (!empty($assignment['expires_on'])) {
424
                $contentToExport[] = api_convert_and_format_date($assignment['expires_on']);
425
            }
426
427
            $fieldValue = new ExtraFieldValue('work');
428
            $resultExtra = $fieldValue->getAllValuesForAnItem($work->iid, true);
429
430
            foreach ($resultExtra as $field) {
431
                $field = $field['value'];
432
433
                if ($workingTime == $field->getField()->getVariable()) {
434
                    $time = $field->getValue();
435
436
                    $contentToExport[] = $time;
437
                }
438
            }
439
440
            $taskTable[] = $contentToExport;
441
        }
442
    }
443
444
    return Display::page_subheader2(get_lang('ToolStudentPublication')).PHP_EOL
445
        .Export::convert_array_to_html($taskTable);
446
}
447
448
function generateHtmlForCourse(int $studentId, array $coursesInSessions, int $courseId, int $sessionId): ?string
449
{
450
    if (empty($coursesInSessions[$sessionId]) || !in_array($courseId, $coursesInSessions[$sessionId])) {
451
        return null;
452
    }
453
454
    $courseInfo = api_get_course_info_by_id($courseId);
455
456
    $courseHtml = [];
457
458
    if ($sessionId) {
459
        $sessionInfo = api_get_session_info($sessionId);
460
461
        $dateSession = empty($sessionInfo['duration'])
462
            ? '('.SessionManager::parseSessionDates($sessionInfo, true)['display'].')'
463
            : '';
464
465
        $courseHtml[] = Display::page_header($sessionInfo['name'].PHP_EOL.Display::tag('small', $dateSession))
466
            .Display::page_subheader($courseInfo['title']);
467
    } else {
468
        $courseHtml[] = Display::page_header($courseInfo['title']);
469
    }
470
471
    $courseHtml[] = generateHtmlForLearningPaths($studentId, $courseInfo, $sessionId);
472
    $courseHtml[] = generateHtmlForQuizzes($studentId, $courseInfo, $sessionId);
473
    $courseHtml[] = generateHtmlForTasks($studentId, $courseInfo, $sessionId);
474
475
    return implode(PHP_EOL, $courseHtml);
476
}
477
478
$coursesInSessions = getCoursesInSession($studentInfo['id']);
479
480
$form = generateForm($studentInfo['id'], $coursesInSessions);
481
482
if ($form->validate()) {
483
    $values = $form->exportValues();
484
485
    $studentInfo['status'] = api_get_status_langvars()[$studentInfo['status']];
486
    $studentInfo['official_code'] = empty($studentInfo['official_code']) ? get_lang('NoOfficialCode')
487
        : $studentInfo['code'];
488
    $studentInfo['phone'] = empty($studentInfo['phone']) ? get_lang('NoTel') : $studentInfo['phone'];
489
    $studentInfo['first_login'] = Tracking::get_first_connection_date($studentInfo['id']) ?? get_lang('NoConnexion');
490
    $studentInfo['last_login'] = Tracking::get_last_connection_date($studentInfo['id'], true)
491
        ?? get_lang('NoConnexion');
492
    $studentInfo['last_course_connection'] = api_format_date(
493
        Tracking::getLastConnectionInAnyCourse($studentInfo['id']),
494
        DATE_FORMAT_SHORT
495
    );
496
497
    $coursesInfo = [];
498
499
    if (!empty($values['sc'])) {
500
        foreach ($values['sc'] as $courseKey) {
501
            [$sessionId, $courseId] = explode('_', $courseKey);
502
503
            $coursesInfo[] = generateHtmlForCourse($studentInfo['id'], $coursesInSessions, $courseId, $sessionId);
504
        }
505
    }
506
507
    $view = new Template('', false, false, false, true, false, false);
508
    $view->assign('user_info', $studentInfo);
509
    $view->assign('carrers', MyStudents::getBlockForCareers($studentInfo['id']));
510
    $view->assign('skills', Tracking::displayUserSkills($studentInfo['id']));
511
    $view->assign('classes', MyStudents::getBlockForClasses($studentInfo['id']));
512
    $view->assign('courses_info', $coursesInfo);
513
514
    $template = $view->get_template('my_space/student_follow_pdf.tpl');
515
516
    $params = [
517
        'filename' => get_lang('StudentDetails'),
518
        'format' => 'A4',
519
        'orientation' => 'P',
520
    ];
521
522
    $css = api_get_print_css();
523
    $css = '
524
        .user-info { clear: both; }
525
        .user-info__col { float: left; width: 33.33%; }
526
    ';
527
528
    $pdf = new PDF($params['format'], $params['orientation'], $params);
529
530
    try {
531
        $pdf->content_to_pdf(
532
            $view->fetch($template),
533
            $css,
534
            get_lang('StudentDetails'),
535
            null,
536
            'D',
537
            false,
538
            null,
539
            false,
540
            true
541
        );
542
    } catch (MpdfException $e) {
543
        echo Display::return_message(get_lang('ErrorWhileBuildingReport'), 'error');
544
    }
545
546
    exit;
547
}
548
549
echo Display::page_subheader($studentInfo['complete_name_with_username']);
550
$form->display();
551