Completed
Push — master ( e4ee84...996ef7 )
by Julito
48:07 queued 18:14
created

GradebookUtils::getEvaluateList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 48
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 38
nc 1
nop 0
dl 0
loc 48
rs 9.125
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.png';
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->getCourseId());
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->getCourseId());
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->getCourseId());
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
        $table_evaluated = self::getEvaluateList();
449
        return Database::get_course_table($table_evaluated[$type][0]);
450
    }
451
452
    public static function getEvaluateList()
453
    {
454
        $table_evaluated = [];
455
        $table_evaluated[LINK_EXERCISE] = array(
456
            TABLE_QUIZ_TEST,
457
            'title',
458
            'id',
459
            get_lang('Exercise'),
460
        );
461
        $table_evaluated[LINK_DROPBOX] = array(
462
            TABLE_DROPBOX_FILE,
463
            'name',
464
            'id',
465
            get_lang('Dropbox'),
466
        );
467
        $table_evaluated[LINK_STUDENTPUBLICATION] = array(
468
            TABLE_STUDENT_PUBLICATION,
469
            'url',
470
            'id',
471
            get_lang('Student_publication'),
472
        );
473
        $table_evaluated[LINK_LEARNPATH] = array(
474
            TABLE_LP_MAIN,
475
            'name',
476
            'id',
477
            get_lang('Learnpath'),
478
        );
479
        $table_evaluated[LINK_FORUM_THREAD] = array(
480
            TABLE_FORUM_THREAD,
481
            'thread_title_qualify',
482
            'thread_id',
483
            get_lang('Forum'),
484
        );
485
        $table_evaluated[LINK_ATTENDANCE] = array(
486
            TABLE_ATTENDANCE,
487
            'attendance_title_qualify',
488
            'id',
489
            get_lang('Attendance'),
490
        );
491
        $table_evaluated[LINK_SURVEY] = array(
492
            TABLE_SURVEY,
493
            'code',
494
            'survey_id',
495
            get_lang('Survey'),
496
        );
497
498
        return $table_evaluated;
499
    }
500
501
    /**
502
     * @param Category $cat
503
     * @param $users
504
     * @param $alleval
505
     * @param $alllinks
506
     * @param $params
507
     * @param null $mainCourseCategory
508
     * @return array
509
     */
510
    public static function get_printable_data($cat, $users, $alleval, $alllinks, $params, $mainCourseCategory = null)
511
    {
512
        $datagen = new FlatViewDataGenerator(
513
            $users,
514
            $alleval,
515
            $alllinks,
516
            $params,
517
            $mainCourseCategory
518
        );
519
520
        $offset = isset($_GET['offset']) ? $_GET['offset'] : '0';
521
        $offset = intval($offset);
522
523
        // step 2: generate rows: students
524
        $datagen->category = $cat;
525
526
        $count = (($offset + 10) > $datagen->get_total_items_count()) ? ($datagen->get_total_items_count() - $offset) : GRADEBOOK_ITEM_LIMIT;
527
        $header_names = $datagen->get_header_names($offset, $count, true);
528
        $data_array = $datagen->get_data(
529
            FlatViewDataGenerator :: FVDG_SORT_LASTNAME,
530
            0,
531
            null,
532
            $offset,
533
            $count,
534
            true,
535
            true
536
        );
537
538
        $result = array();
539
        foreach ($data_array as $data) {
540
            $result[] = array_slice($data, 1);
541
        }
542
        $return = array($header_names, $result);
543
544
        return $return;
545
    }
546
547
    /**
548
     * XML-parser: handle character data
549
     */
550
    public static function character_data($parser, $data)
551
    {
552
        global $current_value;
553
        $current_value = $data;
554
    }
555
556
    /**
557
     * XML-parser: handle end of element
558
     */
559
    public static function element_end($parser, $data)
560
    {
561
        global $user;
562
        global $users;
563
        global $current_value;
564
        switch ($data) {
565
            case 'Result':
566
                $users[] = $user;
567
                break;
568
            default:
569
                $user[$data] = $current_value;
570
                break;
571
        }
572
    }
573
574
    /**
575
     * XML-parser: handle start of element
576
     */
577
    public static function element_start($parser, $data)
578
    {
579
        global $user;
580
        global $current_tag;
581
        switch ($data) {
582
            case 'Result':
583
                $user = array();
584
                break;
585
            default:
586
                $current_tag = $data;
587
        }
588
    }
589
590
    public static function overwritescore($resid, $importscore, $eval_max)
591
    {
592
        $result = Result :: load($resid);
593
        if ($importscore > $eval_max) {
594
            header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&overwritemax=');
595
            exit;
596
        }
597
        $result[0]->set_score($importscore);
598
        $result[0]->save();
599
        unset($result);
600
    }
