Completed
Push — master ( 27e209...a08afa )
by Julito
186:04 queued 150:53
created

GradebookUtils::add_resource_to_course_gradebook()   C

Complexity

Conditions 7
Paths 17

Size

Total Lines 42
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 20
nc 17
nop 11
dl 0
loc 42
rs 6.7272
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* 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
     * @param   int
12
     * @param   string  Course code
13
     * @param   int     Resource type (use constants defined in linkfactory.class.php)
14
     * @param   int     Resource ID in the corresponding tool
15
     * @param   string  Resource name to show in the gradebook
16
     * @param   int     Resource weight to set in the gradebook
17
     * @param   int     Resource max
18
     * @param   string  Resource description
19
     * @param   int     Visibility (0 hidden, 1 shown)
20
     * @param   int     Session ID (optional or 0 if not defined)
21
     * @param   int
22
     * @param integer $resource_type
23
     * @return  boolean True on success, false on failure
24
     */
25
    public static function add_resource_to_course_gradebook(
26
        $category_id,
27
        $course_code,
28
        $resource_type,
29
        $resource_id,
30
        $resource_name = '',
31
        $weight = 0,
32
        $max = 0,
33
        $resource_description = '',
34
        $visible = 0,
35
        $session_id = 0,
36
        $link_id = null
0 ignored issues
show
Unused Code introduced by
The parameter $link_id is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

36
        /** @scrutinizer ignore-unused */ $link_id = null

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
37
    ) {
38
        $link = LinkFactory::create($resource_type);
39
        $link->set_user_id(api_get_user_id());
40
        $link->set_course_code($course_code);
41
42
        if (empty($category_id)) {
43
            return false;
44
        }
45
        $link->set_category_id($category_id);
46
        if ($link->needs_name_and_description()) {
47
            $link->set_name($resource_name);
48
        } else {
49
            $link->set_ref_id($resource_id);
50
        }
51
        $link->set_weight($weight);
52
53
        if ($link->needs_max()) {
54
            $link->set_max($max);
55
        }
56
        if ($link->needs_name_and_description()) {
57
            $link->set_description($resource_description);
58
        }
59
60
        $link->set_visible(empty($visible) ? 0 : 1);
61
62
        if (!empty($session_id)) {
63
            $link->set_session_id($session_id);
64
        }
65
        $link->add();
66
        return true;
67
    }
68
69
    /**
70
     * Update a resource weight
71
     * @param    int     Link/Resource ID
72
     * @param   string
73
     * @param float
74
     * @return   bool    false on error, true on success
75
     */
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
    public static function updateResourceFromCourseGradebook(
77
        $link_id,
78
        $course_code,
79
        $weight
80
    ) {
81
        $course_code = Database::escape_string($course_code);
82
        if (!empty($link_id)) {
83
            $link_id = intval($link_id);
84
            $sql = 'UPDATE '.Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK).'
85
                    SET weight = ' . "'".api_float_val($weight)."'".'
86
                    WHERE course_code = "' . $course_code.'" AND id = '.$link_id;
87
            Database::query($sql);
88
        }
89
90
        return true;
91
    }
92
93
    /**
94
     * Remove a resource from the unique gradebook of a given course
95
     * @param    int     Link/Resource ID
96
     * @return   bool    false on error, true on success
97
     */
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...
98
    public static function remove_resource_from_course_gradebook($link_id)
99
    {
100
        if (empty($link_id)) {
101
            return false;
102
        }
103
104
        // TODO find the corresponding category (the first one for this course, ordered by ID)
105
        $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
106
        $sql = "DELETE FROM $l WHERE id = ".(int) $link_id;
107
        Database::query($sql);
108
109
        return true;
110
    }
111
112
    /**
113
     * Block students
114
     */
115
    public static function block_students()
116
    {
117
        if (!api_is_allowed_to_edit()) {
118
            api_not_allowed();
119
        }
120
    }
121
122
    /**
123
     * Builds an img tag for a gradebook item
124
     */
125
    public static function build_type_icon_tag($kind, $attributes = [])
126
    {
127
        return Display::return_icon(
128
            self::get_icon_file_name($kind),
129
            ' ',
130
            $attributes,
131
            ICON_SIZE_SMALL
132
        );
133
    }
134
135
    /**
136
     * Returns the icon filename for a gradebook item
137
     * @param string $type value returned by a gradebookitem's get_icon_name()
138
     * @return string
139
     */
140
    public static function get_icon_file_name($type)
141
    {
142
        switch ($type) {
143
            case 'cat':
144
                $icon = 'gradebook.png';
145
                break;
146
            case 'evalempty':
147
                $icon = 'empty_evaluation.png';
148
                break;
149
            case 'evalnotempty':
150
                $icon = 'no_empty_evaluation.png';
151
                break;
152
            case 'exercise':
153
            case LINK_EXERCISE:
154
                $icon = 'quiz.png';
155
                break;
156
            case 'learnpath':
157
            case LINK_LEARNPATH:
158
                $icon = 'learnpath.png';
159
                break;
160
            case 'studentpublication':
161
            case LINK_STUDENTPUBLICATION:
162
                $icon = 'works.gif';
163
                break;
164
            case 'link':
165
                $icon = 'link.gif';
166
                break;
167
            case 'forum':
168
            case LINK_FORUM_THREAD:
169
                $icon = 'forum.gif';
170
                break;
171
            case 'attendance':
172
            case LINK_ATTENDANCE:
173
                $icon = 'attendance.gif';
174
                break;
175
            case 'survey':
176
            case LINK_SURVEY:
177
                $icon = 'survey.gif';
178
                break;
179
            case 'dropbox':
180
            case LINK_DROPBOX:
181
                $icon = 'dropbox.gif';
182
                break;
183
            default:
184
                $icon = 'link.gif';
185
                break;
186
        }
187
188
        return $icon;
189
    }
190
191
    /**
192
     * Builds the course or platform admin icons to edit a category
193
     * @param Category $cat category
194
     * @param Category $selectcat id of selected category
195
     * @return string
196
     */
197
    public static function build_edit_icons_cat($cat, $selectcat)
