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

generateForm()   B

Complexity

Conditions 8
Paths 17

Size

Total Lines 60
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 36
c 2
b 0
f 0
nc 17
nop 2
dl 0
loc 60
rs 8.0995

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