Passed
Push — master ( 668bf0...77aaf8 )
by Julito
11:36 queued 12s
created

GradebookUtils::generateTable()   D

Complexity

Conditions 11
Paths 288

Size

Total Lines 107
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 71
nc 288
nop 7
dl 0
loc 107
rs 4.9393
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 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 (0 == $parent_id) {
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) || -1 == $grade_model_id) {
1034
            $use_grade_model = false;
1035
        }
1036
1037
        if ($use_grade_model) {
1038
            if (0 == $parent_id) {
1039
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1040
            } else {
1041
                $title = api_strtoupper(get_lang('Average')).'<br />'.$cat[0]->get_description().' - ('.$cat[0]->get_name().')';
1042
            }
1043
        } else {
1044
            if (0 == $parent_id) {
1045
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1046
            } else {
1047
                $title = api_strtoupper(get_lang('Average'));
1048
            }
1049
        }
1050
1051
        $columns = count($printable_data[0]);
1052
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
1053
1054
        $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
1055
        $row = 0;
1056
        $column = 0;
1057
        $table->setHeaderContents($row, $column, get_lang('N°'));
1058
        $column++;
1059
        foreach ($printable_data[0] as $printable_data_cell) {
1060
            if (!is_array($printable_data_cell)) {
1061
                $printable_data_cell = strip_tags($printable_data_cell);
1062
            }
1063
            $table->setHeaderContents($row, $column, $printable_data_cell);
1064
            $column++;
1065
        }
1066
        $row++;
1067
1068
        if ($has_data) {
1069
            $counter = 1;
1070
            foreach ($printable_data[1] as &$printable_data_row) {
1071
                $column = 0;
1072
                $table->setCellContents($row, $column, $counter);
1073
                $table->updateCellAttributes($row, $column, 'align="center"');
1074
                $column++;
1075
                $counter++;
1076
1077
                foreach ($printable_data_row as $key => &$printable_data_cell) {
1078
                    $attributes = [];
1079
                    $attributes['align'] = 'center';
1080
                    $attributes['style'] = null;
1081
1082
                    if ('name' === $key) {
1083
                        $attributes['align'] = 'left';
1084
                    }
1085
                    if ('total' === $key) {
1086
                        $attributes['style'] = 'font-weight:bold';
1087
                    }
1088
                    $table->setCellContents($row, $column, $printable_data_cell);
1089
                    $table->updateCellAttributes($row, $column, $attributes);
1090
                    $column++;
1091
                }
1092
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
1093
                $row++;
1094
            }
1095
        } else {
1096
            $column = 0;
1097
            $table->setCellContents($row, $column, get_lang('No results found'));
1098
            $table->updateCellAttributes($row, $column, 'colspan="'.$columns.'" align="center" class="row_odd"');
1099
        }
1100
1101
        $pdfParams = [
1102
            'filename' => get_lang('List View').'_'.api_get_local_time(),
1103
            'pdf_title' => $title,
1104
            'course_code' => $course_code,
1105
            'add_signatures' => ['Drh', 'Teacher', 'Date'],
1106
        ];
1107
1108
        $page_format = 'landscape' === $params['orientation'] ? 'A4-L' : 'A4';
1109
        ob_start();
1110
        $pdf = new PDF($page_format, $page_format, $pdfParams);
1111
        $pdf->html_to_pdf_with_template($flatviewtable->return_table(), false, false, true);
1112
        $content = ob_get_contents();
1113
        ob_end_clean();
1114
        echo $content;
1115
        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...
1116
    }
1117
1118
    /**
1119
     * @param string[] $list_values
1120
     *
1121
     * @return string
1122
     */
1123
    public static function score_badges($list_values)
1124
    {
1125
        $counter = 1;
1126
        $badges = [];
1127
        foreach ($list_values as $value) {
1128
            $class = 'warning';
1129
            if (1 == $counter) {
1130
                $class = 'success';
1131
            }
1132
            $counter++;
1133
            $badges[] = Display::badge($value, $class);
1134
        }
1135
1136
        return Display::badge_group($badges);
1137
    }
1138
1139
    /**
1140
     * returns users within a course given by param.
1141
     *
1142
     * @param string $courseCode
1143
     *
1144
     * @todo use CourseManager
1145
     *
1146
     * @return array
1147
     */
1148
    public static function get_users_in_course($courseCode)
