Passed
Push — 1.11.x ( ce2afd...1405b1 )
by Julito
10:39
created

GradebookUtils::getComment()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 2
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class GradebookUtils.
7
 */
8
class GradebookUtils
9
{
10
    /**
11
     * Adds a resource to the unique gradebook of a given course.
12
     *
13
     * @param   int
14
     * @param   string  Course code
15
     * @param   int     Resource type (use constants defined in linkfactory.class.php)
16
     * @param   int     Resource ID in the corresponding tool
17
     * @param   string  Resource name to show in the gradebook
18
     * @param   int     Resource weight to set in the gradebook
19
     * @param   int     Resource max
20
     * @param   string  Resource description
21
     * @param   int     Visibility (0 hidden, 1 shown)
22
     * @param   int     Session ID (optional or 0 if not defined)
23
     * @param   int
24
     * @param int $resource_type
25
     *
26
     * @return bool True on success, false on failure
27
     */
28
    public static function add_resource_to_course_gradebook(
29
        $category_id,
30
        $course_code,
31
        $resource_type,
32
        $resource_id,
33
        $resource_name = '',
34
        $weight = 0,
35
        $max = 0,
36
        $resource_description = '',
37
        $visible = 0,
38
        $session_id = 0,
39
        $link_id = null
40
    ) {
41
        $link = LinkFactory::create($resource_type);
42
        $link->set_user_id(api_get_user_id());
43
        $link->set_course_code($course_code);
44
45
        if (empty($category_id)) {
46
            return false;
47
        }
48
        $link->set_category_id($category_id);
49
        if ($link->needs_name_and_description()) {
50
            $link->set_name($resource_name);
51
        } else {
52
            $link->set_ref_id($resource_id);
53
        }
54
        $link->set_weight($weight);
55
56
        if ($link->needs_max()) {
57
            $link->set_max($max);
58
        }
59
        if ($link->needs_name_and_description()) {
60
            $link->set_description($resource_description);
61
        }
62
63
        $link->set_visible(empty($visible) ? 0 : 1);
64
65
        if (!empty($session_id)) {
66
            $link->set_session_id($session_id);
67
        }
68
        $link->add();
69
70
        return true;
71
    }
72
73
    /**
74
     * Update a resource weight.
75
     *
76
     * @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...
77
     * @param   string
78
     * @param float
79
     *
80
     * @return bool false on error, true on success
81
     */
82
    public static function updateResourceFromCourseGradebook(
83
        $link_id,
84
        $course_code,
85
        $weight
86
    ) {
87
        $link_id = (int) $link_id;
88
        if (!empty($link_id)) {
89
            $course_code = Database::escape_string($course_code);
90
            $sql = 'UPDATE '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK).'
91
                    SET weight = '."'".api_float_val($weight)."'".'
92
                    WHERE course_code = "'.$course_code.'" AND id = '.$link_id;
93
            Database::query($sql);
94
        }
95
96
        return true;
97
    }
98
99
    /**
100
     * Remove a resource from the unique gradebook of a given course.
101
     *
102
     * @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...
103
     *
104
     * @return bool false on error, true on success
105
     */
106
    public static function remove_resource_from_course_gradebook($link_id)
107
    {
108
        if (empty($link_id)) {
109
            return false;
110
        }
111
112
        // TODO find the corresponding category (the first one for this course, ordered by ID)
113
        $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
114
        $sql = "DELETE FROM $l WHERE id = ".(int) $link_id;
115
        Database::query($sql);
116
117
        return true;
118
    }
119
120
    /**
121
     * Block students.
122
     */
123
    public static function block_students()
124
    {
125
        $sessionId = api_get_session_id();
126
        if (empty($sessionId)) {
127
            if (!api_is_allowed_to_edit()) {
128
                api_not_allowed();
129
            }
130
        } else {
131
            $isCoach = api_is_coach(api_get_session_id(), api_get_course_int_id());
132
            if (false === $isCoach) {
133
                if (!api_is_allowed_to_edit()) {
134
                    api_not_allowed();
135
                }
136
            }
137
        }
138
    }
139
140
    /**
141
     * Builds an img tag for a gradebook item.
142
     */
143
    public static function build_type_icon_tag($kind, $attributes = [])
144
    {
145
        return Display::return_icon(
146
            self::get_icon_file_name($kind),
147
            ' ',
148
            $attributes,
149
            ICON_SIZE_SMALL
150
        );
151
    }
152
153
    /**
154
     * Returns the icon filename for a gradebook item.
155
     *
156
     * @param string $type value returned by a gradebookitem's get_icon_name()
157
     *
158
     * @return string
159
     */
160
    public static function get_icon_file_name($type)
161
    {
162
        switch ($type) {
163
            case 'cat':
164
                $icon = 'gradebook.png';
165
                break;
166
            case 'evalempty':
167
                $icon = 'empty_evaluation.png';
168
                break;
169
            case 'evalnotempty':
170
                $icon = 'no_empty_evaluation.png';
171
                break;
172
            case 'exercise':
173
            case LINK_EXERCISE:
174
                $icon = 'quiz.png';
175
                break;
176
            case 'learnpath':
177
            case LINK_LEARNPATH:
178
                $icon = 'learnpath.png';
179
                break;
180
            case 'studentpublication':
181
            case LINK_STUDENTPUBLICATION:
182
                $icon = 'works.gif';
183
                break;
184
            case 'link':
185
                $icon = 'link.gif';
186
                break;
187
            case 'forum':
188
            case LINK_FORUM_THREAD:
189
                $icon = 'forum.gif';
190
                break;
191
            case 'attendance':
192
            case LINK_ATTENDANCE:
193
                $icon = 'attendance.gif';
194
                break;
195
            case 'survey':
196
            case LINK_SURVEY:
197
                $icon = 'survey.gif';
198
                break;
199
            case 'dropbox':
200
            case LINK_DROPBOX:
201
                $icon = 'dropbox.gif';
202
                break;
203
            default:
204
                $icon = 'link.gif';
205
                break;
206
        }
207
208
        return $icon;
209
    }
210
211
    /**
212
     * Builds the course or platform admin icons to edit a category.
213
     *
214
     * @param Category $cat       category
215
     * @param Category $selectcat id of selected category
216
     *
217
     * @return string
218
     */
219
    public static function build_edit_icons_cat($cat, $selectcat)