601
602
    /**
603
     * Read the XML-file
604
     * @param string $file Path to the XML-file
605
     * @return array All user information read from the file
606
     */
607 View Code Duplication
    public static function parse_xml_data($file)
608
    {
609
        global $current_tag;
610
        global $current_value;
611
        global $user;
612
        global $users;
613
        $users = array();
614
        $parser = xml_parser_create();
615
        xml_set_element_handler($parser, 'element_start', 'element_end');
616
        xml_set_character_data_handler($parser, "character_data");
617
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
618
        xml_parse($parser, file_get_contents($file));
619
        xml_parser_free($parser);
620
        return $users;
621
    }
622
623
    /**
624
     * register user info about certificate
625
     * @param int $cat_id The category id
626
     * @param int $user_id The user id
627
     * @param float $score_certificate The score obtained for certified
628
     * @param string $date_certificate The date when you obtained the certificate
629
     *
630
     * @return void
631
     */
632
    public static function registerUserInfoAboutCertificate(
633
        $cat_id,
634
        $user_id,
635
        $score_certificate,
636
        $date_certificate
637
    ) {
638
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
639
        $sql = 'SELECT COUNT(id) as count
640
                FROM ' . $table . ' gc
641
                WHERE gc.cat_id="' . intval($cat_id) . '" AND user_id="' . intval($user_id) . '" ';
642
        $rs_exist = Database::query($sql);
643
        $row = Database::fetch_array($rs_exist);
644
        if ($row['count'] == 0) {
645
            $params = [
646
                'cat_id' => $cat_id,
647
                'user_id' => $user_id,
648
                'score_certificate' => $score_certificate,
649
                'created_at' => $date_certificate
650
            ];
651
            Database::insert($table, $params);
652
        }
653
    }
654
655
    /**
656
     * Get date of user certificate
657
     * @param int $cat_id The category id
658
     * @param int $user_id The user id
659
     * @return Datetime The date when you obtained the certificate
660
     */
661
    public static function get_certificate_by_user_id($cat_id, $user_id)
662
    {
663
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
664
        $sql = 'SELECT * FROM ' . $table_certificate . '
665
                WHERE cat_id="' . intval($cat_id) . '" AND user_id="' . intval($user_id) . '"';
666
667
        $result = Database::query($sql);
668
        $row = Database::fetch_array($result, 'ASSOC');
669
670
        return $row;
671
    }
672
673
    /**
674
     * Get list of users certificates
675
     * @param int $cat_id The category id
676
     * @param array $userList Only users in this list
677
     * @return array
678
     */
679
    public static function get_list_users_certificates($cat_id = null, $userList = array())
680
    {
681
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
682
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
683
        $sql = 'SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username
684
                FROM ' . $table_user . ' u
685
                INNER JOIN ' . $table_certificate . ' gc
686
                ON u.user_id=gc.user_id ';
687 View Code Duplication
        if (!is_null($cat_id) && $cat_id > 0) {
688
            $sql.=' WHERE cat_id=' . intval($cat_id);
689
        }
690
        if (!empty($userList)) {
691
            $userList = array_map('intval', $userList);
692
            $userListCondition = implode("','", $userList);
693
            $sql .= " AND u.user_id IN ('$userListCondition')";
694
        }
695
        $sql.=' ORDER BY u.firstname';
696
        $rs = Database::query($sql);
697
698
        $list_users = array();
699
        while ($row = Database::fetch_array($rs)) {
700
            $list_users[] = $row;
701
        }
702
703
        return $list_users;
704
    }
705
706
    /**
707
     * Gets the certificate list by user id
708
     * @param int $user_id The user id
709
     * @param int $cat_id The category id
710
     * @return array
711
     */
712
    public static function get_list_gradebook_certificates_by_user_id($user_id, $cat_id = null)
713
    {
714
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
715
        $sql = 'SELECT gc.score_certificate, gc.created_at, gc.path_certificate, gc.cat_id, gc.user_id, gc.id
716
                FROM  ' . $table_certificate . ' gc
717
                WHERE gc.user_id="' . intval($user_id) . '" ';
718 View Code Duplication
        if (!is_null($cat_id) && $cat_id > 0) {
719
            $sql.=' AND cat_id=' . intval($cat_id);
720
        }
721
722
        $rs = Database::query($sql);
723
        $list_certificate = array();
724
        while ($row = Database::fetch_array($rs)) {
725
            $list_certificate[] = $row;
726
        }
727
        return $list_certificate;
728
    }
729
730
    /**
731
     * @param int $user_id
732
     * @param string $course_code
733
     * @param int $sessionId
734
     * @param bool $is_preview
735
     * @param bool $hide_print_button
736
     *
737
     * @return array
738
     */
