Passed
Pull Request — 1.11.x (#4586)
by Angel Fernando Quiroz
08:27
created

GradebookUtils::add_resource_to_course_gradebook()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 43
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 20
nc 17
nop 11
dl 0
loc 43
rs 8.6666
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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