Completed
Push — master ( d0e06e...1fcdba )
by Julito
09:05
created

GradebookUtils::getTotalCertificates()   A

Complexity

Conditions 6
Paths 16

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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