739
    public static function get_user_certificate_content($user_id, $course_code, $sessionId, $is_preview = false, $hide_print_button = false)
740
    {
741
        // Generate document HTML
742
        $content_html = DocumentManager::replace_user_info_into_html($user_id, $course_code, $sessionId, $is_preview);
743
        $new_content_html = isset($content_html['content']) ? $content_html['content'] : null;
744
        $variables = isset($content_html['variables']) ? $content_html['variables'] : null;
745
        $path_image = api_get_path(WEB_COURSE_PATH) . api_get_course_path($course_code) . '/document/images/gallery';
746
        $new_content_html = str_replace('../images/gallery', $path_image, $new_content_html);
747
748
        $path_image_in_default_course = api_get_path(WEB_CODE_PATH) . 'default_course_document';
749
        $new_content_html = str_replace('/main/default_course_document', $path_image_in_default_course, $new_content_html);
750
        $new_content_html = str_replace(SYS_CODE_PATH . 'img/', api_get_path(WEB_IMG_PATH), $new_content_html);
751
752
        $dom = new DOMDocument();
753
        $dom->loadHTML($new_content_html);
754
755
        //add print header
756
        if (!$hide_print_button) {
757
            $head = $dom->getElementsByTagName('head');
758
            $body = $dom->getElementsByTagName('body');
759
760
            $printStyle = $dom->createElement('style');
761
            $printStyle->setAttribute('media', 'print');
762
            $printStyle->setAttribute('type', 'text/css');
763
            $printStyle->textContent = '#print_div {visibility:hidden;}';
764
765
            $head->item(0)->appendChild($printStyle);
766
767
            $printIcon = $dom->createDocumentFragment();
768
            $printIcon->appendXML(Display::return_icon('printmgr.gif', get_lang('Print')));
769
770
            $printA = $dom->createElement('button');
771
            $printA->setAttribute('onclick', 'window.print();');
772
            $printA->setAttribute('id', 'print_div');
773
            $printA->setAttribute('style', 'float:right; padding:4px; border: 0 none;');
774
            $printA->appendChild($printIcon);
775
776
            $body->item(0)->insertBefore($printA, $body->item(0)->firstChild);
777
        }
778
779
        return array(
780
            'content' => $dom->saveHTML(),
781
            'variables' => $variables
782
        );
783
    }
784
785
    /**
786
     * @param int $courseId
787
     * @param int $gradebook_model_id
788
     * @return mixed
789
     */
790
    public static function createDefaultCourseGradebook($courseId = 0, $gradebook_model_id = 0)
791
    {
792
        if (api_is_allowed_to_edit(true, true)) {
793
            if (!isset($courseId) || empty($courseId)) {
794
                $courseId = api_get_course_int_id();
795
            }
796
797
            $courseInfo = api_get_course_info_by_id($courseId);
798
            $session_id = api_get_session_id();
799
800
            $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
801
            $sql = "SELECT * FROM $t WHERE c_id = '" . Database::escape_string($courseId) . "' ";
802
            if (!empty($session_id)) {
803
                $sql .= " AND session_id = " . (int) $session_id;
804
            } else {
805
                $sql .= " AND (session_id IS NULL OR session_id = 0) ";
806
            }
807
            $sql .= " ORDER BY id";
808
            $res = Database::query($sql);
809
            $course_code = $courseInfo['code'];
810
            if (Database::num_rows($res) < 1) {
811
                //there is no unique category for this course+session combination,
812
                $cat = new Category();
813 View Code Duplication
                if (!empty($session_id)) {
814
                    $my_session_id = api_get_session_id();
815
                    $s_name = api_get_session_name($my_session_id);
816
                    $cat->set_name($course_code . ' - ' . get_lang('Session') . ' ' . $s_name);
817
                    $cat->set_session_id($session_id);
818
                } else {
819
                    $cat->set_name($course_code);
820
                }
821
                $cat->set_course_code($course_code);
822
                $cat->set_description(null);
823
                $cat->set_user_id(api_get_user_id());
824
                $cat->set_parent_id(0);
825
                $default_weight_setting = api_get_setting('gradebook_default_weight');
826
                $default_weight = isset($default_weight_setting) && !empty($default_weight_setting) ? $default_weight_setting : 100;
827
                $cat->set_weight($default_weight);
828
                $cat->set_grade_model_id($gradebook_model_id);
829
                $cat->set_certificate_min_score(75);
830
                $cat->set_visible(0);
831
                $cat->add();
832
                $category_id = $cat->get_id();
833
                unset($cat);
834
            } else {
835
                $row = Database::fetch_array($res);
836
                $category_id = $row['id'];
837
            }
838
839
            return $category_id;
840
        }
841
842
        return false;
843
    }
844
845
    /**
846
     * @param FormValidator $form
847
     */
