Completed
Push — master ( 3341ad...76c133 )
by Julito
33:01
created

GradebookUtils::element_start()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 2
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
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
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
     */
76
    public static function updateResourceFromCourseGradebook($link_id, $courseId, $weight)
77
    {
78
        $courseId = (int) $courseId;
79
        if (!empty($link_id)) {
80
            $link_id = intval($link_id);
81
            $sql = 'UPDATE ' . Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK) . '
82
                    SET weight = ' . "'" . Database::escape_string((float) $weight) . "'" . '
83
                    WHERE c_id = "' . $courseId . '" AND id = ' . $link_id;
84
            Database::query($sql);
85
        }
86
87
        return true;
88
    }
89
90
    /**
91
     * Remove a resource from the unique gradebook of a given course
92
     * @param    int     Link/Resource ID
93
     * @return   bool    false on error, true on success
94
     */
95 View Code Duplication
    public static function remove_resource_from_course_gradebook($link_id)
96
    {
97
        if (empty($link_id)) {
98
            return false;
99
        }
100
101
        // TODO find the corresponding category (the first one for this course, ordered by ID)
102
        $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
103
        $sql = "DELETE FROM $l WHERE id = ".(int)$link_id;
104
        Database::query($sql);
105
106
        return true;
107
    }
108
109
    /**
110
     * Block students
111
     */
112
    public static function block_students()
113
    {
114
        if (!api_is_allowed_to_edit()) {
115
            api_not_allowed();
116
        }
117
    }
118
119
    /**
120
     * Builds an img tag for a gradebook item
121
     */
122
    public static function build_type_icon_tag($kind, $attributes = array())
123
    {
124
        return Display::return_icon(self::get_icon_file_name($kind), ' ', $attributes, ICON_SIZE_SMALL);
125
    }
126
127
    /**
128
     * Returns the icon filename for a gradebook item
129
     * @param string $type value returned by a gradebookitem's get_icon_name()
130
     */
131
    public static function get_icon_file_name($type)
132
    {
133
        switch ($type) {
134
            case 'cat':
135
                $icon = 'gradebook.png';
136
                break;
137
            case 'evalempty':
138
                $icon = 'empty_evaluation.png';
139
                break;
140
            case 'evalnotempty':
141
                $icon = 'no_empty_evaluation.png';
142
                break;
143
            case 'exercise':
144
            case LINK_EXERCISE:
145
                $icon = 'quiz.gif';
146
                break;
147
            case 'learnpath':
148
            case LINK_LEARNPATH:
149
                $icon = 'learnpath.png';
150
                break;
151
            case 'studentpublication':
152
            case LINK_STUDENTPUBLICATION:
153
                $icon = 'works.gif';
154
                break;
155
            case 'link':
156
                $icon = 'link.gif';
157
                break;
158
            case 'forum':
159
            case LINK_FORUM_THREAD:
160
                $icon = 'forum.gif';
161
                break;
162
            case 'attendance':
163
            case LINK_ATTENDANCE:
164
                $icon = 'attendance.gif';
165
                break;
166
            case 'survey':
167
            case LINK_SURVEY:
168
                $icon = 'survey.gif';
169
                break;
170
            case 'dropbox':
171
            case LINK_DROPBOX:
172
                $icon = 'dropbox.gif';
173
                break;
174
            default:
175
                $icon = 'link.gif';
176
                break;
177
        }
178
179
        return $icon;
180
    }
181
182
    /**
183
     * Builds the course or platform admin icons to edit a category
184
     * @param Category $cat category
185
     * @param Category $selectcat id of selected category
186
     */
187
    public static function build_edit_icons_cat($cat, $selectcat)
188
    {
189
        $show_message = $cat->show_message_resource_delete($cat->get_course_code());
190
        $grade_model_id = $selectcat->get_grade_model_id();
191
        $selectcat = $selectcat->get_id();
192
        $modify_icons = null;
193
194
        if ($show_message === false) {
195
            $visibility_icon = ($cat->is_visible() == 0) ? 'invisible' : 'visible';
196
            $visibility_command = ($cat->is_visible() == 0) ? 'set_visible' : 'set_invisible';
197
198
            $modify_icons .= '<a class="view_children" data-cat-id="' . $cat->get_id() . '" href="javascript:void(0);">' .
199
                Display::return_icon('view_more_stats.gif', get_lang('Show'), '', ICON_SIZE_SMALL) . '</a>';
200
201
            if (!api_is_allowed_to_edit(null, true)) {
202
                $modify_icons .= Display::url(
203
                    Display::return_icon(
204
                        'stats.png',
205
                        get_lang('FlatView'),
206
                        '',
207
                        ICON_SIZE_SMALL
208
                    ),
209
                    'personal_stats.php?' . http_build_query([
210
                        'selectcat' => $cat->get_id()
211
                    ]) . '&' . api_get_cidreq(),
212
                    [
213
                        'class' => 'ajax',
214
                        'data-title' => get_lang('FlatView')
215
                    ]
216
                );
217
            }
218
219
            $courseParams = api_get_cidreq_params($cat->get_course_code(), $cat->get_session_id());
220
221
            if (api_is_allowed_to_edit(null, true)) {
222
                // Locking button
223
                if (api_get_setting('gradebook_locking_enabled') == 'true') {
224
                    if ($cat->is_locked()) {
225 View Code Duplication
                        if (api_is_platform_admin()) {
226
                            $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">' .
227
                                Display::return_icon('lock.png', get_lang('UnLockEvaluation'), '', ICON_SIZE_SMALL) . '</a>';
228
                        } else {
229
                            $modify_icons .= '&nbsp;<a href="#">' . Display::return_icon('lock_na.png', get_lang('GradebookLockedAlert'), '', ICON_SIZE_SMALL) . '</a>';
230
                        }
231
                        $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>';
232 View Code Duplication
                    } else {
233
                        $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">' .
234
                            Display::return_icon('unlock.png', get_lang('LockEvaluation'), '', ICON_SIZE_SMALL) . '</a>';
235
                        $modify_icons .= '&nbsp;<a href="#" >' . Display::return_icon('pdf_na.png', get_lang('ExportToPDF'), '', ICON_SIZE_SMALL) . '</a>';
236
                    }
237
                }
238
239
                if (empty($grade_model_id) || $grade_model_id == -1) {
240
                    if ($cat->is_locked() && !api_is_platform_admin()) {
241
                        $modify_icons .= Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
242
                    } else {
243
                        $modify_icons .= '<a href="gradebook_edit_cat.php?editcat=' . $cat->get_id() . '&'.$courseParams.'">' .
244
                            Display::return_icon(
245
                                'edit.png',
246
                                get_lang('Modify'),
247
                                '',
248
                                ICON_SIZE_SMALL
249
                            ) . '</a>';
250
                    }
251
                }
252
253
               $modify_icons .= '<a href="gradebook_edit_all.php?selectcat=' .$cat->get_id() . '&' . $courseParams.'">' .
254
                    Display::return_icon(
255
                        'percentage.png',
256
                        get_lang('EditAllWeights'),
257
                        '',
258
                        ICON_SIZE_SMALL
259
                    ) . '</a>';
260
261
                $modify_icons .= '<a href="gradebook_flatview.php?selectcat=' .$cat->get_id() . '&' . $courseParams. '">' .
262
                    Display::return_icon(
263
                        'stats.png',
264
                        get_lang('FlatView'),
265
                        '',
266
                        ICON_SIZE_SMALL
267
                    ) . '</a>';
268
                $modify_icons .= '&nbsp;<a href="' . api_get_self() .'?visiblecat=' . $cat->get_id() . '&' .$visibility_command . '=&selectcat=' . $selectcat .'&' . $courseParams. '">' .
269
                    Display::return_icon(
270
                        $visibility_icon . '.png',
271
                        get_lang('Visible'),
272
                        '',
273
                        ICON_SIZE_SMALL
274
                    ) . '</a>';
275
276
                if ($cat->is_locked() && !api_is_platform_admin()) {
277
                    $modify_icons .= Display::return_icon('delete_na.png', get_lang('DeleteAll'), '', ICON_SIZE_SMALL);
278
                } else {
279
                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletecat=' . $cat->get_id() . '&selectcat=' . $selectcat . '&' . $courseParams. '" onclick="return confirmation();">' .
280
                        Display::return_icon('delete.png', get_lang('DeleteAll'), '', ICON_SIZE_SMALL) . '</a>';
281
                }
282
            }
283
284
            return $modify_icons;
285
        }
286
    }
