Passed
Push — master ( 6f8cb0...cccadf )
by Julito
09:47
created

GradebookUtils::get_user_array_from_sql_result()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 1
dl 0
loc 16
rs 9.9
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class GradebookUtils.
6
 */
7
class GradebookUtils
8
{
9
    /**
10
     * Adds a resource to the unique gradebook of a given course.
11
     *
12
     * @param   int
13
     * @param   string  Course code
14
     * @param   int     Resource type (use constants defined in linkfactory.class.php)
15
     * @param   int     Resource ID in the corresponding tool
16
     * @param   string  Resource name to show in the gradebook
17
     * @param   int     Resource weight to set in the gradebook
18
     * @param   int     Resource max
19
     * @param   string  Resource description
20
     * @param   int     Visibility (0 hidden, 1 shown)
21
     * @param   int     Session ID (optional or 0 if not defined)
22
     * @param   int
23
     * @param int $resource_type
24
     *
25
     * @return bool True on success, false on failure
26
     */
27
    public static function add_resource_to_course_gradebook(
28
        $category_id,
29
        $course_code,
30
        $resource_type,
31
        $resource_id,
32
        $resource_name = '',
33
        $weight = 0,
34
        $max = 0,
35
        $resource_description = '',
36
        $visible = 0,
37
        $session_id = 0,
38
        $link_id = null
39
    ) {
40
        $link = LinkFactory::create($resource_type);
41
        $link->set_user_id(api_get_user_id());
42
        $link->set_course_code($course_code);
43
44
        if (empty($category_id)) {
45
            return false;
46
        }
47
        $link->set_category_id($category_id);
48
        if ($link->needs_name_and_description()) {
49
            $link->set_name($resource_name);
50
        } else {
51
            $link->set_ref_id($resource_id);
52
        }
53
        $link->set_weight($weight);
54
55
        if ($link->needs_max()) {
56
            $link->set_max($max);
57
        }
58
        if ($link->needs_name_and_description()) {
59
            $link->set_description($resource_description);
60
        }
61
62
        $link->set_visible(empty($visible) ? 0 : 1);
63
64
        if (!empty($session_id)) {
65
            $link->set_session_id($session_id);
66
        }
67
        $link->add();
68
69
        return true;
70
    }
71
72
    /**
73
     * Update a resource weight.
74
     *
75
     * @param    int     Link/Resource ID
0 ignored issues
show
Documentation Bug introduced by
The doc comment Link/Resource at position 0 could not be parsed: Unknown type name 'Link/Resource' at position 0 in Link/Resource.
Loading history...
76
     * @param   string
77
     * @param float
78
     *
79
     * @return bool false on error, true on success
80
     */
81
    public static function updateResourceFromCourseGradebook(
82
        $link_id,
83
        $course_code,
84
        $weight
85
    ) {
86
        $link_id = (int) $link_id;
87
        $courseInfo = api_get_course_info($course_code);
88
        if (!empty($link_id) && !empty($courseInfo)) {
89
            $link_id = intval($link_id);
90
            $courseId = $courseInfo['real_id'];
91
            $sql = 'UPDATE '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK).'
92
                    SET weight = '."'".api_float_val($weight)."'".'
93
                    WHERE c_id = "'.$courseId.'" AND id = '.$link_id;
94
            Database::query($sql);
95
        }
96
97
        return true;
98
    }
99
100
    /**
101
     * Remove a resource from the unique gradebook of a given course.
102
     *
103
     * @param    int     Link/Resource ID
0 ignored issues
show
Documentation Bug introduced by
The doc comment Link/Resource at position 0 could not be parsed: Unknown type name 'Link/Resource' at position 0 in Link/Resource.
Loading history...
104
     *
105
     * @return bool false on error, true on success
106
     */
107
    public static function remove_resource_from_course_gradebook($link_id)
108
    {
109
        if (empty($link_id)) {
110
            return false;
111
        }
112
113
        // TODO find the corresponding category (the first one for this course, ordered by ID)
114
        $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
115
        $sql = "DELETE FROM $l WHERE id = ".(int) $link_id;
116
        Database::query($sql);
117
118
        return true;
119
    }
120
121
    /**
122
     * Block students.
123
     */
124
    public static function block_students()
125
    {
126
        $sessionId = api_get_session_id();
127
        if (empty($sessionId)) {
128
            if (!api_is_allowed_to_edit()) {
129
                api_not_allowed();
130
            }
131
        } else {
132
            $isCoach = api_is_coach(api_get_session_id(), api_get_course_int_id());
133
            if ($isCoach === false) {
134
                if (!api_is_allowed_to_edit()) {
135
                    api_not_allowed();
136
                }
137
            }
138
        }
139
    }
140
141
    /**
142
     * Builds an img tag for a gradebook item.
143
     */
144
    public static function build_type_icon_tag($kind, $attributes = [])
145
    {
146
        return Display::return_icon(
147
            self::get_icon_file_name($kind),
148
            ' ',
149
            $attributes,
150
            ICON_SIZE_SMALL
151
        );
152
    }
153
154
    /**
155
     * Returns the icon filename for a gradebook item.
156
     *
157
     * @param string $type value returned by a gradebookitem's get_icon_name()
158
     *
159
     * @return string
160
     */
161
    public static function get_icon_file_name($type)
162
    {
163
        switch ($type) {
164
            case 'cat':
165
                $icon = 'gradebook.png';
166
                break;
167
            case 'evalempty':
168
                $icon = 'empty_evaluation.png';
169
                break;
170
            case 'evalnotempty':
171
                $icon = 'no_empty_evaluation.png';
172
                break;
173
            case 'exercise':
174
            case LINK_EXERCISE:
175
                $icon = 'quiz.png';
176
                break;
177
            case 'learnpath':
178
            case LINK_LEARNPATH:
179
                $icon = 'learnpath.png';
180
                break;
181
            case 'studentpublication':
182
            case LINK_STUDENTPUBLICATION:
183
                $icon = 'works.gif';
184
                break;
185
            case 'link':
186
                $icon = 'link.gif';
187
                break;
188
            case 'forum':
189
            case LINK_FORUM_THREAD:
190
                $icon = 'forum.gif';
191
                break;
192
            case 'attendance':
193
            case LINK_ATTENDANCE:
194
                $icon = 'attendance.gif';
195
                break;
196
            case 'survey':
197
            case LINK_SURVEY:
198
                $icon = 'survey.gif';
199
                break;
200
            case 'dropbox':
201
            case LINK_DROPBOX:
202
                $icon = 'dropbox.gif';
203
                break;
204
            default:
205
                $icon = 'link.gif';
206
                break;
207
        }
208
209
        return $icon;
210
    }
211
212
    /**
213
     * Builds the course or platform admin icons to edit a category.
214
     *
215
     * @param Category $cat       category
216
     * @param Category $selectcat id of selected category
217
     *
218
     * @return string
219
     */
220
    public static function build_edit_icons_cat($cat, $selectcat)