848
    public static function load_gradebook_select_in_tool($form)
849
    {
850
        $course_code = api_get_course_id();
851
        $session_id = api_get_session_id();
852
853
        self::createDefaultCourseGradebook();
854
855
        // Cat list
856
        $all_categories = Category :: load(null, null, $course_code, null, null, $session_id, false);
857
        $select_gradebook = $form->addElement('select', 'category_id', get_lang('SelectGradebook'));
858
859
        if (!empty($all_categories)) {
860
            foreach ($all_categories as $my_cat) {
861 View Code Duplication
                if ($my_cat->get_course_code() == api_get_course_id()) {
862
                    $grade_model_id = $my_cat->get_grade_model_id();
863
                    if (empty($grade_model_id)) {
864
                        if ($my_cat->get_parent_id() == 0) {
865
                            //$default_weight = $my_cat->get_weight();
866
                            $select_gradebook->addoption(get_lang('Default'), $my_cat->get_id());
867
                            $cats_added[] = $my_cat->get_id();
868
                        } else {
869
                            $select_gradebook->addoption($my_cat->get_name(), $my_cat->get_id());
870
                            $cats_added[] = $my_cat->get_id();
871
                        }
872
                    } else {
873
                        $select_gradebook->addoption(get_lang('Select'), 0);
874
                    }
875
                }
876
            }
877
        }
878
    }
879
880
    /**
881
     * @param FlatViewTable $flatviewtable
882
     * @param Category $cat
883
     * @param $users
884
     * @param $alleval
885
     * @param $alllinks
886
     * @param array $params
887
     * @param null $mainCourseCategory
888
     */
889
    public static function export_pdf_flatview(
890
        $flatviewtable,
891
        $cat,
892
        $users,
893
        $alleval,
894
        $alllinks,
895
        $params = array(),
896
        $mainCourseCategory = null
897
    ) {
898
899
        // Getting data
900
        $printable_data = self::get_printable_data(
901
            $cat[0],
902
            $users,
903
            $alleval,
904
            $alllinks,
905
            $params,
906
            $mainCourseCategory
907
        );
908
909
        // HTML report creation first
910
        $course_code = trim($cat[0]->get_course_code());
911
        $displayscore = ScoreDisplay :: instance();
912
        $customdisplays = $displayscore->get_custom_score_display_settings();
913
914
        $total = array();
915
        if (is_array($customdisplays) && count(($customdisplays))) {
916
            foreach ($customdisplays as $custom) {
917
                $total[$custom['display']] = 0;
918
            }
919
            $user_results = $flatviewtable->datagen->get_data_to_graph2(false);
920
            foreach ($user_results as $user_result) {
921
                $total[$user_result[count($user_result) - 1][1]]++;
922
            }
923
        }
924
925
        $parent_id = $cat[0]->get_parent_id();
926
        if (isset($cat[0]) && isset($parent_id)) {
927
            if ($parent_id == 0) {
928
                $grade_model_id = $cat[0]->get_grade_model_id();
929
            } else {
930
                $parent_cat = Category::load($parent_id);
931
                $grade_model_id = $parent_cat[0]->get_grade_model_id();
932
            }
933
        }
934
935
        $use_grade_model = true;
936
        if (empty($grade_model_id) || $grade_model_id == -1) {
937
            $use_grade_model = false;
938
        }
939
940
        if ($use_grade_model) {
941
            if ($parent_id == 0) {
942
                $title = api_strtoupper(get_lang('Average')) . '<br />' . get_lang('Detailed');
943
            } else {
944
                $title = api_strtoupper(get_lang('Average')) . '<br />' . $cat[0]->get_description() . ' - (' . $cat[0]->get_name() . ')';
945
            }
946
        } else {
947
            if ($parent_id == 0) {
948
                $title = api_strtoupper(get_lang('Average')) . '<br />' . get_lang('Detailed');
949
            } else {
950
                $title = api_strtoupper(get_lang('Average'));
951
            }
952
        }
953
954
        $columns = count($printable_data[0]);
955
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
956
957
        $table = new HTML_Table(array('class' => 'data_table'));
958
        $row = 0;
959
        $column = 0;
960
961
        $table->setHeaderContents($row, $column, get_lang('NumberAbbreviation'));
962
        $column++;
963
        foreach ($printable_data[0] as $printable_data_cell) {
964
            if (!is_array($printable_data_cell)) {
965
                $printable_data_cell = strip_tags($printable_data_cell);
966
            }
967
            $table->setHeaderContents($row, $column, $printable_data_cell);
968
            $column++;
969
        }
970
        $row++;
971
972
        if ($has_data) {
973
            $counter = 1;
974
            foreach ($printable_data[1] as &$printable_data_row) {
975
                $column = 0;
976
                $table->setCellContents($row, $column, $counter);
977
                $table->updateCellAttributes($row, $column, 'align="center"');
978
                $column++;
979
                $counter++;
980
981
                foreach ($printable_data_row as $key => &$printable_data_cell) {
982
                    $attributes = array();
983
                    $attributes['align'] = 'center';
984
                    $attributes['style'] = null;
985
986
                    if ($key === 'name') {
987
                        $attributes['align'] = 'left';
988
                    }
989
                    if ($key === 'total') {
990
                        $attributes['style'] = 'font-weight:bold';
991
                    }
992
                    $table->setCellContents($row, $column, $printable_data_cell);
993
                    $table->updateCellAttributes($row, $column, $attributes);
994
                    $column++;
995
                }
996
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
997
                $row++;
998
            }
999
        } else {
1000
            $column = 0;
1001
            $table->setCellContents($row, $column, get_lang('NoResults'));
1002
            $table->updateCellAttributes($row, $column, 'colspan="' . $columns . '" align="center" class="row_odd"');
1003
        }
1004
1005
        $pdfParams = array(
1006
            'filename' => get_lang('FlatView') . '_' . api_get_utc_datetime(),
1007
            'pdf_title' => $title,
1008
            'course_code' => $course_code,
1009
            'add_signatures' => true
1010
        );
1011
1012
        $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
1013
        ob_start();
1014
        $pdf = new PDF($page_format, $page_format, $pdfParams);
1015
        $pdf->html_to_pdf_with_template($flatviewtable->return_table());
1016
        $content = ob_get_contents();
1017
        ob_end_clean();
1018
        echo $content;
1019
        exit;
1020
    }