1149
    {
1150
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1151
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1152
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1153
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
1154
1155
        $current_session = api_get_session_id();
1156
        $courseCode = Database::escape_string($courseCode);
1157
        $courseInfo = api_get_course_info($courseCode);
1158
        $courseId = $courseInfo['real_id'];
1159
1160
        if (!empty($current_session)) {
1161
            $sql = "SELECT user.id as user_id, user.username, lastname, firstname, official_code
1162
                    FROM $tbl_session_course_user as scru
1163
                    INNER JOIN $tbl_user as user
1164
                    ON (scru.user_id = user.id)
1165
                    WHERE
1166
                        scru.status = 0 AND
1167
                        scru.c_id='$courseId' AND
1168
                        session_id ='$current_session'
1169
                    $order_clause
1170
                    ";
1171
        } else {
1172
            $sql = 'SELECT user.id as user_id, user.username, lastname, firstname, official_code
1173
                    FROM '.$tbl_course_user.' as course_rel_user
1174
                    INNER JOIN '.$tbl_user.' as user
1175
                    ON (course_rel_user.user_id = user.id)
1176
                    WHERE
1177
                        course_rel_user.status = '.STUDENT.' AND
1178
                        course_rel_user.c_id = "'.$courseId.'" '.
1179
                    $order_clause;
1180
        }
1181
1182
        $result = Database::query($sql);
1183
1184
        return self::get_user_array_from_sql_result($result);
1185
    }
1186
1187
    /**
1188
     * @param Doctrine\DBAL\Driver\Statement|null $result
1189
     *
1190
     * @return array
1191
     */
1192
    public static function get_user_array_from_sql_result($result)
1193
    {
1194
        $a_students = [];
1195
        while ($user = Database::fetch_array($result)) {
1196
            if (!array_key_exists($user['user_id'], $a_students)) {
1197
                $a_current_student = [];
1198
                $a_current_student[] = $user['user_id'];
1199
                $a_current_student[] = $user['username'];
1200
                $a_current_student[] = $user['lastname'];
1201
                $a_current_student[] = $user['firstname'];
1202
                $a_current_student[] = $user['official_code'];
1203
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1204
            }
1205
        }
1206
1207
        return $a_students;
1208
    }
1209
1210
    /**
1211
     * @param array $evals
1212
     * @param array $links
1213
     *
1214
     * @return array
1215
     */
1216
    public static function get_all_users($evals = [], $links = [])
1217
    {
1218
        $coursecodes = [];
1219
        // By default add all user in course
1220
        $coursecodes[api_get_course_id()] = '1';
1221
        $users = self::get_users_in_course(api_get_course_id());
1222
1223
        foreach ($evals as $eval) {
1224
            $coursecode = $eval->get_course_code();
1225
            // evaluation in course
1226
            if (isset($coursecode) && !empty($coursecode)) {
1227
                if (!array_key_exists($coursecode, $coursecodes)) {
1228
                    $coursecodes[$coursecode] = '1';
1229
                    $users = array_merge($users, self::get_users_in_course($coursecode));
1230
                }
1231
            } else {
1232
                // course independent evaluation
1233
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1234
                $tbl_res = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1235
1236
                $sql = 'SELECT user.id as user_id, lastname, firstname, user.official_code
1237
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1238
                        WHERE
1239
                            res.evaluation_id = '.intval($eval->get_id()).' AND
1240
                            res.user_id = user.id
1241
                        ';
1242
                $sql .= ' ORDER BY lastname, firstname';
1243
                if (api_is_western_name_order()) {
1244
                    $sql .= ' ORDER BY firstname, lastname';
1245
                }
1246
1247
                $result = Database::query($sql);
1248
                $users = array_merge(
1249
                    $users,
1250
                    self::get_user_array_from_sql_result($result)
1251
                );
1252
            }
1253
        }
1254
1255
        foreach ($links as $link) {
1256
            // links are always in a course
1257
            $coursecode = $link->get_course_code();
1258
            if (!array_key_exists($coursecode, $coursecodes)) {
1259
                $coursecodes[$coursecode] = '1';
1260
                $users = array_merge(
1261
                    $users,
1262
                    self::get_users_in_course($coursecode)
1263
                );
1264
            }
1265
        }
1266
1267
        return $users;
1268
    }