198
    {
199
        $show_message = $cat->show_message_resource_delete($cat->get_course_code());
200
        $grade_model_id = $selectcat->get_grade_model_id();
201
        $selectcat = $selectcat->get_id();
202
        $modify_icons = null;
203
204
        if ($show_message === false) {
205
            $visibility_icon = ($cat->is_visible() == 0) ? 'invisible' : 'visible';
206
            $visibility_command = ($cat->is_visible() == 0) ? 'set_visible' : 'set_invisible';
207
208
            $modify_icons .= '<a class="view_children" data-cat-id="'.$cat->get_id().'" href="javascript:void(0);">'.
209
                Display::return_icon(
210
                    'view_more_stats.gif',
211
                    get_lang('Show'),
212
                    '',
213
                    ICON_SIZE_SMALL
214
                ).
215
                '</a>';
216
217
            if (!api_is_allowed_to_edit(null, true)) {
218
                $modify_icons .= Display::url(
219
                    Display::return_icon(
220
                        'stats.png',
221
                        get_lang('FlatView'),
222
                        '',
223
                        ICON_SIZE_SMALL
224
                    ),
225
                    'personal_stats.php?'.http_build_query([
226
                        'selectcat' => $cat->get_id()
227
                    ]).'&'.api_get_cidreq(),
228
                    [
229
                        'class' => 'ajax',
230
                        'data-title' => get_lang('FlatView')
231
                    ]
232
                );
233
            }
234
235
            $courseParams = api_get_cidreq_params(
236
                $cat->get_course_code(),
237
                $cat->get_session_id()
238
            );
239
240
            if (api_is_allowed_to_edit(null, true)) {
241
                // Locking button
242
                if (api_get_setting('gradebook_locking_enabled') == 'true') {
243
                    if ($cat->is_locked()) {
244
                        if (api_is_platform_admin()) {
245
                            $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">'.
246
                                Display::return_icon('lock.png', get_lang('UnLockEvaluation'), '', ICON_SIZE_SMALL).'</a>';
247
                        } else {
248
                            $modify_icons .= '&nbsp;<a href="#">'.Display::return_icon('lock_na.png', get_lang('GradebookLockedAlert'), '', ICON_SIZE_SMALL).'</a>';
249
                        }
250
                        $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>';
251
                    } else {
252
                        $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">'.
253
                            Display::return_icon('unlock.png', get_lang('LockEvaluation'), '', ICON_SIZE_SMALL).'</a>';
254
                        $modify_icons .= '&nbsp;<a href="#" >'.Display::return_icon('pdf_na.png', get_lang('ExportToPDF'), '', ICON_SIZE_SMALL).'</a>';
255
                    }
256
                }
257
258
                if (empty($grade_model_id) || $grade_model_id == -1) {
259
                    if ($cat->is_locked() && !api_is_platform_admin()) {
260
                        $modify_icons .= Display::return_icon(
261
                            'edit_na.png',
262
                            get_lang('Modify'),
263
                            '',
264
                            ICON_SIZE_SMALL
265
                        );
266
                    } else {
267
                        $modify_icons .= '<a href="gradebook_edit_cat.php?editcat='.$cat->get_id().'&'.$courseParams.'">'.
268
                            Display::return_icon(
269
                                'edit.png',
270
                                get_lang('Modify'),
271
                                '',
272
                                ICON_SIZE_SMALL
273
                            ).'</a>';
274
                    }
275
                }
276
277
                $modify_icons .= '<a href="gradebook_edit_all.php?selectcat='.$cat->get_id().'&'.$courseParams.'">'.
278
                    Display::return_icon(
279
                        'percentage.png',
280
                        get_lang('EditAllWeights'),
281
                        '',
282
                        ICON_SIZE_SMALL
283
                    ).'</a>';
284
285
                $modify_icons .= '<a href="gradebook_flatview.php?selectcat='.$cat->get_id().'&'.$courseParams.'">'.
286
                    Display::return_icon(
287
                        'stats.png',
288
                        get_lang('FlatView'),
289
                        '',
290
                        ICON_SIZE_SMALL
291
                    ).'</a>';
292
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visiblecat='.$cat->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.'">'.
293
                    Display::return_icon(
294
                        $visibility_icon.'.png',
295
                        get_lang('Visible'),
296
                        '',
297
                        ICON_SIZE_SMALL
298
                    ).'</a>';
299
300
                if ($cat->is_locked() && !api_is_platform_admin()) {
301
                    $modify_icons .= Display::return_icon(
302
                        'delete_na.png',
303
                        get_lang('DeleteAll'),
304
                        '',
305
                        ICON_SIZE_SMALL
306
                    );
307
                } else {
308
                    $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deletecat='.$cat->get_id().'&selectcat='.$selectcat.'&'.$courseParams.'" onclick="return confirmation();">'.
309
                        Display::return_icon(
310
                            'delete.png',
311
                            get_lang('DeleteAll'),
312
                            '',
313
                            ICON_SIZE_SMALL
314
                        ).
315
                        '</a>';
316
                }
317
            }
318
319
            return $modify_icons;
320
        }
321
    }
322
323
    /**
324
     * Builds the course or platform admin icons to edit an evaluation
325
     * @param  Evaluation $eval evaluation object
326
     * @param int $selectcat id of selected category
327
     * @return string
328
     */
329
    public static function build_edit_icons_eval($eval, $selectcat)
330
    {
331
        $is_locked = $eval->is_locked();
332
        $eval->get_course_code();
333
        $cat = new Category();
334
        $message_eval = $cat->show_message_resource_delete($eval->get_course_code());
335
        $courseParams = api_get_cidreq_params($eval->get_course_code(), $eval->getSessionId());
336
337
        if ($message_eval === false && api_is_allowed_to_edit(null, true)) {
338
            $visibility_icon = ($eval->is_visible() == 0) ? 'invisible' : 'visible';
339
            $visibility_command = ($eval->is_visible() == 0) ? 'set_visible' : 'set_invisible';
340
            if ($is_locked && !api_is_platform_admin()) {
341
                $modify_icons = Display::return_icon(
342
                    'edit_na.png',
343
                    get_lang('Modify'),
344
                    '',
345
                    ICON_SIZE_SMALL
346
                );
347
            } else {
348
                $modify_icons = '<a href="gradebook_edit_eval.php?editeval='.$eval->get_id().'&'.$courseParams.'">'.
349
                    Display::return_icon(
350
                        'edit.png',
351
                        get_lang('Modify'),
352
                        '',
353
                        ICON_SIZE_SMALL
354
                    ).
355
                    '</a>';
356
            }
357
358
            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visibleeval='.$eval->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.' ">'.
359
                Display::return_icon(
360
                    $visibility_icon.'.png',
361
                    get_lang('Visible'),
362
                    '',
363
                    ICON_SIZE_SMALL
364
                ).
365
                '</a>';
366
            if (api_is_allowed_to_edit(null, true)) {
367
                $modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog='.$eval->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'">'.
368
                    Display::return_icon(
369
                        'history.png',
370
                        get_lang('GradebookQualifyLog'),
371
                        '',
372
                        ICON_SIZE_SMALL
373
                    ).
374
                    '</a>';
375
            }
376
377
            if ($is_locked && !api_is_platform_admin()) {
378
                $modify_icons .= '&nbsp;'.
379
                    Display::return_icon(
380
                        'delete_na.png',
381
                        get_lang('Delete'),
382
                        '',
383
                        ICON_SIZE_SMALL
384
                    );
385
            } else {
386
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deleteeval='.$eval->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'" onclick="return confirmation();">'.
387
                    Display::return_icon(
388
                        'delete.png',
389
                        get_lang('Delete'),
390
                        '',
391
                        ICON_SIZE_SMALL
392
                    ).
393
                    '</a>';
394
            }
395
            return $modify_icons;
396
        }
397
    }