221
    {
222
        $show_message = $cat->show_message_resource_delete($cat->get_course_code());
223
        $grade_model_id = $selectcat->get_grade_model_id();
224
        $selectcat = $selectcat->get_id();
225
        $modify_icons = null;
226
227
        if ($show_message === false) {
228
            $visibility_icon = ($cat->is_visible() == 0) ? 'invisible' : 'visible';
229
            $visibility_command = ($cat->is_visible() == 0) ? 'set_visible' : 'set_invisible';
230
231
            $modify_icons .= '<a class="view_children" data-cat-id="'.$cat->get_id().'" href="javascript:void(0);">'.
232
                Display::return_icon(
233
                    'view_more_stats.gif',
234
                    get_lang('Show'),
235
                    '',
236
                    ICON_SIZE_SMALL
237
                ).
238
                '</a>';
239
240
            if (!api_is_allowed_to_edit(null, true)) {
241
                $modify_icons .= Display::url(
242
                    Display::return_icon(
243
                        'statistics.png',
244
                        get_lang('FlatView'),
245
                        '',
246
                        ICON_SIZE_SMALL
247
                    ),
248
                    'personal_stats.php?'.http_build_query([
249
                        'selectcat' => $cat->get_id(),
250
                    ]).'&'.api_get_cidreq(),
251
                    [
252
                        'class' => 'ajax',
253
                        'data-title' => get_lang('FlatView'),
254
                    ]
255
                );
256
            }
257
258
            $courseParams = api_get_cidreq_params(
259
                $cat->get_course_code(),
260
                $cat->get_session_id()
261
            );
262
263
            if (api_is_allowed_to_edit(null, true)) {
264
                // Locking button
265
                if (api_get_setting('gradebook_locking_enabled') == 'true') {
266
                    if ($cat->is_locked()) {
267
                        if (api_is_platform_admin()) {
268
                            $modify_icons .= '&nbsp;<a onclick="javascript:if (!confirm(\''.addslashes(get_lang('ConfirmToUnlockElement')).'\')) return false;" href="'.api_get_self().'?'.api_get_cidreq().'&category_id='.$cat->get_id().'&action=unlock">'.
269
                                Display::return_icon('lock.png', get_lang('UnLockEvaluation'), '', ICON_SIZE_SMALL).'</a>';
270
                        } else {
271
                            $modify_icons .= '&nbsp;<a href="#">'.
272
                                Display::return_icon('lock_na.png', get_lang('GradebookLockedAlert'), '', ICON_SIZE_SMALL).'</a>';
273
                        }
274
                        $modify_icons .= '&nbsp;<a href="gradebook_flatview.php?export_pdf=category&selectcat='.$cat->get_id().'" >'.Display::return_icon('pdf.png', get_lang('ExportToPDF'), '', ICON_SIZE_SMALL).'</a>';
275
                    } else {
276
                        $modify_icons .= '&nbsp;<a onclick="javascript:if (!confirm(\''.addslashes(get_lang('ConfirmToLockElement')).'\')) return false;" href="'.api_get_self().'?'.api_get_cidreq().'&category_id='.$cat->get_id().'&action=lock">'.
277
                            Display::return_icon('unlock.png', get_lang('LockEvaluation'), '', ICON_SIZE_SMALL).'</a>';
278
                        $modify_icons .= '&nbsp;<a href="#" >'.
279
                            Display::return_icon('pdf_na.png', get_lang('ExportToPDF'), '', ICON_SIZE_SMALL).'</a>';
280
                    }
281
                }
282
283
                if (empty($grade_model_id) || $grade_model_id == -1) {
284
                    if ($cat->is_locked() && !api_is_platform_admin()) {
285
                        $modify_icons .= Display::return_icon(
286
                            'edit_na.png',
287
                            get_lang('Modify'),
288
                            '',
289
                            ICON_SIZE_SMALL
290
                        );
291
                    } else {
292
                        $modify_icons .= '<a href="gradebook_edit_cat.php?editcat='.$cat->get_id().'&'.$courseParams.'">'.
293
                            Display::return_icon(
294
                                'edit.png',
295
                                get_lang('Modify'),
296
                                '',
297
                                ICON_SIZE_SMALL
298
                            ).'</a>';
299
                    }
300
                }
301
302
                $modify_icons .= '<a href="gradebook_edit_all.php?selectcat='.$cat->get_id().'&'.$courseParams.'">'.
303
                    Display::return_icon(
304
                        'percentage.png',
305
                        get_lang('EditAllWeights'),
306
                        '',
307
                        ICON_SIZE_SMALL
308
                    ).'</a>';
309
310
                $modify_icons .= '<a href="gradebook_flatview.php?selectcat='.$cat->get_id().'&'.$courseParams.'">'.
311
                    Display::return_icon(
312
                        'statistics.png',
313
                        get_lang('FlatView'),
314
                        '',
315
                        ICON_SIZE_SMALL
316
                    ).'</a>';
317
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visiblecat='.$cat->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.'">'.
318
                    Display::return_icon(
319
                        $visibility_icon.'.png',
320
                        get_lang('Visible'),
321
                        '',
322
                        ICON_SIZE_SMALL
323
                    ).'</a>';
324
325
                if ($cat->is_locked() && !api_is_platform_admin()) {
326
                    $modify_icons .= Display::return_icon(
327
                        'delete_na.png',
328
                        get_lang('DeleteAll'),
329
                        '',
330
                        ICON_SIZE_SMALL
331
                    );
332
                } else {
333
                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deletecat='.$cat->get_id().'&selectcat='.$selectcat.'&'.$courseParams.'" onclick="return confirmation();">'.
334
                        Display::return_icon(
335
                            'delete.png',
336
                            get_lang('DeleteAll'),
337
                            '',
338
                            ICON_SIZE_SMALL
339
                        ).
340
                        '</a>';
341
                }
342
            }
343
344
            return $modify_icons;
345
        }
346
    }
347
348
    /**
349
     * Builds the course or platform admin icons to edit an evaluation.
350
     *
351
     * @param Evaluation $eval      evaluation object
352
     * @param int        $selectcat id of selected category
353
     *
354
     * @return string
355
     */
356
    public static function build_edit_icons_eval($eval, $selectcat)