1021
1022
    /**
1023
     * @param string[] $list_values
1024
     * @return string
1025
     */
1026
    public static function score_badges($list_values)
1027
    {
1028
        $counter = 1;
1029
        $badges = array();
1030
        foreach ($list_values as $value) {
1031
            $class = 'warning';
1032
            if ($counter == 1) {
1033
                $class = 'success';
1034
            }
1035
            $counter++;
1036
            $badges[] = Display::badge($value, $class);
1037
        }
1038
        return Display::badge_group($badges);
1039
    }
1040
1041
    /**
1042
     * returns users within a course given by param
1043
     * @param string $courseCode
1044
     */
1045
    public static function get_users_in_course($courseCode)
1046
    {
1047
        $tbl_course_user = Database:: get_main_table(TABLE_MAIN_COURSE_USER);
1048
        $tbl_session_course_user = Database:: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
1049
        $tbl_user = Database:: get_main_table(TABLE_MAIN_USER);
1050
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
1051
1052
        $current_session = api_get_session_id();
1053
        $courseCode = Database::escape_string($courseCode);
1054
        $courseInfo = api_get_course_info($courseCode);
1055
        $courseId = $courseInfo['real_id'];
1056
1057
        if (!empty($current_session)) {
1058
            $sql = "SELECT user.user_id, user.username, lastname, firstname, official_code
1059
                    FROM $tbl_session_course_user as scru, $tbl_user as user
1060
                    WHERE
1061
                        scru.user_id = user.user_id AND
1062
                        scru.status=0  AND
1063
                        scru.c_id='$courseId' AND
1064
                        session_id ='$current_session'
1065
                    $order_clause
1066
                    ";
1067
        } else {
1068
            $sql = 'SELECT user.user_id, user.username, lastname, firstname, official_code
1069
                    FROM '.$tbl_course_user.' as course_rel_user, '.$tbl_user.' as user
1070
                    WHERE
1071
                        course_rel_user.user_id=user.user_id AND
1072
                        course_rel_user.status='.STUDENT.' AND
1073
                        course_rel_user.c_id = "'.$courseId.'" '.
1074
                    $order_clause;
1075
        }
1076
1077
        $result = Database::query($sql);
1078
1079
        return self::get_user_array_from_sql_result($result);
1080
    }
1081
1082
    /**
1083
     * @param Doctrine\DBAL\Driver\Statement|null $result
1084
     * @return array
1085
     */
1086
    public static function get_user_array_from_sql_result($result)