287
288
    /**
289
     * Builds the course or platform admin icons to edit an evaluation
290
     * @param  Evaluation $eval evaluation object
291
     * @param int $selectcat id of selected category
292
     */
293 View Code Duplication
    public static function build_edit_icons_eval($eval, $selectcat)
294
    {
295
        $is_locked = $eval->is_locked();
296
        $eval->get_course_code();
0 ignored issues
show
Unused Code introduced by
The call to the method Evaluation::get_course_code() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
297
        $cat = new Category();
298
        $message_eval = $cat->show_message_resource_delete($eval->get_course_code());
299
        $courseParams = api_get_cidreq_params($eval->get_course_code(), $eval->getSessionId());
300
301
        if ($message_eval === false && api_is_allowed_to_edit(null, true)) {
302
            $visibility_icon = ($eval->is_visible() == 0) ? 'invisible' : 'visible';
303
            $visibility_command = ($eval->is_visible() == 0) ? 'set_visible' : 'set_invisible';
304
            if ($is_locked && !api_is_platform_admin()) {
305
                $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
306
            } else {
307
                $modify_icons = '<a href="gradebook_edit_eval.php?editeval=' . $eval->get_id() . '&' . $courseParams. '">' .
308
                    Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
309
            }
310
311
            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visibleeval=' . $eval->get_id() . '&' . $visibility_command . '=&selectcat=' . $selectcat . '&'.$courseParams. ' ">' .
312
                Display::return_icon($visibility_icon . '.png', get_lang('Visible'), '', ICON_SIZE_SMALL) . '</a>';
313
            if (api_is_allowed_to_edit(null, true)) {
314
                $modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog=' . $eval->get_id() . '&selectcat=' . $selectcat . ' &' . $courseParams. '">' .
315
                    Display::return_icon('history.png', get_lang('GradebookQualifyLog'), '', ICON_SIZE_SMALL) . '</a>';
316
            }
317
318
            if ($is_locked && !api_is_platform_admin()) {
319
                $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
320
            } else {
321
                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deleteeval=' . $eval->get_id() . '&selectcat=' . $selectcat . ' &' . $courseParams. '" onclick="return confirmation();">' .
322
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
323
            }
324
            return $modify_icons;
325
        }
326
    }
327
328
    /**
329
     * Builds the course or platform admin icons to edit a link
330
     * @param AbstractLink $link
331
     * @param int $selectcat id of selected category
332
     */
333 View Code Duplication
    public static function build_edit_icons_link($link, $selectcat)
334
    {
335
        $cat = new Category();
336
        $message_link = $cat->show_message_resource_delete($link->get_course_code());
337
        $is_locked = $link->is_locked();
338
339
        $modify_icons = null;
340
341
        if (!api_is_allowed_to_edit(null, true)) {
342
            return null;
343
        }
344
345
        $courseParams = api_get_cidreq_params($link->get_course_code(), $link->get_session_id());
346
347
        if ($message_link === false) {
348
            $visibility_icon = ($link->is_visible() == 0) ? 'invisible' : 'visible';
349
            $visibility_command = ($link->is_visible() == 0) ? 'set_visible' : 'set_invisible';
350
351
            if ($is_locked && !api_is_platform_admin()) {
352
                $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
353
            } else {
354
                $modify_icons = '<a href="gradebook_edit_link.php?editlink=' . $link->get_id() . '&' . $courseParams.'">' .
355
                    Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
356
            }
357
            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visiblelink=' . $link->get_id() . '&' . $visibility_command . '=&selectcat=' . $selectcat . '&'.$courseParams. ' ">' .
358
                Display::return_icon($visibility_icon . '.png', get_lang('Visible'), '', ICON_SIZE_SMALL) . '</a>';
359
            $modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink=' . $link->get_id() . '&selectcat=' . $selectcat . '&' . $courseParams. '">' .
360
                Display::return_icon('history.png', get_lang('GradebookQualifyLog'), '', ICON_SIZE_SMALL) . '</a>';
361
362
            //If a work is added in a gradebook you can only delete the link in the work tool
363
364
            if ($is_locked && !api_is_platform_admin()) {
365
                $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
366
            } else {
367
                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletelink=' . $link->get_id() . '&selectcat=' . $selectcat . ' &' . $courseParams. '" onclick="return confirmation();">' .
368
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
369
            }
370
371
            return $modify_icons;
372
        }
373
    }