398
399
    /**
400
     * Builds the course or platform admin icons to edit a link
401
     * @param AbstractLink $link
402
     * @param int $selectcat id of selected category
403
     *
404
     * @return string
405
     */
406
    public static function build_edit_icons_link($link, $selectcat)
407
    {
408
        $cat = new Category();
409
        $message_link = $cat->show_message_resource_delete($link->get_course_code());
410
        $is_locked = $link->is_locked();
411
412
        $modify_icons = null;
413
414
        if (!api_is_allowed_to_edit(null, true)) {
415
            return null;
416
        }
417
418
        $courseParams = api_get_cidreq_params(
419
            $link->get_course_code(),
420
            $link->get_session_id()
421
        );
422
423
        if ($message_link === false) {
424
            $visibility_icon = ($link->is_visible() == 0) ? 'invisible' : 'visible';
425
            $visibility_command = ($link->is_visible() == 0) ? 'set_visible' : 'set_invisible';
426
427
            if ($is_locked && !api_is_platform_admin()) {
428
                $modify_icons = Display::return_icon(
429
                    'edit_na.png',
430
                    get_lang('Modify'),
431
                    '',
432
                    ICON_SIZE_SMALL
433
                );
434
            } else {
435
                $modify_icons = '<a href="gradebook_edit_link.php?editlink='.$link->get_id().'&'.$courseParams.'">'.
436
                    Display::return_icon(
437
                        'edit.png',
438
                        get_lang('Modify'),
439
                        '',
440
                        ICON_SIZE_SMALL
441
                    ).
442
                    '</a>';
443
            }
444
            $modify_icons .= '&nbsp;<a href="'.api_get_self().'?visiblelink='.$link->get_id().'&'.$visibility_command.'=&selectcat='.$selectcat.'&'.$courseParams.' ">'.
445
                Display::return_icon(
446
                    $visibility_icon.'.png',
447
                    get_lang('Visible'),
448
                    '',
449
                    ICON_SIZE_SMALL
450
                ).
451
                '</a>';
452
            $modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink='.$link->get_id().'&selectcat='.$selectcat.'&'.$courseParams.'">'.
453
                Display::return_icon(
454
                    'history.png',
455
                    get_lang('GradebookQualifyLog'),
456
                    '',
457
                    ICON_SIZE_SMALL
458
                ).
459
                '</a>';
460
461
            //If a work is added in a gradebook you can only delete the link in the work tool
462
            if ($is_locked && !api_is_platform_admin()) {
463
                $modify_icons .= '&nbsp;'.
464
                    Display::return_icon(
465
                        'delete_na.png',
466
                        get_lang('Delete'),
467
                        '',
468
                        ICON_SIZE_SMALL
469
                    );
470
            } else {
471
                $modify_icons .= '&nbsp;<a href="'.api_get_self().'?deletelink='.$link->get_id().'&selectcat='.$selectcat.' &'.$courseParams.'" onclick="return confirmation();">'.
472
                    Display::return_icon(
473
                        'delete.png',
474
                        get_lang('Delete'),
475
                        '',
476
                        ICON_SIZE_SMALL
477
                    ).
478
                    '</a>';
479
            }
480
481
            return $modify_icons;
482
        }
483
    }
484
485
    /**
486
     * Checks if a resource is in the unique gradebook of a given course
487
     * @param    string  $course_code Course code
488
     * @param    int     $resource_type Resource type (use constants defined in linkfactory.class.php)
489
     * @param    int     $resource_id Resource ID in the corresponding tool
490
     * @param    int     $session_id Session ID (optional -  0 if not defined)
491
     *
492
     * @return   array     false on error or array of resource
493
     */
494
    public static function isResourceInCourseGradebook(
495
        $course_code,
496
        $resource_type,
497
        $resource_id,
498
        $session_id = 0
0 ignored issues
show
Unused Code introduced by
The parameter $session_id is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

498
        /** @scrutinizer ignore-unused */ $session_id = 0

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
499
    ) {
500
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
501
        $course_code = Database::escape_string($course_code);
502
        $sql = "SELECT * FROM $table l
503
                WHERE
504
                    course_code = '$course_code' AND
505
                    type = ".(int) $resource_type." AND
506
                    ref_id = " . (int) $resource_id;
507
        $res = Database::query($sql);
508
509
        if (Database::num_rows($res) < 1) {
510
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
511
        }
512
        $row = Database::fetch_array($res, 'ASSOC');
513
514
        return $row;
515
    }
516
517
    /**
518
     * Remove a resource from the unique gradebook of a given course
519
     * @param    int     Link/Resource ID
520
     * @return   bool    false on error, true on success
521
     */
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...
522
    public static function get_resource_from_course_gradebook($link_id)
523
    {
524
        if (empty($link_id)) {
525
            return false;
526
        }
527
        // TODO find the corresponding category (the first one for this course, ordered by ID)
528
        $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
529
        $sql = "SELECT * FROM $l WHERE id = ".(int) $link_id;
530
        $res = Database::query($sql);
531
        $row = [];
532
        if (Database::num_rows($res) > 0) {
533
            $row = Database::fetch_array($res, 'ASSOC');
534
        }
535
        return $row;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $row also could return the type array which is incompatible with the documented return type boolean.
Loading history...
536
    }
537
538
    /**
539
     * Return the course id
540
     * @param    int
541
     * @return   String
542
     */
543
    public static function get_course_id_by_link_id($id_link)
544
    {
545
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
546
        $tbl_grade_links = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
547
        $sql = 'SELECT c.id FROM '.$course_table.' c
548
                INNER JOIN ' . $tbl_grade_links.' l
549
                ON c.code = l.course_code
550
                WHERE l.id=' . intval($id_link).' OR l.category_id='.intval($id_link);
551
        $res = Database::query($sql);
552
        $array = Database::fetch_array($res, 'ASSOC');
553
        return $array['id'];
554
    }
555
556
    /**
557
     * @param $type
558
     * @return string
559
     */
560
    public static function get_table_type_course($type)
561
    {
562
        global $table_evaluated;
563
        return Database::get_course_table($table_evaluated[$type][0]);
564
    }
565
566
    /**
567
     * @param Category $cat
568
     * @param $users
569
     * @param $alleval
570
     * @param $alllinks
571
     * @param $params
572
     * @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...
573
     * @return array
574
     */