1087
    {
1088
        $a_students = array();
1089
        while ($user = Database::fetch_array($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result defined by parameter $result on line 1086 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...
1090
            if (!array_key_exists($user['user_id'], $a_students)) {
1091
                $a_current_student = array ();
1092
                $a_current_student[] = $user['user_id'];
1093
                $a_current_student[] = $user['username'];
1094
                $a_current_student[] = $user['lastname'];
1095
                $a_current_student[] = $user['firstname'];
1096
                $a_current_student[] = $user['official_code'];
1097
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1098
            }
1099
        }
1100
        return $a_students;
1101
    }
1102
1103
    /**
1104
     * @param array $evals
1105
     * @param array $links
1106
     * @return array
1107
     */
1108
    public static function get_all_users($evals = array(), $links = array())
1109
    {
1110
        $coursecodes = array();
1111
1112
        // By default add all user in course
1113
        $coursecodes[api_get_course_id()] = '1';
1114
        $users = GradebookUtils::get_users_in_course(api_get_course_id());
1115
1116
        foreach ($evals as $eval) {
1117
            $coursecode = $eval->get_course_code();
1118
            // evaluation in course
1119
            if (isset($coursecode) && !empty($coursecode)) {
1120 View Code Duplication
                if (!array_key_exists($coursecode, $coursecodes)) {
1121
                    $coursecodes[$coursecode] = '1';
1122
                    $users = array_merge($users, GradebookUtils::get_users_in_course($coursecode));
1123
                }
1124
            } else {
1125
                // course independent evaluation
1126
                $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
1127
                $tbl_res = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1128
1129
                $sql = 'SELECT user.user_id, lastname, firstname, user.official_code
1130
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1131
                        WHERE
1132
                            res.evaluation_id = '.intval($eval->get_id()).' AND
1133
                            res.user_id = user.user_id
1134
                        ';
1135
                $sql .= ' ORDER BY lastname, firstname';
1136
                if (api_is_western_name_order()) {
1137
                    $sql .= ' ORDER BY firstname, lastname';
1138
                }
1139
1140
                $result = Database::query($sql);
1141
                $users = array_merge($users, GradebookUtils::get_user_array_from_sql_result($result));
1142
            }
1143
        }
1144
1145
        foreach ($links as $link) {
1146
            // links are always in a course
1147
            $coursecode = $link->get_course_code();
1148 View Code Duplication
            if (!array_key_exists($coursecode,$coursecodes)) {
1149
                $coursecodes[$coursecode] = '1';
1150
                $users = array_merge($users, GradebookUtils::get_users_in_course($coursecode));
1151
            }
1152
        }
1153
1154
        return $users;
1155
    }
1156
1157
    /**
1158
     * Search students matching a given last name and/or first name
1159
     * @author Bert Steppé
1160
     */
1161
    public static function find_students($mask= '')
1162
    {
1163
        // students shouldn't be here // don't search if mask empty
1164
        if (!api_is_allowed_to_edit() || empty ($mask)) {
1165
            return null;
1166
        }
1167
        $mask = Database::escape_string($mask);
1168
1169
        $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
1170
        $tbl_cru = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
1171
        $sql = 'SELECT DISTINCT user.user_id, user.lastname, user.firstname, user.email, user.official_code
1172
                FROM ' . $tbl_user . ' user';
1173
        if (!api_is_platform_admin()) {
1174
            $sql .= ', ' . $tbl_cru . ' cru';
1175
        }
1176
1177
        $sql .= ' WHERE user.status = ' . STUDENT;
1178
        $sql .= ' AND (user.lastname LIKE '."'%" . $mask . "%'";
1179
        $sql .= ' OR user.firstname LIKE '."'%" . $mask . "%')";
1180
1181
        if (!api_is_platform_admin()) {
1182
            $sql .= ' AND user.user_id = cru.user_id AND
1183
                      cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' AND
1184
                      cru.c_id in (
1185
                            SELECT c_id FROM '.$tbl_cru . '
1186
                            WHERE
1187
                                user_id = ' . api_get_user_id() . ' AND
1188
                                status = ' . COURSEMANAGER . '
1189
                        )
1190
                    ';
1191
        }
1192
1193
        $sql .= ' ORDER BY lastname, firstname';
1194
        if (api_is_western_name_order()) {
1195
            $sql .= ' ORDER BY firstname, lastname';
1196
        }
1197
1198
        $result = Database::query($sql);
1199
        $users = Database::store_result($result);
1200
1201
        return $users;
1202
    }
1203
1204
    /**
1205
     * @param int $linkId
1206
     * @param float $weight
1207
     */
1208
    public static function updateLinkWeight($linkId, $name, $weight)
1209
    {
1210
        $linkId = intval($linkId);
1211
        $weight = floatval($weight);
1212
        $course_id = api_get_course_int_id();
1213
1214
        AbstractLink::add_link_log($linkId, $name);
1215
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1216
1217
        $em = Database::getManager();
1218
        $tbl_forum_thread = Database:: get_course_table(TABLE_FORUM_THREAD);
1219
        $tbl_attendance = Database:: get_course_table(TABLE_ATTENDANCE);
1220
1221
        $sql = 'UPDATE '.$table_link.' SET weight = '."'".Database::escape_string($weight)."'".'
1222
                WHERE id = '.$linkId;
1223
1224
        Database::query($sql);
1225
1226
        // Update weight for attendance
1227
        $sql = 'SELECT ref_id FROM '.$table_link.'
1228
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1229
1230
        $rs_attendance  = Database::query($sql);
1231 View Code Duplication
        if (Database::num_rows($rs_attendance) > 0) {
1232
            $row_attendance = Database::fetch_array($rs_attendance);
1233
            $sql = 'UPDATE '.$tbl_attendance.' SET attendance_weight ='.$weight.'
1234
                    WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
1235
            Database::query($sql);
1236
        }
1237
        // Update weight into forum thread
1238
        $sql = 'UPDATE '.$tbl_forum_thread.' SET thread_weight='.$weight.'
1239
                WHERE
1240
                    c_id = '.$course_id.' AND
1241
                    thread_id = (
1242
                        SELECT ref_id FROM '.$table_link.'
1243
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1244
                    )
1245
                ';
1246
        Database::query($sql);
1247
        //Update weight into student publication(work)
1248
        $em
1249
            ->createQuery('
1250
                UPDATE ChamiloCourseBundle:CStudentPublication w
1251
                SET w.weight = :final_weight
1252
                WHERE w.cId = :course
1253
                    AND w.id = (
1254
                        SELECT l.refId FROM ChamiloCoreBundle:GradebookLink l
1255
                        WHERE l.id = :link AND l.type = :type
1256
                    )
1257
            ')
1258
            ->execute([
1259
                'final_weight' => $weight,
1260
                'course' => $course_id,
1261
                'link' => $linkId,
1262
                'type' => LINK_STUDENTPUBLICATION
1263
            ]);
1264
    }
1265
1266
    /**
1267
     * @param int $id
1268
     * @param float $weight
1269
     */
1270 View Code Duplication
    public static function updateEvaluationWeight($id, $weight)
1271
    {
1272
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1273
        $id = intval($id);
1274
        $evaluation = new Evaluation();
1275
        $evaluation->add_evaluation_log($id);
1276
        $sql = 'UPDATE '.$table_evaluation.'
1277
               SET weight = '."'".Database::escape_string($weight)."'".'
1278
               WHERE id = '.$id;
1279
        Database::query($sql);
1280
    }
1281
1282
    /**
1283
     *
1284
     * Get the achieved certificates for a user in courses
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 getUserCertificatesInCourses($userId, $includeNonPublicCertificates = true)
1290
    {
1291
        $userId = intval($userId);
1292
        $courseList = [];
1293
1294
        $courses = CourseManager::get_courses_list_by_user_id($userId);
1295
1296
        foreach ($courses as $course) {
1297
            if (!$includeNonPublicCertificates) {
1298
                $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course['code']);
1299
1300
                if (empty($allowPublicCertificates)) {
1301
                    continue;
1302
                }
1303
            }
1304
1305
            $courseGradebookCategory = Category::load(null, null, $course['code']);
1306
1307
            if (empty($courseGradebookCategory)) {
1308
                continue;
1309
            }
1310
1311
            $courseGradebookId = $courseGradebookCategory[0]->get_id();
1312
1313
            $certificateInfo = GradebookUtils::get_certificate_by_user_id($courseGradebookId, $userId);
1314
1315
            if (empty($certificateInfo)) {
1316
                continue;
1317
            }
1318
1319
            $courseInfo = api_get_course_info_by_id($course['real_id']);
1320
1321
            $courseList[] = [
1322
                'course' => $courseInfo['title'],
1323
                'score' => $certificateInfo['score_certificate'],
1324
                'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1325
                'link' => api_get_path(WEB_PATH) . "certificates/index.php?id={$certificateInfo['id']}"
1326
            ];
1327
        }
1328
1329
        return $courseList;
1330
    }
1331
1332
    /**
1333
     * Get the achieved certificates for a user in course sessions
1334
     * @param int $userId The user id
1335
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1336
     * @return array
1337
     */
1338
    public static function getUserCertificatesInSessions($userId, $includeNonPublicCertificates = true)
1339
    {
1340
        $userId = intval($userId);
1341
        $sessionList = [];
1342
1343
        $sessions = SessionManager::get_sessions_by_user($userId, true, true);
1344
1345
        foreach ($sessions as $session) {
1346
            if (empty($session['courses'])) {
1347
                continue;
1348
            }
1349
            $sessionCourses = SessionManager::get_course_list_by_session_id($session['session_id']);
1350
1351
            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...
1352
                if (!$includeNonPublicCertificates) {
1353
                    $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course['code']);
1354
1355
                    if (empty($allowPublicCertificates)) {
1356
                        continue;
1357
                    }
1358
                }
1359
1360
                $courseGradebookCategory = Category::load(
1361
                    null,
1362
                    null,
1363
                    $course['code'],
1364
                    null,
1365
                    null,
1366
                    $session['session_id']
1367
                );
1368
1369
                if (empty($courseGradebookCategory)) {
1370
                    continue;
1371
                }
1372
1373
                $courseGradebookId = $courseGradebookCategory[0]->get_id();
1374
1375
                $certificateInfo = GradebookUtils::get_certificate_by_user_id(
1376
                    $courseGradebookId,
1377
                    $userId
1378
                );
1379
1380
                if (empty($certificateInfo)) {
1381
                    continue;
1382
                }
1383
1384
                $sessionList[] = [
1385
                    'session' => $session['session_name'],
1386
                    'course' => $course['title'],
1387
                    'score' => $certificateInfo['score_certificate'],
1388
                    'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1389
                    'link' => api_get_path(WEB_PATH) . "certificates/index.php?id={$certificateInfo['id']}"
1390
                ];
1391
            }
1392
        }
1393
1394
        return $sessionList;
1395
    }