374
375
    /**
376
     * Checks if a resource is in the unique gradebook of a given course
377
     * @param    int $courseId
378
     * @param    int     $resource_type Resource type (use constants defined in linkfactory.class.php)
379
     * @param    int     $resource_id Resource ID in the corresponding tool
380
     * @param    int     $session_id Session ID (optional -  0 if not defined)
381
     *
382
     * @return   array     false on error or array of resource
383
     */
384
    public static function isResourceInCourseGradebook($courseId, $resource_type, $resource_id, $session_id = 0)
385
    {
386
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
387
        $courseId = (int)$courseId;
388
        $sql = "SELECT * FROM $table l
389
                WHERE
390
                    c_id = '$courseId' AND
391
                    type = ".(int)$resource_type . " AND
392
                    ref_id = " . (int)$resource_id;
393
        $res = Database::query($sql);
394
395
        if (Database::num_rows($res) < 1) {
396
            return false;
397
        }
398
        $row = Database::fetch_array($res, 'ASSOC');
399
400
        return $row;
401
    }
402
403
    /**
404
     * Remove a resource from the unique gradebook of a given course
405
     * @param    int     Link/Resource ID
406
     * @return   bool    false on error, true on success
407
     */
408 View Code Duplication
    public static function get_resource_from_course_gradebook($link_id)
409
    {
410
        if (empty($link_id)) {
411
            return false;
412
        }
413
        // TODO find the corresponding category (the first one for this course, ordered by ID)
414
        $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
415
        $sql = "SELECT * FROM $l WHERE id = " . (int) $link_id;
416
        $res = Database::query($sql);
417
        $row = array();
418
        if (Database::num_rows($res) > 0) {
419
            $row = Database::fetch_array($res, 'ASSOC');
420
        }
421
        return $row;
422
    }
423
424
    /**
425
     * Return the course id
426
     * @param    int
427
     * @return   String
428
     */
429 View Code Duplication
    public static function get_course_id_by_link_id($id_link)
430
    {
431
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
432
        $tbl_grade_links = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
433
        $sql = 'SELECT c.id FROM ' . $course_table . ' c
434
                INNER JOIN ' . $tbl_grade_links . ' l
435
                ON c.id = l.c_id
436
                WHERE l.id=' . intval($id_link) . ' OR l.category_id=' . intval($id_link);
437
        $res = Database::query($sql);
438
        $array = Database::fetch_array($res, 'ASSOC');
439
        return $array['id'];
440
    }
441
442
    /**
443
     * @param $type
444
     * @return string
445
     */
446
    public static function get_table_type_course($type)
447
    {
448
        global $table_evaluated;
449
        return Database::get_course_table($table_evaluated[$type][0]);
450
    }
451
452
    /**
453
     * @param Category $cat
454
     * @param $users
455
     * @param $alleval
456
     * @param $alllinks
457
     * @param $params
458
     * @param null $mainCourseCategory
459
     * @return array
460
     */
461
    public static function get_printable_data($cat, $users, $alleval, $alllinks, $params, $mainCourseCategory = null)
462
    {
463
        $datagen = new FlatViewDataGenerator(
464
            $users,
465
            $alleval,
466
            $alllinks,
467
            $params,
468
            $mainCourseCategory
469
        );
470
471
        $offset = isset($_GET['offset']) ? $_GET['offset'] : '0';
472
        $offset = intval($offset);
473
474
        // step 2: generate rows: students
475
        $datagen->category = $cat;
476
477
        $count = (($offset + 10) > $datagen->get_total_items_count()) ? ($datagen->get_total_items_count() - $offset) : GRADEBOOK_ITEM_LIMIT;
478
        $header_names = $datagen->get_header_names($offset, $count, true);
479
        $data_array = $datagen->get_data(
480
            FlatViewDataGenerator :: FVDG_SORT_LASTNAME,
481
            0,
482
            null,
483
            $offset,
484
            $count,
485
            true,
486
            true
487
        );
488
489
        $result = array();
490
        foreach ($data_array as $data) {
491
            $result[] = array_slice($data, 1);
492
        }
493
        $return = array($header_names, $result);
494
495
        return $return;
496
    }
497
498
    /**
499
     * XML-parser: handle character data
500
     */
501
    public static function character_data($parser, $data)
502
    {
503
        global $current_value;
504
        $current_value = $data;
505
    }
506
507
    /**
508
     * XML-parser: handle end of element
509
     */
510
    public static function element_end($parser, $data)
511
    {
512
        global $user;
513
        global $users;
514
        global $current_value;
515
        switch ($data) {
516
            case 'Result':
517
                $users[] = $user;
518
                break;
519
            default:
520
                $user[$data] = $current_value;
521
                break;
522
        }
523
    }
524
525
    /**
526
     * XML-parser: handle start of element
527
     */
528
    public static function element_start($parser, $data)
529
    {
530
        global $user;
531
        global $current_tag;
532
        switch ($data) {
533
            case 'Result':
534
                $user = array();
535
                break;
536
            default:
537
                $current_tag = $data;
538
        }
539
    }
540
541
    public static function overwritescore($resid, $importscore, $eval_max)
542
    {
543
        $result = Result :: load($resid);
544
        if ($importscore > $eval_max) {
545
            header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&overwritemax=');
546
            exit;
547
        }
548
        $result[0]->set_score($importscore);
549
        $result[0]->save();
550
        unset($result);
551
    }
552
553
    /**
554
     * Read the XML-file
555
     * @param string $file Path to the XML-file
556
     * @return array All user information read from the file
557
     */
558 View Code Duplication
    public static function parse_xml_data($file)
559
    {
560
        global $current_tag;
561
        global $current_value;
562
        global $user;
563
        global $users;
564
        $users = array();
565
        $parser = xml_parser_create();
566
        xml_set_element_handler($parser, 'element_start', 'element_end');
567
        xml_set_character_data_handler($parser, "character_data");
568
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
569
        xml_parse($parser, file_get_contents($file));
570
        xml_parser_free($parser);
571
        return $users;
572
    }
573
574
    /**
575
     * register user info about certificate
576
     * @param int $cat_id The category id
577
     * @param int $user_id The user id
578
     * @param float $score_certificate The score obtained for certified
579
     * @param string $date_certificate The date when you obtained the certificate
580
     *
581
     * @return void
582
     */