1269
1270
    /**
1271
     * Search students matching a given last name and/or first name.
1272
     *
1273
     * @author Bert Steppé
1274
     */
1275
    public static function find_students($mask = '')
1276
    {
1277
        // students shouldn't be here // don't search if mask empty
1278
        if (!api_is_allowed_to_edit() || empty($mask)) {
1279
            return null;
1280
        }
1281
        $mask = Database::escape_string($mask);
1282
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1283
        $tbl_cru = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1284
        $sql = 'SELECT DISTINCT user.id as user_id, user.lastname, user.firstname, user.email, user.official_code
1285
                FROM '.$tbl_user.' user';
1286
        if (!api_is_platform_admin()) {
1287
            $sql .= ', '.$tbl_cru.' cru';
1288
        }
1289
1290
        $sql .= ' WHERE user.status = '.STUDENT;
1291
        $sql .= ' AND (user.lastname LIKE '."'%".$mask."%'";
1292
        $sql .= ' OR user.firstname LIKE '."'%".$mask."%')";
1293
1294
        if (!api_is_platform_admin()) {
1295
            $sql .= ' AND user.id = cru.user_id AND
1296
                      cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' AND
1297
                      cru.c_id in (
1298
                            SELECT c_id FROM '.$tbl_cru.'
1299
                            WHERE
1300
                                user_id = '.api_get_user_id().' AND
1301
                                status = '.COURSEMANAGER.'
1302
                        )
1303
                    ';
1304
        }
1305
1306
        $sql .= ' ORDER BY lastname, firstname';
1307
        if (api_is_western_name_order()) {
1308
            $sql .= ' ORDER BY firstname, lastname';
1309
        }
1310
1311
        $result = Database::query($sql);
1312
1313
        return Database::store_result($result);
1314
    }
1315
1316
    /**
1317
     * @param int   $linkId
1318
     * @param float $weight
1319
     */
1320
    public static function updateLinkWeight($linkId, $name, $weight)
1321
    {
1322
        $linkId = (int) $linkId;
1323
        $weight = api_float_val($weight);
1324
        $course_id = api_get_course_int_id();
1325
1326
        AbstractLink::add_link_log($linkId, $name);
1327
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1328
1329
        $em = Database::getManager();
1330
        $tbl_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
1331
        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
1332
1333
        $sql = 'UPDATE '.$table_link.'
1334
                SET weight = '."'".Database::escape_string($weight)."'".'
1335
                WHERE id = '.$linkId;
1336
1337
        Database::query($sql);
1338
1339
        // Update weight for attendance
1340
        $sql = 'SELECT ref_id FROM '.$table_link.'
1341
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1342
1343
        $rs_attendance = Database::query($sql);
1344
        if (Database::num_rows($rs_attendance) > 0) {
1345
            $row_attendance = Database::fetch_array($rs_attendance);
1346
            $sql = 'UPDATE '.$tbl_attendance.' SET
1347
                    attendance_weight ='.api_float_val($weight).'
1348
                    WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
1349
            Database::query($sql);
1350
        }
1351
        // Update weight into forum thread
1352
        $sql = 'UPDATE '.$tbl_forum_thread.' SET
1353
                thread_weight = '.api_float_val($weight).'
1354
                WHERE
1355
                    c_id = '.$course_id.' AND
1356
                    iid = (
1357
                        SELECT ref_id FROM '.$table_link.'
1358
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1359
                    )
1360
                ';
1361
        Database::query($sql);
1362
        //Update weight into student publication(work)
1363
        $em
1364
            ->createQuery('
1365
                UPDATE ChamiloCourseBundle:CStudentPublication w
1366
                SET w.weight = :final_weight
1367
                WHERE w.cId = :course
1368
                    AND w.iid = (
1369
                        SELECT l.refId FROM ChamiloCoreBundle:GradebookLink l
1370
                        WHERE l.id = :link AND l.type = :type
1371
                    )
1372
            ')
1373
            ->execute([
1374
                'final_weight' => $weight,
1375
                'course' => $course_id,
1376
                'link' => $linkId,
1377
                'type' => LINK_STUDENTPUBLICATION,
1378
            ]);
1379
    }
1380
1381
    /**
1382
     * @param int   $id
1383
     * @param float $weight
1384
     */
1385
    public static function updateEvaluationWeight($id, $weight)
1386
    {
1387
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1388
        $id = (int) $id;
1389
        $evaluation = new Evaluation();
1390
        $evaluation->addEvaluationLog($id);
1391
        $sql = 'UPDATE '.$table_evaluation.'
1392
               SET weight = '."'".Database::escape_string($weight)."'".'
1393
               WHERE id = '.$id;
1394
        Database::query($sql);
1395
    }
1396
1397
    /**
1398
     * Get the achieved certificates for a user in courses.
1399
     *
1400
     * @param int  $userId                       The user id
1401
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1402
     *
1403
     * @return array
1404
     */
1405
    public static function getUserCertificatesInCourses(
1406
        $userId,
1407
        $includeNonPublicCertificates = true
1408
    ) {
1409
        $userId = (int) $userId;
1410
        $courseList = [];
1411
        $courses = CourseManager::get_courses_list_by_user_id($userId);
1412
1413
        foreach ($courses as $course) {
1414
            if (!$includeNonPublicCertificates) {
1415
                $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course);
1416
1417
                if (empty($allowPublicCertificates)) {
1418
                    continue;
1419
                }
1420
            }
1421
1422
            $category = Category::load(null, null, $course['code']);
1423
1424
            if (empty($category)) {
1425
                continue;
1426
            }
1427
1428
            if (!isset($category[0])) {
1429
                continue;
1430
            }
1431
            /** @var Category $category */
1432
            $category = $category[0];
1433
1434
            if (empty($category->getGenerateCertificates())) {
1435
                continue;
1436
            }
1437
1438
            $categoryId = $category->get_id();
1439
            $certificateInfo = self::get_certificate_by_user_id($categoryId, $userId);
1440
1441
            if (empty($certificateInfo)) {
1442
                continue;
1443
            }
1444
1445
            $courseInfo = api_get_course_info_by_id($course['real_id']);
1446
            if (empty($courseInfo)) {
1447
                continue;
1448
            }
1449
1450
            $courseList[] = [
1451
                'course' => $courseInfo['title'],
1452
                'score' => $certificateInfo['score_certificate'],
1453
                'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1454
                'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}",
1455
                'pdf' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}&user_id={$userId}&action=export",
1456
            ];
1457
        }
