Passed
Push — master ( afb2ec...e80e7a )
by Julito
09:13
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
        $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->getCourseId(),
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
        $cat = new Category();
361
        $message_eval = $cat->show_message_resource_delete($eval->get_course_code());
362
        $courseParams = api_get_cidreq_params($eval->getCourseId(), $eval->getSessionId());
363
364
        if (false === $message_eval && api_is_allowed_to_edit(null, true)) {
365
            $visibility_icon = 0 == $eval->is_visible() ? 'invisible' : 'visible';
366
            $visibility_command = 0 == $eval->is_visible() ? 'set_visible' : 'set_invisible';
367
            if ($is_locked && !api_is_platform_admin()) {
368
                $modify_icons = Display::return_icon(
369
                    'edit_na.png',
370
                    get_lang('Edit'),
371
                    '',
372
                    ICON_SIZE_SMALL
373
                );
374
            } else {
375
                $modify_icons = '<a href="gradebook_edit_eval.php?editeval='.$eval->get_id().'&'.$courseParams.'">'.
376
                    Display::return_icon(
377
                        'edit.png',
378
                        get_lang('Edit'),
379
                        '',
380
                        ICON_SIZE_SMALL
381
                    ).
382
                    '</a>';
383
            }
384
385
            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visibleeval='.$eval->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.' ">'.
386
                Display::return_icon(
387
                    $visibility_icon.'.png',
388
                    get_lang('Visible'),
389
                    '',
390
                    ICON_SIZE_SMALL
391
                ).
392
                '</a>';
393
394
            if (api_is_allowed_to_edit(null, true)) {
395
                $modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog='.$eval->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'">'.
396
                    Display::return_icon(
397
                        'history.png',
398
                        get_lang('Assessment history'),
399
                        '',
400
                        ICON_SIZE_SMALL
401
                    ).
402
                    '</a>';
403
404
                $allowStats = api_get_configuration_value('allow_gradebook_stats');
405
                if ($allowStats) {
406
                    $modify_icons .= Display::url(
407
                        Display::return_icon('reload.png', get_lang('Generate statistics')),
408
                        api_get_self().'?itemId='.$eval->get_id().'&action=generate_eval_stats&selectcat='.$selectcat.'&'.$courseParams
409
                    );
410
                }
411
            }
412
413
            if ($is_locked && !api_is_platform_admin()) {
414
                $modify_icons .= '&nbsp;'.
415
                    Display::return_icon(
416
                        'delete_na.png',
417
                        get_lang('Delete'),
418
                        '',
419
                        ICON_SIZE_SMALL
420
                    );
421
            } else {
422
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deleteeval='.$eval->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'" onclick="return confirmation();">'.
423
                    Display::return_icon(
424
                        'delete.png',
425
                        get_lang('Delete'),
426
                        '',
427
                        ICON_SIZE_SMALL
428
                    ).
429
                    '</a>';
430
            }
431
432
            return $modify_icons;
433
        }
434
    }
435
436
    /**
437
     * Builds the course or platform admin icons to edit a link.
438
     *
439
     * @param AbstractLink $link
440
     * @param int          $selectcat id of selected category
441
     *
442
     * @return string
443
     */
444
    public static function build_edit_icons_link($link, $selectcat)
445
    {
446
        $cat = new Category();
447
        $message_link = $cat->show_message_resource_delete($link->get_course_code());
448
        $is_locked = $link->is_locked();
449
        $modify_icons = null;
450
451
        if (!api_is_allowed_to_edit(null, true)) {
452
            return null;
453
        }
454
455
        $courseParams = api_get_cidreq_params(
456
            $link->getCourseId(),
457
            $link->get_session_id()
458
        );
459
460
        if (false === $message_link) {
461
            $visibility_icon = 0 == $link->is_visible() ? 'invisible' : 'visible';
462
            $visibility_command = 0 == $link->is_visible() ? 'set_visible' : 'set_invisible';
463
464
            if ($is_locked && !api_is_platform_admin()) {
465
                $modify_icons = Display::return_icon(
466
                    'edit_na.png',
467
                    get_lang('Edit'),
468
                    '',
469
                    ICON_SIZE_SMALL
470
                );
471
            } else {
472
                $modify_icons = '<a href="gradebook_edit_link.php?editlink='.$link->get_id().'&'.$courseParams.'">'.
473
                    Display::return_icon(
474
                        'edit.png',
475
                        get_lang('Edit'),
476
                        '',
477
                        ICON_SIZE_SMALL
478
                    ).
479
                    '</a>';
480
            }
481
            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visiblelink='.$link->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.' ">'.
482
                Display::return_icon(
483
                    $visibility_icon.'.png',
484
                    get_lang('Visible'),
485
                    '',
486
                    ICON_SIZE_SMALL
487
                ).
488
                '</a>';
489
490
            $modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink='.$link->get_id().'&selectcat='.$selectcat.'&'.$courseParams.'">'.
491
                Display::return_icon(
492
                    'history.png',
493
                    get_lang('Assessment history'),
494
                    '',
495
                    ICON_SIZE_SMALL
496
                ).
497
                '</a>';
498
499
            $allowStats = api_get_configuration_value('allow_gradebook_stats');
500
            if ($allowStats && LINK_EXERCISE == $link->get_type()) {
501
                $modify_icons .= Display::url(
502
                    Display::return_icon('reload.png', get_lang('Generate statistics')),
503
                    api_get_self().'?itemId='.$link->get_id().'&action=generate_link_stats&selectcat='.$selectcat.'&'.$courseParams
504
                );
505
            }
506
507
            //If a work is added in a gradebook you can only delete the link in the work tool
508
            if ($is_locked && !api_is_platform_admin()) {
509
                $modify_icons .= '&nbsp;'.
510
                    Display::return_icon(
511
                        'delete_na.png',
512
                        get_lang('Delete'),
513
                        '',
514
                        ICON_SIZE_SMALL
515
                    );
516
            } else {
517
                $modify_icons .= '&nbsp;
518
                <a
519
                    href="'.api_get_self().'?deletelink='.$link->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'"
520
                    onclick="return confirmation();">'.
521
                    Display::return_icon(
522
                        'delete.png',
523
                        get_lang('Delete'),
524
                        '',
525
                        ICON_SIZE_SMALL
526
                    ).
527
                    '</a>';
528
            }
529
530
            return $modify_icons;
531
        }
532
    }