583
    public static function registerUserInfoAboutCertificate(
584
        $cat_id,
585
        $user_id,
586
        $score_certificate,
587
        $date_certificate
588
    ) {
589
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
590
        $sql = 'SELECT COUNT(id) as count
591
                FROM ' . $table . ' gc
592
                WHERE gc.cat_id="' . intval($cat_id) . '" AND user_id="' . intval($user_id) . '" ';
593
        $rs_exist = Database::query($sql);
594
        $row = Database::fetch_array($rs_exist);
595
        if ($row['count'] == 0) {
596
            $params = [
597
                'cat_id' => $cat_id,
598
                'user_id' => $user_id,
599
                'score_certificate' => $score_certificate,
600
                'created_at' => $date_certificate
601
            ];
602
            Database::insert($table, $params);
603
        }
604
    }
605
606
    /**
607
     * Get date of user certificate
608
     * @param int $cat_id The category id
609
     * @param int $user_id The user id
610
     * @return Datetime The date when you obtained the certificate
611
     */
612
    public static function get_certificate_by_user_id($cat_id, $user_id)
613
    {
614
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
615
        $sql = 'SELECT * FROM ' . $table_certificate . '
616
                WHERE cat_id="' . intval($cat_id) . '" AND user_id="' . intval($user_id) . '"';
617
618
        $result = Database::query($sql);
619
        $row = Database::fetch_array($result, 'ASSOC');
620
621
        return $row;
622
    }
623
624
    /**
625
     * Get list of users certificates
626
     * @param int $cat_id The category id
627
     * @param array $userList Only users in this list
628
     * @return array
629
     */
630
    public static function get_list_users_certificates($cat_id = null, $userList = array())
631
    {
632
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
633
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
634
        $sql = 'SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username
635
                FROM ' . $table_user . ' u
636
                INNER JOIN ' . $table_certificate . ' gc
637
                ON u.user_id=gc.user_id ';
638 View Code Duplication
        if (!is_null($cat_id) && $cat_id > 0) {
639
            $sql.=' WHERE cat_id=' . intval($cat_id);
640
        }
641
        if (!empty($userList)) {
642
            $userList = array_map('intval', $userList);
643
            $userListCondition = implode("','", $userList);
644
            $sql .= " AND u.user_id IN ('$userListCondition')";
645
        }
646
        $sql.=' ORDER BY u.firstname';
647
        $rs = Database::query($sql);
648
649
        $list_users = array();
650
        while ($row = Database::fetch_array($rs)) {
651
            $list_users[] = $row;
652
        }
653
654
        return $list_users;
655
    }
656
657
    /**
658
     * Gets the certificate list by user id
659
     * @param int $user_id The user id
660
     * @param int $cat_id The category id
661
     * @return array
662
     */
663
    public static function get_list_gradebook_certificates_by_user_id($user_id, $cat_id = null)
664
    {
665
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
666
        $sql = 'SELECT gc.score_certificate, gc.created_at, gc.path_certificate, gc.cat_id, gc.user_id, gc.id
667
                FROM  ' . $table_certificate . ' gc
668
                WHERE gc.user_id="' . intval($user_id) . '" ';
669 View Code Duplication
        if (!is_null($cat_id) && $cat_id > 0) {
670
            $sql.=' AND cat_id=' . intval($cat_id);
671
        }
672
673
        $rs = Database::query($sql);
674
        $list_certificate = array();
675
        while ($row = Database::fetch_array($rs)) {
676
            $list_certificate[] = $row;
677
        }
678
        return $list_certificate;
679
    }
680
681
    /**
682
     * @param int $user_id
683
     * @param string $course_code
684
     * @param int $sessionId
685
     * @param bool $is_preview
686
     * @param bool $hide_print_button
687
     *
688
     * @return array
689
     */
690
    public static function get_user_certificate_content($user_id, $course_code, $sessionId, $is_preview = false, $hide_print_button = false)
691
    {
692
        // Generate document HTML
693
        $content_html = DocumentManager::replace_user_info_into_html($user_id, $course_code, $sessionId, $is_preview);
694
        $new_content_html = isset($content_html['content']) ? $content_html['content'] : null;
695
        $variables = isset($content_html['variables']) ? $content_html['variables'] : null;
696
        $path_image = api_get_path(WEB_COURSE_PATH) . api_get_course_path($course_code) . '/document/images/gallery';
697
        $new_content_html = str_replace('../images/gallery', $path_image, $new_content_html);
698
699
        $path_image_in_default_course = api_get_path(WEB_CODE_PATH) . 'default_course_document';
700
        $new_content_html = str_replace('/main/default_course_document', $path_image_in_default_course, $new_content_html);
701
        $new_content_html = str_replace(SYS_CODE_PATH . 'img/', api_get_path(WEB_IMG_PATH), $new_content_html);
702
703
        $dom = new DOMDocument();
704
        $dom->loadHTML($new_content_html);
705
706
        //add print header
707
        if (!$hide_print_button) {
708
            $head = $dom->getElementsByTagName('head');
709
            $body = $dom->getElementsByTagName('body');
710
711
            $printStyle = $dom->createElement('style');
712
            $printStyle->setAttribute('media', 'print');
713
            $printStyle->setAttribute('type', 'text/css');
714
            $printStyle->textContent = '#print_div {visibility:hidden;}';
715
716
            $head->item(0)->appendChild($printStyle);
717
718
            $printIcon = $dom->createDocumentFragment();
719
            $printIcon->appendXML(Display::return_icon('printmgr.gif', get_lang('Print')));
720
721
            $printA = $dom->createElement('button');
722
            $printA->setAttribute('onclick', 'window.print();');
723
            $printA->setAttribute('id', 'print_div');
724
            $printA->setAttribute('style', 'float:right; padding:4px; border: 0 none;');
725
            $printA->appendChild($printIcon);
726
727
            $body->item(0)->insertBefore($printA, $body->item(0)->firstChild);
728
        }
729
730
        return array(
731
            'content' => $dom->saveHTML(),
732
            'variables' => $variables
733
        );
734
    }
735
736
    /**
737
     * @param int $courseId
738
     * @param int $gradebook_model_id
739
     * @return mixed
740
     */
741
    public static function createDefaultCourseGradebook($courseId = 0, $gradebook_model_id = 0)
