Passed
Push — master ( 16cab1...51d316 )
by
unknown
18:45 queued 09:14
created

GradebookUtils::build_edit_icons_cat()   C

Complexity

Conditions 15
Paths 201

Size

Total Lines 98
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 71
c 0
b 0
f 0
nc 201
nop 2
dl 0
loc 98
rs 5.0708

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
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
        if (!isset($table_evaluated[$type][0])) {
537
            throw new \InvalidArgumentException('Unknown evaluated type: '.$type);
538
        }
539
540
        return Database::get_course_table($table_evaluated[$type][0]);
541
    }
542
543
    /**
544
     * @param Category $cat
545
     * @param $users
546
     * @param $alleval
547
     * @param $alllinks
548
     * @param $params
549
     * @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...
550
     *
551
     * @return array
552
     */
553
    public static function get_printable_data(
554
        $cat,
555
        $users,
556
        $alleval,
557
        $alllinks,
558
        $params,
559
        $mainCourseCategory = null
560
    ) {
561
        $datagen = new FlatViewDataGenerator(
562
            $users,
563
            $alleval,
564
            $alllinks,
565
            $params,
566
            $mainCourseCategory
567
        );
568
569
        $offset = isset($_GET['offset']) ? (int) $_GET['offset'] : 0;
570
571
        // step 2: generate rows: students
572
        $datagen->category = $cat;
573
574
        $count = (($offset + 10) > $datagen->get_total_items_count()) ? ($datagen->get_total_items_count() - $offset) : GRADEBOOK_ITEM_LIMIT;
575
        $header_names = $datagen->get_header_names($offset, $count, true);
576
        $data_array = $datagen->get_data(
577
            FlatViewDataGenerator::FVDG_SORT_LASTNAME,
578
            0,
579
            null,
580
            $offset,
581
            $count,
582
            true,
583
            true
584
        );
585
586
        $result = [];
587
        foreach ($data_array as $data) {
588
            $result[] = array_slice($data, 1);
589
        }
590
        $return = [$header_names, $result];
591
592
        return $return;
593
    }
594
595
    /**
596
     * XML-parser: handle character data.
597
     */
598
    public static function character_data($parser, $data)
599
    {
600
        global $current_value;
601
        $current_value = $data;
602
    }
603
604
    public static function overwritescore($resid, $importscore, $eval_max)