220
    {
221
        $show_message = $cat->show_message_resource_delete($cat->get_course_code());
222
        $grade_model_id = $selectcat->get_grade_model_id();
223
        $selectcat = $selectcat->get_id();
224
        $modify_icons = null;
225
226
        if ($show_message === false) {
227
            $visibility_icon = ($cat->is_visible() == 0) ? 'invisible' : 'visible';
228
            $visibility_command = ($cat->is_visible() == 0) ? 'set_visible' : 'set_invisible';
229
230
            $modify_icons .= '<a class="view_children" data-cat-id="'.$cat->get_id().'" href="javascript:void(0);">'.
231
                Display::return_icon(
232
                    'view_more_stats.gif',
233
                    get_lang('Show'),
234
                    '',
235
                    ICON_SIZE_SMALL
236
                ).
237
                '</a>';
238
239
            if (!api_is_allowed_to_edit(null, true)) {
240
                $modify_icons .= Display::url(
241
                    Display::return_icon(
242
                        'statistics.png',
243
                        get_lang('FlatView'),
244
                        '',
245
                        ICON_SIZE_SMALL
246
                    ),
247
                    'personal_stats.php?'.http_build_query([
248
                        'selectcat' => $cat->get_id(),
249
                    ]).'&'.api_get_cidreq(),
250
                    [
251
                        'class' => 'ajax',
252
                        'data-title' => get_lang('FlatView'),
253
                    ]
254
                );
255
            }
256
257
            $courseParams = api_get_cidreq_params(
258
                $cat->get_course_code(),
259
                $cat->get_session_id()
260
            );
261
262
            if (api_is_allowed_to_edit(null, true)) {
263
                // Locking button
264
                if (api_get_setting('gradebook_locking_enabled') === 'true') {
265
                    if ($cat->is_locked()) {
266
                        if (api_is_platform_admin()) {
267
                            $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">'.
268
                                Display::return_icon('lock.png', get_lang('UnLockEvaluation'), '', ICON_SIZE_SMALL).'</a>';
269
                        } else {
270
                            $modify_icons .= '&nbsp;<a href="#">'.
271
                                Display::return_icon('lock_na.png', get_lang('GradebookLockedAlert'), '', ICON_SIZE_SMALL).'</a>';
272
                        }
273
                        $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>';
274
                    } else {
275
                        $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">'.
276
                            Display::return_icon('unlock.png', get_lang('LockEvaluation'), '', ICON_SIZE_SMALL).'</a>';
277
                        $modify_icons .= '&nbsp;<a href="#" >'.
278
                            Display::return_icon('pdf_na.png', get_lang('ExportToPDF'), '', ICON_SIZE_SMALL).'</a>';
279
                    }
280
                }
281
282
                if (empty($grade_model_id) || $grade_model_id == -1) {
283
                    if ($cat->is_locked() && !api_is_platform_admin()) {
284
                        $modify_icons .= Display::return_icon(
285
                            'edit_na.png',
286
                            get_lang('Modify'),
287
                            '',
288
                            ICON_SIZE_SMALL
289
                        );
290
                    } else {
291
                        $modify_icons .= '<a href="gradebook_edit_cat.php?editcat='.$cat->get_id().'&'.$courseParams.'">'.
292
                            Display::return_icon(
293
                                'edit.png',
294
                                get_lang('Modify'),
295
                                '',
296
                                ICON_SIZE_SMALL
297
                            ).'</a>';
298
                    }
299
                }
300
301
                $modify_icons .= '<a href="gradebook_edit_all.php?selectcat='.$cat->get_id().'&'.$courseParams.'">'.
302
                    Display::return_icon(
303
                        'percentage.png',
304
                        get_lang('EditAllWeights'),
305
                        '',
306
                        ICON_SIZE_SMALL
307
                    ).'</a>';
308
309
                $modify_icons .= '<a href="gradebook_flatview.php?selectcat='.$cat->get_id().'&'.$courseParams.'">'.
310
                    Display::return_icon(
311
                        'statistics.png',
312
                        get_lang('FlatView'),
313
                        '',
314
                        ICON_SIZE_SMALL
315
                    ).'</a>';
316
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visiblecat='.$cat->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.'">'.
317
                    Display::return_icon(
318
                        $visibility_icon.'.png',
319
                        get_lang('Visible'),
320
                        '',
321
                        ICON_SIZE_SMALL
322
                    ).'</a>';
323
324
                if ($cat->is_locked() && !api_is_platform_admin()) {
325
                    $modify_icons .= Display::return_icon(
326
                        'delete_na.png',
327
                        get_lang('DeleteAll'),
328
                        '',
329
                        ICON_SIZE_SMALL
330
                    );
331
                } else {
332
                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deletecat='.$cat->get_id().'&selectcat='.$selectcat.'&'.$courseParams.'" onclick="return confirmation();">'.
333
                        Display::return_icon(
334
                            'delete.png',
335
                            get_lang('DeleteAll'),
336
                            '',
337
                            ICON_SIZE_SMALL
338
                        ).
339
                        '</a>';
340
                }
341
            }
342
343
            return $modify_icons;
344
        }
345
    }
346
347
    /**
348
     * Builds the course or platform admin icons to edit an evaluation.
349
     *
350
     * @param Evaluation $eval      evaluation object
351
     * @param int        $selectcat id of selected category
352
     *
353
     * @return string
354
     */
355
    public static function build_edit_icons_eval($eval, $selectcat)
356
    {
357
        $is_locked = $eval->is_locked();
358
        $eval->get_course_code();
359
        $cat = new Category();
360
        $message_eval = $cat->show_message_resource_delete($eval->get_course_code());
361
        $courseParams = api_get_cidreq_params($eval->get_course_code(), $eval->getSessionId());
362
363
        if ($message_eval === false && api_is_allowed_to_edit(null, true)) {
364
            $visibility_icon = $eval->is_visible() == 0 ? 'invisible' : 'visible';
365
            $visibility_command = $eval->is_visible() == 0 ? 'set_visible' : 'set_invisible';
366
            if ($is_locked && !api_is_platform_admin()) {
367
                $modify_icons = Display::return_icon(
368
                    'edit_na.png',
369
                    get_lang('Modify'),
370
                    '',
371
                    ICON_SIZE_SMALL
372
                );
373
            } else {
374
                $modify_icons = '<a href="gradebook_edit_eval.php?editeval='.$eval->get_id().'&'.$courseParams.'">'.
375
                    Display::return_icon(
376
                        'edit.png',
377
                        get_lang('Modify'),
378
                        '',
379
                        ICON_SIZE_SMALL
380
                    ).
381
                    '</a>';
382
            }
383
384
            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visibleeval='.$eval->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.' ">'.
385
                Display::return_icon(
386
                    $visibility_icon.'.png',
387
                    get_lang('Visible'),
388
                    '',
389
                    ICON_SIZE_SMALL
390
                ).
391
                '</a>';
392
393
            if (api_is_allowed_to_edit(null, true)) {
394
                $modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog='.$eval->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'">'.
395
                    Display::return_icon(
396
                        'history.png',
397
                        get_lang('GradebookQualifyLog'),
398
                        '',
399
                        ICON_SIZE_SMALL
400
                    ).
401
                    '</a>';
402
403
                $allowStats = api_get_configuration_value('allow_gradebook_stats');
404
                if ($allowStats) {
405
                    $modify_icons .= Display::url(
406
                        Display::return_icon('reload.png', get_lang('GenerateStats')),
407
                        api_get_self().'?itemId='.$eval->get_id().'&action=generate_eval_stats&selectcat='.$selectcat.'&'.$courseParams
408
                    );
409
                }
410
            }
411
412
            if ($is_locked && !api_is_platform_admin()) {
413
                $modify_icons .= '&nbsp;'.
414
                    Display::return_icon(
415
                        'delete_na.png',
416
                        get_lang('Delete'),
417
                        '',
418
                        ICON_SIZE_SMALL
419
                    );
420
            } else {
421
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deleteeval='.$eval->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'" onclick="return confirmation();">'.
422
                    Display::return_icon(
423
                        'delete.png',
424
                        get_lang('Delete'),
425
                        '',
426
                        ICON_SIZE_SMALL
427
                    ).
428
                    '</a>';
429
            }
430
431
            return $modify_icons;
432
        }
433
    }