742
    {
743
        if (api_is_allowed_to_edit(true, true)) {
744
            if (!isset($courseId) || empty($courseId)) {
745
                $courseId = api_get_course_int_id();
746
            }
747
748
            $courseInfo = api_get_course_info_by_id($courseId);
749
            $session_id = api_get_session_id();
750
751
            $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
752
            $sql = "SELECT * FROM $t WHERE c_id = '" . Database::escape_string($courseId) . "' ";
753
            if (!empty($session_id)) {
754
                $sql .= " AND session_id = " . (int) $session_id;
755
            } else {
756
                $sql .= " AND (session_id IS NULL OR session_id = 0) ";
757
            }
758
            $sql .= " ORDER BY id";
759
            $res = Database::query($sql);
760
            $course_code = $courseInfo['code'];
761
            if (Database::num_rows($res) < 1) {
762
                //there is no unique category for this course+session combination,
763
                $cat = new Category();
764 View Code Duplication
                if (!empty($session_id)) {
765
                    $my_session_id = api_get_session_id();
766
                    $s_name = api_get_session_name($my_session_id);
767
                    $cat->set_name($course_code . ' - ' . get_lang('Session') . ' ' . $s_name);
768
                    $cat->set_session_id($session_id);
769
                } else {
770
                    $cat->set_name($course_code);
771
                }
772
                $cat->set_course_code($course_code);
773
                $cat->set_description(null);
774
                $cat->set_user_id(api_get_user_id());
775
                $cat->set_parent_id(0);
776
                $default_weight_setting = api_get_setting('gradebook_default_weight');
777
                $default_weight = isset($default_weight_setting) && !empty($default_weight_setting) ? $default_weight_setting : 100;
778
                $cat->set_weight($default_weight);
779
                $cat->set_grade_model_id($gradebook_model_id);
780
                $cat->set_certificate_min_score(75);
781
                $cat->set_visible(0);
782
                $cat->add();
783
                $category_id = $cat->get_id();
784
                unset($cat);
785
            } else {
786
                $row = Database::fetch_array($res);
787
                $category_id = $row['id'];
788
            }
789
790
            return $category_id;
791
        }
792
793
        return false;
794
    }
795
796
    /**
797
     * @param FormValidator $form
798
     */
799
    public static function load_gradebook_select_in_tool($form)
800
    {
801
        $course_code = api_get_course_id();
802
        $session_id = api_get_session_id();
803
804
        self::createDefaultCourseGradebook();
805
806
        // Cat list
807
        $all_categories = Category :: load(null, null, $course_code, null, null, $session_id, false);
808
        $select_gradebook = $form->addElement('select', 'category_id', get_lang('SelectGradebook'));
809
810
        if (!empty($all_categories)) {
811
            foreach ($all_categories as $my_cat) {
812 View Code Duplication
                if ($my_cat->get_course_code() == api_get_course_id()) {
813
                    $grade_model_id = $my_cat->get_grade_model_id();
814
                    if (empty($grade_model_id)) {
815
                        if ($my_cat->get_parent_id() == 0) {
816
                            //$default_weight = $my_cat->get_weight();
817
                            $select_gradebook->addoption(get_lang('Default'), $my_cat->get_id());
818
                            $cats_added[] = $my_cat->get_id();
819
                        } else {
820
                            $select_gradebook->addoption($my_cat->get_name(), $my_cat->get_id());
821
                            $cats_added[] = $my_cat->get_id();
822
                        }
823
                    } else {
824
                        $select_gradebook->addoption(get_lang('Select'), 0);
825
                    }
826
                }
827
            }
828
        }
829
    }
830
831
    /**
832
     * @param FlatViewTable $flatviewtable
833
     * @param Category $cat
834
     * @param $users
835
     * @param $alleval
836
     * @param $alllinks
837
     * @param array $params
838
     * @param null $mainCourseCategory
839
     */
840
    public static function export_pdf_flatview(
841
        $flatviewtable,
842
        $cat,
843
        $users,
844
        $alleval,
845
        $alllinks,
846
        $params = array(),
847
        $mainCourseCategory = null
848
    ) {
849
850
        // Getting data
851
        $printable_data = self::get_printable_data(
852
            $cat[0],
853
            $users,
854
            $alleval,
855
            $alllinks,
856
            $params,
857
            $mainCourseCategory
858
        );
859
860
        // HTML report creation first
861
        $course_code = trim($cat[0]->get_course_code());
862
        $displayscore = ScoreDisplay :: instance();
863
        $customdisplays = $displayscore->get_custom_score_display_settings();
864
865
        $total = array();
866
        if (is_array($customdisplays) && count(($customdisplays))) {
867
            foreach ($customdisplays as $custom) {
868
                $total[$custom['display']] = 0;
869
            }
870
            $user_results = $flatviewtable->datagen->get_data_to_graph2(false);
871
            foreach ($user_results as $user_result) {
872
                $total[$user_result[count($user_result) - 1][1]]++;
873
            }
874
        }
875
876
        $parent_id = $cat[0]->get_parent_id();
877
        if (isset($cat[0]) && isset($parent_id)) {
878
            if ($parent_id == 0) {
879
                $grade_model_id = $cat[0]->get_grade_model_id();
880
            } else {
881
                $parent_cat = Category::load($parent_id);
882
                $grade_model_id = $parent_cat[0]->get_grade_model_id();
883
            }
884
        }
885
886
        $use_grade_model = true;
887
        if (empty($grade_model_id) || $grade_model_id == -1) {
888
            $use_grade_model = false;
889
        }
890
891
        if ($use_grade_model) {
892
            if ($parent_id == 0) {
893
                $title = api_strtoupper(get_lang('Average')) . '<br />' . get_lang('Detailed');
894
            } else {
895
                $title = api_strtoupper(get_lang('Average')) . '<br />' . $cat[0]->get_description() . ' - (' . $cat[0]->get_name() . ')';
896
            }
897
        } else {
898
            if ($parent_id == 0) {
899
                $title = api_strtoupper(get_lang('Average')) . '<br />' . get_lang('Detailed');
900
            } else {
901
                $title = api_strtoupper(get_lang('Average'));
902
            }
903
        }
904
905
        $columns = count($printable_data[0]);
906
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
907
908
        $table = new HTML_Table(array('class' => 'data_table'));
909
        $row = 0;
910
        $column = 0;
911
912
        $table->setHeaderContents($row, $column, get_lang('NumberAbbreviation'));
913
        $column++;
914
        foreach ($printable_data[0] as $printable_data_cell) {
915
            if (!is_array($printable_data_cell)) {
916
                $printable_data_cell = strip_tags($printable_data_cell);
917
            }
918
            $table->setHeaderContents($row, $column, $printable_data_cell);
919
            $column++;
920
        }
921
        $row++;
922
923
        if ($has_data) {
924
            $counter = 1;
925
            foreach ($printable_data[1] as &$printable_data_row) {
926
                $column = 0;
927
                $table->setCellContents($row, $column, $counter);
928
                $table->updateCellAttributes($row, $column, 'align="center"');
929
                $column++;
930
                $counter++;
931
932
                foreach ($printable_data_row as $key => &$printable_data_cell) {
933
                    $attributes = array();
934
                    $attributes['align'] = 'center';
935
                    $attributes['style'] = null;
936
937
                    if ($key === 'name') {
938
                        $attributes['align'] = 'left';
939
                    }
940
                    if ($key === 'total') {
941
                        $attributes['style'] = 'font-weight:bold';
942
                    }
943
                    $table->setCellContents($row, $column, $printable_data_cell);
944
                    $table->updateCellAttributes($row, $column, $attributes);
945
                    $column++;
946
                }
947
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
948
                $row++;
949
            }
950
        } else {
951
            $column = 0;
952
            $table->setCellContents($row, $column, get_lang('NoResults'));
953
            $table->updateCellAttributes($row, $column, 'colspan="' . $columns . '" align="center" class="row_odd"');
954
        }
955
956
        $pdfParams = array(
957
            'filename' => get_lang('FlatView') . '_' . api_get_utc_datetime(),
958
            'pdf_title' => $title,
959
            'course_code' => $course_code,
960
            'add_signatures' => true
961
        );
962
963
        $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
964
        ob_start();
965
        $pdf = new PDF($page_format, $page_format, $pdfParams);
966
        $pdf->html_to_pdf_with_template($flatviewtable->return_table());
967
        $content = ob_get_contents();
968
        ob_end_clean();
969
        echo $content;
970
        exit;
971
    }