605
    {
606
        $result = Result::load($resid);
607
        if ($importscore > $eval_max) {
608
            header('Location: gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'&overwritemax=');
609
            exit;
610
        }
611
        $result[0]->set_score($importscore);
612
        $result[0]->save();
613
        unset($result);
614
    }
615
616
    /**
617
     * register user info about certificate.
618
     *
619
     * @param int    $cat_id            The category id
620
     * @param int    $user_id           The user id
621
     * @param float  $score_certificate The score obtained for certified
622
     * @param string $date_certificate  The date when you obtained the certificate
623
     */
624
    public static function registerUserInfoAboutCertificate(
625
        $cat_id,
626
        $user_id,
627
        $score_certificate,
628
        $date_certificate
629
    ) {
630
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
631
        $cat_id = (int) $cat_id;
632
        $user_id = (int) $user_id;
633
634
        $sql = "SELECT COUNT(id) as count
635
                FROM $table gc
636
                WHERE gc.cat_id = $cat_id AND user_id = $user_id ";
637
        $rs_exist = Database::query($sql);
638
        $row = Database::fetch_array($rs_exist);
639
        if (0 == $row['count']) {
640
            if ($cat_id === 0) {
641
                $cat_id = Null;
642
            }
643
            $params = [
644
                'cat_id' => $cat_id,
645
                'user_id' => $user_id,
646
                'score_certificate' => $score_certificate,
647
                'created_at' => $date_certificate,
648
            ];
649
            Database::insert($table, $params);
650
        }
651
    }
652
653
    /**
654
     * Get date of user certificate.
655
     *
656
     * @param int $cat_id  The category id
657
     * @param int $user_id The user id
658
     *
659
     * @return array
660
     */
661
    public static function get_certificate_by_user_id($cat_id, $user_id)
662
    {
663
        $repository = Container::getGradeBookCertificateRepository();
664
        $certificate = $repository->getCertificateByUserId($cat_id, $user_id, true);
665
666
        return $certificate;
667
    }
668
669
    /**
670
     * Get list of users certificates.
671
     *
672
     * @param int   $cat_id   The category id
673
     * @param array $userList Only users in this list
674
     *
675
     * @return array
676
     */
677
    public static function get_list_users_certificates($cat_id = null, $userList = [])
678
    {
679
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
680
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
681
682
        $sql = 'SELECT DISTINCT u.id AS user_id, u.lastname, u.firstname, u.username, gc.created_at
683
            FROM '.$table_user.' u
684
            INNER JOIN '.$table_certificate.' gc ON u.id = gc.user_id';
685
686
        $where = [];
687
688
        if (!is_null($cat_id) && $cat_id > 0) {
689
            $where[] = 'gc.cat_id = '.(int) $cat_id;
690
        }
691
        if (!empty($userList)) {
692
            $ids = array_map('intval', $userList);
693
            $where[] = 'u.id IN ('.implode(',', $ids).')';
694
        }
695
        if ($where) {
696
            $sql .= ' WHERE '.implode(' AND ', $where);
697
        }
698
699
        $sql .= ' ORDER BY '.(api_sort_by_first_name() ? 'u.firstname' : 'u.lastname');
700
        $rs = Database::query($sql);
701
702
        $list_users = [];
703
        while ($row = Database::fetch_array($rs)) {
704
            $list_users[] = $row;
705
        }
706
707
        return $list_users;
708
    }
709
710
    /**
711
     * Gets the certificate list by user id.
712
     *
713
     * @param int $user_id The user id
714
     * @param int $cat_id  The category id
715
     *
716
     * @return array
717
     */
718
    public static function get_list_gradebook_certificates_by_user_id(
719
        $user_id,
720
        $cat_id = null
721
    ) {
722
        $user_id = (int) $user_id;
723
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
724
        $sql = 'SELECT
725
                    gc.score_certificate,
726
                    gc.created_at,
727
                    gc.path_certificate,
728
                    gc.cat_id,
729
                    gc.user_id,
730
                    gc.id,
731
                    gc.publish
732
                FROM  '.$table_certificate.' gc
733
                WHERE gc.user_id = "'.$user_id.'" ';
734
        if (!is_null($cat_id) && $cat_id > 0) {
735
            $sql .= ' AND cat_id='.intval($cat_id);
736
        }
737
738
        $rs = Database::query($sql);
739
        $list = [];
740
        while ($row = Database::fetch_array($rs)) {
741
            $list[] = $row;
742
        }
743
744
        return $list;
745
    }
746
747
    /**
748
     * Gets the content of an HTML document with placeholders replaced
749
     * @param int    $user_id
750
     * @param int    $courseId
751
     * @param int    $sessionId
752
     * @param bool   $is_preview
753
     * @param bool   $hide_print_button
754
     *
755
     * @return array
756
     */
757
    public static function get_user_certificate_content(
758
        int $user_id,
759
        int $courseId,
760
        int $sessionId,
761
        ?bool $is_preview = false,
762
        ?bool $hide_print_button = false
763
    ): array
764
    {
765
        // Generate document HTML
766
        $content_html = DocumentManager::replace_user_info_into_html(
767
            $user_id,
768
            api_get_course_info_by_id($courseId),
769
            $sessionId,
770
            $is_preview
771
        );
772
773
        $new_content_html = isset($content_html['content']) ? $content_html['content'] : null;
774
        $variables = isset($content_html['variables']) ? $content_html['variables'] : null;
775
        $path_image = api_get_path(WEB_PUBLIC_PATH).'/img/gallery';
776
        $new_content_html = str_replace('../images/gallery', $path_image, $new_content_html);
777
778
        $path_image_in_default_course = api_get_path(WEB_CODE_PATH).'default_course_document';
779
        $new_content_html = str_replace('/main/default_course_document', $path_image_in_default_course, $new_content_html);
780
        $new_content_html = str_replace(SYS_CODE_PATH.'img/', api_get_path(WEB_IMG_PATH), $new_content_html);
781
782
        //add print header
783
        if (!$hide_print_button) {
784
            $print = '<style>#print_div {
785
                padding:4px;border: 0 none;position: absolute;top: 0px;right: 0px;
786
            }
787
            @media print {
788
                #print_div  {
789
                    display: none !important;
790
                }
791
            }
792
            </style>';
793
794
            $print .= Display::div(
795
                Display::url(
796
                    Display::getMdiIcon(ActionIcon::PRINT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Print')),
797
                    'javascript:void()',
798
                    ['onclick' => 'window.print();']
799
                ),
800
                ['id' => 'print_div']
801
            );
802
            $print .= '</html>';
803
            $new_content_html = str_replace('</html>', $print, $new_content_html);
804
        }
805
806
        return [
807
            'content' => $new_content_html,
808
            'variables' => $variables,
809
        ];
810
    }