434
435
    /**
436
     * Builds the course or platform admin icons to edit a link.
437
     *
438
     * @param AbstractLink $link
439
     * @param int          $selectcat id of selected category
440
     *
441
     * @return string
442
     */
443
    public static function build_edit_icons_link($link, $selectcat)
444
    {
445
        $cat = new Category();
446
        $message_link = $cat->show_message_resource_delete($link->get_course_code());
447
        $is_locked = $link->is_locked();
448
        $modify_icons = null;
449
450
        if (!api_is_allowed_to_edit(null, true)) {
451
            return null;
452
        }
453
454
        $courseParams = api_get_cidreq_params(
455
            $link->get_course_code(),
456
            $link->get_session_id()
457
        );
458
459
        if ($message_link === false) {
460
            $visibility_icon = $link->is_visible() == 0 ? 'invisible' : 'visible';
461
            $visibility_command = $link->is_visible() == 0 ? 'set_visible' : 'set_invisible';
462
463
            if ($is_locked && !api_is_platform_admin()) {
464
                $modify_icons = Display::return_icon(
465
                    'edit_na.png',
466
                    get_lang('Modify'),
467
                    '',
468
                    ICON_SIZE_SMALL
469
                );
470
            } else {
471
                $modify_icons = '<a href="gradebook_edit_link.php?editlink='.$link->get_id().'&'.$courseParams.'">'.
472
                    Display::return_icon(
473
                        'edit.png',
474
                        get_lang('Modify'),
475
                        '',
476
                        ICON_SIZE_SMALL
477
                    ).
478
                    '</a>';
479
            }
480
            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visiblelink='.$link->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.' ">'.
481
                Display::return_icon(
482
                    $visibility_icon.'.png',
483
                    get_lang('Visible'),
484
                    '',
485
                    ICON_SIZE_SMALL
486
                ).
487
                '</a>';
488
489
            $modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink='.$link->get_id().'&selectcat='.$selectcat.'&'.$courseParams.'">'.
490
                Display::return_icon(
491
                    'history.png',
492
                    get_lang('GradebookQualifyLog'),
493
                    '',
494
                    ICON_SIZE_SMALL
495
                ).
496
                '</a>';
497
498
            $allowStats = api_get_configuration_value('allow_gradebook_stats');
499
            if ($allowStats && $link->get_type() == LINK_EXERCISE) {
500
                $modify_icons .= Display::url(
501
                    Display::return_icon('reload.png', get_lang('GenerateStats')),
502
                    api_get_self().'?itemId='.$link->get_id().'&action=generate_link_stats&selectcat='.$selectcat.'&'.$courseParams
503
                );
504
            }
505
506
            //If a work is added in a gradebook you can only delete the link in the work tool
507
            if ($is_locked && !api_is_platform_admin()) {
508
                $modify_icons .= '&nbsp;'.
509
                    Display::return_icon(
510
                        'delete_na.png',
511
                        get_lang('Delete'),
512
                        '',
513
                        ICON_SIZE_SMALL
514
                    );
515
            } else {
516
                $modify_icons .= '&nbsp;
517
                <a
518
                    href="'.api_get_self().'?deletelink='.$link->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'"
519
                    onclick="return confirmation();">'.
520
                    Display::return_icon(
521
                        'delete.png',
522
                        get_lang('Delete'),
523
                        '',
524
                        ICON_SIZE_SMALL
525
                    ).
526
                    '</a>';
527
            }
528
529
            return $modify_icons;
530
        }
531
    }
532
533
    /**
534
     * Checks if a resource is in the unique gradebook of a given course.
535
     *
536
     * @param string $course_code   Course code
537
     * @param int    $resource_type Resource type (use constants defined in linkfactory.class.php)
538
     * @param int    $resource_id   Resource ID in the corresponding tool
539
     * @param int    $session_id    Session ID (optional -  0 if not defined)
540
     *
541
     * @return array false on error or array of resource
542
     */
543
    public static function isResourceInCourseGradebook(
544
        $course_code,
545
        $resource_type,
546
        $resource_id,
547
        $session_id = 0
548
    ) {
549
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
550
        $course_code = Database::escape_string($course_code);
551
        $sql = "SELECT * FROM $table l
552
                WHERE
553
                    course_code = '$course_code' AND
554
                    type = ".(int) $resource_type." AND
555
                    ref_id = ".(int) $resource_id;
556
        $res = Database::query($sql);
557
558
        if (Database::num_rows($res) < 1) {
559
            return false;
560
        }
561
562
        return Database::fetch_array($res, 'ASSOC');
563
    }
564
565
    /**
566
     * Return the course id.
567
     *
568
     * @param    int
569
     *
570
     * @return string
571
     */
572
    public static function get_course_id_by_link_id($id_link)
573
    {
574
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
575
        $tbl_grade_links = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
576
        $id_link = (int) $id_link;
577
578
        $sql = 'SELECT c.id FROM '.$course_table.' c
579
                INNER JOIN '.$tbl_grade_links.' l
580
                ON c.code = l.course_code
581
                WHERE l.id='.$id_link.' OR l.category_id='.$id_link;
582
        $res = Database::query($sql);
583
        $array = Database::fetch_array($res, 'ASSOC');
584
585
        return $array['id'];
586
    }
587
588
    /**
589
     * @param $type
590
     *
591
     * @return string
592
     */
593
    public static function get_table_type_course($type)
594
    {
595
        global $table_evaluated;
596
597
        return Database::get_course_table($table_evaluated[$type][0]);
598
    }
599
600
    /**
601
     * @param Category $cat
602
     * @param $users
603
     * @param $alleval
604
     * @param $alllinks
605
     * @param $params
606
     * @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...
607
     *
608
     * @return array
609
     */
610
    public static function get_printable_data(
611
        $cat,
612
        $users,
613
        $alleval,
614
        $alllinks,
615
        $params,
616
        $mainCourseCategory = null
617
    ) {
618
        $datagen = new FlatViewDataGenerator(
619
            $users,
620
            $alleval,
621
            $alllinks,
622
            $params,
623
            $mainCourseCategory
624
        );
625
626
        $offset = isset($_GET['offset']) ? (int) $_GET['offset'] : 0;
627
628
        // step 2: generate rows: students
629
        $datagen->category = $cat;
630
631
        $count = (($offset + 10) > $datagen->get_total_items_count()) ? ($datagen->get_total_items_count() - $offset) : GRADEBOOK_ITEM_LIMIT;
632
        $header_names = $datagen->get_header_names($offset, $count, true);
633
        $data_array = $datagen->get_data(
634
            FlatViewDataGenerator::FVDG_SORT_LASTNAME,
635
            0,
636
            null,
637
            $offset,
638
            $count,
639
            true,
640
            true
641
        );
642
643
        $result = [];
644
        foreach ($data_array as $data) {
645
            $result[] = array_slice($data, 1);
646
        }
647
        $return = [$header_names, $result];
648
649
        return $return;
650
    }