357
    {
358
        $is_locked = $eval->is_locked();
359
        $eval->get_course_code();
360
        $cat = new Category();
361
        $message_eval = $cat->show_message_resource_delete($eval->get_course_code());
362
        $courseParams = api_get_cidreq_params($eval->get_course_code(), $eval->getSessionId());
363
364
        if ($message_eval === false && api_is_allowed_to_edit(null, true)) {
365
            $visibility_icon = $eval->is_visible() == 0 ? 'invisible' : 'visible';
366
            $visibility_command = $eval->is_visible() == 0 ? 'set_visible' : 'set_invisible';
367
            if ($is_locked && !api_is_platform_admin()) {
368
                $modify_icons = Display::return_icon(
369
                    'edit_na.png',
370
                    get_lang('Modify'),
371
                    '',
372
                    ICON_SIZE_SMALL
373
                );
374
            } else {
375
                $modify_icons = '<a href="gradebook_edit_eval.php?editeval='.$eval->get_id().'&'.$courseParams.'">'.
376
                    Display::return_icon(
377
                        'edit.png',
378
                        get_lang('Modify'),
379
                        '',
380
                        ICON_SIZE_SMALL
381
                    ).
382
                    '</a>';
383
            }
384
385
            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visibleeval='.$eval->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.' ">'.
386
                Display::return_icon(
387
                    $visibility_icon.'.png',
388
                    get_lang('Visible'),
389
                    '',
390
                    ICON_SIZE_SMALL
391
                ).
392
                '</a>';
393
394
            if (api_is_allowed_to_edit(null, true)) {
395
                $modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog='.$eval->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'">'.
396
                    Display::return_icon(
397
                        'history.png',
398
                        get_lang('GradebookQualifyLog'),
399
                        '',
400
                        ICON_SIZE_SMALL
401
                    ).
402
                    '</a>';
403
404
                $allowStats = api_get_configuration_value('allow_gradebook_stats');
405
                if ($allowStats) {
406
                    $modify_icons .= Display::url(
407
                        Display::return_icon('reload.png', get_lang('GenerateStats')),
408
                        api_get_self().'?itemId='.$eval->get_id().'&action=generate_eval_stats&selectcat='.$selectcat.'&'.$courseParams
409
                    );
410
                }
411
            }
412
413
            if ($is_locked && !api_is_platform_admin()) {
414
                $modify_icons .= '&nbsp;'.
415
                    Display::return_icon(
416
                        'delete_na.png',
417
                        get_lang('Delete'),
418
                        '',
419
                        ICON_SIZE_SMALL
420
                    );
421
            } else {
422
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deleteeval='.$eval->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'" onclick="return confirmation();">'.
423
                    Display::return_icon(
424
                        'delete.png',
425
                        get_lang('Delete'),
426
                        '',
427
                        ICON_SIZE_SMALL
428
                    ).
429
                    '</a>';
430
            }
431
432
            return $modify_icons;
433
        }
434
    }
435
436
    /**
437
     * Builds the course or platform admin icons to edit a link.
438
     *
439
     * @param AbstractLink $link
440
     * @param int          $selectcat id of selected category
441
     *
442
     * @return string
443
     */
444
    public static function build_edit_icons_link($link, $selectcat)
445
    {
446
        $cat = new Category();
447
        $message_link = $cat->show_message_resource_delete($link->get_course_code());
448
        $is_locked = $link->is_locked();
449
450
        $modify_icons = null;
451
452
        if (!api_is_allowed_to_edit(null, true)) {
453
            return null;
454
        }
455
456
        $courseParams = api_get_cidreq_params(
457
            $link->get_course_code(),
458
            $link->get_session_id()
459
        );
460
461
        if ($message_link === false) {
462
            $visibility_icon = $link->is_visible() == 0 ? 'invisible' : 'visible';
463
            $visibility_command = $link->is_visible() == 0 ? 'set_visible' : 'set_invisible';
464
465
            if ($is_locked && !api_is_platform_admin()) {
466
                $modify_icons = Display::return_icon(
467
                    'edit_na.png',
468
                    get_lang('Modify'),
469
                    '',
470
                    ICON_SIZE_SMALL
471
                );
472
            } else {
473
                $modify_icons = '<a href="gradebook_edit_link.php?editlink='.$link->get_id().'&'.$courseParams.'">'.
474
                    Display::return_icon(
475
                        'edit.png',
476
                        get_lang('Modify'),
477
                        '',
478
                        ICON_SIZE_SMALL
479
                    ).
480
                    '</a>';
481
            }
482
            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visiblelink='.$link->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.' ">'.
483
                Display::return_icon(
484
                    $visibility_icon.'.png',
485
                    get_lang('Visible'),
486
                    '',
487
                    ICON_SIZE_SMALL
488
                ).
489
                '</a>';
490
491
            $modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink='.$link->get_id().'&selectcat='.$selectcat.'&'.$courseParams.'">'.
492
                Display::return_icon(
493
                    'history.png',
494
                    get_lang('GradebookQualifyLog'),
495
                    '',
496
                    ICON_SIZE_SMALL
497
                ).
498
                '</a>';
499
500
            $allowStats = api_get_configuration_value('allow_gradebook_stats');
501
            if ($allowStats && $link->get_type() == LINK_EXERCISE) {
502
                $modify_icons .= Display::url(
503
                    Display::return_icon('reload.png', get_lang('GenerateStats')),
504
                    api_get_self().'?itemId='.$link->get_id().'&action=generate_link_stats&selectcat='.$selectcat.'&'.$courseParams
505
                );
506
            }
507
508
            //If a work is added in a gradebook you can only delete the link in the work tool
509
            if ($is_locked && !api_is_platform_admin()) {
510
                $modify_icons .= '&nbsp;'.
511
                    Display::return_icon(
512
                        'delete_na.png',
513
                        get_lang('Delete'),
514
                        '',
515
                        ICON_SIZE_SMALL
516
                    );
517
            } else {
518
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deletelink='.$link->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'" onclick="return confirmation();">'.
519
                    Display::return_icon(
520
                        'delete.png',
521
                        get_lang('Delete'),
522
                        '',
523
                        ICON_SIZE_SMALL
524
                    ).
525
                    '</a>';
526
            }
527
528
            return $modify_icons;
529
        }
530
    }
531
532
    /**
533
     * Checks if a resource is in the unique gradebook of a given course.
534
     *
535
     * @param string $course_code   Course code
536
     * @param int    $resource_type Resource type (use constants defined in linkfactory.class.php)
537
     * @param int    $resource_id   Resource ID in the corresponding tool
538
     * @param int    $session_id    Session ID (optional -  0 if not defined)
539
     *
540
     * @return array false on error or array of resource
541
     */
542
    public static function isResourceInCourseGradebook(
543
        $course_code,
544
        $resource_type,
545
        $resource_id,
546
        $session_id = 0
547
    ) {
548
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
549
        $courseInfo = api_get_course_info($course_code);
550
        if (empty($courseInfo)) {
551
            return [];
552
        }
553
554
        $sql = "SELECT * FROM $table l
555
                WHERE
556
                    c_id = ".$courseInfo['real_id']." AND
557
                    type = ".(int) $resource_type." AND
558
                    ref_id = ".(int) $resource_id;
559
        $res = Database::query($sql);
560
561
        if (Database::num_rows($res) < 1) {
562
            return false;
563
        }
564
        $row = Database::fetch_array($res, 'ASSOC');
565
566
        return $row;
567
    }
568
569
    /**
570
     * Return the course id.
571
     *
572
     * @param    int
573
     *
574
     * @return string
575
     */
576
    public static function get_course_id_by_link_id($id_link)
577
    {
578
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
579
        $tbl_grade_links = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
580
        $id_link = (int) $id_link;
581
582
        $sql = 'SELECT c.id FROM '.$course_table.' c
583
                INNER JOIN '.$tbl_grade_links.' l
584
                ON c.id = l.c_id
585
                WHERE l.id='.intval($id_link).' OR l.category_id='.intval($id_link);
586
        $res = Database::query($sql);
587
        $array = Database::fetch_array($res, 'ASSOC');
588
589
        return $array['id'];
590
    }
591
592
    /**
593
     * @param $type
594
     *
595
     * @return string
596
     */
597
    public static function get_table_type_course($type)
598
    {
599
        global $table_evaluated;
600
601
        return Database::get_course_table($table_evaluated[$type][0]);
602
    }
603
604
    /**
605
     * @param Category $cat
606
     * @param $users
607
     * @param $alleval
608
     * @param $alllinks
609
     * @param $params
610
     * @param null $mainCourseCategory
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $mainCourseCategory is correct as it would always require null to be passed?
Loading history...
611
     *
612
     * @return array
613
     */