811
812
    /**
813
     * Create a gradebook in the given course if no gradebook exists yet
814
     * @param ?int $courseId
815
     * @param ?int $gradebook_model_id
816
     *
817
     * @return int 0 on failure, gradebook ID otherwise
818
     * @throws Exception
819
     */
820
    public static function create_default_course_gradebook(
821
        ?int $courseId = null,
822
        ?int $gradebook_model_id = 0
823
    ): int
824
    {
825
        if (api_is_allowed_to_edit(true, true)) {
826
            if (empty($courseId)) {
827
                $courseId = api_get_course_int_id();
828
            }
829
            $session_id = api_get_session_id();
830
831
            $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
832
            $sql = "SELECT * FROM $t
833
                    WHERE c_id = $courseId ";
834
            if (!empty($session_id)) {
835
                $sql .= " AND session_id = ".$session_id;
836
            } else {
837
                $sql .= ' AND (session_id IS NULL OR session_id = 0) ';
838
            }
839
            $sql .= ' ORDER BY id ';
840
            $res = Database::query($sql);
841
            if (Database::num_rows($res) < 1) {
842
                //there is no unique category for this course+session combination,
843
                $cat = new Category();
844
                if (!empty($session_id)) {
845
                    $my_session_id = api_get_session_id();
846
                    $s_name = api_get_session_name($my_session_id);
847
                    $cat->set_name($courseId.' - '.get_lang('Session').' '.$s_name);
848
                    $cat->set_session_id($session_id);
849
                } else {
850
                    $cat->set_name(strval($courseId));
851
                }
852
                $cat->setCourseId($courseId);
853
                $cat->set_description('');
854
                $cat->set_user_id(api_get_user_id());
855
                $cat->set_parent_id(0);
856
                $default_weight_setting = api_get_setting('gradebook_default_weight');
857
                $default_weight = !empty($default_weight_setting) ? $default_weight_setting : 100;
858
                $cat->set_weight($default_weight);
859
                $cat->set_grade_model_id($gradebook_model_id);
860
                $cat->set_certificate_min_score(75);
861
                $cat->set_visible(0);
862
                $cat->add();
863
                $category_id = $cat->get_id();
864
                unset($cat);
865
            } else {
866
                $row = Database::fetch_array($res);
867
                $category_id = $row['id'];
868
            }
869
870
            return $category_id;
871
        }
872
873
        return 0;
874
    }
875
876
    /**
877
     * @param FormValidator $form
878
     */
879
    public static function load_gradebook_select_in_tool($form)
880
    {
881
        $session_id = api_get_session_id();
882
883
        self::create_default_course_gradebook();
884
885
        // Cat list
886
        $all_categories = Category::load(
887
            null,
888
            null,
889
            api_get_course_int_id(),
890
            null,
891
            null,
892
            $session_id,
893
            null
894
        );
895
        $select_gradebook = $form->addSelect(
896
            'category_id',
897
            get_lang('Select assessment')
898
        );
899
900
        if (!empty($all_categories)) {
901
            foreach ($all_categories as $my_cat) {
902
                if ($my_cat->getCourseId() == api_get_course_int_id()) {
903
                    $grade_model_id = $my_cat->get_grade_model_id();
904
                    if (empty($grade_model_id)) {
905
                        if (0 == $my_cat->get_parent_id()) {
906
                            $select_gradebook->addOption(get_lang('Default'), $my_cat->get_id());
907
                            $cats_added[] = $my_cat->get_id();
908
                        } else {
909
                            $select_gradebook->addOption($my_cat->get_name(), $my_cat->get_id());
910
                            $cats_added[] = $my_cat->get_id();
911
                        }
912
                    } else {
913
                        $select_gradebook->addOption(get_lang('Select'), 0);
914
                    }
915
                }
916
            }
917
        }
918
    }
919
920
    /**
921
     * @param FlatViewTable $flatviewtable
922
     * @param array         $cat
923
     * @param               $users
924
     * @param               $alleval
925
     * @param               $alllinks
926
     * @param array         $params
927
     * @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...
928
     */