651
652
    /**
653
     * XML-parser: handle character data.
654
     */
655
    public static function character_data($parser, $data)
656
    {
657
        global $current_value;
658
        $current_value = $data;
659
    }
660
661
    public static function overwritescore($resid, $importscore, $eval_max)
662
    {
663
        $result = Result::load($resid);
664
        if ($importscore > $eval_max) {
665
            header('Location: gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'&overwritemax=');
666
            exit;
667
        }
668
        $result[0]->set_score($importscore);
669
        $result[0]->save();
670
        unset($result);
671
    }
672
673
    /**
674
     * register user info about certificate.
675
     *
676
     * @param int    $cat_id            The category id
677
     * @param int    $user_id           The user id
678
     * @param float  $score_certificate The score obtained for certified
679
     * @param string $date_certificate  The date when you obtained the certificate
680
     */
681
    public static function registerUserInfoAboutCertificate(
682
        $cat_id,
683
        $user_id,
684
        $score_certificate,
685
        $date_certificate
686
    ) {
687
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
688
        $cat_id = (int) $cat_id;
689
        $user_id = (int) $user_id;
690
691
        $sql = "SELECT COUNT(id) as count
692
                FROM $table gc
693
                WHERE gc.cat_id = $cat_id AND user_id = $user_id ";
694
        $rs_exist = Database::query($sql);
695
        $row = Database::fetch_array($rs_exist);
696
        if (0 == $row['count']) {
697
            $params = [
698
                'cat_id' => $cat_id,
699
                'user_id' => $user_id,
700
                'score_certificate' => $score_certificate,
701
                'created_at' => $date_certificate,
702
            ];
703
            Database::insert($table, $params);
704
        }
705
    }
706
707
    /**
708
     * Get date of user certificate.
709
     *
710
     * @param int $cat_id  The category id
711
     * @param int $user_id The user id
712
     *
713
     * @return Datetime The date when you obtained the certificate
714
     */
715
    public static function get_certificate_by_user_id($cat_id, $user_id)
716
    {
717
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
718
        $cat_id = (int) $cat_id;
719
        $user_id = (int) $user_id;
720
721
        $sql = "SELECT * FROM $table
722
                WHERE cat_id = $cat_id AND user_id = $user_id ";
723
724
        $result = Database::query($sql);
725
        $row = Database::fetch_array($result, 'ASSOC');
726
727
        return $row;
728
    }
729
730
    /**
731
     * Get list of users certificates.
732
     *
733
     * @param int   $cat_id   The category id
734
     * @param array $userList Only users in this list
735
     *
736
     * @return array
737
     */
738
    public static function get_list_users_certificates($cat_id = null, $userList = [])
739
    {
740
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
741
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
742
        $sql = 'SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username, gc.created_at
743
                FROM '.$table_user.' u
744
                INNER JOIN '.$table_certificate.' gc
745
                ON u.user_id=gc.user_id ';
746
        if (!is_null($cat_id) && $cat_id > 0) {
747
            $sql .= ' WHERE cat_id='.intval($cat_id);
748
        }
749
        if (!empty($userList)) {
750
            $userList = array_map('intval', $userList);
751
            $userListCondition = implode("','", $userList);
752
            $sql .= " AND u.user_id IN ('$userListCondition')";
753
        }
754
        $sql .= ' ORDER BY '.(api_sort_by_first_name() ? 'u.firstname' : 'u.lastname');
755
        $rs = Database::query($sql);
756
757
        $list_users = [];
758
        while ($row = Database::fetch_array($rs)) {
759
            $list_users[] = $row;
760
        }
761
762
        return $list_users;
763
    }
764
765
    /**
766
     * Gets the certificate list by user id.
767
     *
768
     * @param int $user_id The user id
769
     * @param int $cat_id  The category id
770
     *
771
     * @return array
772
     */
773
    public static function get_list_gradebook_certificates_by_user_id(
774
        $user_id,
775
        $cat_id = null
776
    ) {
777
        $user_id = (int) $user_id;
778
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
779
        $sql = 'SELECT
780
                    gc.score_certificate,
781
                    gc.created_at,
782
                    gc.path_certificate,
783
                    gc.cat_id,
784
                    gc.user_id,
785
                    gc.id
786
                FROM  '.$table_certificate.' gc
787
                WHERE gc.user_id = "'.$user_id.'" ';
788
        if (!is_null($cat_id) && $cat_id > 0) {
789
            $sql .= ' AND cat_id='.intval($cat_id);
790
        }
791
792
        $rs = Database::query($sql);
793
        $list = [];
794
        while ($row = Database::fetch_array($rs)) {
795
            $list[] = $row;
796
        }
797
798
        return $list;
799
    }
800
801
    /**
802
     * @param int    $user_id
803
     * @param string $course_code
804
     * @param int    $sessionId
805
     * @param bool   $is_preview
806
     * @param bool   $hide_print_button
807
     *
808
     * @return array
809
     */
810
    public static function get_user_certificate_content(
811
        $user_id,
812
        $course_code,
813
        $sessionId,
814
        $is_preview = false,
815
        $hide_print_button = false
816
    ) {
817
        // Generate document HTML
818
        $content_html = DocumentManager::replace_user_info_into_html(
819
            $user_id,
820
            $course_code,
821
            $sessionId,
822
            $is_preview
823
        );
824
825
        $new_content_html = isset($content_html['content']) ? $content_html['content'] : null;
826
        $variables = isset($content_html['variables']) ? $content_html['variables'] : null;
827
        $path_image = api_get_path(WEB_COURSE_PATH).api_get_course_path($course_code).'/document/images/gallery';
828
        $new_content_html = str_replace('../images/gallery', $path_image, $new_content_html);
829
830
        $path_image_in_default_course = api_get_path(WEB_CODE_PATH).'default_course_document';
831
        $new_content_html = str_replace('/main/default_course_document', $path_image_in_default_course, $new_content_html);
832
        $new_content_html = str_replace(SYS_CODE_PATH.'img/', api_get_path(WEB_IMG_PATH), $new_content_html);
833
834
        //add print header
835
        if (!$hide_print_button) {
836
            $print = '<style>#print_div {
837
                padding:4px;border: 0 none;position: absolute;top: 0px;right: 0px;
838
            }
839
            @media print {
840
                #print_div  {
841
                    display: none !important;
842
                }
843
            }
844
            </style>';
845
846
            $print .= Display::div(
847
                Display::url(
848
                    Display::return_icon('printmgr.gif', get_lang('Print')),
849
                    'javascript:void()',
850
                    ['onclick' => 'window.print();']
851
                ),
852
                ['id' => 'print_div']
853
            );
854
            $print .= '</html>';
855
            $new_content_html = str_replace('</html>', $print, $new_content_html);
856
        }
857
858
        return [
859
            'content' => $new_content_html,
860
            'variables' => $variables,
861
        ];
862
    }
863
864
    /**
865
     * @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...
866
     * @param int  $gradebook_model_id
867
     *
868
     * @return mixed
869
     */