614
    public static function get_printable_data(
615
        $cat,
616
        $users,
617
        $alleval,
618
        $alllinks,
619
        $params,
620
        $mainCourseCategory = null
621
    ) {
622
        $datagen = new FlatViewDataGenerator(
623
            $users,
624
            $alleval,
625
            $alllinks,
626
            $params,
627
            $mainCourseCategory
628
        );
629
630
        $offset = isset($_GET['offset']) ? (int) $_GET['offset'] : 0;
631
632
        // step 2: generate rows: students
633
        $datagen->category = $cat;
634
635
        $count = (($offset + 10) > $datagen->get_total_items_count()) ? ($datagen->get_total_items_count() - $offset) : GRADEBOOK_ITEM_LIMIT;
636
        $header_names = $datagen->get_header_names($offset, $count, true);
637
        $data_array = $datagen->get_data(
638
            FlatViewDataGenerator::FVDG_SORT_LASTNAME,
639
            0,
640
            null,
641
            $offset,
642
            $count,
643
            true,
644
            true
645
        );
646
647
        $result = [];
648
        foreach ($data_array as $data) {
649
            $result[] = array_slice($data, 1);
650
        }
651
        $return = [$header_names, $result];
652
653
        return $return;
654
    }
655
656
    /**
657
     * XML-parser: handle character data.
658
     */
659
    public static function character_data($parser, $data)
660
    {
661
        global $current_value;
662
        $current_value = $data;
663
    }
664
665
    public static function overwritescore($resid, $importscore, $eval_max)
666
    {
667
        $result = Result::load($resid);
668
        if ($importscore > $eval_max) {
669
            header('Location: gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'&overwritemax=');
670
            exit;
671
        }
672
        $result[0]->set_score($importscore);
673
        $result[0]->save();
674
        unset($result);
675
    }
676
677
    /**
678
     * register user info about certificate.
679
     *
680
     * @param int    $cat_id            The category id
681
     * @param int    $user_id           The user id
682
     * @param float  $score_certificate The score obtained for certified
683
     * @param string $date_certificate  The date when you obtained the certificate
684
     */
685
    public static function registerUserInfoAboutCertificate(
686
        $cat_id,
687
        $user_id,
688
        $score_certificate,
689
        $date_certificate
690
    ) {
691
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
692
        $cat_id = (int) $cat_id;
693
        $user_id = (int) $user_id;
694
695
        $sql = "SELECT COUNT(id) as count
696
                FROM $table gc
697
                WHERE gc.cat_id = $cat_id AND user_id = $user_id ";
698
        $rs_exist = Database::query($sql);
699
        $row = Database::fetch_array($rs_exist);
700
        if ($row['count'] == 0) {
701
            $params = [
702
                'cat_id' => $cat_id,
703
                'user_id' => $user_id,
704
                'score_certificate' => $score_certificate,
705
                'created_at' => $date_certificate,
706
            ];
707
            Database::insert($table, $params);
708
        }
709
    }
710
711
    /**
712
     * Get date of user certificate.
713
     *
714
     * @param int $cat_id  The category id
715
     * @param int $user_id The user id
716
     *
717
     * @return Datetime The date when you obtained the certificate
718
     */
719
    public static function get_certificate_by_user_id($cat_id, $user_id)
720
    {
721
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
722
        $cat_id = (int) $cat_id;
723
        $user_id = (int) $user_id;
724
725
        $sql = "SELECT * FROM $table
726
                WHERE cat_id = $cat_id AND user_id = $user_id ";
727
728
        $result = Database::query($sql);
729
        $row = Database::fetch_array($result, 'ASSOC');
730
731
        return $row;
732
    }
733
734
    /**
735
     * Get list of users certificates.
736
     *
737
     * @param int   $cat_id   The category id
738
     * @param array $userList Only users in this list
739
     *
740
     * @return array
741
     */
742
    public static function get_list_users_certificates($cat_id = null, $userList = [])
743
    {
744
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
745
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
746
        $sql = 'SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username
747
                FROM '.$table_user.' u
748
                INNER JOIN '.$table_certificate.' gc
749
                ON u.user_id=gc.user_id ';
750
        if (!is_null($cat_id) && $cat_id > 0) {
751
            $sql .= ' WHERE cat_id='.intval($cat_id);
752
        }
753
        if (!empty($userList)) {
754
            $userList = array_map('intval', $userList);
755
            $userListCondition = implode("','", $userList);
756
            $sql .= " AND u.user_id IN ('$userListCondition')";
757
        }
758
        $sql .= ' ORDER BY '.(api_sort_by_first_name() ? 'u.firstname' : 'u.lastname');
759
        $rs = Database::query($sql);
760
761
        $list_users = [];
762
        while ($row = Database::fetch_array($rs)) {
763
            $list_users[] = $row;
764
        }
765
766
        return $list_users;
767
    }
768
769
    public static function getTotalCertificates($urlId)
770
    {
771
        $urlId = (int) $urlId;
772
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
773
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
774
        $sql = 'SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username
775
                FROM '.$table_user.' u
776
                INNER JOIN '.$table_certificate.' gc
777
                ON u.user_id=gc.user_id ';
778
        if (!is_null($cat_id) && $cat_id > 0) {
779
            $sql .= ' WHERE cat_id='.intval($cat_id);
780
        }
781
        if (!empty($userList)) {
782
            $userList = array_map('intval', $userList);
783
            $userListCondition = implode("','", $userList);
784
            $sql .= " AND u.user_id IN ('$userListCondition')";
785
        }
786
        $sql .= ' ORDER BY '.(api_sort_by_first_name() ? 'u.firstname' : 'u.lastname');
787
        $rs = Database::query($sql);
788
789
        $list_users = [];
790
        while ($row = Database::fetch_array($rs)) {
791
            $list_users[] = $row;
792
        }
793
794
        return $list_users;
795
    }
796
797
    /**
798
     * Gets the certificate list by user id.
799
     *
800
     * @param int $user_id The user id
801
     * @param int $cat_id  The category id
802
     *
803
     * @return array
804
     */
805
    public static function get_list_gradebook_certificates_by_user_id(
806
        $user_id,
807
        $cat_id = null
808
    ) {
809
        $user_id = (int) $user_id;
810
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
811
        $sql = 'SELECT
812
                    gc.score_certificate,
813
                    gc.created_at,
814
                    gc.path_certificate,
815
                    gc.cat_id,
816
                    gc.user_id,
817
                    gc.id
818
                FROM  '.$table_certificate.' gc
819
                WHERE gc.user_id = "'.$user_id.'" ';
820
        if (!is_null($cat_id) && $cat_id > 0) {
821
            $sql .= ' AND cat_id='.intval($cat_id);
822
        }
823
824
        $rs = Database::query($sql);
825
        $list = [];
826
        while ($row = Database::fetch_array($rs)) {
827
            $list[] = $row;
828
        }
829
830
        return $list;
831
    }
832
833
    /**
834
     * @param int    $user_id
835
     * @param string $course_code
836
     * @param int    $sessionId
837
     * @param bool   $is_preview
838
     * @param bool   $hide_print_button
839
     *
840
     * @return array
841
     */
842
    public static function get_user_certificate_content(
843
        $user_id,
844
        $course_code,
845
        $sessionId,
846
        $is_preview = false,
847
        $hide_print_button = false
848
    ) {
849
        // Generate document HTML
850
        $content_html = DocumentManager::replace_user_info_into_html(
851
            $user_id,
852
            api_get_course_info($course_code),
853
            $sessionId,
854
            $is_preview
855
        );
856
857
        $new_content_html = isset($content_html['content']) ? $content_html['content'] : null;
858
        $variables = isset($content_html['variables']) ? $content_html['variables'] : null;
859
        $path_image = api_get_path(WEB_COURSE_PATH).api_get_course_path($course_code).'/document/images/gallery';
860
        $new_content_html = str_replace('../images/gallery', $path_image, $new_content_html);
861
862
        $path_image_in_default_course = api_get_path(WEB_CODE_PATH).'default_course_document';
863
        $new_content_html = str_replace('/main/default_course_document', $path_image_in_default_course, $new_content_html);
864
        $new_content_html = str_replace(SYS_CODE_PATH.'img/', api_get_path(WEB_IMG_PATH), $new_content_html);
865
866
        //add print header
867
        if (!$hide_print_button) {
868
            $print = '<style>#print_div {
869
                padding:4px;border: 0 none;position: absolute;top: 0px;right: 0px;
870
            }
871
            @media print {
872
                #print_div  {
873
                    display: none !important;
874
                }
875
            }
876
            </style>';
877
878
            $print .= Display::div(
879
                Display::url(
880
                    Display::return_icon('printmgr.gif', get_lang('Print')),
881
                    'javascript:void()',
882
                    ['onclick' => 'window.print();']
883
                ),
884
                ['id' => 'print_div']
885
            );
886
            $print .= '</html>';
887
            $new_content_html = str_replace('</html>', $print, $new_content_html);
888
        }