929
    public static function export_pdf_flatview(
930
        $flatviewtable,
931
        $cat,
932
        $users,
933
        $alleval,
934
        $alllinks,
935
        $params = [],
936
        $mainCourseCategory = null
937
    ) {
938
        $cat = $cat[0] ?? null;
939
        // Getting data
940
        $printable_data = self::get_printable_data(
941
            $cat,
942
            $users,
943
            $alleval,
944
            $alllinks,
945
            $params,
946
            $mainCourseCategory
947
        );
948
949
        // HTML report creation first
950
951
        $displayscore = ScoreDisplay::instance();
952
        $customDisplays = $displayscore->get_custom_score_display_settings();
953
954
        $total = [];
955
        if (is_array($customDisplays) && count(($customDisplays))) {
956
            foreach ($customDisplays as $custom) {
957
                $total[$custom['display']] = 0;
958
            }
959
            $user_results = $flatviewtable->datagen->get_data_to_graph2(false);
960
            foreach ($user_results as $user_result) {
961
                $item = $user_result[count($user_result) - 1];
962
                $customTag = isset($item[1]) ? strip_tags($item[1]) : '';
963
                $total[$customTag]++;
964
            }
965
        }
966
967
        $parent_id = $cat->get_parent_id();
968
        if (isset($cat) && isset($parent_id)) {
969
            if (0 == $parent_id) {
970
                $grade_model_id = $cat->get_grade_model_id();
971
            } else {
972
                $parent_cat = Category::load($parent_id);
973
                $grade_model_id = $parent_cat[0]->get_grade_model_id();
974
            }
975
        }
976
977
        $use_grade_model = true;
978
        if (empty($grade_model_id) || -1 == $grade_model_id) {
979
            $use_grade_model = false;
980
        }
981
982
        if ($use_grade_model) {
983
            if (0 == $parent_id) {
984
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
985
            } else {
986
                $title = api_strtoupper(get_lang('Average')).'<br />'.$cat[0]->get_description().' - ('.$cat[0]->get_name().')';
987
            }
988
        } else {
989
            if (0 == $parent_id) {
990
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
991
            } else {
992
                $title = api_strtoupper(get_lang('Average'));
993
            }
994
        }
995
996
        $columns = count($printable_data[0]);
997
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
998
999
        $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
1000
        $row = 0;
1001
        $column = 0;
1002
        $table->setHeaderContents($row, $column, get_lang('N°'));
1003
        $column++;
1004
        foreach ($printable_data[0] as $printable_data_cell) {
1005
            if (!is_array($printable_data_cell)) {
1006
                $printable_data_cell = strip_tags($printable_data_cell);
1007
            }
1008
            $table->setHeaderContents($row, $column, $printable_data_cell);
1009
            $column++;
1010
        }
1011
        $row++;
1012
1013
        if ($has_data) {
1014
            $counter = 1;
1015
            foreach ($printable_data[1] as &$printable_data_row) {
1016
                $column = 0;
1017
                $table->setCellContents($row, $column, $counter);
1018
                $table->updateCellAttributes($row, $column, 'align="center"');
1019
                $column++;
1020
                $counter++;
1021
1022
                foreach ($printable_data_row as $key => &$printable_data_cell) {
1023
                    $attributes = [];
1024
                    $attributes['align'] = 'center';
1025
                    $attributes['style'] = null;
1026
1027
                    if ('name' === $key) {
1028
                        $attributes['align'] = 'left';
1029
                    }
1030
                    if ('total' === $key) {
1031
                        $attributes['style'] = 'font-weight:bold';
1032
                    }
1033
                    $table->setCellContents($row, $column, $printable_data_cell);
1034
                    $table->updateCellAttributes($row, $column, $attributes);
1035
                    $column++;
1036
                }
1037
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
1038
                $row++;
1039
            }
1040
        } else {
1041
            $column = 0;
1042
            $table->setCellContents($row, $column, get_lang('No results found'));
1043
            $table->updateCellAttributes($row, $column, 'colspan="'.$columns.'" align="center" class="row_odd"');
1044
        }
1045
1046
        $course_code = trim($cat->get_course_code());
1047
        $pdfParams = [
1048
            'filename' => get_lang('List View').'_'.api_get_local_time(),
1049
            'pdf_title' => $title,
1050
            'course_code' => $course_code,
1051
            'add_signatures' => ['Drh', 'Teacher', 'Date'],
1052
        ];
1053
1054
        $page_format = 'landscape' === $params['orientation'] ? 'A4-L' : 'A4';
1055
        ob_start();
1056
        $pdf = new PDF($page_format, $page_format, $pdfParams);
1057
        $pdf->html_to_pdf_with_template($flatviewtable->return_table(), false, false, true);
1058
        $content = ob_get_contents();
1059
        ob_end_clean();
1060
        echo $content;
1061
        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...
1062
    }