1458
1459
        return $courseList;
1460
    }
1461
1462
    /**
1463
     * Get the achieved certificates for a user in course sessions.
1464
     *
1465
     * @param int  $userId                       The user id
1466
     * @param bool $includeNonPublicCertificates Whether include the non-public certificates
1467
     *
1468
     * @return array
1469
     */
1470
    public static function getUserCertificatesInSessions($userId, $includeNonPublicCertificates = true)
1471
    {
1472
        $userId = (int) $userId;
1473
        $sessionList = [];
1474
        $sessions = SessionManager::get_sessions_by_user($userId, true, true);
1475
1476
        foreach ($sessions as $session) {
1477
            if (empty($session['courses'])) {
1478
                continue;
1479
            }
1480
            $sessionCourses = SessionManager::get_course_list_by_session_id($session['session_id']);
1481
1482
            if (empty($sessionCourses)) {
1483
                continue;
1484
            }
1485
1486
            foreach ($sessionCourses as $course) {
1487
                if (!$includeNonPublicCertificates) {
1488
                    $allowPublicCertificates = api_get_course_setting('allow_public_certificates');
1489
1490
                    if (empty($allowPublicCertificates)) {
1491
                        continue;
1492
                    }
1493
                }
1494
1495
                $category = Category::load(
1496
                    null,
1497
                    null,
1498
                    $course['code'],
1499
                    null,
1500
                    null,
1501
                    $session['session_id']
1502
                );
1503
1504
                if (empty($category)) {
1505
                    continue;
1506
                }
1507
1508
                if (!isset($category[0])) {
1509
                    continue;
1510
                }
1511
1512
                /** @var Category $category */
1513
                $category = $category[0];
1514
1515
                // Don't allow generate of certifications
1516
                if (empty($category->getGenerateCertificates())) {
1517
                    continue;
1518
                }
1519
1520
                $categoryId = $category->get_id();
1521
                $certificateInfo = self::get_certificate_by_user_id(
1522
                    $categoryId,
1523
                    $userId
1524
                );
1525
1526
                if (empty($certificateInfo)) {
1527
                    continue;
1528
                }
1529
1530
                $sessionList[] = [
1531
                    'session' => $session['session_name'],
1532
                    'course' => $course['title'],
1533
                    'score' => $certificateInfo['score_certificate'],
1534
                    'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1535
                    'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}",
1536
                ];
1537
            }
1538
        }
1539
1540
        return $sessionList;
1541
    }