889
890
        return [
891
            'content' => $new_content_html,
892
            'variables' => $variables,
893
        ];
894
    }
895
896
    /**
897
     * @param null $course_code
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $course_code is correct as it would always require null to be passed?
Loading history...
898
     * @param int  $gradebook_model_id
899
     *
900
     * @return mixed
901
     */
902
    public static function create_default_course_gradebook(
903
        $course_code = null,
904
        $gradebook_model_id = 0
905
    ) {
906
        if (api_is_allowed_to_edit(true, true)) {
907
            if (!isset($course_code) || empty($course_code)) {
908
                $course_code = api_get_course_id();
909
            }
910
            $session_id = api_get_session_id();
911
            $courseInfo = api_get_course_info($course_code);
912
913
            $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
914
            $sql = "SELECT * FROM $t 
915
                    WHERE c_id = '".$courseInfo['real_id']."' ";
916
            if (!empty($session_id)) {
917
                $sql .= " AND session_id = ".$session_id;
918
            } else {
919
                $sql .= ' AND (session_id IS NULL OR session_id = 0) ';
920
            }
921
            $sql .= ' ORDER BY id ';
922
            $res = Database::query($sql);
923
            if (Database::num_rows($res) < 1) {
924
                //there is no unique category for this course+session combination,
925
                $cat = new Category();
926
                if (!empty($session_id)) {
927
                    $my_session_id = api_get_session_id();
928
                    $s_name = api_get_session_name($my_session_id);
929
                    $cat->set_name($course_code.' - '.get_lang('Session').' '.$s_name);
930
                    $cat->set_session_id($session_id);
931
                } else {
932
                    $cat->set_name($course_code);
933
                }
934
                $cat->set_course_code($course_code);
935
                $cat->set_description(null);
936
                $cat->set_user_id(api_get_user_id());
937
                $cat->set_parent_id(0);
938
                $default_weight_setting = api_get_setting('gradebook_default_weight');
939
                $default_weight = isset($default_weight_setting) && !empty($default_weight_setting) ? $default_weight_setting : 100;
940
                $cat->set_weight($default_weight);
941
                $cat->set_grade_model_id($gradebook_model_id);
942
                $cat->set_certificate_min_score(75);
943
944
                $cat->set_visible(0);
945
                $cat->add();
946
                $category_id = $cat->get_id();
947
                unset($cat);
948
            } else {
949
                $row = Database::fetch_array($res);
950
                $category_id = $row['id'];
951
            }
952
953
            return $category_id;
954
        }
955
956
        return false;
957
    }
958
959
    /**
960
     * @param FormValidator $form
961
     */
962
    public static function load_gradebook_select_in_tool($form)
963
    {
964
        $course_code = api_get_course_id();
965
        $session_id = api_get_session_id();
966
967
        self::create_default_course_gradebook();
968
969
        // Cat list
970
        $all_categories = Category::load(
971
            null,
972
            null,
973
            $course_code,
974
            null,
975
            null,
976
            $session_id,
977
            false
978
        );
979
        $select_gradebook = $form->addElement(
980
            'select',
981
            'category_id',
982
            get_lang('SelectGradebook')
983
        );
984
985
        if (!empty($all_categories)) {
986
            foreach ($all_categories as $my_cat) {
987
                if ($my_cat->get_course_code() == api_get_course_id()) {
988
                    $grade_model_id = $my_cat->get_grade_model_id();
989
                    if (empty($grade_model_id)) {
990
                        if ($my_cat->get_parent_id() == 0) {
991
                            //$default_weight = $my_cat->get_weight();
992
                            $select_gradebook->addoption(get_lang('Default'), $my_cat->get_id());
993
                            $cats_added[] = $my_cat->get_id();
994
                        } else {
995
                            $select_gradebook->addoption($my_cat->get_name(), $my_cat->get_id());
996
                            $cats_added[] = $my_cat->get_id();
997
                        }
998
                    } else {
999
                        $select_gradebook->addoption(get_lang('Select'), 0);
1000
                    }
1001
                }
1002
            }
1003
        }
1004
    }
1005
1006
    /**
1007
     * @param FlatViewTable $flatviewtable
1008
     * @param Category      $cat
1009
     * @param $users
1010
     * @param $alleval
1011
     * @param $alllinks
1012
     * @param array $params
1013
     * @param null  $mainCourseCategory
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $mainCourseCategory is correct as it would always require null to be passed?
Loading history...
1014
     */