1063
1064
    /**
1065
     * @param string[] $listValues
1066
     *
1067
     * @return string
1068
     */
1069
    public static function scoreBadges($listValues)
1070
    {
1071
        $counter = 1;
1072
        $badges = [];
1073
        foreach ($listValues as $value) {
1074
            $class = 'warning';
1075
            if (1 == $counter) {
1076
                $class = 'success';
1077
            }
1078
            $counter++;
1079
            $badges[] = Display::label($value, $class);
1080
        }
1081
1082
        return Display::badgeGroup($badges);
1083
    }
1084
1085
    /**
1086
     * returns users within a course given by param.
1087
     *
1088
     * @param ?int $courseId
1089
     *
1090
     * @return array
1091
     * @throws Exception
1092
     * @todo use CourseManager
1093
     *
1094
     */
1095
    public static function get_users_in_course(?int $courseId = 0)
1096
    {
1097
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1098
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1099
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1100
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
1101
        $current_session = api_get_session_id();
1102
1103
        if (!empty($current_session)) {
1104
            $sql = "SELECT user.id as user_id, user.username, lastname, firstname, official_code
1105
                    FROM $tbl_session_course_user as scru
1106
                    INNER JOIN $tbl_user as user
1107
                    ON (scru.user_id = user.id)
1108
                    WHERE
1109
                        scru.status = ".Session::STUDENT." AND
1110
                        scru.c_id = $courseId AND
1111
                        session_id = '$current_session'
1112
                    $order_clause
1113
                    ";
1114
        } else {
1115
            $sql = 'SELECT user.id as user_id, user.username, lastname, firstname, official_code
1116
                    FROM '.$tbl_course_user.' as course_rel_user
1117
                    INNER JOIN '.$tbl_user.' as user
1118
                    ON (course_rel_user.user_id = user.id)
1119
                    WHERE
1120
                        course_rel_user.status = '.STUDENT.' AND
1121
                        course_rel_user.c_id = '.$courseId.' '.
1122
                    $order_clause;
1123
        }
1124
1125
        $result = Database::query($sql);
1126
1127
        return self::get_user_array_from_sql_result($result);
1128
    }
1129
1130
    /**
1131
     * @param Doctrine\DBAL\Driver\Statement|null $result
1132
     *
1133
     * @return array
1134
     */
1135
    public static function get_user_array_from_sql_result($result)
1136
    {
1137
        $a_students = [];
1138
        while ($user = Database::fetch_array($result)) {
1139
            if (!array_key_exists($user['user_id'], $a_students)) {
1140
                $a_current_student = [];
1141
                $a_current_student[] = $user['user_id'];
1142
                $a_current_student[] = $user['username'];
1143
                $a_current_student[] = $user['lastname'];
1144
                $a_current_student[] = $user['firstname'];
1145
                $a_current_student[] = $user['official_code'];
1146
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1147
            }
1148
        }
1149
1150
        return $a_students;
1151
    }
1152
1153
    /**
1154
     * @param array $evals
1155
     * @param array $links
1156
     *
1157
     * @return array
1158
     * @throws Exception
1159
     */
1160
    public static function get_all_users($evals = [], $links = []): array
1161
    {
1162
        $courseId = api_get_course_int_id();
1163
        // By default, add all user in course
1164
        $courseIds[$courseId] = '1';
1165
        $users = self::get_users_in_course($courseId);
1166
1167
        foreach ($evals as $eval) {
1168
            /* @var Evaluation $eval */
1169
            $loopCourseId = $eval->getCourseId();
1170
            // evaluation in course
1171
            if (!empty($loopCourseId)) {
1172
                if (!array_key_exists($loopCourseId, $courseIds)) {
1173
                    $courseIds[$loopCourseId] = '1';
1174
                    $users = array_merge($users, self::get_users_in_course($loopCourseId));
1175
                }
1176
            } else {
1177
                // course independent evaluation
1178
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1179
                $tbl_res = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1180
1181
                $sql = 'SELECT user.id as user_id, lastname, firstname, user.official_code
1182
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1183
                        WHERE
1184
                            res.evaluation_id = '.$eval->get_id().' AND
1185
                            res.user_id = user.id
1186
                        ';
1187
                $sql .= ' ORDER BY lastname, firstname';
1188
                if (api_is_western_name_order()) {
1189
                    $sql .= ' ORDER BY firstname, lastname';
1190
                }
1191
1192
                $result = Database::query($sql);
1193
                $users = array_merge(
1194
                    $users,
1195
                    self::get_user_array_from_sql_result($result)
1196
                );
1197
            }
1198
        }
1199
1200
        foreach ($links as $link) {
1201
            // links are always in a course
1202
            /** @var EvalLink $link */
1203
            $loopCourseId = $link->getCourseId();
1204
            if (!array_key_exists($loopCourseId, $courseIds)) {
1205
                $courseIds[$loopCourseId] = '1';
1206
                $users = array_merge(
1207
                    $users,
1208
                    self::get_users_in_course($loopCourseId)
1209
                );
1210
            }
1211
        }
1212
1213
        return $users;
1214
    }