1396
1397
    /**
1398
     * @param int $userId
1399
     * @param array $cats
1400
     * @param bool $saveToFile
1401
     * @param bool $saveToHtmlFile
1402
     * @param array $studentList
1403
     * @param PDF $pdf
1404
     *
1405
     * @return string
1406
     */
1407
    public static function generateTable(
1408
        $userId,
1409
        $cats,
1410
        $saveToFile = false,
1411
        $saveToHtmlFile = false,
1412
        $studentList = array(),
1413
        $pdf = null
1414
    ) {
1415
        $courseInfo = api_get_course_info();
1416
        $userInfo = api_get_user_info($userId);
1417
1418
        $cat = $cats[0];
1419
1420
        $allcat = $cats[0]->get_subcategories(
1421
            $userId,
1422
            api_get_course_id(),
1423
            api_get_session_id()
1424
        );
1425
        $alleval = $cats[0]->get_evaluations($userId);
1426
        $alllink = $cats[0]->get_links($userId);
1427
1428
        $gradebooktable = new GradebookTable(
1429
            $cat,
1430
            $allcat,
1431
            $alleval,
1432
            $alllink,
1433
            null, // params
1434
            true, // $exportToPdf
1435
            false, // showteacher
1436
            $userId,
1437
            $studentList
1438
        );
1439
1440
        $gradebooktable->userId = $userId;
1441
1442 View Code Duplication
        if (api_is_allowed_to_edit()) {
1443
            $gradebooktable->td_attributes = [
1444
                4 => 'class=centered'
1445
            ];
1446
        } else {
1447
            $gradebooktable->td_attributes = [
1448
                3 => 'class=centered',
1449
                4 => 'class=centered',
1450
                5 => 'class=centered',
1451
                6 => 'class=centered',
1452
                7 => 'class=centered'
1453
            ];
1454
        }
1455
1456
        $table = $gradebooktable->return_table();
1457
        $graph = $gradebooktable->getGraph();
1458
1459
        $sessionName = api_get_session_name(api_get_session_id());
1460
        $sessionName = !empty($sessionName) ? " - $sessionName" : '';
1461
1462
        $params = array(
1463
            'pdf_title' => sprintf(get_lang('GradeFromX'), $courseInfo['name']),
1464
            'session_info' => '',
1465
            'course_info' => '',
1466
            'pdf_date' => '',
1467
            'course_code' => api_get_course_id(),
1468
            'add_signatures' => false,
1469
            'student_info' => $userInfo,
1470
            'show_grade_generated_date' => true,
1471
            'show_real_course_teachers' => false,
1472
            'show_teacher_as_myself' => false,
1473
            'orientation' => 'P'
1474
        );
1475
1476
        if (empty($pdf)) {
1477
            $pdf = new PDF('A4', $params['orientation'], $params);
1478
        }
1479
1480
        $pdf->params['student_info'] = $userInfo;
1481
1482
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid().'.html';
1483
1484
        $content =
1485
            $table.
1486
            $graph.
1487
            '<br />'.get_lang('Feedback').'<br />
1488
            <textarea rows="5" cols="100" ></textarea>';
1489
1490
        $address = api_get_setting('institution_address');
1491
        $phone = api_get_setting('administratorTelephone');
1492
        $address = str_replace('\n', '<br />', $address);
1493
1494
        $pdf->custom_header = array('html' => "<h5 align='right'>$address <br />$phone</h5>");
1495
1496
        $result = $pdf->html_to_pdf_with_template(
1497
            $content,
1498
            $saveToFile,
1499
            $saveToHtmlFile
1500
        );
1501
1502
        if ($saveToHtmlFile) {
1503
            file_put_contents($file, $result);
1504
            return $file;
1505
        }
1506
1507
        return $file;
1508
    }
1509
}
1510