972
973
    /**
974
     * @param string[] $list_values
975
     * @return string
976
     */
977
    public static function score_badges($list_values)
978
    {
979
        $counter = 1;
980
        $badges = array();
981
        foreach ($list_values as $value) {
982
            $class = 'warning';
983
            if ($counter == 1) {
984
                $class = 'success';
985
            }
986
            $counter++;
987
            $badges[] = Display::badge($value, $class);
988
        }
989
        return Display::badge_group($badges);
990
    }
991
992
    /**
993
     * returns users within a course given by param
994
     * @param string $courseCode
995
     */
996
    public static function get_users_in_course($courseCode)
997
    {
998
        $tbl_course_user = Database:: get_main_table(TABLE_MAIN_COURSE_USER);
999
        $tbl_session_course_user = Database:: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1000
        $tbl_user = Database:: get_main_table(TABLE_MAIN_USER);
1001
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
1002
1003
        $current_session = api_get_session_id();
1004
        $courseCode = Database::escape_string($courseCode);
1005
        $courseInfo = api_get_course_info($courseCode);
1006
        $courseId = $courseInfo['real_id'];
1007
1008
        if (!empty($current_session)) {
1009
            $sql = "SELECT user.user_id, user.username, lastname, firstname, official_code
1010
                    FROM $tbl_session_course_user as scru, $tbl_user as user
1011
                    WHERE
1012
                        scru.user_id = user.user_id AND
1013
                        scru.status=0  AND
1014
                        scru.c_id='$courseId' AND
1015
                        session_id ='$current_session'
1016
                    $order_clause
1017
                    ";
1018
        } else {
1019
            $sql = 'SELECT user.user_id, user.username, lastname, firstname, official_code
1020
                    FROM '.$tbl_course_user.' as course_rel_user, '.$tbl_user.' as user
1021
                    WHERE
1022
                        course_rel_user.user_id=user.user_id AND
1023
                        course_rel_user.status='.STUDENT.' AND
1024
                        course_rel_user.c_id = "'.$courseId.'" '.
1025
                    $order_clause;
1026
        }
1027
1028
        $result = Database::query($sql);
1029
1030
        return self::get_user_array_from_sql_result($result);
1031
    }
1032
1033
    /**
1034
     * @param Doctrine\DBAL\Driver\Statement|null $result
1035
     * @return array
1036
     */
1037
    public static function get_user_array_from_sql_result($result)
