Passed
Pull Request — 1.11.x (#3859)
by Angel Fernando Quiroz
09:48
created

generateHtmlForLearningPaths()   F

Complexity

Conditions 27
Paths > 20000

Size

Total Lines 174
Code Lines 109

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 27
eloc 109
c 1
b 0
f 0
nc 83008
nop 3
dl 0
loc 174
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
use Chamilo\CourseBundle\Entity\CLpCategory;
6
use Chamilo\UserBundle\Entity\User;
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
$studentId = isset($_GET['student']) ? (int) $_GET['student'] : 0;
26
27
$student = api_get_user_entity($studentId);
28
29
if (empty($student)) {
30
    api_not_allowed(true);
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
            $date_session = empty($sessionInfo['duration'])
87
                ? '('.SessionManager::parseSessionDates($sessionInfo, true)['display'].')'
88
                : '';
89
90
            $fieldTitle = $sessionInfo['name'].PHP_EOL.Display::tag('small', $date_session);
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(User $student, array $courseInfo, int $sessionId): string
130
{
131
    $html = Display::page_subheader2(get_lang('ToolLearnpath'));;
132
133
    $columnHeaders = [];
134
    $columnHeaders['lp'] = get_lang('LearningPath');
135
    $columnHeaders['time'] = get_lang('Time');
136
    $columnHeaders['best_score'] = get_lang('BestScore');
137
    $columnHeaders['latest_attempt_avg_score'] = get_lang('LatestAttemptAverageScore');
138
    $columnHeaders['progress'] = get_lang('Progress');
139
    $columnHeaders['last_connection'] = get_lang('LastConnexion');
140
141
    $trackingColumns = api_get_configuration_value('tracking_columns');
142
143
    if (isset($trackingColumns['my_students_lp'])) {
144
        foreach ($columnHeaders as $key => $value) {
145
            if (!isset($trackingColumns['my_progress_lp'][$key]) || $trackingColumns['my_students_lp'][$key] == false) {
146
                unset($columnHeaders[$key]);
147
            }
148
        }
149
    }
150
151
    if (true === api_get_configuration_value('student_follow_page_add_LP_subscription_info')) {
152
        $columnHeaders['student_follow_page_add_LP_subscription_info'] = get_lang('Unlock');
153
    }
154
155
    if (true === api_get_configuration_value('student_follow_page_add_LP_acquisition_info')) {
156
        $columnHeaders['student_follow_page_add_LP_acquisition_info'] = get_lang('Acquisition');
157
    }
158
159
    $columnHeadersKeys = array_keys($columnHeaders);
160
161
    $timeCourse = Tracking::minimumTimeAvailable($sessionId, $courseInfo['real_id'])
162
        ? Tracking::getCalculateTime($student->getId(), $courseInfo['real_id'], $sessionId)
163
        : null;
164
165
    $lpCategories = learnpath::getCategories($courseInfo['real_id'], true);
166
167
    /** @var CLpCategory $item */
168
    foreach ($lpCategories as $item) {
169
        $categoryId = $item->getId();
170
171
        if (!learnpath::categoryIsVisibleForStudent($item, $student, $courseInfo['real_id'], $sessionId)) {
172
            continue;
173
        }
174
175
        $lpList = new LearnpathList(
176
            api_get_user_id(),
177
            $courseInfo,
178
            $sessionId,
179
            null,
180
            false,
181
            $categoryId,
182
            false,
183
            true
184
        );
185
186
        $flat_list = $lpList->get_flat_list();
187
188
        if (count($lpCategories) > 1) {
189
            $html .= Display::page_subheader3($item->getName());
190
        }
191
192
        $lpTable = [$columnHeaders];
193
194
        foreach ($flat_list as $learnpath) {
195
            $lp_id = $learnpath['lp_old_id'];
196
197
            $contentToExport = [];
198
199
            if (in_array('lp', $columnHeadersKeys)) {
200
                $contentToExport[] = api_html_entity_decode(stripslashes($learnpath['lp_name']), ENT_QUOTES);
201
            }
202
203
            if (in_array('time', $columnHeadersKeys)) {
204
                // Get time in lp
205
                if (!empty($timeCourse)) {
206
                    $lpTime = $timeCourse[TOOL_LEARNPATH] ?? 0;
207
                    $total_time = isset($lpTime[$lp_id]) ? (int) $lpTime[$lp_id] : 0;
208
                } else {
209
                    $total_time = Tracking::get_time_spent_in_lp(
210
                        $student->getId(),
211
                        $courseInfo['code'],
212
                        [$lp_id],
213
                        $sessionId
214
                    );
215
                }
216
217
                $contentToExport[] = api_time_to_hms($total_time);
218
            }
219
220
            if (in_array('best_score', $columnHeadersKeys)) {
221
                $bestScore = Tracking::get_avg_student_score(
222
                    $student->getId(),
223
                    $courseInfo['code'],
224
                    [$lp_id],
225
                    $sessionId,
226
                    false,
227
                    false,
228
                    true
229
                );
230
231
                $contentToExport[] = empty($bestScore) ? '': "$bestScore %";
232
            }
233
234
            if (in_array('latest_attempt_avg_score', $columnHeadersKeys)) {
235
                $score_latest = Tracking::get_avg_student_score(
236
                    $student->getId(),
237
                    $courseInfo['code'],
238
                    [$lp_id],
239
                    $sessionId,
240
                    false,
241
                    true
242
                );
243
244
                if (isset($score_latest) && is_numeric($score_latest)) {
245
                    $score_latest = "$score_latest %";
246
                }
247
248
                $contentToExport[] = $score_latest;
249
            }
250
251
            if (in_array('progress', $columnHeadersKeys)) {
252
                $progress = Tracking::get_avg_student_progress(
253
                    $student->getId(),
254
                    $courseInfo['code'],
255
                    [$lp_id],
256
                    $sessionId
257
                );
258
259
                $contentToExport[] = is_numeric($progress) ? "$progress %" : '0 %';
260
            }
261
262
            if (in_array('last_connection', $columnHeadersKeys)) {
263
                // Get last connection time in lp
264
                $start_time = Tracking::get_last_connection_time_in_lp(
265
                    $student->getId(),
266
                    $courseInfo['code'],
267
                    $lp_id,
268
                    $sessionId
269
                );
270
271
                $contentToExport[] = empty($start_time)
272
                    ? '-'
273
                    : api_convert_and_format_date($start_time, DATE_TIME_FORMAT_LONG);
274
            }
275
276
            if (in_array('student_follow_page_add_LP_subscription_info', $columnHeadersKeys)) {
277
                $lpSubscription = StudentFollowPage::getLpSubscription(
278
                    $learnpath,
279
                    $student->getId(),
280
                    $courseInfo['real_id'],
281
                    $sessionId
282
                );
283
                $contentToExport[] = strip_tags(str_replace('<br>', "\n", $lpSubscription));
284
            }
285
286
            if (in_array('student_follow_page_add_LP_acquisition_info', $columnHeadersKeys)) {
287
                $lpAcquisition = StudentFollowPage::getLpAcquisition(
288
                    $learnpath,
289
                    $student->getId(),
290
                    $courseInfo['real_id'],
291
                    $sessionId
292
                );
293
                $contentToExport[] = strip_tags(str_replace('<br>', "\n", $lpAcquisition));
294
            }
295
296
            $lpTable[] = $contentToExport;
297
        }
298
299
        $html .= Export::convert_array_to_html($lpTable);
300
    }
301
302
    return $html;
303
}
304
305
function generateHtmlForQuizzes(int $studentId, array $courseInfo, int $sessionId): string
306
{
307
    $html = Display::page_subheader2(get_lang('ToolQuiz'));;
308
309
    $columnHeaders = [];
310
    $columnHeaders[] = get_lang('Exercises');
311
    $columnHeaders[] = get_lang('LearningPath');
312
    $columnHeaders[] = get_lang('AvgCourseScore');
313
    $columnHeaders[] = get_lang('Attempts');
314
315
    $taskTable = [$columnHeaders];
316
317
    $tblQuiz = Database::get_course_table(TABLE_QUIZ_TEST);
318
    $sessionCondition = api_get_session_condition($sessionId, true, true, 'quiz.session_id');
319
320
    $sql = "SELECT quiz.title, id
321
        FROM $tblQuiz AS quiz
322
        WHERE
323
            quiz.c_id = ".$courseInfo['real_id']."
324
            AND active IN (0, 1)
325
            $sessionCondition
326
        ORDER BY quiz.title ASC";
327
    $result_exercices = Database::query($sql);
328
329
    if (Database::num_rows($result_exercices) > 0) {
330
        while ($exercices = Database::fetch_array($result_exercices)) {
331
            $exerciseId = (int) $exercices['id'];
332
            $countAttempts = Tracking::count_student_exercise_attempts(
333
                $studentId,
334
                $courseInfo['real_id'],
335
                $exerciseId,
336
                0,
337
                0,
338
                $sessionId,
339
                2
340
            );
341
            $scorePercentage = Tracking::get_avg_student_exercise_score(
342
                $studentId,
343
                $courseInfo['code'],
344
                $exerciseId,
345
                $sessionId,
346
                1,
347
                0
348
            );
349
350
            $lpName = '-';
351
352
            if (!isset($scorePercentage) && $countAttempts > 0) {
353
                $lpScores = Tracking::get_avg_student_exercise_score(
354
                    $studentId,
355
                    $courseInfo['code'],
356
                    $exerciseId,
357
                    $sessionId,
358
                    2,
359
                    1
360
                );
361
                $scorePercentage = $lpScores[0];
362
                $lpName = $lpScores[1];
363
            }
364
            $lpName = !empty($lpName) ? $lpName : get_lang('NoLearnpath');
365
366
            $contentToExport = [];
367
            $contentToExport[] = Exercise::get_formated_title_variable($exercices['title']);
368
            $contentToExport[] = empty($lpName) ? '-' : $lpName;
369
            $contentToExport[] = $countAttempts > 0 ? sprintf(get_lang('XPercent'), $scorePercentage) : '-';
370
            $contentToExport[] = $countAttempts;
371
372
            $taskTable[] = $contentToExport;
373
        }
374
375
        $html .= Export::convert_array_to_html($taskTable);
376
    }
377
378
    return $html;
379
}
380
381
function generateHtmlForTasks(int $studentId, array $courseInfo, int $sessionId): string
382
{
383
    $columnHeaders = [];
384
    $columnHeaders[] = get_lang('Tasks');
385
    $columnHeaders[] = get_lang('DocumentNumber');
386
    $columnHeaders[] = get_lang('Note');
387
    $columnHeaders[] = get_lang('HandedOut');
388
    $columnHeaders[] = get_lang('HandOutDateLimit');
389
    $columnHeaders[] = get_lang('ConsideredWorkingTime');
390
391
    $workingTime = api_get_configuration_value('considered_working_time');
392
393
    $userWorks = getWorkPerUser($studentId, $courseInfo['real_id'], $sessionId);
394
395
    $taskTable = [$columnHeaders];
396
397
    foreach ($userWorks as $work) {
398
        $work = $work['work'];
399
400
        foreach ($work->user_results as $key => $results) {
401
            $documentNumber = $key + 1;
402
403
            $contentToExport = [];
404
405
            $contentToExport[] = $work->title;
406
            $contentToExport[] = $documentNumber;
407
            $contentToExport[] = !empty($results['qualification']) ? $results['qualification'] : '-';
408
            $contentToExport[] = api_convert_and_format_date($results['sent_date_from_db']).PHP_EOL
409
                .$results['expiry_note'];
410
411
            $assignment = get_work_assignment_by_id($work->id, $courseInfo['real_id']);
412
413
            if (!empty($assignment['expires_on'])) {
414
                $contentToExport[] = api_convert_and_format_date($assignment['expires_on']);
415
            }
416
417
            $fieldValue = new ExtraFieldValue('work');
418
            $resultExtra = $fieldValue->getAllValuesForAnItem($work->iid, true);
419
420
            foreach ($resultExtra as $field) {
421
                $field = $field['value'];
422
423
                if ($workingTime == $field->getField()->getVariable()) {
424
                    $time = $field->getValue();
425
426
                    $contentToExport[] = $time;
427
                }
428
            }
429
430
            $taskTable[] = $contentToExport;
431
        }
432
    }
433
434
    return Display::page_subheader2(get_lang('ToolStudentPublication')).PHP_EOL
435
        .Export::convert_array_to_html($taskTable);
436
}
437
438
$coursesInSessions = getCoursesInSession($studentId);
439
440
$form = generateForm($studentId, $coursesInSessions);
441
442
if ($form->validate()) {
443
    $values = $form->exportValues();
444
445
    $pdfHtml = [];
446
447
    if (!empty($values['sc'])) {
448
        foreach ($values['sc'] as $courseKey) {
449
            [$sessionId, $courseId] = explode('_', $courseKey);
450
451
            if (empty($coursesInSessions[$sessionId]) || !in_array($courseId, $coursesInSessions[$sessionId])) {
452
                continue;
453
            }
454
455
            $courseInfo = api_get_course_info_by_id($courseId);
456
457
            $courseHtml = '';
458
459
            if ($sessionId) {
460
                $sessionInfo = api_get_session_info($sessionId);
461
462
                $date_session = empty($sessionInfo['duration'])
463
                    ? '('.SessionManager::parseSessionDates($sessionInfo, true)['display'].')'
464
                    : '';
465
466
                $courseHtml .= Display::page_header($sessionInfo['name'].PHP_EOL.Display::tag('small', $date_session))
467
                    .Display::page_subheader($courseInfo['title']);
468
            } else {
469
                $courseHtml .= Display::page_header($courseInfo['title']);
470
            }
471
472
            $courseHtml .= generateHtmlForLearningPaths($student, $courseInfo, $sessionId);
473
            $courseHtml .= generateHtmlForQuizzes($studentId, $courseInfo, $sessionId);
474
            $courseHtml .= generateHtmlForTasks($studentId, $courseInfo, $sessionId);
475
476
            $pdfHtml[] = $courseHtml;
477
        }
478
    }
479
480
    $params = [
481
        'filename' => get_lang('StudentFollow'),
482
        'pdf_title' => $student->getCompleteNameWithUsername(),
483
        'format' => 'A4',
484
        'orientation' => 'P',
485
    ];
486
487
    $pdf = new PDF($params['format'], $params['orientation'], $params);
488
    $pdf->html_to_pdf_with_template(implode('<pagebreak>', $pdfHtml));
489
490
    exit;
491
}
492
493
echo Display::page_subheader($student->getCompleteNameWithUsername());
494
$form->display();
495