575
    public static function get_printable_data(
576
        $cat,
577
        $users,
578
        $alleval,
579
        $alllinks,
580
        $params,
581
        $mainCourseCategory = null
582
    ) {
583
        $datagen = new FlatViewDataGenerator(
584
            $users,
585
            $alleval,
586
            $alllinks,
587
            $params,
588
            $mainCourseCategory
589
        );
590
591
        $offset = isset($_GET['offset']) ? $_GET['offset'] : '0';
592
        $offset = intval($offset);
593
594
        // step 2: generate rows: students
595
        $datagen->category = $cat;
596
597
        $count = (($offset + 10) > $datagen->get_total_items_count()) ? ($datagen->get_total_items_count() - $offset) : GRADEBOOK_ITEM_LIMIT;
598
        $header_names = $datagen->get_header_names($offset, $count, true);
599
        $data_array = $datagen->get_data(
600
            FlatViewDataGenerator::FVDG_SORT_LASTNAME,
601
            0,
602
            null,
603
            $offset,
604
            $count,
605
            true,
606
            true
607
        );
608
609
        $result = [];
610
        foreach ($data_array as $data) {
611
            $result[] = array_slice($data, 1);
612
        }
613
        $return = [$header_names, $result];
614
615
        return $return;
616
    }
617
618
    /**
619
     * XML-parser: handle character data
620
     */
621
    public static function character_data($parser, $data)
0 ignored issues
show
Unused Code introduced by
The parameter $parser is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

621
    public static function character_data(/** @scrutinizer ignore-unused */ $parser, $data)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
622
    {
623
        global $current_value;
624
        $current_value = $data;
625
    }
626
627
    /**
628
     * XML-parser: handle end of element
629
     */
630
    public static function element_end($parser, $data)
631
    {
632
        global $user;
633
        global $users;
634
        global $current_value;
635
        switch ($data) {
636
            case 'Result':
637
                $users[] = $user;
638
                break;
639
            default:
640
                $user[$data] = $current_value;
641
                break;
642
        }
643
    }
644
645
    /**
646
     * XML-parser: handle start of element
647
     */
648
    public static function element_start($parser, $data)
649
    {
650
        global $user;
651
        global $current_tag;
652
        switch ($data) {
653
            case 'Result':
654
                $user = [];
655
                break;
656
            default:
657
                $current_tag = $data;
658
        }
659
    }
660
661
    public static function overwritescore($resid, $importscore, $eval_max)
662
    {
663
        $result = Result::load($resid);
664
        if ($importscore > $eval_max) {
665
            header('Location: gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'&overwritemax=');
666
            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...
667
        }
668
        $result[0]->set_score($importscore);
669
        $result[0]->save();
670
        unset($result);
671
    }
672
673
    /**
674
     * Read the XML-file
675
     * @param string $file Path to the XML-file
676
     * @return array All user information read from the file
677
     */
678
    public static function parse_xml_data($file)
679
    {
680
        global $current_tag;
681
        global $current_value;
682
        global $user;
683
        global $users;
684
        $users = [];
685
        $parser = xml_parser_create();
686
        xml_set_element_handler($parser, 'element_start', 'element_end');
687
        xml_set_character_data_handler($parser, "character_data");
688
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
689
        xml_parse($parser, file_get_contents($file));
690
        xml_parser_free($parser);
691
        return $users;
692
    }
693
694
    /**
695
     * register user info about certificate
696
     * @param int $cat_id The category id
697
     * @param int $user_id The user id
698
     * @param float $score_certificate The score obtained for certified
699
     * @param string $date_certificate The date when you obtained the certificate
700
     *
701
     * @return void
702
     */
703
    public static function registerUserInfoAboutCertificate(
704
        $cat_id,
705
        $user_id,
706
        $score_certificate,
707
        $date_certificate
708
    ) {
709
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
710
        $sql = 'SELECT COUNT(id) as count
711
                FROM ' . $table.' gc
712
                WHERE gc.cat_id="' . intval($cat_id).'" AND user_id="'.intval($user_id).'" ';
713
        $rs_exist = Database::query($sql);
714
        $row = Database::fetch_array($rs_exist);
715
        if ($row['count'] == 0) {
716
            $params = [
717
                'cat_id' => $cat_id,
718
                'user_id' => $user_id,
719
                'score_certificate' => $score_certificate,
720
                'created_at' => $date_certificate
721
            ];
722
            Database::insert($table, $params);
723
        }
724
    }
725
726
    /**
727
     * Get date of user certificate
728
     * @param int $cat_id The category id
729
     * @param int $user_id The user id
730
     * @return Datetime The date when you obtained the certificate
731
     */
732
    public static function get_certificate_by_user_id($cat_id, $user_id)
733
    {
734
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
735
        $sql = 'SELECT * FROM '.$table.'
736
                WHERE cat_id="' . intval($cat_id).'" AND user_id="'.intval($user_id).'"';
737
738
        $result = Database::query($sql);
739
        $row = Database::fetch_array($result, 'ASSOC');
740
741
        return $row;
742
    }
743
744
    /**
745
     * Get list of users certificates
746
     * @param int $cat_id The category id
747
     * @param array $userList Only users in this list
748
     * @return array
749
     */
750
    public static function get_list_users_certificates($cat_id = null, $userList = [])
751
    {
752
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
753
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
754
        $sql = 'SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username
755
                FROM ' . $table_user.' u
756
                INNER JOIN ' . $table_certificate.' gc
757
                ON u.user_id=gc.user_id ';
758
        if (!is_null($cat_id) && $cat_id > 0) {
759
            $sql .= ' WHERE cat_id='.intval($cat_id);
760
        }
761
        if (!empty($userList)) {
762
            $userList = array_map('intval', $userList);
763
            $userListCondition = implode("','", $userList);
764
            $sql .= " AND u.user_id IN ('$userListCondition')";
765
        }
766
        $sql .= ' ORDER BY u.firstname';
767
        $rs = Database::query($sql);
768
769
        $list_users = [];
770
        while ($row = Database::fetch_array($rs)) {
771
            $list_users[] = $row;
772
        }
773
774
        return $list_users;
775
    }
776
777
    /**
778
     * Gets the certificate list by user id
779
     * @param int $user_id The user id
780
     * @param int $cat_id The category id
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
        return $list_certificate;
807
    }
808
809
    /**
810
     * @param int $user_id
811
     * @param string $course_code
812
     * @param int $sessionId
813
     * @param bool $is_preview
814
     * @param bool $hide_print_button
815
     *
816
     * @return array
817
     */
818
    public static function get_user_certificate_content(
819
        $user_id,
820
        $course_code,
821
        $sessionId,
822
        $is_preview = false,
823
        $hide_print_button = false
824
    ) {
825
        // Generate document HTML
826
        $content_html = DocumentManager::replace_user_info_into_html(
827
            $user_id,
828
            $course_code,
829
            $sessionId,
830
            $is_preview
831
        );
832
833
        $new_content_html = isset($content_html['content']) ? $content_html['content'] : null;
834
        $variables = isset($content_html['variables']) ? $content_html['variables'] : null;
835
        $path_image = api_get_path(WEB_COURSE_PATH).api_get_course_path($course_code).'/document/images/gallery';
836
        $new_content_html = str_replace('../images/gallery', $path_image, $new_content_html);
837
838
        $path_image_in_default_course = api_get_path(WEB_CODE_PATH).'default_course_document';
839
        $new_content_html = str_replace('/main/default_course_document', $path_image_in_default_course, $new_content_html);
840
        $new_content_html = str_replace(SYS_CODE_PATH.'img/', api_get_path(WEB_IMG_PATH), $new_content_html);
841
842
        //add print header
843
        if (!$hide_print_button) {
844
            $print = '<style>#print_div {               
845
                padding:4px;border: 0 none;position: absolute;top: 0px;right: 0px;
846
            }            
847
            @media print {
848
                #print_div  {
849
                    display: none !important;
850
                }
851
            }
852
            </style>';
853
854
            $print .= Display::div(
855
                Display::url(
856
                    Display::return_icon('printmgr.gif', get_lang('Print')),
857
                    'javascript:void()',
858
                    ['onclick' => 'window.print();']
859
                ),
860
                ['id' => 'print_div']
861
            );
862
            $print .= '</html>';
863
            $new_content_html = str_replace('</html>', $print, $new_content_html);
864
        }