1038
    {
1039
        $a_students = array();
1040
        while ($user = Database::fetch_array($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result defined by parameter $result on line 1037 can be null; however, Database::fetch_array() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
1041
            if (!array_key_exists($user['user_id'], $a_students)) {
1042
                $a_current_student = array ();
1043
                $a_current_student[] = $user['user_id'];
1044
                $a_current_student[] = $user['username'];
1045
                $a_current_student[] = $user['lastname'];
1046
                $a_current_student[] = $user['firstname'];
1047
                $a_current_student[] = $user['official_code'];
1048
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1049
            }
1050
        }
1051
        return $a_students;
1052
    }
1053
1054
    /**
1055
     * @param array $evals
1056
     * @param array $links
1057
     * @return array
1058
     */
1059
    public static function get_all_users($evals = array(), $links = array())
1060
    {
1061
        $coursecodes = array();
1062
1063
        // By default add all user in course
1064
        $coursecodes[api_get_course_id()] = '1';
1065
        $users = GradebookUtils::get_users_in_course(api_get_course_id());
1066
1067
        foreach ($evals as $eval) {
1068
            $coursecode = $eval->get_course_code();
1069
            // evaluation in course
1070
            if (isset($coursecode) && !empty($coursecode)) {
1071 View Code Duplication
                if (!array_key_exists($coursecode, $coursecodes)) {
1072
                    $coursecodes[$coursecode] = '1';
1073
                    $users = array_merge($users, GradebookUtils::get_users_in_course($coursecode));
1074
                }
1075
            } else {
1076
                // course independent evaluation
1077
                $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
1078
                $tbl_res = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1079
1080
                $sql = 'SELECT user.user_id, lastname, firstname, user.official_code
1081
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1082
                        WHERE
1083
                            res.evaluation_id = '.intval($eval->get_id()).' AND
1084
                            res.user_id = user.user_id
1085
                        ';
1086
                $sql .= ' ORDER BY lastname, firstname';
1087
                if (api_is_western_name_order()) {
1088
                    $sql .= ' ORDER BY firstname, lastname';
1089
                }
1090
1091
                $result = Database::query($sql);
1092
                $users = array_merge($users, GradebookUtils::get_user_array_from_sql_result($result));
1093
            }
1094
        }
1095
1096
        foreach ($links as $link) {
1097
            // links are always in a course
1098
            $coursecode = $link->get_course_code();
1099 View Code Duplication
            if (!array_key_exists($coursecode,$coursecodes)) {
1100
                $coursecodes[$coursecode] = '1';
1101
                $users = array_merge($users, GradebookUtils::get_users_in_course($coursecode));
1102
            }
1103
        }
1104
1105
        return $users;
1106
    }
1107
1108
    /**
1109
     * Search students matching a given last name and/or first name
1110
     * @author Bert Steppé
1111
     */
1112
    public static function find_students($mask= '')
1113
    {
1114
        // students shouldn't be here // don't search if mask empty
1115
        if (!api_is_allowed_to_edit() || empty ($mask)) {
1116
            return null;
1117
        }
1118
        $mask = Database::escape_string($mask);
1119
1120
        $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
1121
        $tbl_cru = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
1122
        $sql = 'SELECT DISTINCT user.user_id, user.lastname, user.firstname, user.email, user.official_code
1123
                FROM ' . $tbl_user . ' user';
1124
        if (!api_is_platform_admin()) {
1125
            $sql .= ', ' . $tbl_cru . ' cru';
1126
        }
1127
1128
        $sql .= ' WHERE user.status = ' . STUDENT;
1129
        $sql .= ' AND (user.lastname LIKE '."'%" . $mask . "%'";
1130
        $sql .= ' OR user.firstname LIKE '."'%" . $mask . "%')";
1131
1132
        if (!api_is_platform_admin()) {
1133
            $sql .= ' AND user.user_id = cru.user_id AND
1134
                      cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' AND
1135
                      cru.c_id in (
1136
                            SELECT c_id FROM '.$tbl_cru . '
1137
                            WHERE
1138
                                user_id = ' . api_get_user_id() . ' AND
1139
                                status = ' . COURSEMANAGER . '
1140
                        )
1141
                    ';
1142
        }
1143
1144
        $sql .= ' ORDER BY lastname, firstname';
1145
        if (api_is_western_name_order()) {
1146
            $sql .= ' ORDER BY firstname, lastname';
1147
        }
1148
1149
        $result = Database::query($sql);
1150
        $users = Database::store_result($result);
1151
1152
        return $users;
1153
    }
1154
1155
    /**
1156
     * @param int $linkId
1157
     * @param float $weight
1158
     */
1159
    public static function updateLinkWeight($linkId, $name, $weight)
1160
    {
1161
        $linkId = intval($linkId);
1162
        $weight = floatval($weight);
1163
        $course_id = api_get_course_int_id();
1164
1165
        AbstractLink::add_link_log($linkId, $name);
1166
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1167
1168
        $em = Database::getManager();
1169
        $tbl_forum_thread = Database:: get_course_table(TABLE_FORUM_THREAD);
1170
        $tbl_attendance = Database:: get_course_table(TABLE_ATTENDANCE);
1171
1172
        $sql = 'UPDATE '.$table_link.' SET weight = '."'".Database::escape_string($weight)."'".'
1173
                WHERE id = '.$linkId;
1174
1175
        Database::query($sql);
1176
1177
        // Update weight for attendance
1178
        $sql = 'SELECT ref_id FROM '.$table_link.'
1179
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1180
1181
        $rs_attendance  = Database::query($sql);
1182 View Code Duplication
        if (Database::num_rows($rs_attendance) > 0) {
1183
            $row_attendance = Database::fetch_array($rs_attendance);
1184
            $sql = 'UPDATE '.$tbl_attendance.' SET attendance_weight ='.$weight.'
1185
                    WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
1186
            Database::query($sql);
1187
        }
1188
        // Update weight into forum thread
1189
        $sql = 'UPDATE '.$tbl_forum_thread.' SET thread_weight='.$weight.'
1190
                WHERE
1191
                    c_id = '.$course_id.' AND
1192
                    thread_id = (
1193
                        SELECT ref_id FROM '.$table_link.'
1194
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1195
                    )
1196
                ';
1197
        Database::query($sql);
1198
        //Update weight into student publication(work)
1199
        $em
1200
            ->createQuery('
1201
                UPDATE ChamiloCourseBundle:CStudentPublication w
1202
                SET w.weight = :final_weight
1203
                WHERE w.cId = :course
1204
                    AND w.id = (
1205
                        SELECT l.refId FROM ChamiloCoreBundle:GradebookLink l
1206
                        WHERE l.id = :link AND l.type = :type
1207
                    )
1208
            ')
1209
            ->execute([
1210
                'final_weight' => $weight,
1211
                'course' => $course_id,
1212
                'link' => $linkId,
1213
                'type' => LINK_STUDENTPUBLICATION
1214
            ]);
1215
    }
1216
1217
    /**
1218
     * @param int $id
1219
     * @param float $weight
1220
     */
1221 View Code Duplication
    public static function updateEvaluationWeight($id, $weight)
1222
    {
1223
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1224
        $id = intval($id);
1225
        $evaluation = new Evaluation();
1226
        $evaluation->add_evaluation_log($id);
1227
        $sql = 'UPDATE '.$table_evaluation.'
1228
               SET weight = '."'".Database::escape_string($weight)."'".'
1229
               WHERE id = '.$id;
1230
        Database::query($sql);
1231
    }
1232
1233
    /**
1234
     *
1235
     * Get the achieved certificates for a user in courses
1236
     * @param int $userId The user id
1237
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1238
     * @return array
1239
     */
1240
    public static function getUserCertificatesInCourses($userId, $includeNonPublicCertificates = true)
1241
    {
1242
        $userId = intval($userId);
1243
        $courseList = [];
1244
1245
        $courses = CourseManager::get_courses_list_by_user_id($userId);
1246
1247
        foreach ($courses as $course) {
1248
            if (!$includeNonPublicCertificates) {
1249
                $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course['code']);
1250
1251
                if (empty($allowPublicCertificates)) {
1252
                    continue;
1253
                }
1254
            }
1255
1256
            $courseGradebookCategory = Category::load(null, null, $course['code']);
1257
1258
            if (empty($courseGradebookCategory)) {
1259
                continue;
1260
            }
1261
1262
            $courseGradebookId = $courseGradebookCategory[0]->get_id();
1263
1264
            $certificateInfo = GradebookUtils::get_certificate_by_user_id($courseGradebookId, $userId);
1265
1266
            if (empty($certificateInfo)) {
1267
                continue;
1268
            }
1269
1270
            $courseInfo = api_get_course_info_by_id($course['real_id']);
1271
1272
            $courseList[] = [
1273
                'course' => $courseInfo['title'],
1274
                'score' => $certificateInfo['score_certificate'],
1275
                'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1276
                'link' => api_get_path(WEB_PATH) . "certificates/index.php?id={$certificateInfo['id']}"
1277
            ];
1278
        }
1279
1280
        return $courseList;
1281
    }
1282
1283
    /**
1284
     * Get the achieved certificates for a user in course sessions
1285
     * @param int $userId The user id
1286
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1287
     * @return array
1288
     */
1289
    public static function getUserCertificatesInSessions($userId, $includeNonPublicCertificates = true)
1290
    {
1291
        $userId = intval($userId);
1292
        $sessionList = [];
1293
1294
        $sessions = SessionManager::get_sessions_by_user($userId, true, true);
1295
1296
        foreach ($sessions as $session) {
1297
            if (empty($session['courses'])) {
1298
                continue;
1299
            }
1300
            $sessionCourses = SessionManager::get_course_list_by_session_id($session['session_id']);
1301
1302
            foreach ($sessionCourses as $course) {
0 ignored issues
show
Bug introduced by
The expression $sessionCourses of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1303
                if (!$includeNonPublicCertificates) {
1304
                    $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course['code']);
1305
1306
                    if (empty($allowPublicCertificates)) {
1307
                        continue;
1308
                    }
1309
                }
1310
1311
                $courseGradebookCategory = Category::load(
1312
                    null,
1313
                    null,
1314
                    $course['code'],
1315
                    null,
1316
                    null,
1317
                    $session['session_id']
1318
                );
1319
1320
                if (empty($courseGradebookCategory)) {
1321
                    continue;
1322
                }
1323
1324
                $courseGradebookId = $courseGradebookCategory[0]->get_id();
1325
1326
                $certificateInfo = GradebookUtils::get_certificate_by_user_id(
1327
                    $courseGradebookId,
1328
                    $userId
1329
                );
1330
1331
                if (empty($certificateInfo)) {
1332
                    continue;
1333
                }
1334
1335
                $sessionList[] = [
1336
                    'session' => $session['session_name'],
1337
                    'course' => $course['title'],
1338
                    'score' => $certificateInfo['score_certificate'],
1339
                    'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1340
                    'link' => api_get_path(WEB_PATH) . "certificates/index.php?id={$certificateInfo['id']}"
1341
                ];
1342
            }
1343
        }
1344
1345
        return $sessionList;
1346
    }