1015
    public static function export_pdf_flatview(
1016
        $flatviewtable,
1017
        $cat,
1018
        $users,
1019
        $alleval,
1020
        $alllinks,
1021
        $params = [],
1022
        $mainCourseCategory = null
1023
    ) {
1024
        // Getting data
1025
        $printable_data = self::get_printable_data(
1026
            $cat[0],
1027
            $users,
1028
            $alleval,
1029
            $alllinks,
1030
            $params,
1031
            $mainCourseCategory
1032
        );
1033
1034
        // HTML report creation first
1035
        $course_code = trim($cat[0]->get_course_code());
1036
1037
        $displayscore = ScoreDisplay::instance();
1038
        $customDisplays = $displayscore->get_custom_score_display_settings();
1039
1040
        $total = [];
1041
        if (is_array($customDisplays) && count(($customDisplays))) {
1042
            foreach ($customDisplays as $custom) {
1043
                $total[$custom['display']] = 0;
1044
            }
1045
            $user_results = $flatviewtable->datagen->get_data_to_graph2(false);
1046
            foreach ($user_results as $user_result) {
1047
                $item = $user_result[count($user_result) - 1];
1048
                $customTag = isset($item[1]) ? strip_tags($item[1]) : '';
1049
                $total[$customTag]++;
1050
            }
1051
        }
1052
1053
        $parent_id = $cat[0]->get_parent_id();
1054
        if (isset($cat[0]) && isset($parent_id)) {
1055
            if ($parent_id == 0) {
1056
                $grade_model_id = $cat[0]->get_grade_model_id();
1057
            } else {
1058
                $parent_cat = Category::load($parent_id);
1059
                $grade_model_id = $parent_cat[0]->get_grade_model_id();
1060
            }
1061
        }
1062
1063
        $use_grade_model = true;
1064
        if (empty($grade_model_id) || $grade_model_id == -1) {
1065
            $use_grade_model = false;
1066
        }
1067
1068
        if ($use_grade_model) {
1069
            if ($parent_id == 0) {
1070
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1071
            } else {
1072
                $title = api_strtoupper(get_lang('Average')).'<br />'.$cat[0]->get_description().' - ('.$cat[0]->get_name().')';
1073
            }
1074
        } else {
1075
            if ($parent_id == 0) {
1076
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1077
            } else {
1078
                $title = api_strtoupper(get_lang('Average'));
1079
            }
1080
        }
1081
1082
        $columns = count($printable_data[0]);
1083
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
1084
1085
        $table = new HTML_Table(['class' => 'data_table']);
1086
        $row = 0;
1087
        $column = 0;
1088
        $table->setHeaderContents($row, $column, get_lang('NumberAbbreviation'));
1089
        $column++;
1090
        foreach ($printable_data[0] as $printable_data_cell) {
1091
            if (!is_array($printable_data_cell)) {
1092
                $printable_data_cell = strip_tags($printable_data_cell);
1093
            }
1094
            $table->setHeaderContents($row, $column, $printable_data_cell);
1095
            $column++;
1096
        }
1097
        $row++;
1098
1099
        if ($has_data) {
1100
            $counter = 1;
1101
            foreach ($printable_data[1] as &$printable_data_row) {
1102
                $column = 0;
1103
                $table->setCellContents($row, $column, $counter);
1104
                $table->updateCellAttributes($row, $column, 'align="center"');
1105
                $column++;
1106
                $counter++;
1107
1108
                foreach ($printable_data_row as $key => &$printable_data_cell) {
1109
                    $attributes = [];
1110
                    $attributes['align'] = 'center';
1111
                    $attributes['style'] = null;
1112
1113
                    if ($key === 'name') {
1114
                        $attributes['align'] = 'left';
1115
                    }
1116
                    if ($key === 'total') {
1117
                        $attributes['style'] = 'font-weight:bold';
1118
                    }
1119
                    $table->setCellContents($row, $column, $printable_data_cell);
1120
                    $table->updateCellAttributes($row, $column, $attributes);
1121
                    $column++;
1122
                }
1123
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
1124
                $row++;
1125
            }
1126
        } else {
1127
            $column = 0;
1128
            $table->setCellContents($row, $column, get_lang('NoResults'));
1129
            $table->updateCellAttributes($row, $column, 'colspan="'.$columns.'" align="center" class="row_odd"');
1130
        }
1131
1132
        $pdfParams = [
1133
            'filename' => get_lang('FlatView').'_'.api_get_local_time(),
1134
            'pdf_title' => $title,
1135
            'course_code' => $course_code,
1136
            'add_signatures' => ['Drh', 'Teacher', 'Date'],
1137
        ];
1138
1139
        $page_format = $params['orientation'] === 'landscape' ? 'A4-L' : 'A4';
1140
        ob_start();
1141
        $pdf = new PDF($page_format, $page_format, $pdfParams);
1142
        $pdf->html_to_pdf_with_template($flatviewtable->return_table(), false, false, true);
1143
        $content = ob_get_contents();
1144
        ob_end_clean();
1145
        echo $content;
1146
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1147
    }
1148
1149
    /**
1150
     * @param string[] $list_values
1151
     *
1152
     * @return string
1153
     */
1154
    public static function score_badges($list_values)
1155
    {
1156
        $counter = 1;
1157
        $badges = [];
1158
        foreach ($list_values as $value) {
1159
            $class = 'warning';
1160
            if ($counter == 1) {
1161
                $class = 'success';
1162
            }
1163
            $counter++;
1164
            $badges[] = Display::badge($value, $class);
1165
        }
1166
1167
        return Display::badge_group($badges);
1168
    }
1169
1170
    /**
1171
     * returns users within a course given by param.
1172
     *
1173
     * @param string $courseCode
1174
     *
1175
     * @deprecated use CourseManager
1176
     *
1177
     * @return array
1178
     */
1179
    public static function get_users_in_course($courseCode)
1180
    {
1181
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1182
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1183
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1184
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
1185
1186
        $current_session = api_get_session_id();
1187
        $courseCode = Database::escape_string($courseCode);
1188
        $courseInfo = api_get_course_info($courseCode);
1189
        $courseId = $courseInfo['real_id'];
1190
1191
        if (!empty($current_session)) {
1192
            $sql = "SELECT user.user_id, user.username, lastname, firstname, official_code
1193
                    FROM $tbl_session_course_user as scru 
1194
                    INNER JOIN $tbl_user as user
1195
                    ON (scru.user_id = user.user_id)
1196
                    WHERE                        
1197
                        scru.status = 0 AND
1198
                        scru.c_id='$courseId' AND
1199
                        session_id ='$current_session'
1200
                    $order_clause
1201
                    ";
1202
        } else {
1203
            $sql = 'SELECT user.user_id, user.username, lastname, firstname, official_code
1204
                    FROM '.$tbl_course_user.' as course_rel_user
1205
                    INNER JOIN '.$tbl_user.' as user
1206
                    ON (course_rel_user.user_id = user.id)
1207
                    WHERE
1208
                        course_rel_user.status = '.STUDENT.' AND
1209
                        course_rel_user.c_id = "'.$courseId.'" '.
1210
                    $order_clause;
1211
        }
1212
1213
        $result = Database::query($sql);
1214
1215
        return self::get_user_array_from_sql_result($result);
1216
    }
1217
1218
    /**
1219
     * @param Doctrine\DBAL\Driver\Statement|null $result
1220
     *
1221
     * @return array
1222
     */
1223
    public static function get_user_array_from_sql_result($result)
1224
    {
1225
        $a_students = [];
1226
        while ($user = Database::fetch_array($result)) {
1227
            if (!array_key_exists($user['user_id'], $a_students)) {
1228
                $a_current_student = [];
1229
                $a_current_student[] = $user['user_id'];
1230
                $a_current_student[] = $user['username'];
1231
                $a_current_student[] = $user['lastname'];
1232
                $a_current_student[] = $user['firstname'];
1233
                $a_current_student[] = $user['official_code'];
1234
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1235
            }
1236
        }
1237
1238
        return $a_students;
1239
    }
1240
1241
    /**
1242
     * @param array $evals
1243
     * @param array $links
1244
     *
1245
     * @return array
1246
     */
1247
    public static function get_all_users($evals = [], $links = [])