865
866
        return [
867
            'content' => $new_content_html,
868
            'variables' => $variables
869
        ];
870
    }
871
872
    /**
873
     * @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...
874
     * @param int $gradebook_model_id
875
     * @return mixed
876
     */
877
    public static function create_default_course_gradebook(
878
        $course_code = null,
879
        $gradebook_model_id = 0
880
    ) {
881
        if (api_is_allowed_to_edit(true, true)) {
882
            if (!isset($course_code) || empty($course_code)) {
883
                $course_code = api_get_course_id();
884
            }
885
            $session_id = api_get_session_id();
886
887
            $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
888
            $sql = "SELECT * FROM $t 
889
                    WHERE course_code = '".Database::escape_string($course_code)."' ";
890
            if (!empty($session_id)) {
891
                $sql .= " AND session_id = ".(int) $session_id;
892
            } else {
893
                $sql .= " AND (session_id IS NULL OR session_id = 0) ";
894
            }
895
            $sql .= " ORDER BY id";
896
            $res = Database::query($sql);
897
            if (Database::num_rows($res) < 1) {
898
                //there is no unique category for this course+session combination,
899
                $cat = new Category();
900
                if (!empty($session_id)) {
901
                    $my_session_id = api_get_session_id();
902
                    $s_name = api_get_session_name($my_session_id);
903
                    $cat->set_name($course_code.' - '.get_lang('Session').' '.$s_name);
904
                    $cat->set_session_id($session_id);
905
                } else {
906
                    $cat->set_name($course_code);
907
                }
908
                $cat->set_course_code($course_code);
909
                $cat->set_description(null);
910
                $cat->set_user_id(api_get_user_id());
911
                $cat->set_parent_id(0);
912
                $default_weight_setting = api_get_setting('gradebook_default_weight');
913
                $default_weight = isset($default_weight_setting) && !empty($default_weight_setting) ? $default_weight_setting : 100;
914
                $cat->set_weight($default_weight);
915
                $cat->set_grade_model_id($gradebook_model_id);
916
                $cat->set_certificate_min_score(75);
917
918
                $cat->set_visible(0);
919
                $cat->add();
920
                $category_id = $cat->get_id();
921
                unset($cat);
922
            } else {
923
                $row = Database::fetch_array($res);
924
                $category_id = $row['id'];
925
            }
926
927
            return $category_id;
928
        }
929
930
        return false;
931
    }
932
933
    /**
934
     * @param FormValidator $form
935
     */
936
    public static function load_gradebook_select_in_tool($form)
937
    {
938
        $course_code = api_get_course_id();
939
        $session_id = api_get_session_id();
940
941
        self::create_default_course_gradebook();
942
943
        // Cat list
944
        $all_categories = Category::load(
945
            null,
946
            null,
947
            $course_code,
948
            null,
949
            null,
950
            $session_id,
951
            false
952
        );
953
        $select_gradebook = $form->addElement(
954
            'select',
955
            'category_id',
956
            get_lang('SelectGradebook')
957
        );
958
959
        if (!empty($all_categories)) {
960
            foreach ($all_categories as $my_cat) {
961
                if ($my_cat->get_course_code() == api_get_course_id()) {
962
                    $grade_model_id = $my_cat->get_grade_model_id();
963
                    if (empty($grade_model_id)) {
964
                        if ($my_cat->get_parent_id() == 0) {
965
                            //$default_weight = $my_cat->get_weight();
966
                            $select_gradebook->addoption(get_lang('Default'), $my_cat->get_id());
0 ignored issues
show
Bug introduced by
The method addoption() does not exist on HTML_QuickForm_element. It seems like you code against a sub-type of HTML_QuickForm_element such as HTML_QuickForm_select. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

966
                            $select_gradebook->/** @scrutinizer ignore-call */ 
967
                                               addoption(get_lang('Default'), $my_cat->get_id());
Loading history...
967
                            $cats_added[] = $my_cat->get_id();
968
                        } else {
969
                            $select_gradebook->addoption($my_cat->get_name(), $my_cat->get_id());
970
                            $cats_added[] = $my_cat->get_id();
971
                        }
972
                    } else {
973
                        $select_gradebook->addoption(get_lang('Select'), 0);
974
                    }
975
                }
976
            }
977
        }
978
    }
979
980
    /**
981
     * @param FlatViewTable $flatviewtable
982
     * @param Category $cat
983
     * @param $users
984
     * @param $alleval
985
     * @param $alllinks
986
     * @param array $params
987
     * @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...
988
     */