870
    public static function create_default_course_gradebook(
871
        $course_code = null,
872
        $gradebook_model_id = 0
873
    ) {
874
        if (api_is_allowed_to_edit(true, true)) {
875
            if (!isset($course_code) || empty($course_code)) {
876
                $course_code = api_get_course_id();
877
            }
878
            $session_id = api_get_session_id();
879
880
            $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
881
            $sql = "SELECT * FROM $t
882
                    WHERE course_code = '".Database::escape_string($course_code)."' ";
883
            if (!empty($session_id)) {
884
                $sql .= " AND session_id = ".$session_id;
885
            } else {
886
                $sql .= ' AND (session_id IS NULL OR session_id = 0) ';
887
            }
888
            $sql .= ' ORDER BY id ';
889
            $res = Database::query($sql);
890
            if (Database::num_rows($res) < 1) {
891
                //there is no unique category for this course+session combination,
892
                $cat = new Category();
893
                if (!empty($session_id)) {
894
                    $my_session_id = api_get_session_id();
895
                    $s_name = api_get_session_name($my_session_id);
896
                    $cat->set_name($course_code.' - '.get_lang('Session').' '.$s_name);
897
                    $cat->set_session_id($session_id);
898
                } else {
899
                    $cat->set_name($course_code);
900
                }
901
                $cat->set_course_code($course_code);
902
                $cat->set_description(null);
903
                $cat->set_user_id(api_get_user_id());
904
                $cat->set_parent_id(0);
905
                $default_weight_setting = api_get_setting('gradebook_default_weight');
906
                $default_weight = isset($default_weight_setting) && !empty($default_weight_setting) ? $default_weight_setting : 100;
907
                $cat->set_weight($default_weight);
908
                $cat->set_grade_model_id($gradebook_model_id);
909
                $cat->set_certificate_min_score(75);
910
                $cat->set_visible(0);
911
                $cat->add();
912
                $category_id = $cat->get_id();
913
                unset($cat);
914
            } else {
915
                $row = Database::fetch_array($res);
916
                $category_id = $row['id'];
917
            }
918
919
            return $category_id;
920
        }
921
922
        return false;
923
    }
924
925
    /**
926
     * @param FormValidator $form
927
     */
928
    public static function load_gradebook_select_in_tool($form)
929
    {
930
        $course_code = api_get_course_id();
931
        $session_id = api_get_session_id();
932
933
        self::create_default_course_gradebook();
934
935
        // Cat list
936
        $all_categories = Category::load(
937
            null,
938
            null,
939
            $course_code,
940
            null,
941
            null,
942
            $session_id,
943
            false
944
        );
945
        $select_gradebook = $form->addElement(
946
            'select',
947
            'category_id',
948
            get_lang('SelectGradebook')
949
        );
950
951
        if (!empty($all_categories)) {
952
            foreach ($all_categories as $my_cat) {
953
                if ($my_cat->get_course_code() == api_get_course_id()) {
954
                    $grade_model_id = $my_cat->get_grade_model_id();
955
                    if (empty($grade_model_id)) {
956
                        if ($my_cat->get_parent_id() == 0) {
957
                            $select_gradebook->addOption(get_lang('Default'), $my_cat->get_id());
958
                            $cats_added[] = $my_cat->get_id();
959
                        } else {
960
                            $select_gradebook->addOption($my_cat->get_name(), $my_cat->get_id());
961
                            $cats_added[] = $my_cat->get_id();
962
                        }
963
                    } else {
964
                        $select_gradebook->addOption(get_lang('Select'), 0);
965
                    }
966
                }
967
            }
968
        }
969
    }
970
971
    /**
972
     * @param FlatViewTable $flatviewtable
973
     * @param Category      $cat
974
     * @param $users
975
     * @param $alleval
976
     * @param $alllinks
977
     * @param array $params
978
     * @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...
979
     */
980
    public static function export_pdf_flatview(
981
        $flatviewtable,
982
        $cat,
983
        $users,
984
        $alleval,
985
        $alllinks,
986
        $params = [],
987
        $mainCourseCategory = null
988
    ) {
989
        // Getting data
990
        $printable_data = self::get_printable_data(
991
            $cat[0],
992
            $users,
993
            $alleval,
994
            $alllinks,
995
            $params,
996
            $mainCourseCategory
997
        );
998
999
        // HTML report creation first
1000
        $course_code = trim($cat[0]->get_course_code());
1001
1002
        $displayscore = ScoreDisplay::instance();
1003
        $customDisplays = $displayscore->get_custom_score_display_settings();
1004
1005
        $total = [];
1006
        if (is_array($customDisplays) && count(($customDisplays))) {
1007
            foreach ($customDisplays as $custom) {
1008
                $total[$custom['display']] = 0;
1009
            }
1010
            $user_results = $flatviewtable->datagen->get_data_to_graph2(false);
1011
            foreach ($user_results as $user_result) {
1012
                $item = $user_result[count($user_result) - 1];
1013
                $customTag = isset($item[1]) ? strip_tags($item[1]) : '';
1014
                $total[$customTag]++;
1015
            }
1016
        }
1017
1018
        $parent_id = $cat[0]->get_parent_id();
1019
        if (isset($cat[0]) && isset($parent_id)) {
1020
            if ($parent_id == 0) {
1021
                $grade_model_id = $cat[0]->get_grade_model_id();
1022
            } else {
1023
                $parent_cat = Category::load($parent_id);
1024
                $grade_model_id = $parent_cat[0]->get_grade_model_id();
1025
            }
1026
        }
1027
1028
        $use_grade_model = true;
1029
        if (empty($grade_model_id) || $grade_model_id == -1) {
1030
            $use_grade_model = false;
1031
        }
1032
1033
        if ($use_grade_model) {
1034
            if ($parent_id == 0) {
1035
                $title = api_strtoupper(get_lang('Average')).
1036
                    '<br />'.get_lang('Detailed');
1037
            } else {
1038
                $title = api_strtoupper(get_lang('Average')).
1039
                    '<br />'.$cat[0]->get_description().' - ('.$cat[0]->get_name().')';
1040
            }
1041
        } else {
1042
            if ($parent_id == 0) {
1043
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1044
            } else {
1045
                $title = api_strtoupper(get_lang('Average'));
1046
            }
1047
        }
1048
1049
        $columns = count($printable_data[0]);
1050
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
1051
1052
        $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
1053
        $row = 0;
1054
        $column = 0;
1055
        $table->setHeaderContents($row, $column, get_lang('NumberAbbreviation'));
1056
        $column++;
1057
        foreach ($printable_data[0] as $printable_data_cell) {
1058
            if (!is_array($printable_data_cell)) {
1059
                $printable_data_cell = strip_tags($printable_data_cell);
1060
            }
1061
            $table->setHeaderContents($row, $column, $printable_data_cell);
1062
            $column++;
1063
        }
1064
        $row++;
1065
1066
        if ($has_data) {
1067
            $counter = 1;
1068
            foreach ($printable_data[1] as &$printable_data_row) {
1069
                $column = 0;
1070
                $table->setCellContents($row, $column, $counter);
1071
                $table->updateCellAttributes($row, $column, 'align="center"');
1072
                $column++;
1073
                $counter++;
1074
1075
                foreach ($printable_data_row as $key => &$printable_data_cell) {
1076
                    $attributes = [];
1077
                    $attributes['align'] = 'center';
1078
                    $attributes['style'] = null;
1079
1080
                    if ($key === 'name') {
1081
                        $attributes['align'] = 'left';
1082
                    }
1083
                    if ($key === 'total') {
1084
                        $attributes['style'] = 'font-weight:bold';
1085
                    }
1086
                    $table->setCellContents($row, $column, $printable_data_cell);
1087
                    $table->updateCellAttributes($row, $column, $attributes);
1088
                    $column++;
1089
                }
1090
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
1091
                $row++;
1092
            }
1093
        } else {
1094
            $column = 0;
1095
            $table->setCellContents($row, $column, get_lang('NoResults'));
1096
            $table->updateCellAttributes($row, $column, 'colspan="'.$columns.'" align="center" class="row_odd"');
1097
        }
1098
1099
        $pdfParams = [
1100
            'filename' => get_lang('FlatView').'_'.api_get_local_time(),
1101
            'pdf_title' => $title,
1102
            'course_code' => $course_code,
1103
            'add_signatures' => ['Drh', 'Teacher', 'Date'],
1104
        ];
1105
1106
        $page_format = $params['orientation'] === 'landscape' ? 'A4-L' : 'A4';
1107
        ob_start();
1108
        $pdf = new PDF($page_format, $page_format, $pdfParams);
1109
        $pdf->html_to_pdf_with_template($flatviewtable->return_table(), false, false, true);
1110
        $content = ob_get_contents();
1111
        ob_end_clean();
1112
        echo $content;
1113
        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...
1114
    }