1248
    {
1249
        $coursecodes = [];
1250
        // By default add all user in course
1251
        $coursecodes[api_get_course_id()] = '1';
1252
        $users = self::get_users_in_course(api_get_course_id());
1253
1254
        foreach ($evals as $eval) {
1255
            $coursecode = $eval->get_course_code();
1256
            // evaluation in course
1257
            if (isset($coursecode) && !empty($coursecode)) {
1258
                if (!array_key_exists($coursecode, $coursecodes)) {
1259
                    $coursecodes[$coursecode] = '1';
1260
                    $users = array_merge($users, self::get_users_in_course($coursecode));
1261
                }
1262
            } else {
1263
                // course independent evaluation
1264
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1265
                $tbl_res = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1266
1267
                $sql = 'SELECT user.user_id, lastname, firstname, user.official_code
1268
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1269
                        WHERE
1270
                            res.evaluation_id = '.intval($eval->get_id()).' AND
1271
                            res.user_id = user.user_id
1272
                        ';
1273
                $sql .= ' ORDER BY lastname, firstname';
1274
                if (api_is_western_name_order()) {
1275
                    $sql .= ' ORDER BY firstname, lastname';
1276
                }
1277
1278
                $result = Database::query($sql);
1279
                $users = array_merge(
1280
                    $users,
1281
                    self::get_user_array_from_sql_result($result)
1282
                );
1283
            }
1284
        }
1285
1286
        foreach ($links as $link) {
1287
            // links are always in a course
1288
            $coursecode = $link->get_course_code();
1289
            if (!array_key_exists($coursecode, $coursecodes)) {
1290
                $coursecodes[$coursecode] = '1';
1291
                $users = array_merge(
1292
                    $users,
1293
                    self::get_users_in_course($coursecode)
1294
                );
1295
            }
1296
        }
1297
1298
        return $users;
1299
    }
1300
1301
    /**
1302
     * Search students matching a given last name and/or first name.
1303
     *
1304
     * @author Bert Steppé
1305
     */
1306
    public static function find_students($mask = '')
1307
    {
1308
        // students shouldn't be here // don't search if mask empty
1309
        if (!api_is_allowed_to_edit() || empty($mask)) {
1310
            return null;
1311
        }
1312
        $mask = Database::escape_string($mask);
1313
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1314
        $tbl_cru = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1315
        $sql = 'SELECT DISTINCT user.user_id, user.lastname, user.firstname, user.email, user.official_code
1316
                FROM '.$tbl_user.' user';
1317
        if (!api_is_platform_admin()) {
1318
            $sql .= ', '.$tbl_cru.' cru';
1319
        }
1320
1321
        $sql .= ' WHERE user.status = '.STUDENT;
1322
        $sql .= ' AND (user.lastname LIKE '."'%".$mask."%'";
1323
        $sql .= ' OR user.firstname LIKE '."'%".$mask."%')";
1324
1325
        if (!api_is_platform_admin()) {
1326
            $sql .= ' AND user.user_id = cru.user_id AND
1327
                      cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' AND
1328
                      cru.c_id in (
1329
                            SELECT c_id FROM '.$tbl_cru.'
1330
                            WHERE
1331
                                user_id = '.api_get_user_id().' AND
1332
                                status = '.COURSEMANAGER.'
1333
                        )
1334
                    ';
1335
        }
1336
1337
        $sql .= ' ORDER BY lastname, firstname';
1338
        if (api_is_western_name_order()) {
1339
            $sql .= ' ORDER BY firstname, lastname';
1340
        }
1341
1342
        $result = Database::query($sql);
1343
        $users = Database::store_result($result);
1344
1345
        return $users;
1346
    }
1347
1348
    /**
1349
     * @param int   $linkId
1350
     * @param float $weight
1351
     */
1352
    public static function updateLinkWeight($linkId, $name, $weight)
1353
    {
1354
        $linkId = (int) $linkId;
1355
        $weight = api_float_val($weight);
1356
        $course_id = api_get_course_int_id();
1357
1358
        AbstractLink::add_link_log($linkId, $name);
1359
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1360
1361
        $em = Database::getManager();
1362
        $tbl_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
1363
        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
1364
1365
        $sql = 'UPDATE '.$table_link.' 
1366
                SET weight = '."'".Database::escape_string($weight)."'".'
1367
                WHERE id = '.$linkId;
1368
1369
        Database::query($sql);
1370
1371
        // Update weight for attendance
1372
        $sql = 'SELECT ref_id FROM '.$table_link.'
1373
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1374
1375
        $rs_attendance = Database::query($sql);
1376
        if (Database::num_rows($rs_attendance) > 0) {
1377
            $row_attendance = Database::fetch_array($rs_attendance);
1378
            $sql = 'UPDATE '.$tbl_attendance.' SET 
1379
                    attendance_weight ='.api_float_val($weight).'
1380
                    WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
1381
            Database::query($sql);
1382
        }
1383
        // Update weight into forum thread
1384
        $sql = 'UPDATE '.$tbl_forum_thread.' SET 
1385
                thread_weight = '.api_float_val($weight).'
1386
                WHERE
1387
                    c_id = '.$course_id.' AND
1388
                    thread_id = (
1389
                        SELECT ref_id FROM '.$table_link.'
1390
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1391
                    )
1392
                ';
1393
        Database::query($sql);
1394
        //Update weight into student publication(work)
1395
        $em
1396
            ->createQuery('
1397
                UPDATE ChamiloCourseBundle:CStudentPublication w
1398
                SET w.weight = :final_weight
1399
                WHERE w.cId = :course
1400
                    AND w.id = (
1401
                        SELECT l.refId FROM ChamiloCoreBundle:GradebookLink l
1402
                        WHERE l.id = :link AND l.type = :type
1403
                    )
1404
            ')
1405
            ->execute([
1406
                'final_weight' => $weight,
1407
                'course' => $course_id,
1408
                'link' => $linkId,
1409
                'type' => LINK_STUDENTPUBLICATION,
1410
            ]);
1411
    }
1412
1413
    /**
1414
     * @param int   $id
1415
     * @param float $weight
1416
     */
1417
    public static function updateEvaluationWeight($id, $weight)
1418
    {
1419
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1420
        $id = (int) $id;
1421
        $evaluation = new Evaluation();
1422
        $evaluation->addEvaluationLog($id);
1423
        $sql = 'UPDATE '.$table_evaluation.'
1424
               SET weight = '."'".Database::escape_string($weight)."'".'
1425
               WHERE id = '.$id;
1426
        Database::query($sql);
1427
    }
1428
1429
    /**
1430
     * Get the achieved certificates for a user in courses.
1431
     *
1432
     * @param int  $userId                       The user id
1433
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1434
     *
1435
     * @return array
1436
     */
1437
    public static function getUserCertificatesInCourses(
1438
        $userId,
1439
        $includeNonPublicCertificates = true
1440
    ) {
1441
        $userId = (int) $userId;
1442
        $courseList = [];
1443
        $courses = CourseManager::get_courses_list_by_user_id($userId);
1444
1445
        foreach ($courses as $course) {
1446
            if (!$includeNonPublicCertificates) {
1447
                $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course);
1448
1449
                if (empty($allowPublicCertificates)) {
1450
                    continue;
1451
                }
1452
            }
1453
1454
            $category = Category::load(null, null, $course['code']);
1455
1456
            if (empty($category)) {
1457
                continue;
1458
            }
1459
1460
            if (!isset($category[0])) {
1461
                continue;
1462
            }
1463
            /** @var Category $category */
1464
            $category = $category[0];
1465
1466
            if (empty($category->getGenerateCertificates())) {
1467
                continue;
1468
            }
1469
1470
            $categoryId = $category->get_id();
1471
            $certificateInfo = self::get_certificate_by_user_id($categoryId, $userId);
1472
1473
            if (empty($certificateInfo)) {
1474
                continue;
1475
            }
1476
1477
            $courseInfo = api_get_course_info_by_id($course['real_id']);
1478
            if (empty($courseInfo)) {
1479
                continue;
1480
            }
1481
1482
            $courseList[] = [
1483
                'course' => $courseInfo['title'],
1484
                'score' => $certificateInfo['score_certificate'],
1485
                'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1486
                'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}",
1487
                'pdf' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}&user_id={$userId}&action=export",
1488
            ];
1489
        }