989
    public static function export_pdf_flatview(
990
        $flatviewtable,
991
        $cat,
992
        $users,
993
        $alleval,
994
        $alllinks,
995
        $params = [],
996
        $mainCourseCategory = null
997
    ) {
998
        // Getting data
999
        $printable_data = self::get_printable_data(
1000
            $cat[0],
1001
            $users,
1002
            $alleval,
1003
            $alllinks,
1004
            $params,
1005
            $mainCourseCategory
1006
        );
1007
1008
        // HTML report creation first
1009
        $course_code = trim($cat[0]->get_course_code());
1010
1011
        $displayscore = ScoreDisplay::instance();
1012
        $customDisplays = $displayscore->get_custom_score_display_settings();
1013
1014
        $total = [];
1015
        if (is_array($customDisplays) && count(($customDisplays))) {
1016
            foreach ($customDisplays as $custom) {
1017
                $total[$custom['display']] = 0;
1018
            }
1019
            $user_results = $flatviewtable->datagen->get_data_to_graph2(false);
1020
            foreach ($user_results as $user_result) {
1021
                $item = $user_result[count($user_result) - 1];
1022
                $customTag = isset($item[1]) ? strip_tags($item[1]) : '';
1023
                $total[$customTag]++;
1024
            }
1025
        }
1026
1027
        $parent_id = $cat[0]->get_parent_id();
1028
        if (isset($cat[0]) && isset($parent_id)) {
1029
            if ($parent_id == 0) {
1030
                $grade_model_id = $cat[0]->get_grade_model_id();
1031
            } else {
1032
                $parent_cat = Category::load($parent_id);
1033
                $grade_model_id = $parent_cat[0]->get_grade_model_id();
1034
            }
1035
        }
1036
1037
        $use_grade_model = true;
1038
        if (empty($grade_model_id) || $grade_model_id == -1) {
1039
            $use_grade_model = false;
1040
        }
1041
1042
        if ($use_grade_model) {
1043
            if ($parent_id == 0) {
1044
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1045
            } else {
1046
                $title = api_strtoupper(get_lang('Average')).'<br />'.$cat[0]->get_description().' - ('.$cat[0]->get_name().')';
1047
            }
1048
        } else {
1049
            if ($parent_id == 0) {
1050
                $title = api_strtoupper(get_lang('Average')).'<br />'.get_lang('Detailed');
1051
            } else {
1052
                $title = api_strtoupper(get_lang('Average'));
1053
            }
1054
        }
1055
1056
        $columns = count($printable_data[0]);
1057
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
1058
1059
        $table = new HTML_Table(['class' => 'data_table']);
1060
        $row = 0;
1061
        $column = 0;
1062
        $table->setHeaderContents($row, $column, get_lang('NumberAbbreviation'));
1063
        $column++;
1064
        foreach ($printable_data[0] as $printable_data_cell) {
1065
            if (!is_array($printable_data_cell)) {
1066
                $printable_data_cell = strip_tags($printable_data_cell);
1067
            }
1068
            $table->setHeaderContents($row, $column, $printable_data_cell);
1069
            $column++;
1070
        }
1071
        $row++;
1072
1073
        if ($has_data) {
1074
            $counter = 1;
1075
            foreach ($printable_data[1] as &$printable_data_row) {
1076
                $column = 0;
1077
                $table->setCellContents($row, $column, $counter);
1078
                $table->updateCellAttributes($row, $column, 'align="center"');
1079
                $column++;
1080
                $counter++;
1081
1082
                foreach ($printable_data_row as $key => &$printable_data_cell) {
1083
                    $attributes = [];
1084
                    $attributes['align'] = 'center';
1085
                    $attributes['style'] = null;
1086
1087
                    if ($key === 'name') {
1088
                        $attributes['align'] = 'left';
1089
                    }
1090
                    if ($key === 'total') {
1091
                        $attributes['style'] = 'font-weight:bold';
1092
                    }
1093
                    $table->setCellContents($row, $column, $printable_data_cell);
1094
                    $table->updateCellAttributes($row, $column, $attributes);
1095
                    $column++;
1096
                }
1097
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
1098
                $row++;
1099
            }
1100
        } else {
1101
            $column = 0;
1102
            $table->setCellContents($row, $column, get_lang('NoResults'));
1103
            $table->updateCellAttributes($row, $column, 'colspan="'.$columns.'" align="center" class="row_odd"');
1104
        }
1105
1106
        $pdfParams = [
1107
            'filename' => get_lang('FlatView').'_'.api_get_local_time(),
1108
            'pdf_title' => $title,
1109
            'course_code' => $course_code,
1110
            'add_signatures' => ['Drh', 'Teacher', 'Date']
1111
        ];
1112
1113
        $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
1114
        ob_start();
1115
        $pdf = new PDF($page_format, $page_format, $pdfParams);
1116
        $pdf->html_to_pdf_with_template($flatviewtable->return_table());
1117
        $content = ob_get_contents();
1118
        ob_end_clean();
1119
        echo $content;
1120
        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...
1121
    }
1122
1123
    /**
1124
     * @param string[] $list_values
1125
     * @return string
1126
     */
1127
    public static function score_badges($list_values)
1128
    {
1129
        $counter = 1;
1130
        $badges = [];
1131
        foreach ($list_values as $value) {
1132
            $class = 'warning';
1133
            if ($counter == 1) {
1134
                $class = 'success';
1135
            }
1136
            $counter++;
1137
            $badges[] = Display::badge($value, $class);
1138
        }
1139
1140
        return Display::badge_group($badges);
1141
    }
1142
1143
    /**
1144
     * returns users within a course given by param
1145
     * @param string $courseCode
1146
     * @return array
1147
     */
1148
    public static function get_users_in_course($courseCode)
1149
    {
1150
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1151
        $tbl_session_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1152
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1153
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
1154
1155
        $current_session = api_get_session_id();
1156
        $courseCode = Database::escape_string($courseCode);
1157
        $courseInfo = api_get_course_info($courseCode);
1158
        $courseId = $courseInfo['real_id'];
1159
1160
        if (!empty($current_session)) {
1161
            $sql = "SELECT user.user_id, user.username, lastname, firstname, official_code
1162
                    FROM $tbl_session_course_user as scru 
1163
                    INNER JOIN $tbl_user as user
1164
                    ON (scru.user_id = user.user_id)
1165
                    WHERE                        
1166
                        scru.status = 0 AND
1167
                        scru.c_id='$courseId' AND
1168
                        session_id ='$current_session'
1169
                    $order_clause
1170
                    ";
1171
        } else {
1172
            $sql = 'SELECT user.user_id, user.username, lastname, firstname, official_code
1173
                    FROM '.$tbl_course_user.' as course_rel_user 
1174
                    INNER JOIN '.$tbl_user.' as user
1175
                    ON (course_rel_user.user_id=user.user_id)
1176
                    WHERE
1177
                        course_rel_user.status = '.STUDENT.' AND
1178
                        course_rel_user.c_id = "'.$courseId.'" '.
1179
                    $order_clause;
1180
        }
1181
1182
        $result = Database::query($sql);
1183
1184
        return self::get_user_array_from_sql_result($result);
1185
    }
1186
1187
    /**
1188
     * @param Doctrine\DBAL\Driver\Statement|null $result
1189
     * @return array
1190
     */
1191
    public static function get_user_array_from_sql_result($result)
