Passed
Push — master ( a5830d...268b85 )
by
unknown
16:33 queued 08:04
created

GradebookUtils::isResourceInCourseGradebook()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 24
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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