1347
1348
    /**
1349
     * @param int $userId
1350
     * @param array $cats
1351
     * @param bool $saveToFile
1352
     * @param bool $saveToHtmlFile
1353
     * @param array $studentList
1354
     * @param PDF $pdf
1355
     *
1356
     * @return string
1357
     */
1358
    public static function generateTable(
1359
        $userId,
1360
        $cats,
1361
        $saveToFile = false,
1362
        $saveToHtmlFile = false,
1363
        $studentList = array(),
1364
        $pdf = null
1365
    ) {
1366
        $courseInfo = api_get_course_info();
1367
        $userInfo = api_get_user_info($userId);
1368
1369
        $cat = $cats[0];
1370
1371
        $allcat = $cats[0]->get_subcategories(
1372
            $userId,
1373
            api_get_course_id(),
1374
            api_get_session_id()
1375
        );
1376
        $alleval = $cats[0]->get_evaluations($userId);
1377
        $alllink = $cats[0]->get_links($userId);
1378
1379
        $gradebooktable = new GradebookTable(
1380
            $cat,
1381
            $allcat,
1382
            $alleval,
1383
            $alllink,
1384
            null, // params
1385
            true, // $exportToPdf
1386
            false, // showteacher
1387
            $userId,
1388
            $studentList
1389
        );
1390
1391
        $gradebooktable->userId = $userId;
1392
1393 View Code Duplication
        if (api_is_allowed_to_edit()) {
1394
            $gradebooktable->td_attributes = [
1395
                4 => 'class=centered'
1396
            ];
1397
        } else {
1398
            $gradebooktable->td_attributes = [
1399
                3 => 'class=centered',
1400
                4 => 'class=centered',
1401
                5 => 'class=centered',
1402
                6 => 'class=centered',
1403
                7 => 'class=centered'
1404
            ];
1405
        }
1406
1407
        $table = $gradebooktable->return_table();
1408
        $graph = $gradebooktable->getGraph();
1409
1410
        $sessionName = api_get_session_name(api_get_session_id());
1411
        $sessionName = !empty($sessionName) ? " - $sessionName" : '';
1412
1413
        $params = array(
1414
            'pdf_title' => sprintf(get_lang('GradeFromX'), $courseInfo['name']),
1415
            'session_info' => '',
1416
            'course_info' => '',
1417
            'pdf_date' => '',
1418
            'course_code' => api_get_course_id(),
1419
            'add_signatures' => false,
1420
            'student_info' => $userInfo,
1421
            'show_grade_generated_date' => true,
1422
            'show_real_course_teachers' => false,
1423
            'show_teacher_as_myself' => false,
1424
            'orientation' => 'P'
1425
        );
1426
1427
        if (empty($pdf)) {
1428
            $pdf = new PDF('A4', $params['orientation'], $params);
1429
        }
1430
1431
        $pdf->params['student_info'] = $userInfo;
1432
1433
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid().'.html';
1434
1435
        $content =
1436
            $table.
1437
            $graph.
1438
            '<br />'.get_lang('Feedback').'<br />
1439
            <textarea rows="5" cols="100" ></textarea>';
1440
1441
        $address = api_get_setting('institution_address');
1442
        $phone = api_get_setting('administratorTelephone');
1443
        $address = str_replace('\n', '<br />', $address);
1444
1445
        $pdf->custom_header = array('html' => "<h5 align='right'>$address <br />$phone</h5>");
1446
1447
        $result = $pdf->html_to_pdf_with_template(
1448
            $content,
1449
            $saveToFile,
1450
            $saveToHtmlFile
1451
        );
1452
1453
        if ($saveToHtmlFile) {
1454
            file_put_contents($file, $result);
1455
            return $file;
1456
        }
1457
1458
        return $file;
1459
    }
1460
}
1461