1115
1116
    /**
1117
     * @param string[] $list_values
1118
     *
1119
     * @return string
1120
     */
1121
    public static function score_badges($list_values)
1122
    {
1123
        $counter = 1;
1124
        $badges = [];
1125
        foreach ($list_values as $value) {
1126
            $class = 'warning';
1127
            if ($counter == 1) {
1128
                $class = 'success';
1129
            }
1130
            $counter++;
1131
            $badges[] = Display::badge($value, $class);
1132
        }
1133
1134
        return Display::badge_group($badges);
1135
    }
1136
1137
    /**
1138
     * returns users within a course given by param.
1139
     *
1140
     * @param string $courseCode
1141
     *
1142
     * @deprecated use CourseManager
1143
     *
1144
     * @return array
1145
     */
1146
    public static function get_users_in_course($courseCode)
1147
    {
1148
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1149
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1150
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1151
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
1152
1153
        $current_session = api_get_session_id();
1154
        $courseCode = Database::escape_string($courseCode);
1155
        $courseInfo = api_get_course_info($courseCode);
1156
        $courseId = $courseInfo['real_id'];
1157
1158
        if (!empty($current_session)) {
1159
            $sql = "SELECT user.user_id, user.username, lastname, firstname, official_code
1160
                    FROM $tbl_session_course_user as scru
1161
                    INNER JOIN $tbl_user as user
1162
                    ON (scru.user_id = user.user_id)
1163
                    WHERE
1164
                        scru.status = 0 AND
1165
                        scru.c_id='$courseId' AND
1166
                        session_id ='$current_session'
1167
                    $order_clause
1168
                    ";
1169
        } else {
1170
            $sql = 'SELECT user.user_id, user.username, lastname, firstname, official_code
1171
                    FROM '.$tbl_course_user.' as course_rel_user
1172
                    INNER JOIN '.$tbl_user.' as user
1173
                    ON (course_rel_user.user_id = user.id)
1174
                    WHERE
1175
                        course_rel_user.status = '.STUDENT.' AND
1176
                        course_rel_user.c_id = "'.$courseId.'" '.
1177
                    $order_clause;
1178
        }
1179
1180
        $result = Database::query($sql);
1181
1182
        return self::get_user_array_from_sql_result($result);
1183
    }
1184
1185
    /**
1186
     * @param Doctrine\DBAL\Driver\Statement|null $result
1187
     *
1188
     * @return array
1189
     */
1190
    public static function get_user_array_from_sql_result($result)
1191
    {
1192
        $a_students = [];
1193
        while ($user = Database::fetch_array($result)) {
1194
            if (!array_key_exists($user['user_id'], $a_students)) {
1195
                $a_current_student = [];
1196
                $a_current_student[] = $user['user_id'];
1197
                $a_current_student[] = $user['username'];
1198
                $a_current_student[] = $user['lastname'];
1199
                $a_current_student[] = $user['firstname'];
1200
                $a_current_student[] = $user['official_code'];
1201
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1202
            }
1203
        }
1204
1205
        return $a_students;
1206
    }
1207
1208
    /**
1209
     * @param array $evals
1210
     * @param array $links
1211
     *
1212
     * @return array
1213
     */
1214
    public static function get_all_users($evals = [], $links = [])
1215
    {
1216
        $coursecodes = [];
1217
        // By default add all user in course
1218
        $coursecodes[api_get_course_id()] = '1';
1219
        $users = self::get_users_in_course(api_get_course_id());
1220
1221
        foreach ($evals as $eval) {
1222
            $coursecode = $eval->get_course_code();
1223
            // evaluation in course
1224
            if (isset($coursecode) && !empty($coursecode)) {
1225
                if (!array_key_exists($coursecode, $coursecodes)) {
1226
                    $coursecodes[$coursecode] = '1';
1227
                    $users = array_merge($users, self::get_users_in_course($coursecode));
1228
                }
1229
            } else {
1230
                // course independent evaluation
1231
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1232
                $tbl_res = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1233
1234
                $sql = 'SELECT user.user_id, lastname, firstname, user.official_code
1235
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1236
                        WHERE
1237
                            res.evaluation_id = '.intval($eval->get_id()).' AND
1238
                            res.user_id = user.user_id
1239
                        ';
1240
                $sql .= ' ORDER BY lastname, firstname';
1241
                if (api_is_western_name_order()) {
1242
                    $sql .= ' ORDER BY firstname, lastname';
1243
                }
1244
1245
                $result = Database::query($sql);
1246
                $users = array_merge(
1247
                    $users,
1248
                    self::get_user_array_from_sql_result($result)
1249
                );
1250
            }
1251
        }
1252
1253
        foreach ($links as $link) {
1254
            // links are always in a course
1255
            $coursecode = $link->get_course_code();
1256
            if (!array_key_exists($coursecode, $coursecodes)) {
1257
                $coursecodes[$coursecode] = '1';
1258
                $users = array_merge(
1259
                    $users,
1260
                    self::get_users_in_course($coursecode)
1261
                );
1262
            }
1263
        }
1264
1265
        return $users;
1266
    }
1267
1268
    /**
1269
     * Search students matching a given last name and/or first name.
1270
     *
1271
     * @author Bert Steppé
1272
     */
1273
    public static function find_students($mask = '')