1490
1491
        return $courseList;
1492
    }
1493
1494
    /**
1495
     * Get the achieved certificates for a user in course sessions.
1496
     *
1497
     * @param int  $userId                       The user id
1498
     * @param bool $includeNonPublicCertificates Whether include the non-public certificates
1499
     *
1500
     * @return array
1501
     */
1502
    public static function getUserCertificatesInSessions($userId, $includeNonPublicCertificates = true)
1503
    {
1504
        $userId = (int) $userId;
1505
        $sessionList = [];
1506
        $sessions = SessionManager::get_sessions_by_user($userId, true, true);
1507
1508
        foreach ($sessions as $session) {
1509
            if (empty($session['courses'])) {
1510
                continue;
1511
            }
1512
            $sessionCourses = SessionManager::get_course_list_by_session_id($session['session_id']);
1513
1514
            if (empty($sessionCourses)) {
1515
                continue;
1516
            }
1517
1518
            foreach ($sessionCourses as $course) {
1519
                if (!$includeNonPublicCertificates) {
1520
                    $allowPublicCertificates = api_get_course_setting('allow_public_certificates');
1521
1522
                    if (empty($allowPublicCertificates)) {
1523
                        continue;
1524
                    }
1525
                }
1526
1527
                $category = Category::load(
1528
                    null,
1529
                    null,
1530
                    $course['code'],
1531
                    null,
1532
                    null,
1533
                    $session['session_id']
1534
                );
1535
1536
                if (empty($category)) {
1537
                    continue;
1538
                }
1539
1540
                if (!isset($category[0])) {
1541
                    continue;
1542
                }
1543
1544
                /** @var Category $category */
1545
                $category = $category[0];
1546
1547
                // Don't allow generate of certifications
1548
                if (empty($category->getGenerateCertificates())) {
1549
                    continue;
1550
                }
1551
1552
                $categoryId = $category->get_id();
1553
                $certificateInfo = self::get_certificate_by_user_id(
1554
                    $categoryId,
1555
                    $userId
1556
                );
1557
1558
                if (empty($certificateInfo)) {
1559
                    continue;
1560
                }
1561
1562
                $sessionList[] = [
1563
                    'session' => $session['session_name'],
1564
                    'course' => $course['title'],
1565
                    'score' => $certificateInfo['score_certificate'],
1566
                    'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1567
                    'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}",
1568
                ];
1569
            }
1570
        }
1571
1572
        return $sessionList;
1573
    }
1574
1575
    /**
1576
     * @param array $courseInfo
1577
     * @param int   $userId
1578
     * @param array $cats
1579
     * @param bool  $saveToFile
1580
     * @param bool  $saveToHtmlFile
1581
     * @param array $studentList
1582
     * @param PDF   $pdf
1583
     *
1584
     * @return string
1585
     */
1586
    public static function generateTable(
1587
        $courseInfo,
1588
        $userId,
1589
        $cats,
1590
        $saveToFile = false,
1591
        $saveToHtmlFile = false,
1592
        $studentList = [],
1593
        $pdf = null
1594
    ) {
1595
        $userInfo = api_get_user_info($userId);
1596
        $model = ExerciseLib::getCourseScoreModel();
1597
        $cat = $cats[0];
1598
        $allcat = $cats[0]->get_subcategories(
1599
            $userId,
1600
            api_get_course_id(),
1601
            api_get_session_id()
1602
        );
1603
        $alleval = $cats[0]->get_evaluations($userId);
1604
        $alllink = $cats[0]->get_links($userId);
1605
1606
        $loadStats = [];
1607
        if (api_get_setting('gradebook_detailed_admin_view') === 'true') {
1608
            $loadStats = [1, 2, 3];
1609
        } else {
1610
            if (api_get_configuration_value('gradebook_enable_best_score') !== false) {
1611
                $loadStats = [2];
1612
            }
1613
        }
1614
1615
        $gradebooktable = new GradebookTable(
1616
            $cat,
1617
            $allcat,
1618
            $alleval,
1619
            $alllink,
1620
            null,
1621
            true,
1622
            false,
1623
            $userId,
1624
            $studentList,
1625
            $loadStats
1626
        );
1627
1628
        $gradebooktable->userId = $userId;
1629
1630
        if (api_is_allowed_to_edit(null, true)) {
1631
        } else {
1632
            if (empty($model)) {
1633
                $gradebooktable->td_attributes = [
1634
                    3 => 'class=centered',
1635
                    4 => 'class=centered',
1636
                    5 => 'class=centered',
1637
                    6 => 'class=centered',
1638
                    7 => 'class=centered',
1639
                ];
1640
            }
1641
        }
1642
        $table = $gradebooktable->return_table();
1643
1644
        $graph = '';
1645
        if (empty($model)) {
1646
            $graph = $gradebooktable->getGraph();
1647
        }
1648
        $params = [
1649
            'pdf_title' => sprintf(get_lang('GradeFromX'), $courseInfo['name']),
1650
            'session_info' => '',
1651
            'course_info' => '',
1652
            'pdf_date' => '',
1653
            'course_code' => api_get_course_id(),
1654
            'student_info' => $userInfo,
1655
            'show_grade_generated_date' => true,
1656
            'show_real_course_teachers' => false,
1657
            'show_teacher_as_myself' => false,
1658
            'orientation' => 'P',
1659
        ];
1660
1661
        if (empty($pdf)) {
1662
            $pdf = new PDF('A4', $params['orientation'], $params);
1663
        }
1664
1665
        $pdf->params['student_info'] = $userInfo;
1666
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid().'.html';
1667
1668
        $content =
1669
            $table.
1670
            $graph.
1671
            '<br />'.get_lang('Feedback').'<br />
1672
            <textarea class="form-control" rows="5" cols="100">&nbsp;</textarea>';
1673
1674
        $result = $pdf->html_to_pdf_with_template(
1675
            $content,
1676
            $saveToFile,
1677
            $saveToHtmlFile,
1678
            true
1679
        );
1680
1681
        if ($saveToHtmlFile) {
1682
            return $result;
1683
            file_put_contents($file, $result);
0 ignored issues
show
Unused Code introduced by
file_put_contents($file, $result) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1684
1685
            return $file;
1686
        }
1687
1688
        return $file;
1689
    }
1690
}
1691