Passed
Push — master ( 78cd0a...f41061 )
by Julito
10:08
created

GradebookUtils::create_default_course_gradebook()   B

Complexity

Conditions 9
Paths 37

Size

Total Lines 55
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 41
nc 37
nop 2
dl 0
loc 55
rs 7.7084
c 0
b 0
f 0

How to fix   Long Method   

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

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1654
1655
            return $file;
1656
        }
1657
1658
        return $file;
1659
    }
1660
}
1661