1274
    {
1275
        // students shouldn't be here // don't search if mask empty
1276
        if (!api_is_allowed_to_edit() || empty($mask)) {
1277
            return null;
1278
        }
1279
        $mask = Database::escape_string($mask);
1280
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1281
        $tbl_cru = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1282
        $sql = 'SELECT DISTINCT user.user_id, user.lastname, user.firstname, user.email, user.official_code
1283
                FROM '.$tbl_user.' user';
1284
        if (!api_is_platform_admin()) {
1285
            $sql .= ', '.$tbl_cru.' cru';
1286
        }
1287
1288
        $sql .= ' WHERE user.status = '.STUDENT;
1289
        $sql .= ' AND (user.lastname LIKE '."'%".$mask."%'";
1290
        $sql .= ' OR user.firstname LIKE '."'%".$mask."%')";
1291
1292
        if (!api_is_platform_admin()) {
1293
            $sql .= ' AND user.user_id = cru.user_id AND
1294
                      cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' AND
1295
                      cru.c_id in (
1296
                            SELECT c_id FROM '.$tbl_cru.'
1297
                            WHERE
1298
                                user_id = '.api_get_user_id().' AND
1299
                                status = '.COURSEMANAGER.'
1300
                        )
1301
                    ';
1302
        }
1303
1304
        $sql .= ' ORDER BY lastname, firstname';
1305
        if (api_is_western_name_order()) {
1306
            $sql .= ' ORDER BY firstname, lastname';
1307
        }
1308
1309
        $result = Database::query($sql);
1310
1311
        return Database::store_result($result);
1312
    }
1313
1314
    /**
1315
     * @param int   $linkId
1316
     * @param float $weight
1317
     */
1318
    public static function updateLinkWeight($linkId, $name, $weight)
1319
    {
1320
        $linkId = (int) $linkId;
1321
        $weight = api_float_val($weight);
1322
        $course_id = api_get_course_int_id();
1323
1324
        AbstractLink::add_link_log($linkId, $name);
1325
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1326
1327
        $em = Database::getManager();
1328
        $tbl_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
1329
        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
1330
1331
        $sql = 'UPDATE '.$table_link.'
1332
                SET weight = '."'".Database::escape_string($weight)."'".'
1333
                WHERE id = '.$linkId;
1334
1335
        Database::query($sql);
1336
1337
        // Update weight for attendance
1338
        $sql = 'SELECT ref_id FROM '.$table_link.'
1339
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1340
1341
        $rs_attendance = Database::query($sql);
1342
        if (Database::num_rows($rs_attendance) > 0) {
1343
            $row_attendance = Database::fetch_array($rs_attendance);
1344
            $sql = 'UPDATE '.$tbl_attendance.' SET
1345
                    attendance_weight ='.api_float_val($weight).'
1346
                    WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
1347
            Database::query($sql);
1348
        }
1349
        // Update weight into forum thread
1350
        $sql = 'UPDATE '.$tbl_forum_thread.' SET
1351
                thread_weight = '.api_float_val($weight).'
1352
                WHERE
1353
                    c_id = '.$course_id.' AND
1354
                    thread_id = (
1355
                        SELECT ref_id FROM '.$table_link.'
1356
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1357
                    )
1358
                ';
1359
        Database::query($sql);
1360
        //Update weight into student publication(work)
1361
        $em
1362
            ->createQuery('
1363
                UPDATE ChamiloCourseBundle:CStudentPublication w
1364
                SET w.weight = :final_weight
1365
                WHERE w.cId = :course
1366
                    AND w.id = (
1367
                        SELECT l.refId FROM ChamiloCoreBundle:GradebookLink l
1368
                        WHERE l.id = :link AND l.type = :type
1369
                    )
1370
            ')
1371
            ->execute([
1372
                'final_weight' => $weight,
1373
                'course' => $course_id,
1374
                'link' => $linkId,
1375
                'type' => LINK_STUDENTPUBLICATION,
1376
            ]);
1377
    }
1378
1379
    /**
1380
     * @param int   $id
1381
     * @param float $weight
1382
     */
1383
    public static function updateEvaluationWeight($id, $weight)
1384
    {
1385
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1386
        $id = (int) $id;
1387
        $evaluation = new Evaluation();
1388
        $evaluation->addEvaluationLog($id);
1389
        $sql = 'UPDATE '.$table_evaluation.'
1390
               SET weight = '."'".Database::escape_string($weight)."'".'
1391
               WHERE id = '.$id;
1392
        Database::query($sql);
1393
    }
1394
1395
    /**
1396
     * Get the achieved certificates for a user in courses.
1397
     *
1398
     * @param int  $userId                       The user id
1399
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1400
     *
1401
     * @return array
1402
     */
1403
    public static function getUserCertificatesInCourses(
1404
        $userId,
1405
        $includeNonPublicCertificates = true
1406
    ) {
1407
        $userId = (int) $userId;
1408
        $courseList = [];
1409
        $courses = CourseManager::get_courses_list_by_user_id($userId);
1410
1411
        foreach ($courses as $course) {
1412
            if (!$includeNonPublicCertificates) {
1413
                $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course);
1414
1415
                if (empty($allowPublicCertificates)) {
1416
                    continue;
1417
                }
1418
            }
1419
1420
            $category = Category::load(null, null, $course['code']);
1421
1422
            if (empty($category)) {
1423
                continue;
1424
            }
1425
1426
            if (!isset($category[0])) {
1427
                continue;
1428
            }
1429
            /** @var Category $category */
1430
            $category = $category[0];
1431
1432
            if (empty($category->getGenerateCertificates())) {
1433
                continue;
1434
            }
1435
1436
            $categoryId = $category->get_id();
1437
            $certificateInfo = self::get_certificate_by_user_id($categoryId, $userId);
1438
1439
            if (empty($certificateInfo)) {
1440
                continue;
1441
            }
1442
1443
            $courseInfo = api_get_course_info_by_id($course['real_id']);
1444
            if (empty($courseInfo)) {
1445
                continue;
1446
            }
1447
1448
            $courseList[] = [
1449
                'course' => $courseInfo['title'],
1450
                'score' => $certificateInfo['score_certificate'],
1451
                'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1452
                'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}",
1453
                'pdf' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}&user_id={$userId}&action=export",
1454
            ];
1455
        }
1456
1457
        return $courseList;
1458
    }
1459
1460
    /**
1461
     * Get the achieved certificates for a user in course sessions.
1462
     *
1463
     * @param int  $userId                       The user id
1464
     * @param bool $includeNonPublicCertificates Whether include the non-public certificates
1465
     *
1466
     * @return array
1467
     */
1468
    public static function getUserCertificatesInSessions($userId, $includeNonPublicCertificates = true)