1542
1543
    /**
1544
     * @param array $courseInfo
1545
     * @param int   $userId
1546
     * @param array $cats
1547
     * @param bool  $saveToFile
1548
     * @param bool  $saveToHtmlFile
1549
     * @param array $studentList
1550
     * @param PDF   $pdf
1551
     *
1552
     * @return string
1553
     */
1554
    public static function generateTable(
1555
        $courseInfo,
1556
        $userId,
1557
        $cats,
1558
        $saveToFile = false,
1559
        $saveToHtmlFile = false,
1560
        $studentList = [],
1561
        $pdf = null
1562
    ) {
1563
        $userInfo = api_get_user_info($userId);
1564
        $model = ExerciseLib::getCourseScoreModel();
1565
        $cat = $cats[0];
1566
        $allcat = $cats[0]->get_subcategories(
1567
            $userId,
1568
            api_get_course_id(),
1569
            api_get_session_id()
1570
        );
1571
        $alleval = $cats[0]->get_evaluations($userId);
1572
        $alllink = $cats[0]->get_links($userId);
1573
1574
        $loadStats = [];
1575
        if ('true' === api_get_setting('gradebook_detailed_admin_view')) {
1576
            $loadStats = [1, 2, 3];
1577
        } else {
1578
            if (false !== api_get_configuration_value('gradebook_enable_best_score')) {
1579
                $loadStats = [2];
1580
            }
1581
        }
1582
1583
        $gradebooktable = new GradebookTable(
1584
            $cat,
1585
            $allcat,
1586
            $alleval,
1587
            $alllink,
1588
            null,
1589
            true,
1590
            false,
1591
            $userId,
1592
            $studentList,
1593
            $loadStats
1594
        );
1595
1596
        $gradebooktable->userId = $userId;
1597
1598
        if (api_is_allowed_to_edit(null, true)) {
1599
        } else {
1600
            if (empty($model)) {
1601
                $gradebooktable->td_attributes = [
1602
                    3 => 'class=centered',
1603
                    4 => 'class=centered',
1604
                    5 => 'class=centered',
1605
                    6 => 'class=centered',
1606
                    7 => 'class=centered',
1607
                ];
1608
            }
1609
        }
1610
        $table = $gradebooktable->return_table();
1611
1612
        $graph = '';
1613
        if (empty($model)) {
1614
            $graph = $gradebooktable->getGraph();
1615
        }
1616
        $params = [
1617
            'pdf_title' => sprintf(get_lang('Grades from course: %s'), $courseInfo['name']),
1618
            'session_info' => '',
1619
            'course_info' => '',
1620
            'pdf_date' => '',
1621
            'course_code' => api_get_course_id(),
1622
            'student_info' => $userInfo,
1623
            'show_grade_generated_date' => true,
1624
            'show_real_course_teachers' => false,
1625
            'show_teacher_as_myself' => false,
1626
            'orientation' => 'P',
1627
        ];
1628
1629
        if (empty($pdf)) {
1630
            $pdf = new PDF('A4', $params['orientation'], $params);
1631
        }
1632
1633
        $pdf->params['student_info'] = $userInfo;
1634
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid().'.html';
1635
1636
        $settings = api_get_configuration_value('gradebook_pdf_export_settings');
1637
        $showFeedBack = true;
1638
        if (isset($settings['hide_feedback_textarea']) && $settings['hide_feedback_textarea']) {
1639
            $showFeedBack = false;
1640
        }
1641
1642
        $feedback = '';
1643
        if ($showFeedBack) {
1644
            $feedback = '<br />'.get_lang('Feedback').'<br />
1645
            <textarea class="form-control" rows="5" cols="100">&nbsp;</textarea>';
1646
1647
        }
1648
        $content = $table.$graph.$feedback;
1649
        $result = $pdf->html_to_pdf_with_template(
1650
            $content,
1651
            $saveToFile,
1652
            $saveToHtmlFile,
1653
            true
1654
        );
1655
1656
        if ($saveToHtmlFile) {
1657
            return $result;
1658
        }
1659
1660
        return $file;
1661
    }
1662
}
1663