533
534
    /**
535
     * Checks if a resource is in the unique gradebook of a given course.
536
     *
537
     * @param string $course_code   Course code
538
     * @param int    $resource_type Resource type (use constants defined in linkfactory.class.php)
539
     * @param int    $resource_id   Resource ID in the corresponding tool
540
     * @param int    $session_id    Session ID (optional -  0 if not defined)
541
     *
542
     * @return array false on error or array of resource
543
     */
544
    public static function isResourceInCourseGradebook(
545
        $course_code,
546
        $resource_type,
547
        $resource_id,
548
        $session_id = 0
549
    ) {
550
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
551
        $courseInfo = api_get_course_info($course_code);
552
        if (empty($courseInfo)) {
553
            return [];
554
        }
555
556
        $sql = "SELECT * FROM $table l
557
                WHERE
558
                    c_id = ".$courseInfo['real_id']." AND
559
                    type = ".(int) $resource_type." AND
560
                    ref_id = ".(int) $resource_id;
561
        $res = Database::query($sql);
562
563
        if (Database::num_rows($res) < 1) {
564
            return false;
565
        }
566
567
        return Database::fetch_array($res, 'ASSOC');
568
    }
569
570
    /**
571
     * Return the course id.
572
     *
573
     * @param    int
574
     *
575
     * @return string
576
     */
577
    public static function get_course_id_by_link_id($id_link)
578
    {
579
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
580
        $tbl_grade_links = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
581
        $id_link = (int) $id_link;
582
583
        $sql = 'SELECT c.id FROM '.$course_table.' c
584
                INNER JOIN '.$tbl_grade_links.' l
585
                ON c.id = l.c_id
586
                WHERE l.id='.intval($id_link).' OR l.category_id='.intval($id_link);
587
        $res = Database::query($sql);
588
        $array = Database::fetch_array($res, 'ASSOC');
589
590
        return $array['id'];
591
    }
592
593
    /**
594
     * @param $type
595
     *
596
     * @return string
597
     */
598
    public static function get_table_type_course($type)
599
    {
600
        global $table_evaluated;
601
602
        return Database::get_course_table($table_evaluated[$type][0]);
603
    }
604
605
    /**
606
     * @param Category $cat
607
     * @param $users
608
     * @param $alleval
609
     * @param $alllinks
610
     * @param $params
611
     * @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...
612
     *
613
     * @return array
614
     */
615
    public static function get_printable_data(
616
        $cat,
617
        $users,
618
        $alleval,
619
        $alllinks,
620
        $params,
621
        $mainCourseCategory = null
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
633
        // step 2: generate rows: students
634
        $datagen->category = $cat;
635
636
        $count = (($offset + 10) > $datagen->get_total_items_count()) ? ($datagen->get_total_items_count() - $offset) : GRADEBOOK_ITEM_LIMIT;
637
        $header_names = $datagen->get_header_names($offset, $count, true);
638
        $data_array = $datagen->get_data(
639
            FlatViewDataGenerator::FVDG_SORT_LASTNAME,
640
            0,
641
            null,
642
            $offset,
643
            $count,
644
            true,
645
            true
646
        );
647
648
        $result = [];
649
        foreach ($data_array as $data) {
650
            $result[] = array_slice($data, 1);
651
        }
652
        $return = [$header_names, $result];
653
654
        return $return;
655
    }
656
657
    /**
658
     * XML-parser: handle character data.
659
     */
660
    public static function character_data($parser, $data)