1469
    {
1470
        $userId = (int) $userId;
1471
        $sessionList = [];
1472
        $sessions = SessionManager::get_sessions_by_user($userId, true, true);
1473
1474
        foreach ($sessions as $session) {
1475
            if (empty($session['courses'])) {
1476
                continue;
1477
            }
1478
            $sessionCourses = SessionManager::get_course_list_by_session_id($session['session_id']);
1479
1480
            if (empty($sessionCourses)) {
1481
                continue;
1482
            }
1483
1484
            foreach ($sessionCourses as $course) {
1485
                if (!$includeNonPublicCertificates) {
1486
                    $allowPublicCertificates = api_get_course_setting('allow_public_certificates');
1487
1488
                    if (empty($allowPublicCertificates)) {
1489
                        continue;
1490
                    }
1491
                }
1492
1493
                $category = Category::load(
1494
                    null,
1495
                    null,
1496
                    $course['code'],
1497
                    null,
1498
                    null,
1499
                    $session['session_id']
1500
                );
1501
1502
                if (empty($category)) {
1503
                    continue;
1504
                }
1505
1506
                if (!isset($category[0])) {
1507
                    continue;
1508
                }
1509
1510
                /** @var Category $category */
1511
                $category = $category[0];
1512
1513
                // Don't allow generate of certifications
1514
                if (empty($category->getGenerateCertificates())) {
1515
                    continue;
1516
                }
1517
1518
                $categoryId = $category->get_id();
1519
                $certificateInfo = self::get_certificate_by_user_id(
1520
                    $categoryId,
1521
                    $userId
1522
                );
1523
1524
                if (empty($certificateInfo)) {
1525
                    continue;
1526
                }
1527
1528
                $sessionList[] = [
1529
                    'session' => $session['session_name'],
1530
                    'course' => $course['title'],
1531
                    'score' => $certificateInfo['score_certificate'],
1532
                    'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1533
                    'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}",
1534
                ];
1535
            }
1536
        }
1537
1538
        return $sessionList;
1539
    }
1540
1541
    /**
1542
     * @param array $courseInfo
1543
     * @param int   $userId
1544
     * @param array $cats
1545
     * @param bool  $saveToFile
1546
     * @param bool  $saveToHtmlFile
1547
     * @param array $studentList
1548
     * @param PDF   $pdf
1549
     *
1550
     * @return string
1551
     */
1552
    public static function generateTable(
1553
        $courseInfo,
1554
        $userId,
1555
        $cats,
1556
        $saveToFile = false,
1557
        $saveToHtmlFile = false,
1558
        $studentList = [],
1559
        $pdf = null
1560
    ) {
1561
        $userInfo = api_get_user_info($userId);
1562
        $model = ExerciseLib::getCourseScoreModel();
1563
        /** @var Category $cat */
1564
        $cat = $cats[0];
1565
        $allcat = $cats[0]->get_subcategories(
1566
            $userId,
1567
            api_get_course_id(),
1568
            api_get_session_id()
1569
        );
1570
        $alleval = $cats[0]->get_evaluations($userId);
1571
        $alllink = $cats[0]->get_links($userId);
1572
1573
        $loadStats = [];
1574
        if (api_get_setting('gradebook_detailed_admin_view') === 'true') {
1575
            $loadStats = [1, 2, 3];
1576
        } else {
1577
            if (api_get_configuration_value('gradebook_enable_best_score') !== false) {
1578
                $loadStats = [2];
1579
            }
1580
        }
1581
1582
        $gradebooktable = new GradebookTable(
1583
            $cat,
1584
            $allcat,
1585
            $alleval,
1586
            $alllink,
1587
            null,
1588
            true,
1589
            false,
1590
            $userId,
1591
            $studentList,
1592
            $loadStats
1593
        );
1594
1595
        $gradebooktable->userId = $userId;
1596
1597
        if (api_is_allowed_to_edit(null, true)) {
1598
        } else {
1599
            if (empty($model)) {
1600
                $gradebooktable->td_attributes = [
1601
                    3 => 'class=centered',
1602
                    4 => 'class=centered',
1603
                    5 => 'class=centered',
1604
                    6 => 'class=centered',
1605
                    7 => 'class=centered',
1606
                ];
1607
            }
1608
        }
1609
        $table = $gradebooktable->return_table();
1610
1611
        $graph = '';
1612
        if (empty($model)) {
1613
            $graph = $gradebooktable->getGraph();
1614
        }
1615
        $params = [
1616
            'pdf_title' => sprintf(get_lang('GradeFromX'), $courseInfo['name']),
1617
            'session_info' => '',
1618
            'course_info' => '',
1619
            'pdf_date' => '',
1620
            'course_code' => api_get_course_id(),
1621
            'student_info' => $userInfo,
1622
            'show_grade_generated_date' => true,
1623
            'show_real_course_teachers' => false,
1624
            'show_teacher_as_myself' => false,
1625
            'orientation' => 'P',
1626
        ];
1627
1628
        if (empty($pdf)) {
1629
            $pdf = new PDF('A4', $params['orientation'], $params);
1630
        }
1631
1632
        $pdf->params['student_info'] = $userInfo;
1633
        $extraRows = [];
1634
        if (api_get_configuration_value('allow_gradebook_comments')) {
1635
            $commentInfo = self::getComment($cat->get_id(), $userId);
1636
            if ($commentInfo) {
1637
                $extraRows[] = [
1638
                    'label' => get_lang('Comment'),
1639
                    'content' => $commentInfo['comment'],
1640
                ];
1641
            }
1642
        }
1643
1644
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid().'.html';
1645
1646
        $settings = api_get_configuration_value('gradebook_pdf_export_settings');
1647
        $showFeedBack = true;
1648
        if (isset($settings['hide_feedback_textarea']) && $settings['hide_feedback_textarea']) {
1649
            $showFeedBack = false;
1650
        }
1651
1652
        $feedback = '';
1653
        if ($showFeedBack) {
1654
            $feedback = '<br />'.get_lang('Feedback').'<br />
1655
            <textarea class="form-control" rows="5" cols="100">&nbsp;</textarea>';
1656
        }
1657
        $content = $table.$graph.$feedback;
1658
        $result = $pdf->html_to_pdf_with_template(
1659
            $content,
1660
            $saveToFile,
1661
            $saveToHtmlFile,
1662
            true,
1663
            $extraRows
1664
        );
1665
1666
        if ($saveToHtmlFile) {
1667
            return $result;
1668
        }
1669
1670
        return $file;
1671
    }
1672
1673
    public static function getComment($gradeBookId, $userId)
1674
    {
1675
        $gradeBookId = (int) $gradeBookId;
1676
        $userId = (int) $userId;
1677
1678
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_COMMENT);
1679
        $sql = "SELECT * FROM $table
1680
                WHERE user_id = $userId AND gradebook_id = $gradeBookId";
1681
        $result = Database::query($sql);
1682
1683
        return Database::fetch_array($result);
1684
    }
1685
1686
    public static function saveComment($gradeBookId, $userId, $comment)
1687
    {
1688
        $commentInfo = self::getComment($gradeBookId, $userId);
1689
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_COMMENT);
1690
        if (empty($commentInfo)) {
1691
            $params = [
1692
                'gradebook_id' => $gradeBookId,
1693
                'user_id' => $userId,
1694
                'comment' => $comment,
1695
                'created_at' => api_get_utc_datetime(),
1696
                'updated_at' => api_get_utc_datetime(),
1697
            ];
1698
            Database::insert($table, $params);
1699
        } else {
1700
            $params = [
1701
                'comment' => $comment,
1702
                'updated_at' => api_get_utc_datetime(),
1703
            ];
1704
            Database::update($table, $params, ['id = ?' => $commentInfo['id']]);
1705
        }
1706
    }
1707
}
1708