1215
1216
    /**
1217
     * Search students matching a given last name and/or first name.
1218
     *
1219
     * @author Bert Steppé
1220
     */
1221
    public static function find_students($mask = '')
1222
    {
1223
        if (!api_is_allowed_to_edit() || $mask === '') {
1224
            return null;
1225
        }
1226
1227
        $mask = Database::escape_string($mask);
1228
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1229
        $tbl_cru  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1230
1231
        $sql = 'SELECT DISTINCT user.id AS user_id, user.lastname, user.firstname, user.email, user.official_code
1232
            FROM '.$tbl_user.' user';
1233
1234
        if (!api_is_platform_admin()) {
1235
            $sql .= ' INNER JOIN '.$tbl_cru.' cru ON (cru.user_id = user.id)
1236
                  AND cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.'
1237
                  AND cru.c_id IN (
1238
                        SELECT c_id FROM '.$tbl_cru.'
1239
                         WHERE user_id = '.api_get_user_id().' AND status = '.COURSEMANAGER.'
1240
                  )';
1241
        }
1242
1243
        $sql .= ' WHERE user.status = '.STUDENT.'
1244
              AND (user.lastname LIKE \'%'.$mask.'%\' OR user.firstname LIKE \'%'.$mask.'%\')';
1245
1246
        $orderBy = api_is_western_name_order() ? 'firstname, lastname' : 'lastname, firstname';
1247
        $sql .= ' ORDER BY '.$orderBy;
1248
1249
        $result = Database::query($sql);
1250
1251
        return Database::store_result($result);
1252
    }
1253
1254
    /**
1255
     * @param int   $linkId
1256
     * @param float $weight
1257
     */
1258
    public static function updateLinkWeight($linkId, $name, $weight)
1259
    {
1260
        $linkId = (int) $linkId;
1261
        $weight = api_float_val($weight);
1262
        $course_id = api_get_course_int_id();
1263
1264
        AbstractLink::add_link_log($linkId, $name);
1265
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1266
1267
        $em = Database::getManager();
1268
        $tbl_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
1269
        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
1270
1271
        $sql = 'UPDATE '.$table_link.'
1272
                SET weight = '."'".Database::escape_string($weight)."'".'
1273
                WHERE id = '.$linkId;
1274
1275
        Database::query($sql);
1276
1277
        // Update weight for attendance
1278
        $sql = 'SELECT ref_id FROM '.$table_link.'
1279
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1280
1281
        $rs_attendance = Database::query($sql);
1282
        if (Database::num_rows($rs_attendance) > 0) {
1283
            $row_attendance = Database::fetch_array($rs_attendance);
1284
            $sql = 'UPDATE '.$tbl_attendance.' SET
1285
                    attendance_weight ='.api_float_val($weight).'
1286
                    WHERE id = '.intval($row_attendance['ref_id']);
1287
            Database::query($sql);
1288
        }
1289
        // Update weight into forum thread
1290
        $sql = 'UPDATE '.$tbl_forum_thread.' SET
1291
                thread_weight = '.api_float_val($weight).'
1292
                WHERE
1293
                    iid = (
1294
                        SELECT ref_id FROM '.$table_link.'
1295
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1296
                    )
1297
                ';
1298
        Database::query($sql);
1299
        //Update weight into student publication(work)
1300
        $em
1301
            ->createQuery('
1302
                UPDATE ChamiloCourseBundle:CStudentPublication w
1303
                SET w.weight = :final_weight
1304
                WHERE
1305
                    w.iid = (
1306
                        SELECT l.refId FROM ChamiloCoreBundle:GradebookLink l
1307
                        WHERE l.id = :link AND l.type = :type
1308
                    )
1309
            ')
1310
            ->execute([
1311
                'final_weight' => $weight,
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