661
    {
662
        global $current_value;
663
        $current_value = $data;
664
    }
665
666
    public static function overwritescore($resid, $importscore, $eval_max)
667
    {
668
        $result = Result::load($resid);
669
        if ($importscore > $eval_max) {
670
            header('Location: gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'&overwritemax=');
671
            exit;
672
        }
673
        $result[0]->set_score($importscore);
674
        $result[0]->save();
675
        unset($result);
676
    }
677
678
    /**
679
     * register user info about certificate.
680
     *
681
     * @param int    $cat_id            The category id
682
     * @param int    $user_id           The user id
683
     * @param float  $score_certificate The score obtained for certified
684
     * @param string $date_certificate  The date when you obtained the certificate
685
     */
686
    public static function registerUserInfoAboutCertificate(
687
        $cat_id,
688
        $user_id,
689
        $score_certificate,
690
        $date_certificate
691
    ) {
692
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
693
        $cat_id = (int) $cat_id;
694
        $user_id = (int) $user_id;
695
696
        $sql = "SELECT COUNT(id) as count
697
                FROM $table gc
698
                WHERE gc.cat_id = $cat_id AND user_id = $user_id ";
699
        $rs_exist = Database::query($sql);
700
        $row = Database::fetch_array($rs_exist);
701
        if (0 == $row['count']) {
702
            $params = [
703
                'cat_id' => $cat_id,
704
                'user_id' => $user_id,
705
                'score_certificate' => $score_certificate,
706
                'created_at' => $date_certificate,
707
            ];
708
            Database::insert($table, $params);
709
        }
710
    }
711
712
    /**
713
     * Get date of user certificate.
714
     *
715
     * @param int $cat_id  The category id
716
     * @param int $user_id The user id
717
     *
718
     * @return array
719
     */
720
    public static function get_certificate_by_user_id($cat_id, $user_id)
721
    {
722
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
723
        $cat_id = (int) $cat_id;
724
        $user_id = (int) $user_id;
725
726
        $sql = "SELECT * FROM $table
727
                WHERE cat_id = $cat_id AND user_id = $user_id ";
728
729
        $result = Database::query($sql);
730
731
        return Database::fetch_array($result, 'ASSOC');
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.id as 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.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.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
            api_get_course_info($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
            $courseInfo = api_get_course_info($course_code);
884
885
            $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
886
            $sql = "SELECT * FROM $t
887
                    WHERE c_id = '".$courseInfo['real_id']."' ";
888
            if (!empty($session_id)) {
889
                $sql .= " AND session_id = ".$session_id;
890
            } else {
891
                $sql .= ' AND (session_id IS NULL OR session_id = 0) ';
892
            }
893
            $sql .= ' ORDER BY id ';
894
            $res = Database::query($sql);
895
            if (Database::num_rows($res) < 1) {
896
                //there is no unique category for this course+session combination,
897
                $cat = new Category();
898
                if (!empty($session_id)) {
899
                    $my_session_id = api_get_session_id();
900
                    $s_name = api_get_session_name($my_session_id);
901
                    $cat->set_name($course_code.' - '.get_lang('Session').' '.$s_name);
902
                    $cat->set_session_id($session_id);
903
                } else {
904
                    $cat->set_name($course_code);
905
                }
906
                $cat->set_course_code($course_code);
907
                $cat->set_description(null);
908
                $cat->set_user_id(api_get_user_id());
909
                $cat->set_parent_id(0);
910
                $default_weight_setting = api_get_setting('gradebook_default_weight');
911
                $default_weight = isset($default_weight_setting) && !empty($default_weight_setting) ? $default_weight_setting : 100;
912
                $cat->set_weight($default_weight);
913
                $cat->set_grade_model_id($gradebook_model_id);
914
                $cat->set_certificate_min_score(75);
915
                $cat->set_visible(0);
916
                $cat->add();
917
                $category_id = $cat->get_id();
918
                unset($cat);
919
            } else {
920
                $row = Database::fetch_array($res);
921
                $category_id = $row['id'];
922
            }
923
924
            return $category_id;
925
        }
926
927
        return false;
928
    }
929
930
    /**
931
     * @param FormValidator $form
932
     */
933
    public static function load_gradebook_select_in_tool($form)
934
    {
935
        $course_code = api_get_course_id();
936
        $session_id = api_get_session_id();
937
938
        self::create_default_course_gradebook();
939
940
        // Cat list
941
        $all_categories = Category::load(
942
            null,
943
            null,
944
            $course_code,
945
            null,
946
            null,
947
            $session_id,
948
            false
949
        );
950
        $select_gradebook = $form->addSelect(
951
            'category_id',
952
            get_lang('Select assessment')
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 (0 == $my_cat->get_parent_id()) {
961
                            $select_gradebook->addOption(get_lang('Default'), $my_cat->get_id());
962
                            $cats_added[] = $my_cat->get_id();
963
                        } else {
964
                            $select_gradebook->addOption($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 array         $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
        $cat = $cat[0] ?? null;
994
        // Getting data
995
        $printable_data = self::get_printable_data(
996
            $cat,
997
            $users,
998
            $alleval,
999
            $alllinks,
1000
            $params,
1001
            $mainCourseCategory
1002
        );
1003
1004
        // HTML report creation first
1005
        $course_code = trim($cat->get_course_code());
1006
1007
        $displayscore = ScoreDisplay::instance();
1008
        $customDisplays = $displayscore->get_custom_score_display_settings();
1009
1010
        $total = [];
1011
        if (is_array($customDisplays) && count(($customDisplays))) {
1012
            foreach ($customDisplays as $custom) {
1013
                $total[$custom['display']] = 0;
1014
            }
1015
            $user_results = $flatviewtable->datagen->get_data_to_graph2(false);
1016
            foreach ($user_results as $user_result) {
1017
                $item = $user_result[count($user_result) - 1];
1018
                $customTag = isset($item[1]) ? strip_tags($item[1]) : '';
1019
                $total[$customTag]++;
1020
            }
1021
        }
1022
1023
        $parent_id = $cat->get_parent_id();
1024
        if (isset($cat) && isset($parent_id)) {
1025
            if (0 == $parent_id) {
1026
                $grade_model_id = $cat->get_grade_model_id();
1027
            } else {
1028
                $parent_cat = Category::load($parent_id);
1029
                $grade_model_id = $parent_cat[0]->get_grade_model_id();
1030
            }
1031
        }
1032
1033
        $use_grade_model = true;
1034
        if (empty($grade_model_id) || -1 == $grade_model_id) {
1035
            $use_grade_model = false;
1036
        }
1037
1038
        if ($use_grade_model) {
1039
            if (0 == $parent_id) {
1040
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1041
            } else {
1042
                $title = api_strtoupper(get_lang('Average')).'<br />'.$cat[0]->get_description().' - ('.$cat[0]->get_name().')';
1043
            }
1044
        } else {
1045
            if (0 == $parent_id) {
1046
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1047
            } else {
1048
                $title = api_strtoupper(get_lang('Average'));
1049
            }
1050
        }
1051
1052
        $columns = count($printable_data[0]);
1053
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
1054
1055
        $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
1056
        $row = 0;
1057
        $column = 0;
1058
        $table->setHeaderContents($row, $column, get_lang('N°'));
1059
        $column++;
1060
        foreach ($printable_data[0] as $printable_data_cell) {
1061
            if (!is_array($printable_data_cell)) {
1062
                $printable_data_cell = strip_tags($printable_data_cell);
1063
            }
1064
            $table->setHeaderContents($row, $column, $printable_data_cell);
1065
            $column++;
1066
        }
1067
        $row++;
1068
1069
        if ($has_data) {
1070
            $counter = 1;
1071
            foreach ($printable_data[1] as &$printable_data_row) {
1072
                $column = 0;
1073
                $table->setCellContents($row, $column, $counter);
1074
                $table->updateCellAttributes($row, $column, 'align="center"');
1075
                $column++;
1076
                $counter++;
1077
1078
                foreach ($printable_data_row as $key => &$printable_data_cell) {
1079
                    $attributes = [];
1080
                    $attributes['align'] = 'center';
1081
                    $attributes['style'] = null;
1082
1083
                    if ('name' === $key) {
1084
                        $attributes['align'] = 'left';
1085
                    }
1086
                    if ('total' === $key) {
1087
                        $attributes['style'] = 'font-weight:bold';
1088
                    }
1089
                    $table->setCellContents($row, $column, $printable_data_cell);
1090
                    $table->updateCellAttributes($row, $column, $attributes);
1091
                    $column++;
1092
                }
1093
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
1094
                $row++;
1095
            }
1096
        } else {
1097
            $column = 0;
1098
            $table->setCellContents($row, $column, get_lang('No results found'));
1099
            $table->updateCellAttributes($row, $column, 'colspan="'.$columns.'" align="center" class="row_odd"');
1100
        }
1101
1102
        $pdfParams = [
1103
            'filename' => get_lang('List View').'_'.api_get_local_time(),
1104
            'pdf_title' => $title,
1105
            'course_code' => $course_code,
1106
            'add_signatures' => ['Drh', 'Teacher', 'Date'],
1107
        ];
1108
1109
        $page_format = 'landscape' === $params['orientation'] ? 'A4-L' : 'A4';
1110
        ob_start();
1111
        $pdf = new PDF($page_format, $page_format, $pdfParams);
1112
        $pdf->html_to_pdf_with_template($flatviewtable->return_table(), false, false, true);
1113
        $content = ob_get_contents();
1114
        ob_end_clean();
1115
        echo $content;
1116
        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...
1117
    }
1118
1119
    /**
1120
     * @param string[] $list_values
1121
     *
1122
     * @return string
1123
     */
1124
    public static function score_badges($list_values)
1125
    {
1126
        $counter = 1;
1127
        $badges = [];
1128
        foreach ($list_values as $value) {
1129
            $class = 'warning';
1130
            if (1 == $counter) {
1131
                $class = 'success';
1132
            }
1133
            $counter++;
1134
            $badges[] = Display::badge($value, $class);
1135
        }
1136
1137
        return Display::badge_group($badges);
1138
    }
1139
1140
    /**
1141
     * returns users within a course given by param.
1142
     *
1143
     * @param string $courseCode
1144
     *
1145
     * @todo use CourseManager
1146
     *
1147
     * @return array
1148
     */
1149
    public static function get_users_in_course($courseCode)
1150
    {
1151
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1152
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1153
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1154
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
1155
1156
        $current_session = api_get_session_id();
1157
        $courseCode = Database::escape_string($courseCode);
1158
        $courseInfo = api_get_course_info($courseCode);
1159
        $courseId = $courseInfo['real_id'];
1160
1161
        if (!empty($current_session)) {
1162
            $sql = "SELECT user.id as user_id, user.username, lastname, firstname, official_code
1163
                    FROM $tbl_session_course_user as scru
1164
                    INNER JOIN $tbl_user as user
1165
                    ON (scru.user_id = user.id)
1166
                    WHERE
1167
                        scru.status = 0 AND
1168
                        scru.c_id='$courseId' AND
1169
                        session_id ='$current_session'
1170
                    $order_clause
1171
                    ";
1172
        } else {
1173
            $sql = 'SELECT user.id as user_id, user.username, lastname, firstname, official_code
1174
                    FROM '.$tbl_course_user.' as course_rel_user
1175
                    INNER JOIN '.$tbl_user.' as user
1176
                    ON (course_rel_user.user_id = user.id)
1177
                    WHERE
1178
                        course_rel_user.status = '.STUDENT.' AND
1179
                        course_rel_user.c_id = "'.$courseId.'" '.
1180
                    $order_clause;
1181
        }
1182
1183
        $result = Database::query($sql);
1184
1185
        return self::get_user_array_from_sql_result($result);
1186
    }
1187
1188
    /**
1189
     * @param Doctrine\DBAL\Driver\Statement|null $result
1190
     *
1191
     * @return array
1192
     */
1193
    public static function get_user_array_from_sql_result($result)
1194
    {
1195
        $a_students = [];
1196
        while ($user = Database::fetch_array($result)) {
1197
            if (!array_key_exists($user['user_id'], $a_students)) {
1198
                $a_current_student = [];
1199
                $a_current_student[] = $user['user_id'];
1200
                $a_current_student[] = $user['username'];
1201
                $a_current_student[] = $user['lastname'];
1202
                $a_current_student[] = $user['firstname'];
1203
                $a_current_student[] = $user['official_code'];
1204
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1205
            }
1206
        }
1207
1208
        return $a_students;
1209
    }
1210
1211
    /**
1212
     * @param array $evals
1213
     * @param array $links
1214
     *
1215
     * @return array
1216
     */
1217
    public static function get_all_users($evals = [], $links = [])
1218
    {
1219
        $coursecodes = [];
1220
        // By default add all user in course
1221
        $coursecodes[api_get_course_id()] = '1';
1222
        $users = self::get_users_in_course(api_get_course_id());
1223
1224
        foreach ($evals as $eval) {
1225
            $coursecode = $eval->get_course_code();
1226
            // evaluation in course
1227
            if (isset($coursecode) && !empty($coursecode)) {
1228
                if (!array_key_exists($coursecode, $coursecodes)) {
1229
                    $coursecodes[$coursecode] = '1';
1230
                    $users = array_merge($users, self::get_users_in_course($coursecode));
1231
                }
1232
            } else {
1233
                // course independent evaluation
1234
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1235
                $tbl_res = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1236
1237
                $sql = 'SELECT user.id as user_id, lastname, firstname, user.official_code
1238
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1239
                        WHERE
1240
                            res.evaluation_id = '.intval($eval->get_id()).' AND
1241
                            res.user_id = user.id
1242
                        ';
1243
                $sql .= ' ORDER BY lastname, firstname';
1244
                if (api_is_western_name_order()) {
1245
                    $sql .= ' ORDER BY firstname, lastname';
1246
                }
1247
1248
                $result = Database::query($sql);
1249
                $users = array_merge(
1250
                    $users,
1251
                    self::get_user_array_from_sql_result($result)
1252
                );
1253
            }
1254
        }
1255
1256
        foreach ($links as $link) {
1257
            // links are always in a course
1258
            $coursecode = $link->get_course_code();
1259
            if (!array_key_exists($coursecode, $coursecodes)) {
1260
                $coursecodes[$coursecode] = '1';
1261
                $users = array_merge(
1262
                    $users,
1263
                    self::get_users_in_course($coursecode)
1264
                );
1265
            }
1266
        }
1267
1268
        return $users;
1269
    }
1270
1271
    /**
1272
     * Search students matching a given last name and/or first name.
1273
     *
1274
     * @author Bert Steppé
1275
     */
1276
    public static function find_students($mask = '')
1277
    {
1278
        // students shouldn't be here // don't search if mask empty
1279
        if (!api_is_allowed_to_edit() || empty($mask)) {
1280
            return null;
1281
        }
1282
        $mask = Database::escape_string($mask);
1283
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1284
        $tbl_cru = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1285
        $sql = 'SELECT DISTINCT user.id as user_id, user.lastname, user.firstname, user.email, user.official_code
1286
                FROM '.$tbl_user.' user';
1287
        if (!api_is_platform_admin()) {
1288
            $sql .= ', '.$tbl_cru.' cru';
1289
        }
1290
1291
        $sql .= ' WHERE user.status = '.STUDENT;
1292
        $sql .= ' AND (user.lastname LIKE '."'%".$mask."%'";
1293
        $sql .= ' OR user.firstname LIKE '."'%".$mask."%')";
1294
1295
        if (!api_is_platform_admin()) {
1296
            $sql .= ' AND user.id = cru.user_id AND
1297
                      cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' AND
1298
                      cru.c_id in (
1299
                            SELECT c_id FROM '.$tbl_cru.'
1300
                            WHERE
1301
                                user_id = '.api_get_user_id().' AND
1302
                                status = '.COURSEMANAGER.'
1303
                        )
1304
                    ';
1305
        }
1306
1307
        $sql .= ' ORDER BY lastname, firstname';
1308
        if (api_is_western_name_order()) {
1309
            $sql .= ' ORDER BY firstname, lastname';
1310
        }
1311
1312
        $result = Database::query($sql);
1313
1314
        return Database::store_result($result);
1315
    }
1316
1317
    /**
1318
     * @param int   $linkId
1319
     * @param float $weight
1320
     */
1321
    public static function updateLinkWeight($linkId, $name, $weight)
1322
    {
1323
        $linkId = (int) $linkId;
1324
        $weight = api_float_val($weight);
1325
        $course_id = api_get_course_int_id();
1326
1327
        AbstractLink::add_link_log($linkId, $name);
1328
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1329
1330
        $em = Database::getManager();
1331
        $tbl_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
1332
        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
1333
1334
        $sql = 'UPDATE '.$table_link.'
1335
                SET weight = '."'".Database::escape_string($weight)."'".'
1336
                WHERE id = '.$linkId;
1337
1338
        Database::query($sql);
1339
1340
        // Update weight for attendance
1341
        $sql = 'SELECT ref_id FROM '.$table_link.'
1342
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1343
1344
        $rs_attendance = Database::query($sql);
1345
        if (Database::num_rows($rs_attendance) > 0) {
1346
            $row_attendance = Database::fetch_array($rs_attendance);
1347
            $sql = 'UPDATE '.$tbl_attendance.' SET
1348
                    attendance_weight ='.api_float_val($weight).'
1349
                    WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
1350
            Database::query($sql);
1351
        }
1352
        // Update weight into forum thread
1353
        $sql = 'UPDATE '.$tbl_forum_thread.' SET
1354
                thread_weight = '.api_float_val($weight).'
1355
                WHERE
1356
                    c_id = '.$course_id.' AND
1357
                    iid = (
1358
                        SELECT ref_id FROM '.$table_link.'
1359
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1360
                    )
1361
                ';
1362
        Database::query($sql);
1363
        //Update weight into student publication(work)
1364
        $em
1365
            ->createQuery('
1366
                UPDATE ChamiloCourseBundle:CStudentPublication w
1367
                SET w.weight = :final_weight
1368
                WHERE w.cId = :course
1369
                    AND w.iid = (
1370
                        SELECT l.refId FROM ChamiloCoreBundle:GradebookLink l
1371
                        WHERE l.id = :link AND l.type = :type
1372
                    )
1373
            ')
1374
            ->execute([
1375
                'final_weight' => $weight,
1376
                'course' => $course_id,
1377
                'link' => $linkId,
1378
                'type' => LINK_STUDENTPUBLICATION,
1379
            ]);
1380
    }
1381
1382
    /**
1383
     * @param int   $id
1384
     * @param float $weight
1385
     */
1386
    public static function updateEvaluationWeight($id, $weight)
1387
    {
1388
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1389
        $id = (int) $id;
1390
        $evaluation = new Evaluation();
1391
        $evaluation->addEvaluationLog($id);
1392
        $sql = 'UPDATE '.$table_evaluation.'
1393
               SET weight = '."'".Database::escape_string($weight)."'".'
1394
               WHERE id = '.$id;
1395
        Database::query($sql);
1396
    }
1397
1398
    /**
1399
     * Get the achieved certificates for a user in courses.
1400
     *
1401
     * @param int  $userId                       The user id
1402
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1403
     *
1404
     * @return array
1405
     */
1406
    public static function getUserCertificatesInCourses(
1407
        $userId,
1408
        $includeNonPublicCertificates = true
1409
    ) {
1410
        $userId = (int) $userId;
1411
        $courseList = [];
1412
        $courses = CourseManager::get_courses_list_by_user_id($userId);
1413
1414
        foreach ($courses as $course) {
1415
            if (!$includeNonPublicCertificates) {
1416
                $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course);
1417
1418
                if (empty($allowPublicCertificates)) {
1419
                    continue;
1420
                }
1421
            }
1422
1423
            $category = Category::load(null, null, $course['code']);
1424
1425
            if (empty($category)) {
1426
                continue;
1427
            }
1428
1429
            if (!isset($category[0])) {
1430
                continue;
1431
            }
1432
            /** @var Category $category */
1433
            $category = $category[0];
1434
1435
            if (empty($category->getGenerateCertificates())) {
1436
                continue;
1437
            }
1438
1439
            $categoryId = $category->get_id();
1440
            $certificateInfo = self::get_certificate_by_user_id($categoryId, $userId);
1441
1442
            if (empty($certificateInfo)) {
1443
                continue;
1444
            }
1445
1446
            $courseInfo = api_get_course_info_by_id($course['real_id']);
1447
            if (empty($courseInfo)) {
1448
                continue;
1449
            }
1450
1451
            $courseList[] = [
1452
                'course' => $courseInfo['title'],
1453
                'score' => $certificateInfo['score_certificate'],
1454
                'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1455
                'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}",
1456
                'pdf' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}&user_id={$userId}&action=export",
1457
            ];
1458
        }
1459
1460
        return $courseList;
1461
    }
1462
1463
    /**
1464
     * Get the achieved certificates for a user in course sessions.
1465
     *
1466
     * @param int  $userId                       The user id
1467
     * @param bool $includeNonPublicCertificates Whether include the non-public certificates
1468
     *
1469
     * @return array
1470
     */
1471
    public static function getUserCertificatesInSessions($userId, $includeNonPublicCertificates = true)
1472
    {
1473
        $userId = (int) $userId;
1474
        $sessionList = [];
1475
        $sessions = SessionManager::get_sessions_by_user($userId, true, true);
1476
1477
        foreach ($sessions as $session) {
1478
            if (empty($session['courses'])) {
1479
                continue;
1480
            }
1481
            $sessionCourses = SessionManager::get_course_list_by_session_id($session['session_id']);
1482
1483
            if (empty($sessionCourses)) {
1484
                continue;
1485
            }
1486
1487
            foreach ($sessionCourses as $course) {
1488
                if (!$includeNonPublicCertificates) {
1489
                    $allowPublicCertificates = api_get_course_setting('allow_public_certificates');
1490
1491
                    if (empty($allowPublicCertificates)) {
1492
                        continue;
1493
                    }
1494
                }
1495
1496
                $category = Category::load(
1497
                    null,
1498
                    null,
1499
                    $course['code'],
1500
                    null,
1501
                    null,
1502
                    $session['session_id']
1503
                );
1504
1505
                if (empty($category)) {
1506
                    continue;
1507
                }
1508
1509
                if (!isset($category[0])) {
1510
                    continue;
1511
                }
1512
1513
                /** @var Category $category */
1514
                $category = $category[0];
1515
1516
                // Don't allow generate of certifications
1517
                if (empty($category->getGenerateCertificates())) {
1518
                    continue;
1519
                }
1520
1521
                $categoryId = $category->get_id();
1522
                $certificateInfo = self::get_certificate_by_user_id(
1523
                    $categoryId,
1524
                    $userId
1525
                );
1526
1527
                if (empty($certificateInfo)) {
1528
                    continue;
1529
                }
1530
1531
                $sessionList[] = [
1532
                    'session' => $session['session_name'],
1533
                    'course' => $course['title'],
1534
                    'score' => $certificateInfo['score_certificate'],
1535
                    'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1536
                    'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}",
1537
                ];
1538
            }
1539
        }
1540
1541
        return $sessionList;
1542
    }
1543
1544
    /**
1545
     * @param array $courseInfo
1546
     * @param int   $userId
1547
     * @param array $cats
1548
     * @param bool  $saveToFile
1549
     * @param bool  $saveToHtmlFile
1550
     * @param array $studentList
1551
     * @param PDF   $pdf
1552
     *
1553
     * @return string
1554
     */
1555
    public static function generateTable(
1556
        $courseInfo,
1557
        $userId,
1558
        $cats,
1559
        $saveToFile = false,
1560
        $saveToHtmlFile = false,
1561
        $studentList = [],
1562
        $pdf = null
1563
    ) {
1564
        $userInfo = api_get_user_info($userId);
1565
        $model = ExerciseLib::getCourseScoreModel();
1566
        $cat = $cats[0];
1567
        $allcat = $cats[0]->get_subcategories(
1568
            $userId,
1569
            api_get_course_id(),
1570
            api_get_session_id()
1571
        );
1572
        $alleval = $cats[0]->get_evaluations($userId);
1573
        $alllink = $cats[0]->get_links($userId);
1574
1575
        $loadStats = [];
1576
        if ('true' === api_get_setting('gradebook_detailed_admin_view')) {
1577
            $loadStats = [1, 2, 3];
1578
        } else {
1579
            if (false !== api_get_configuration_value('gradebook_enable_best_score')) {
1580
                $loadStats = [2];
1581
            }
1582
        }
1583
1584
        $gradebooktable = new GradebookTable(
1585
            $cat,
1586
            $allcat,
1587
            $alleval,
1588
            $alllink,
1589
            null,
1590
            true,
1591
            false,
1592
            $userId,
1593
            $studentList,
1594
            $loadStats
1595
        );
1596
1597
        $gradebooktable->userId = $userId;
1598
1599
        if (api_is_allowed_to_edit(null, true)) {
1600
        } else {
1601
            if (empty($model)) {
1602
                $gradebooktable->td_attributes = [
1603
                    3 => 'class=centered',
1604
                    4 => 'class=centered',
1605
                    5 => 'class=centered',
1606
                    6 => 'class=centered',
1607
                    7 => 'class=centered',
1608
                ];
1609
            }
1610
        }
1611
        $table = $gradebooktable->return_table();
1612
1613
        $graph = '';
1614
        if (empty($model)) {
1615
            $graph = $gradebooktable->getGraph();
1616
        }
1617
        $params = [
1618
            'pdf_title' => sprintf(get_lang('Grades from course: %s'), $courseInfo['name']),
1619
            'session_info' => '',
1620
            'course_info' => '',
1621
            'pdf_date' => '',
1622
            'course_code' => api_get_course_id(),
1623
            'student_info' => $userInfo,
1624
            'show_grade_generated_date' => true,
1625
            'show_real_course_teachers' => false,
1626
            'show_teacher_as_myself' => false,
1627
            'orientation' => 'P',
1628
        ];
1629
1630
        if (empty($pdf)) {
1631
            $pdf = new PDF('A4', $params['orientation'], $params);
1632
        }
1633
1634
        $pdf->params['student_info'] = $userInfo;
1635
        $extraRows = [];
1636
        if (api_get_configuration_value('allow_gradebook_comments')) {
1637
            $commentInfo = self::getComment($cat->get_id(), $userId);
1638
            if ($commentInfo) {
1639
                $extraRows[] = [
1640
                    'label' => get_lang('Comment'),
1641
                    'content' => $commentInfo['comment'],
1642
                ];
1643
            }
1644
        }
1645
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid().'.html';
1646
1647
        $settings = api_get_configuration_value('gradebook_pdf_export_settings');
1648
        $showFeedBack = true;
1649
        if (isset($settings['hide_feedback_textarea']) && $settings['hide_feedback_textarea']) {
1650
            $showFeedBack = false;
1651
        }
1652
1653
        $feedback = '';
1654
        if ($showFeedBack) {
1655
            $feedback = '<br />'.get_lang('Feedback').'<br />
1656
            <textarea class="form-control" rows="5" cols="100">&nbsp;</textarea>';
1657
1658
        }
1659
        $content = $table.$graph.$feedback;
1660
        $result = $pdf->html_to_pdf_with_template(
1661
            $content,
1662
            $saveToFile,
1663
            $saveToHtmlFile,
1664
            true,
1665
            $extraRows
1666
        );
1667
1668
        if ($saveToHtmlFile) {
1669
            return $result;
1670
        }
1671
1672
        return $file;
1673
    }
1674
1675
    public static function getComment($gradeBookId, $userId)
1676
    {
1677
        $gradeBookId = (int) $gradeBookId;
1678
        $userId = (int) $userId;
1679
1680
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_COMMENT);
1681
        $sql = "SELECT * FROM $table
1682
                WHERE user_id = $userId AND gradebook_id = $gradeBookId";
1683
        $result = Database::query($sql);
1684
1685
        return Database::fetch_array($result);
1686
    }
1687
1688
    public static function saveComment($gradeBookId, $userId, $comment)
1689
    {
1690
        $commentInfo = self::getComment($gradeBookId, $userId);
1691
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_COMMENT);
1692
        if (empty($commentInfo)) {
1693
            $params = [
1694
                'gradebook_id' => $gradeBookId,
1695
                'user_id' => $userId,
1696
                'comment' => $comment,
1697
                'created_at' => api_get_utc_datetime(),
1698
                'updated_at' => api_get_utc_datetime(),
1699
            ];
1700
            Database::insert($table, $params);
1701
        } else {
1702
            $params = [
1703
                'comment' => $comment,
1704
                'updated_at' => api_get_utc_datetime(),
1705
            ];
1706
            Database::update($table, $params, ['id = ?' => $commentInfo['id']]);
1707
        }
1708
    }
1709
}
1710