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

generateHtmlForTasks()   B

Complexity

Conditions 7
Paths 14

Size

Total Lines 55
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 33
c 1
b 0
f 0
nc 14
nop 3
dl 0
loc 55
rs 8.4586

How to fix   Long Method   

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