1192
    {
1193
        $a_students = [];
1194
        while ($user = Database::fetch_array($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type null; however, parameter $result of Database::fetch_array() does only seem to accept Doctrine\DBAL\Driver\Statement, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1194
        while ($user = Database::fetch_array(/** @scrutinizer ignore-type */ $result)) {
Loading history...
1195
            if (!array_key_exists($user['user_id'], $a_students)) {
1196
                $a_current_student = [];
1197
                $a_current_student[] = $user['user_id'];
1198
                $a_current_student[] = $user['username'];
1199
                $a_current_student[] = $user['lastname'];
1200
                $a_current_student[] = $user['firstname'];
1201
                $a_current_student[] = $user['official_code'];
1202
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1203
            }
1204
        }
1205
        return $a_students;
1206
    }
1207
1208
    /**
1209
     * @param array $evals
1210
     * @param array $links
1211
     * @return array
1212
     */
1213
    public static function get_all_users($evals = [], $links = [])
1214
    {
1215
        $coursecodes = [];
1216
        // By default add all user in course
1217
        $coursecodes[api_get_course_id()] = '1';
1218
        $users = self::get_users_in_course(api_get_course_id());
1219
1220
        foreach ($evals as $eval) {
1221
            $coursecode = $eval->get_course_code();
1222
            // evaluation in course
1223
            if (isset($coursecode) && !empty($coursecode)) {
1224
                if (!array_key_exists($coursecode, $coursecodes)) {
1225
                    $coursecodes[$coursecode] = '1';
1226
                    $users = array_merge($users, self::get_users_in_course($coursecode));
1227
                }
1228
            } else {
1229
                // course independent evaluation
1230
                $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1231
                $tbl_res = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1232
1233
                $sql = 'SELECT user.user_id, lastname, firstname, user.official_code
1234
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1235
                        WHERE
1236
                            res.evaluation_id = '.intval($eval->get_id()).' AND
1237
                            res.user_id = user.user_id
1238
                        ';
1239
                $sql .= ' ORDER BY lastname, firstname';
1240
                if (api_is_western_name_order()) {
1241
                    $sql .= ' ORDER BY firstname, lastname';
1242
                }
1243
1244
                $result = Database::query($sql);
1245
                $users = array_merge(
1246
                    $users,
1247
                    self::get_user_array_from_sql_result($result)
1248
                );
1249
            }
1250
        }
1251
1252
        foreach ($links as $link) {
1253
            // links are always in a course
1254
            $coursecode = $link->get_course_code();
1255
            if (!array_key_exists($coursecode, $coursecodes)) {
1256
                $coursecodes[$coursecode] = '1';
1257
                $users = array_merge(
1258
                    $users,
1259
                    self::get_users_in_course($coursecode)
1260
                );
1261
            }
1262
        }
1263
1264
        return $users;
1265
    }
1266
1267
    /**
1268
     * Search students matching a given last name and/or first name
1269
     * @author Bert Steppé
1270
     */
1271
    public static function find_students($mask = '')
1272
    {
1273
        // students shouldn't be here // don't search if mask empty
1274
        if (!api_is_allowed_to_edit() || empty($mask)) {
1275
            return null;
1276
        }
1277
        $mask = Database::escape_string($mask);
1278
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1279
        $tbl_cru = Database::get_main_table(TABLE_MAIN_COURSE_USER);
1280
        $sql = 'SELECT DISTINCT user.user_id, user.lastname, user.firstname, user.email, user.official_code
1281
                FROM ' . $tbl_user.' user';
1282
        if (!api_is_platform_admin()) {
1283
            $sql .= ', '.$tbl_cru.' cru';
1284
        }
1285
1286
        $sql .= ' WHERE user.status = '.STUDENT;
1287
        $sql .= ' AND (user.lastname LIKE '."'%".$mask."%'";
1288
        $sql .= ' OR user.firstname LIKE '."'%".$mask."%')";
1289
1290
        if (!api_is_platform_admin()) {
1291
            $sql .= ' AND user.user_id = cru.user_id AND
1292
                      cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' AND
1293
                      cru.c_id in (
1294
                            SELECT c_id FROM '.$tbl_cru.'
1295
                            WHERE
1296
                                user_id = ' . api_get_user_id().' AND
1297
                                status = ' . COURSEMANAGER.'
1298
                        )
1299
                    ';
1300
        }
1301
1302
        $sql .= ' ORDER BY lastname, firstname';
1303
        if (api_is_western_name_order()) {
1304
            $sql .= ' ORDER BY firstname, lastname';
1305
        }
1306
1307
        $result = Database::query($sql);
1308
        $users = Database::store_result($result);
1309
1310
        return $users;
1311
    }
1312
1313
    /**
1314
     * @param int $linkId
1315
     * @param float $weight
1316
     */
1317
    public static function updateLinkWeight($linkId, $name, $weight)
1318
    {
1319
        $linkId = intval($linkId);
1320
        $weight = api_float_val($weight);
1321
        $course_id = api_get_course_int_id();
1322
1323
        AbstractLink::add_link_log($linkId, $name);
1324
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1325
1326
        $em = Database::getManager();
1327
        $tbl_forum_thread = Database::get_course_table(TABLE_FORUM_THREAD);
1328
        $tbl_attendance = Database::get_course_table(TABLE_ATTENDANCE);
1329
1330
        $sql = 'UPDATE '.$table_link.' 
1331
                SET weight = '."'".Database::escape_string($weight)."'".'
1332
                WHERE id = '.$linkId;
1333
1334
        Database::query($sql);
1335
1336
        // Update weight for attendance
1337
        $sql = 'SELECT ref_id FROM '.$table_link.'
1338
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1339
1340
        $rs_attendance = Database::query($sql);
1341
        if (Database::num_rows($rs_attendance) > 0) {
1342
            $row_attendance = Database::fetch_array($rs_attendance);
1343
            $sql = 'UPDATE '.$tbl_attendance.' SET 
1344
                    attendance_weight ='.api_float_val($weight).'
1345
                    WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
1346
            Database::query($sql);
1347
        }
1348
        // Update weight into forum thread
1349
        $sql = 'UPDATE '.$tbl_forum_thread.' SET 
1350
                thread_weight = '.api_float_val($weight).'
1351
                WHERE
1352
                    c_id = '.$course_id.' AND
1353
                    thread_id = (
1354
                        SELECT ref_id FROM '.$table_link.'
1355
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1356
                    )
1357
                ';
1358
        Database::query($sql);
1359
        //Update weight into student publication(work)
1360
        $em
1361
            ->createQuery('
1362
                UPDATE ChamiloCourseBundle:CStudentPublication w
1363
                SET w.weight = :final_weight
1364
                WHERE w.cId = :course
1365
                    AND w.id = (
1366
                        SELECT l.refId FROM ChamiloCoreBundle:GradebookLink l
1367
                        WHERE l.id = :link AND l.type = :type
1368
                    )
1369
            ')
1370
            ->execute([
1371
                'final_weight' => $weight,
1372
                'course' => $course_id,
1373
                'link' => $linkId,
1374
                'type' => LINK_STUDENTPUBLICATION
1375
            ]);
1376
    }
1377
1378
    /**
1379
     * @param int $id
1380
     * @param float $weight
1381
     */
1382
    public static function updateEvaluationWeight($id, $weight)
1383
    {
1384
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1385
        $id = intval($id);
1386
        $evaluation = new Evaluation();
1387
        $evaluation->addEvaluationLog($id);
1388
        $sql = 'UPDATE '.$table_evaluation.'
1389
               SET weight = '."'".Database::escape_string($weight)."'".'
1390
               WHERE id = '.$id;
1391
        Database::query($sql);
1392
    }
1393
1394
    /**
1395
     *
1396
     * Get the achieved certificates for a user in courses
1397
     * @param int $userId The user id
1398
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1399
     * @return array
1400
     */
1401
    public static function getUserCertificatesInCourses(
1402
        $userId,
1403
        $includeNonPublicCertificates = true
1404
    ) {
1405
        $userId = intval($userId);
1406
        $courseList = [];
1407
        $courses = CourseManager::get_courses_list_by_user_id($userId);
1408
1409
        foreach ($courses as $course) {
1410
            if (!$includeNonPublicCertificates) {
1411
                $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course['code']);
1412
1413
                if (empty($allowPublicCertificates)) {
1414
                    continue;
1415
                }
1416
            }
1417
1418
            $category = Category::load(null, null, $course['code']);
1419
1420
            if (empty($category)) {
1421
                continue;
1422
            }
1423
1424
            if (!isset($category[0])) {
1425
                continue;
1426
            }
1427
            /** @var Category $category */
1428
            $category = $category[0];
1429
1430
            if (empty($category->getGenerateCertificates())) {
1431
                continue;
1432
            }
1433
1434
            $categoryId = $category->get_id();
1435
            $certificateInfo = self::get_certificate_by_user_id($categoryId, $userId);
1436
1437
            if (empty($certificateInfo)) {
1438
                continue;
1439
            }
1440
1441
            $courseInfo = api_get_course_info_by_id($course['real_id']);
1442
            if (empty($courseInfo)) {
1443
                continue;
1444
            }
1445
1446
            $courseList[] = [
1447
                'course' => $courseInfo['title'],
1448
                'score' => $certificateInfo['score_certificate'],
1449
                'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1450
                'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}"
1451
            ];
1452
        }
1453
1454
        return $courseList;
1455
    }
1456
1457
    /**
1458
     * Get the achieved certificates for a user in course sessions
1459
     * @param int $userId The user id
1460
     * @param bool $includeNonPublicCertificates Whether include the non-public certificates
1461
     * @return array
1462
     */
1463
    public static function getUserCertificatesInSessions($userId, $includeNonPublicCertificates = true)
1464
    {
1465
        $userId = intval($userId);
1466
        $sessionList = [];
1467
        $sessions = SessionManager::get_sessions_by_user($userId, true, true);
1468
1469
        foreach ($sessions as $session) {
1470
            if (empty($session['courses'])) {
1471
                continue;
1472
            }
1473
            $sessionCourses = SessionManager::get_course_list_by_session_id($session['session_id']);
1474
1475
            if (empty($sessionCourses)) {
1476
                continue;
1477
            }
1478
1479
            foreach ($sessionCourses as $course) {
1480
                if (!$includeNonPublicCertificates) {
1481
                    $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course['code']);
1482
1483
                    if (empty($allowPublicCertificates)) {
1484
                        continue;
1485
                    }
1486
                }
1487
1488
                $category = Category::load(
1489
                    null,
1490
                    null,
1491
                    $course['code'],
1492
                    null,
1493
                    null,
1494
                    $session['session_id']
1495
                );
1496
1497
                if (empty($category)) {
1498
                    continue;
1499
                }
1500
1501
                if (!isset($category[0])) {
1502
                    continue;
1503
                }
1504
1505
                /** @var Category $category */
1506
                $category = $category[0];
1507
1508
                // Don't allow generate of certifications
1509
                if (empty($category->getGenerateCertificates())) {
1510
                    continue;
1511
                }
1512
1513
                $categoryId = $category->get_id();
1514
                $certificateInfo = self::get_certificate_by_user_id(
1515
                    $categoryId,
1516
                    $userId
1517
                );
1518
1519
                if (empty($certificateInfo)) {
1520
                    continue;
1521
                }
1522
1523
                $sessionList[] = [
1524
                    'session' => $session['session_name'],
1525
                    'course' => $course['title'],
1526
                    'score' => $certificateInfo['score_certificate'],
1527
                    'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1528
                    'link' => api_get_path(WEB_PATH)."certificates/index.php?id={$certificateInfo['id']}"
1529
                ];
1530
            }
1531
        }
1532
1533
        return $sessionList;
1534
    }
1535
1536
    /**
1537
     * @param int $userId
1538
     * @param array $cats
1539
     * @param bool $saveToFile
1540
     * @param bool $saveToHtmlFile
1541
     * @param array $studentList
1542
     * @param PDF $pdf
1543
     *
1544
     * @return string
1545
     */
1546
    public static function generateTable(
1547
        $userId,
1548
        $cats,
1549
        $saveToFile = false,
1550
        $saveToHtmlFile = false,
1551
        $studentList = [],
1552
        $pdf = null
1553
    ) {
1554
        $courseInfo = api_get_course_info();
1555
        $userInfo = api_get_user_info($userId);
1556
1557
        $cat = $cats[0];
1558
1559
        $allcat = $cats[0]->get_subcategories(
1560
            $userId,
1561
            api_get_course_id(),
1562
            api_get_session_id()
1563
        );
1564
        $alleval = $cats[0]->get_evaluations($userId);
1565
        $alllink = $cats[0]->get_links($userId);
1566
1567
        $gradebooktable = new GradebookTable(
1568
            $cat,
1569
            $allcat,
1570
            $alleval,
1571
            $alllink,
1572
            null, // params
1573
            true, // $exportToPdf
1574
            false, // showteacher
1575
            $userId,
1576
            $studentList
1577
        );
1578
1579
        $gradebooktable->userId = $userId;
1580
1581
        if (api_is_allowed_to_edit()) {
1582
            $gradebooktable->td_attributes = [
1583
                4 => 'class=centered'
1584
            ];
1585
        } else {
1586
            $gradebooktable->td_attributes = [
1587
                3 => 'class=centered',
1588
                4 => 'class=centered',
1589
                5 => 'class=centered',
1590
                6 => 'class=centered',
1591
                7 => 'class=centered'
1592
            ];
1593
        }
1594
1595
        $table = $gradebooktable->return_table();
1596
        $graph = $gradebooktable->getGraph();
1597
1598
        $params = [
1599
            'pdf_title' => sprintf(get_lang('GradeFromX'), $courseInfo['name']),
1600
            'session_info' => '',
1601
            'course_info' => '',
1602
            'pdf_date' => '',
1603
            'course_code' => api_get_course_id(),
1604
            'student_info' => $userInfo,
1605
            'show_grade_generated_date' => true,
1606
            'show_real_course_teachers' => false,
1607
            'show_teacher_as_myself' => false,
1608
            'orientation' => 'P'
1609
        ];
1610
1611
        if (empty($pdf)) {
1612
            $pdf = new PDF('A4', $params['orientation'], $params);
1613
        }
1614
1615
        $pdf->params['student_info'] = $userInfo;
1616
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid().'.html';
1617
1618
        $content =
1619
            $table.
1620
            $graph.
1621
            '<br />'.get_lang('Feedback').'<br />
1622
            <textarea rows="5" cols="100" ></textarea>';
1623
1624
        $result = $pdf->html_to_pdf_with_template(
1625
            $content,
1626
            $saveToFile,
1627
            $saveToHtmlFile
1628
        );
1629
1630
        if ($saveToHtmlFile) {
1631
            file_put_contents($file, $result);
1632
            return $file;
1633
        }
1634
1635
        return $file;
1636
    }
1637
}
1638