Passed
Push — 1.10.x ( e86630...7dd9ca )
by
unknown
53:41
created

GradebookUtils::generateTable()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 102
Code Lines 73

Duplication

Lines 13
Ratio 12.75 %
Metric Value
dl 13
loc 102
rs 8.1463
cc 5
eloc 73
nc 16
nop 6

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class GradebookUtils
6
 */
7
class GradebookUtils
8
{
9
    /**
10
     * Adds a resource to the unique gradebook of a given course
11
     * @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
     * @return  boolean True on success, false on failure
23
     */
24
    public static function add_resource_to_course_gradebook(
25
        $category_id,
26
        $course_code,
27
        $resource_type,
28
        $resource_id,
29
        $resource_name = '',
30
        $weight = 0,
31
        $max = 0,
32
        $resource_description = '',
33
        $visible = 0,
34
        $session_id = 0,
35
        $link_id = null
36
    ) {
37
        $link = LinkFactory :: create($resource_type);
38
        $link->set_user_id(api_get_user_id());
39
        $link->set_course_code($course_code);
40
41
        if (empty($category_id)) {
42
            return false;
43
        }
44
        $link->set_category_id($category_id);
45
        if ($link->needs_name_and_description()) {
46
            $link->set_name($resource_name);
47
        } else {
48
            $link->set_ref_id($resource_id);
49
        }
50
        $link->set_weight($weight);
51
52
        if ($link->needs_max()) {
53
            $link->set_max($max);
54
        }
55
        if ($link->needs_name_and_description()) {
56
            $link->set_description($resource_description);
57
        }
58
59
        $link->set_visible(empty($visible) ? 0 : 1);
60
61
        if (!empty($session_id)) {
62
            $link->set_session_id($session_id);
63
        }
64
        $link->add();
65
        return true;
66
    }
67
68
    /**
69
     * Update a resource weight
70
     * @param    int     Link/Resource ID
71
     * @param   string
72
     * @param float
73
     * @return   bool    false on error, true on success
74
     */
75 View Code Duplication
    public static function update_resource_from_course_gradebook($link_id, $course_code, $weight)
76
    {
77
        $course_code = Database::escape_string($course_code);
78
        if (!empty($link_id)) {
79
            $link_id = intval($link_id);
80
            $sql = 'UPDATE ' . Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK) . '
81
                    SET weight = ' . "'" . Database::escape_string((float) $weight) . "'" . '
82
                    WHERE course_code = "' . $course_code . '" AND id = ' . $link_id;
83
            Database::query($sql);
84
        }
85
86
        return true;
87
    }
88
89
    /**
90
     * Remove a resource from the unique gradebook of a given course
91
     * @param    int     Link/Resource ID
92
     * @return   bool    false on error, true on success
93
     */
94 View Code Duplication
    public static function remove_resource_from_course_gradebook($link_id)
95
    {
96
        if (empty($link_id)) {
97
            return false;
98
        }
99
100
        // TODO find the corresponding category (the first one for this course, ordered by ID)
101
        $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
102
        $sql = "DELETE FROM $l WHERE id = ".(int)$link_id;
103
        Database::query($sql);
104
105
        return true;
106
    }
107
108
    /**
109
     * Block students
110
     */
111
    public static function block_students()
112
    {
113
        if (!api_is_allowed_to_edit()) {
114
            api_not_allowed();
115
        }
116
    }
117
118
    /**
119
     * Builds an img tag for a gradebook item
120
     * @param string $type value returned by a gradebookitem's get_icon_name()
0 ignored issues
show
Bug introduced by
There is no parameter named $type. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
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
            if (api_is_allowed_to_edit(null, true)) {
220
221
                // Locking button
222
                if (api_get_setting('gradebook_locking_enabled') == 'true') {
223
                    if ($cat->is_locked()) {
224 View Code Duplication
                        if (api_is_platform_admin()) {
225
                            $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">' .
226
                                Display::return_icon('lock.png', get_lang('UnLockEvaluation'), '', ICON_SIZE_SMALL) . '</a>';
227
                        } else {
228
                            $modify_icons .= '&nbsp;<a href="#">' . Display::return_icon('lock_na.png', get_lang('GradebookLockedAlert'), '', ICON_SIZE_SMALL) . '</a>';
229
                        }
230
                        $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>';
231 View Code Duplication
                    } else {
232
                        $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">' .
233
                            Display::return_icon('unlock.png', get_lang('LockEvaluation'), '', ICON_SIZE_SMALL) . '</a>';
234
                        $modify_icons .= '&nbsp;<a href="#" >' . Display::return_icon('pdf_na.png', get_lang('ExportToPDF'), '', ICON_SIZE_SMALL) . '</a>';
235
                    }
236
                }
237
238
                if (empty($grade_model_id) || $grade_model_id == -1) {
239
                    if ($cat->is_locked() && !api_is_platform_admin()) {
240
                        $modify_icons .= Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
241
                    } else {
242
                        $modify_icons .= '<a href="gradebook_edit_cat.php?' .'editcat=' . $cat->get_id() . '&cidReq=' .$cat->get_course_code() . '&id_session='.$cat->get_session_id().'">' .
243
                            Display::return_icon(
244
                                'edit.png',
245
                                get_lang('Modify'),
246
                                '',
247
                                ICON_SIZE_SMALL
248
                            ) . '</a>';
249
                    }
250
                }
251
252
               $modify_icons .= '<a href="gradebook_edit_all.php?selectcat=' .$cat->get_id() . '&cidReq=' . $cat->get_course_code() . '&id_session='.$cat->get_session_id().'">' .
253
                    Display::return_icon(
254
                        'percentage.png',
255
                        get_lang('EditAllWeights'),
256
                        '',
257
                        ICON_SIZE_SMALL
258
                    ) . '</a>';
259
260
                $modify_icons .= '<a href="gradebook_flatview.php?selectcat=' .$cat->get_id() . '&cidReq=' . $cat->get_course_code() . '&id_session='.$cat->get_session_id(). '">' .
261
                    Display::return_icon(
262
                        'stats.png',
263
                        get_lang('FlatView'),
264
                        '',
265
                        ICON_SIZE_SMALL
266
                    ) . '</a>';
267
                $modify_icons .= '&nbsp;<a href="' . api_get_self() .'?visiblecat=' . $cat->get_id() . '&' .$visibility_command . '=&selectcat=' . $selectcat .'&cidReq=' . $cat->get_course_code() . '&id_session='.$cat->get_session_id(). '">' .
268
                    Display::return_icon(
269
                        $visibility_icon . '.png',
270
                        get_lang('Visible'),
271
                        '',
272
                        ICON_SIZE_SMALL
273
                    ) . '</a>';
274
275 View Code Duplication
                if ($cat->is_locked() && !api_is_platform_admin()) {
276
                    $modify_icons .= Display::return_icon('delete_na.png', get_lang('DeleteAll'), '', ICON_SIZE_SMALL);
277
                } else {
278
                    $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletecat=' . $cat->get_id() . '&selectcat=' . $selectcat . '&cidReq=' . $cat->get_course_code() . '&id_session='.$cat->get_session_id(). '" onclick="return confirmation();">' .
279
                        Display::return_icon('delete.png', get_lang('DeleteAll'), '', ICON_SIZE_SMALL) . '</a>';
280
                }
281
            }
282
283
            return $modify_icons;
284
        }
285
    }
286
287
    /**
288
     * Builds the course or platform admin icons to edit an evaluation
289
     * @param  Evaluation $eval evaluation object
290
     * @param int $selectcat id of selected category
291
     */
292
    public static function build_edit_icons_eval($eval, $selectcat)
293
    {
294
        $status = CourseManager::get_user_in_course_status(api_get_user_id(), api_get_course_id());
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
300
        if ($message_eval === false && api_is_allowed_to_edit(null, true)) {
301
            $visibility_icon = ($eval->is_visible() == 0) ? 'invisible' : 'visible';
302
            $visibility_command = ($eval->is_visible() == 0) ? 'set_visible' : 'set_invisible';
303 View Code Duplication
            if ($is_locked && !api_is_platform_admin()) {
304
                $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
305
            } else {
306
                $modify_icons = '<a href="gradebook_edit_eval.php?editeval=' . $eval->get_id() . '&cidReq=' . $eval->get_course_code() . '&id_session='.$eval->getSessionId(). '">' .
307
                    Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
308
            }
309
310
            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visibleeval=' . $eval->get_id() . '&' . $visibility_command . '=&selectcat=' . $selectcat . '&id_session='.$eval->getSessionId(). ' ">' .
311
                Display::return_icon($visibility_icon . '.png', get_lang('Visible'), '', ICON_SIZE_SMALL) . '</a>';
312
            if (api_is_allowed_to_edit(null, true)) {
313
                $modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog=' . $eval->get_id() . '&selectcat=' . $selectcat . ' &cidReq=' . $eval->get_course_code() . '&id_session='.$eval->getSessionId(). '">' .
314
                    Display::return_icon('history.png', get_lang('GradebookQualifyLog'), '', ICON_SIZE_SMALL) . '</a>';
315
            }
316
317 View Code Duplication
            if ($is_locked && !api_is_platform_admin()) {
318
                $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
319
            } else {
320
                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deleteeval=' . $eval->get_id() . '&selectcat=' . $selectcat . ' &cidReq=' . $eval->get_course_code() . '&id_session='.$eval->getSessionId(). '" onclick="return confirmation();">' . Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
321
            }
322
            return $modify_icons;
323
        }
324
    }
325
326
    /**
327
     * Builds the course or platform admin icons to edit a link
328
     * @param AbstractLink $link
329
     * @param int $selectcat id of selected category
330
     */
331
    public static function build_edit_icons_link($link, $selectcat)
332
    {
333
        $cat = new Category();
334
        $message_link = $cat->show_message_resource_delete($link->get_course_code());
335
        $is_locked = $link->is_locked();
336
337
        $modify_icons = null;
338
339
        if (!api_is_allowed_to_edit(null, true)) {
340
            return null;
341
        }
342
343
        if ($message_link === false) {
344
            $visibility_icon = ($link->is_visible() == 0) ? 'invisible' : 'visible';
345
            $visibility_command = ($link->is_visible() == 0) ? 'set_visible' : 'set_invisible';
346
347 View Code Duplication
            if ($is_locked && !api_is_platform_admin()) {
348
                $modify_icons = Display::return_icon('edit_na.png', get_lang('Modify'), '', ICON_SIZE_SMALL);
349
            } else {
350
                $modify_icons = '<a href="gradebook_edit_link.php?editlink=' . $link->get_id() . '&cidReq=' . $link->get_course_code() . '&id_session='.$link->get_session_id().'">' .
351
                    Display::return_icon('edit.png', get_lang('Modify'), '', ICON_SIZE_SMALL) . '</a>';
352
            }
353
            $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visiblelink=' . $link->get_id() . '&' . $visibility_command . '=&selectcat=' . $selectcat . '&id_session='.$link->get_session_id(). ' ">' .
354
                Display::return_icon($visibility_icon . '.png', get_lang('Visible'), '', ICON_SIZE_SMALL) . '</a>';
355
            $modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink=' . $link->get_id() . '&selectcat=' . $selectcat . '&cidReq=' . $link->get_course_code() . '&id_session='.$link->get_session_id(). '">' .
356
                Display::return_icon('history.png', get_lang('GradebookQualifyLog'), '', ICON_SIZE_SMALL) . '</a>';
357
358
            //If a work is added in a gradebook you can only delete the link in the work tool
359
360 View Code Duplication
            if ($is_locked && !api_is_platform_admin()) {
361
                $modify_icons .= '&nbsp;' . Display::return_icon('delete_na.png', get_lang('Delete'), '', ICON_SIZE_SMALL);
362
            } else {
363
                $modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletelink=' . $link->get_id() . '&selectcat=' . $selectcat . ' &cidReq=' . $link->get_course_code() . '&id_session='.$link->get_session_id(). '" onclick="return confirmation();">' .
364
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL) . '</a>';
365
            }
366
            return $modify_icons;
367
        }
368
    }
369
370
    /**
371
     * Checks if a resource is in the unique gradebook of a given course
372
     * @param    string  Course code
373
     * @param    int     Resource type (use constants defined in linkfactory.class.php)
374
     * @param    int     Resource ID in the corresponding tool
375
     * @param    int     Session ID (optional -  0 if not defined)
376
     * @return   int     false on error or array of resource
377
     */
378
    public static function is_resource_in_course_gradebook($course_code, $resource_type, $resource_id, $session_id = 0)
379
    {
380
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
381
        $course_code = Database::escape_string($course_code);
382
        $sql = "SELECT * FROM $table l
383
                WHERE
384
                    course_code = '$course_code' AND
385
                    type = ".(int)$resource_type . " AND
386
                    ref_id = " . (int)$resource_id;
387
        $res = Database::query($sql);
388
389
        if (Database::num_rows($res) < 1) {
390
            return false;
391
        }
392
        $row = Database::fetch_array($res, 'ASSOC');
393
        return $row;
394
    }
395
396
    /**
397
     * Remove a resource from the unique gradebook of a given course
398
     * @param    int     Link/Resource ID
399
     * @return   bool    false on error, true on success
400
     */
401
    public static function get_resource_from_course_gradebook($link_id)
402
    {
403
        if (empty($link_id)) {
404
            return false;
405
        }
406
        // TODO find the corresponding category (the first one for this course, ordered by ID)
407
        $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
408
        $sql = "SELECT * FROM $l WHERE id = " . (int) $link_id;
409
        $res = Database::query($sql);
410
        $row = array();
411
        if (Database::num_rows($res) > 0) {
412
            $row = Database::fetch_array($res, 'ASSOC');
413
        }
414
        return $row;
415
    }
416
417
    /**
418
     * Return the course id
419
     * @param    int
420
     * @return   String
421
     */
422 View Code Duplication
    public static function get_course_id_by_link_id($id_link)
423
    {
424
        $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
425
        $tbl_grade_links = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
426
        $sql = 'SELECT c.id FROM ' . $course_table . ' c
427
                INNER JOIN ' . $tbl_grade_links . ' l
428
                ON c.code = l.course_code
429
                WHERE l.id=' . intval($id_link) . ' OR l.category_id=' . intval($id_link);
430
        $res = Database::query($sql);
431
        $array = Database::fetch_array($res, 'ASSOC');
432
        return $array['id'];
433
    }
434
435
    /**
436
     * @param $type
437
     * @return string
438
     */
439
    public static function get_table_type_course($type)
440
    {
441
        global $table_evaluated;
442
        return Database::get_course_table($table_evaluated[$type][0]);
443
    }
444
445
    /**
446
     * @param Category $cat
447
     * @param $users
448
     * @param $alleval
449
     * @param $alllinks
450
     * @param $params
451
     * @param null $mainCourseCategory
452
     * @return array
453
     */
454
    public static function get_printable_data($cat, $users, $alleval, $alllinks, $params, $mainCourseCategory = null)
455
    {
456
        $datagen = new FlatViewDataGenerator(
457
            $users,
458
            $alleval,
459
            $alllinks,
460
            $params,
461
            $mainCourseCategory
462
        );
463
464
        $offset = isset($_GET['offset']) ? $_GET['offset'] : '0';
465
        $offset = intval($offset);
466
467
        // step 2: generate rows: students
468
        $datagen->category = $cat;
0 ignored issues
show
Documentation Bug introduced by
It seems like $cat of type object<Category> is incompatible with the declared type array of property $category.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
469
470
        $count = (($offset + 10) > $datagen->get_total_items_count()) ? ($datagen->get_total_items_count() - $offset) : GRADEBOOK_ITEM_LIMIT;
471
        $header_names = $datagen->get_header_names($offset, $count, true);
472
        $data_array = $datagen->get_data(
473
            FlatViewDataGenerator :: FVDG_SORT_LASTNAME,
474
            0,
475
            null,
476
            $offset,
477
            $count,
478
            true,
479
            true
480
        );
481
482
        $result = array();
483
        foreach ($data_array as $data) {
484
            $result[] = array_slice($data, 1);
485
        }
486
        $return = array($header_names, $result);
487
488
        return $return;
489
    }
490
491
    /**
492
     * XML-parser: handle character data
493
     */
494
    public static function character_data($parser, $data)
495
    {
496
        global $current_value;
497
        $current_value = $data;
498
    }
499
500
    /**
501
     * XML-parser: handle end of element
502
     */
503
    public static function element_end($parser, $data)
504
    {
505
        global $user;
506
        global $users;
507
        global $current_value;
508
        switch ($data) {
509
            case 'Result' :
510
                $users[] = $user;
511
                break;
512
            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
513
                $user[$data] = $current_value;
514
                break;
515
        }
516
    }
517
518
    /**
519
     * XML-parser: handle start of element
520
     */
521
    public static function element_start($parser, $data)
522
    {
523
        global $user;
524
        global $current_tag;
525
        switch ($data) {
526
            case 'Result' :
527
                $user = array();
528
                break;
529
            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
530
                $current_tag = $data;
531
        }
532
    }
533
534
    public static function overwritescore($resid, $importscore, $eval_max)
535
    {
536
        $result = Result :: load($resid);
537
        if ($importscore > $eval_max) {
538
            header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&overwritemax=');
539
            exit;
540
        }
541
        $result[0]->set_score($importscore);
542
        $result[0]->save();
543
        unset($result);
544
    }
545
546
    /**
547
     * Read the XML-file
548
     * @param string $file Path to the XML-file
549
     * @return array All user information read from the file
550
     */
551 View Code Duplication
    public static function parse_xml_data($file)
552
    {
553
        global $current_tag;
554
        global $current_value;
555
        global $user;
556
        global $users;
557
        $users = array();
558
        $parser = xml_parser_create();
559
        xml_set_element_handler($parser, 'element_start', 'element_end');
560
        xml_set_character_data_handler($parser, "character_data");
561
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
562
        xml_parse($parser, file_get_contents($file));
563
        xml_parser_free($parser);
564
        return $users;
565
    }
566
567
    /**
568
     * register user info about certificate
569
     * @param int The category id
570
     * @param int The user id
571
     * @param float The score obtained for certified
572
     * @param Datetime The date when you obtained the certificate
573
     * @return void()
0 ignored issues
show
Documentation introduced by
The doc-type void() could not be parsed: Expected "|" or "end of type", but got "(" at position 4. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
574
     */
575
    public static function register_user_info_about_certificate($cat_id, $user_id, $score_certificate, $date_certificate)
576
    {
577
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
578
        $sql = 'SELECT COUNT(*) as count
579
                FROM ' . $table . ' gc
580
                WHERE gc.cat_id="' . intval($cat_id) . '" AND user_id="' . intval($user_id) . '" ';
581
        $rs_exist = Database::query($sql);
582
        $row = Database::fetch_array($rs_exist);
583
        if ($row['count'] == 0) {
584
            $params = [
585
                'cat_id' => $cat_id,
586
                'user_id' => $user_id,
587
                'score_certificate' => $score_certificate,
588
                'created_at' => $date_certificate
589
            ];
590
            Database::insert($table, $params);
591
        }
592
    }
593
594
    /**
595
     * Get date of user certificate
596
     * @param int $cat_id The category id
597
     * @param int $user_id The user id
598
     * @return Datetime The date when you obtained the certificate
599
     */
600
    public static function get_certificate_by_user_id($cat_id, $user_id)
601
    {
602
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
603
        $sql = 'SELECT * FROM ' . $table_certificate . '
604
                WHERE cat_id="' . intval($cat_id) . '" AND user_id="' . intval($user_id) . '"';
605
606
        $result = Database::query($sql);
607
        $row = Database::fetch_array($result, 'ASSOC');
608
609
        return $row;
610
    }
611
612
    /**
613
     * Get list of users certificates
614
     * @param int $cat_id The category id
615
     * @param array $userList Only users in this list
616
     * @return array
617
     */
618
    public static function get_list_users_certificates($cat_id = null, $userList = array())
619
    {
620
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
621
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
622
        $sql = 'SELECT DISTINCT u.user_id, u.lastname, u.firstname, u.username
623
                FROM ' . $table_user . ' u
624
                INNER JOIN ' . $table_certificate . ' gc
625
                ON u.user_id=gc.user_id ';
626 View Code Duplication
        if (!is_null($cat_id) && $cat_id > 0) {
627
            $sql.=' WHERE cat_id=' . intval($cat_id);
628
        }
629
        if (!empty($userList)) {
630
            $userList = array_map('intval', $userList);
631
            $userListCondition = implode("','", $userList);
632
            $sql .= " AND u.user_id IN ('$userListCondition')";
633
        }
634
        $sql.=' ORDER BY u.firstname';
635
        $rs = Database::query($sql);
636
637
        $list_users = array();
638
        while ($row = Database::fetch_array($rs)) {
639
            $list_users[] = $row;
640
        }
641
642
        return $list_users;
643
    }
644
645
    /**
646
     * Gets the certificate list by user id
647
     * @param int $user_id The user id
648
     * @param int $cat_id The category id
649
     * @return array
650
     */
651
    public static function get_list_gradebook_certificates_by_user_id($user_id, $cat_id = null)
652
    {
653
        $table_certificate = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CERTIFICATE);
654
        $sql = 'SELECT gc.score_certificate, gc.created_at, gc.path_certificate, gc.cat_id, gc.user_id, gc.id
655
                FROM  ' . $table_certificate . ' gc
656
                WHERE gc.user_id="' . intval($user_id) . '" ';
657 View Code Duplication
        if (!is_null($cat_id) && $cat_id > 0) {
658
            $sql.=' AND cat_id=' . intval($cat_id);
659
        }
660
661
        $rs = Database::query($sql);
662
        $list_certificate = array();
663
        while ($row = Database::fetch_array($rs)) {
664
            $list_certificate[] = $row;
665
        }
666
        return $list_certificate;
667
    }
668
669
    /**
670
     * @param int $user_id
671
     * @param string $course_code
672
     * @param int $sessionId
673
     * @param bool $is_preview
674
     * @param bool $hide_print_button
675
     *
676
     * @return array
677
     */
678
    public static function get_user_certificate_content($user_id, $course_code, $sessionId, $is_preview = false, $hide_print_button = false)
679
    {
680
        // Generate document HTML
681
        $content_html = DocumentManager::replace_user_info_into_html($user_id, $course_code, $sessionId, $is_preview);
682
        $new_content_html = null;
683
        $variables = null;
684
        $contentHead = null;
685
686
        if (isset($content_html['content'])) {
687
            $new_content = explode('</head>', $content_html['content']);
688
            $new_content_html = $new_content[1];
689
            $contentHead = $new_content[0];
690
        }
691
692
        if (isset($content_html['variables'])) {
693
            $variables = $content_html['variables'];
694
        }
695
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
        //add print header
704 View Code Duplication
        if ($hide_print_button == false) {
705
            $print = '<style media="print" type="text/css">#print_div {visibility:hidden;}</style>';
706
            $print .= '<a href="javascript:window.print();" style="float:right; padding:4px;" id="print_div">';
707
            $print .= Display::return_icon('printmgr.gif', get_lang('Print'));
708
            $print .= '</a>';
709
        }
710
711
        // Add header
712
        $new_content_html =  $contentHead. $print . '</head>' . $new_content_html;
713
714
        return array(
715
            'content' => $new_content_html,
716
            'variables' => $variables
717
        );
718
    }
719
720
    /**
721
     * @param null $course_code
722
     * @param int $gradebook_model_id
723
     * @return mixed
724
     */
725
    public static function create_default_course_gradebook($course_code = null, $gradebook_model_id = 0)
726
    {
727
        if (api_is_allowed_to_edit(true, true)) {
728
            if (!isset($course_code) || empty($course_code)) {
729
                $course_code = api_get_course_id();
730
            }
731
            $session_id = api_get_session_id();
732
733
            $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
734
            $sql = "SELECT * FROM $t WHERE course_code = '" . Database::escape_string($course_code) . "' ";
735
            if (!empty($session_id)) {
736
                $sql .= " AND session_id = " . (int) $session_id;
737
            } else {
738
                $sql .= " AND (session_id IS NULL OR session_id = 0) ";
739
            }
740
            $sql .= " ORDER BY id";
741
            $res = Database::query($sql);
742
            if (Database::num_rows($res) < 1) {
743
                //there is no unique category for this course+session combination,
744
                $cat = new Category();
745 View Code Duplication
                if (!empty($session_id)) {
746
                    $my_session_id = api_get_session_id();
747
                    $s_name = api_get_session_name($my_session_id);
748
                    $cat->set_name($course_code . ' - ' . get_lang('Session') . ' ' . $s_name);
749
                    $cat->set_session_id($session_id);
750
                } else {
751
                    $cat->set_name($course_code);
752
                }
753
                $cat->set_course_code($course_code);
754
                $cat->set_description(null);
755
                $cat->set_user_id(api_get_user_id());
756
                $cat->set_parent_id(0);
757
                $default_weight_setting = api_get_setting('gradebook_default_weight');
758
                $default_weight = isset($default_weight_setting) && !empty($default_weight_setting) ? $default_weight_setting : 100;
759
                $cat->set_weight($default_weight);
760
761
                $cat->set_grade_model_id($gradebook_model_id);
762
                $cat->set_certificate_min_score(75);
763
764
                $cat->set_visible(0);
765
                $cat->add();
766
                $category_id = $cat->get_id();
767
                unset($cat);
768
            } else {
769
                $row = Database::fetch_array($res);
770
                $category_id = $row['id'];
771
            }
772
            
773
            return $category_id;
774
        }
775
776
        return false;
777
    }
778
779
    /**
780
     * @param FormValidator $form
781
     */
782
    public static function load_gradebook_select_in_tool($form)
783
    {
784
        $course_code = api_get_course_id();
785
        $session_id = api_get_session_id();
786
787
        self::create_default_course_gradebook();
788
789
        // Cat list
790
        $all_categories = Category :: load(null, null, $course_code, null, null, $session_id, false);
791
        $select_gradebook = $form->addElement('select', 'category_id', get_lang('SelectGradebook'));
792
793
        if (!empty($all_categories)) {
794
            foreach ($all_categories as $my_cat) {
795 View Code Duplication
                if ($my_cat->get_course_code() == api_get_course_id()) {
796
                    $grade_model_id = $my_cat->get_grade_model_id();
797
                    if (empty($grade_model_id)) {
798
                        if ($my_cat->get_parent_id() == 0) {
799
                            //$default_weight = $my_cat->get_weight();
800
                            $select_gradebook->addoption(get_lang('Default'), $my_cat->get_id());
801
                            $cats_added[] = $my_cat->get_id();
802
                        } else {
803
                            $select_gradebook->addoption($my_cat->get_name(), $my_cat->get_id());
804
                            $cats_added[] = $my_cat->get_id();
805
                        }
806
                    } else {
807
                        $select_gradebook->addoption(get_lang('Select'), 0);
808
                    }
809
                }
810
            }
811
        }
812
    }
813
814
    /**
815
     * @param FlatViewTable $flatviewtable
816
     * @param Category $cat
817
     * @param $users
818
     * @param $alleval
819
     * @param $alllinks
820
     * @param array $params
821
     * @param null $mainCourseCategory
822
     */
823
    public static function export_pdf_flatview(
824
        $flatviewtable,
825
        $cat,
826
        $users,
827
        $alleval,
828
        $alllinks,
829
        $params = array(),
830
        $mainCourseCategory = null
831
    ) {
832
833
        // Getting data
834
        $printable_data = self::get_printable_data($cat[0], $users, $alleval, $alllinks, $params, $mainCourseCategory);
835
836
        // HTML report creation first
837
        $course_code = trim($cat[0]->get_course_code());
838
839
        $displayscore = ScoreDisplay :: instance();
840
        $customdisplays = $displayscore->get_custom_score_display_settings();
841
842
        $total = array();
843
        if (is_array($customdisplays) && count(($customdisplays))) {
844
            foreach ($customdisplays as $custom) {
845
                $total[$custom['display']] = 0;
846
            }
847
            $user_results = $flatviewtable->datagen->get_data_to_graph2(false);
848
            foreach ($user_results as $user_result) {
849
                $total[$user_result[count($user_result) - 1][1]]++;
850
            }
851
        }
852
853
        $parent_id = $cat[0]->get_parent_id();
854
        if (isset($cat[0]) && isset($parent_id)) {
855
            if ($parent_id == 0) {
856
                $grade_model_id = $cat[0]->get_grade_model_id();
857
            } else {
858
                $parent_cat = Category::load($parent_id);
859
                $grade_model_id = $parent_cat[0]->get_grade_model_id();
860
            }
861
        }
862
863
        $use_grade_model = true;
864
        if (empty($grade_model_id) || $grade_model_id == -1) {
865
            $use_grade_model = false;
866
        }
867
868
        if ($use_grade_model) {
869
            if ($parent_id == 0) {
870
                $title = api_strtoupper(get_lang('Average')) . '<br />' . get_lang('Detailed');
871
            } else {
872
                $title = api_strtoupper(get_lang('Average')) . '<br />' . $cat[0]->get_description() . ' - (' . $cat[0]->get_name() . ')';
873
            }
874
        } else {
875
            if ($parent_id == 0) {
876
                $title = api_strtoupper(get_lang('Average')) . '<br />' . get_lang('Detailed');
877
            } else {
878
                $title = api_strtoupper(get_lang('Average'));
879
            }
880
        }
881
882
        $columns = count($printable_data[0]);
883
        $has_data = is_array($printable_data[1]) && count($printable_data[1]) > 0;
884
885
        $table = new HTML_Table(array('class' => 'data_table'));
886
        $row = 0;
887
        $column = 0;
888
889
        $table->setHeaderContents($row, $column, get_lang('NumberAbbreviation'));
890
        $column++;
891
        foreach ($printable_data[0] as $printable_data_cell) {
892
            if (!is_array($printable_data_cell)) {
893
                $printable_data_cell = strip_tags($printable_data_cell);
894
            }
895
            $table->setHeaderContents($row, $column, $printable_data_cell);
896
            $column++;
897
        }
898
        $row++;
899
900
        if ($has_data) {
901
            $counter = 1;
902
            foreach ($printable_data[1] as &$printable_data_row) {
903
                $column = 0;
904
                $table->setCellContents($row, $column, $counter);
905
                $table->updateCellAttributes($row, $column, 'align="center"');
906
                $column++;
907
                $counter++;
908
909
                foreach ($printable_data_row as $key => &$printable_data_cell) {
910
                    $attributes = array();
911
                    $attributes['align'] = 'center';
912
                    $attributes['style'] = null;
913
914
                    if ($key === 'name') {
915
                        $attributes['align'] = 'left';
916
                    }
917
                    if ($key === 'total') {
918
                        $attributes['style'] = 'font-weight:bold';
919
                    }
920
                    $table->setCellContents($row, $column, $printable_data_cell);
921
                    $table->updateCellAttributes($row, $column, $attributes);
922
                    $column++;
923
                }
924
                $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
925
                $row++;
926
            }
927
        } else {
928
            $column = 0;
929
            $table->setCellContents($row, $column, get_lang('NoResults'));
930
            $table->updateCellAttributes($row, $column, 'colspan="' . $columns . '" align="center" class="row_odd"');
931
        }
932
933
        $pdfParams = array(
934
            'filename' => get_lang('FlatView') . '_' . api_get_utc_datetime(),
935
            'pdf_title' => $title,
936
            'course_code' => $course_code,
937
            'add_signatures' => true
938
        );
939
940
        $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
941
        ob_start();
942
        $pdf = new PDF($page_format, $page_format, $pdfParams);
943
        $pdf->html_to_pdf_with_template($flatviewtable->return_table());
944
        $content = ob_get_contents();
945
        ob_end_clean();
946
        echo $content;
947
        exit;
948
    }
949
950
    /**
951
     * @param array $list_values
952
     * @return string
953
     */
954
    public static function score_badges($list_values)
955
    {
956
        $counter = 1;
957
        $badges = array();
958
        foreach ($list_values as $value) {
959
            $class = 'warning';
960
            if ($counter == 1) {
961
                $class = 'success';
962
            }
963
            $counter++;
964
            $badges[] = Display::badge($value, $class);
965
        }
966
        return Display::badge_group($badges);
967
    }
968
969
    /**
970
     * returns users within a course given by param
971
     * @param string $courseCode
972
     */
973
    public static function get_users_in_course($courseCode)
974
    {
975
        $tbl_course_user = Database:: get_main_table(TABLE_MAIN_COURSE_USER);
976
        $tbl_session_course_user = Database:: get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
977
        $tbl_user = Database:: get_main_table(TABLE_MAIN_USER);
978
        $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname ASC' : ' ORDER BY lastname, firstname ASC';
979
980
        $current_session = api_get_session_id();
981
        $courseCode = Database::escape_string($courseCode);
982
        $courseInfo = api_get_course_info($courseCode);
983
        $courseId = $courseInfo['real_id'];
984
985
        if (!empty($current_session)) {
986
            $sql = "SELECT user.user_id, user.username, lastname, firstname, official_code
987
                    FROM $tbl_session_course_user as scru, $tbl_user as user
988
                    WHERE
989
                        scru.user_id = user.user_id AND
990
                        scru.status=0  AND
991
                        scru.c_id='$courseId' AND
992
                        session_id ='$current_session'
993
                    $order_clause
994
                    ";
995
        } else {
996
            $sql = 'SELECT user.user_id, user.username, lastname, firstname, official_code
997
                    FROM '.$tbl_course_user.' as course_rel_user, '.$tbl_user.' as user
998
                    WHERE
999
                        course_rel_user.user_id=user.user_id AND
1000
                        course_rel_user.status='.STUDENT.' AND
1001
                        course_rel_user.c_id = "'.$courseId.'" '.
1002
                    $order_clause;
1003
        }
1004
1005
        $result = Database::query($sql);
1006
1007
        return self::get_user_array_from_sql_result($result);
1008
    }
1009
1010
    /**
1011
     * @param $result
1012
     * @return array
1013
     */
1014
    public static function get_user_array_from_sql_result($result)
1015
    {
1016
        $a_students = array();
1017
        while ($user = Database::fetch_array($result)) {
1018
            if (!array_key_exists($user['user_id'], $a_students)) {
1019
                $a_current_student = array ();
1020
                $a_current_student[] = $user['user_id'];
1021
                $a_current_student[] = $user['username'];
1022
                $a_current_student[] = $user['lastname'];
1023
                $a_current_student[] = $user['firstname'];
1024
                $a_current_student[] = $user['official_code'];
1025
                $a_students['STUD'.$user['user_id']] = $a_current_student;
1026
            }
1027
        }
1028
        return $a_students;
1029
    }
1030
1031
    /**
1032
     * @param array $evals
1033
     * @param array $links
1034
     * @return array
1035
     */
1036
    public static function get_all_users($evals = array(), $links = array())
1037
    {
1038
        $coursecodes = array();
1039
        $users = array();
1040
1041
        // By default add all user in course
1042
        $coursecodes[api_get_course_id()] = '1';
1043
        $users = GradebookUtils::get_users_in_course(api_get_course_id());
1044
1045
        foreach ($evals as $eval) {
1046
            $coursecode = $eval->get_course_code();
1047
            // evaluation in course
1048
            if (isset($coursecode) && !empty($coursecode)) {
1049 View Code Duplication
                if (!array_key_exists($coursecode, $coursecodes)) {
1050
                    $coursecodes[$coursecode] = '1';
1051
                    $users = array_merge($users, GradebookUtils::get_users_in_course($coursecode));
1052
                }
1053
            } else {
1054
                // course independent evaluation
1055
                $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
1056
                $tbl_res = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
1057
1058
                $sql = 'SELECT user.user_id, lastname, firstname, user.official_code
1059
                        FROM '.$tbl_res.' as res, '.$tbl_user.' as user
1060
                        WHERE
1061
                            res.evaluation_id = '.intval($eval->get_id()).' AND
1062
                            res.user_id = user.user_id
1063
                        ';
1064
                $sql .= ' ORDER BY lastname, firstname';
1065
                if (api_is_western_name_order()) {
1066
                    $sql .= ' ORDER BY firstname, lastname';
1067
                }
1068
1069
                $result = Database::query($sql);
1070
                $users = array_merge($users, GradebookUtils::get_user_array_from_sql_result($result));
1071
            }
1072
        }
1073
1074
        foreach ($links as $link) {
1075
            // links are always in a course
1076
            $coursecode = $link->get_course_code();
1077 View Code Duplication
            if (!array_key_exists($coursecode,$coursecodes)) {
1078
                $coursecodes[$coursecode] = '1';
1079
                $users = array_merge($users, GradebookUtils::get_users_in_course($coursecode));
1080
            }
1081
        }
1082
1083
        return $users;
1084
    }
1085
1086
    /**
1087
     * Search students matching a given last name and/or first name
1088
     * @author Bert Steppé
1089
     */
1090
    public static function find_students($mask= '')
1091
    {
1092
        // students shouldn't be here // don't search if mask empty
1093
        if (!api_is_allowed_to_edit() || empty ($mask)) {
1094
            return null;
1095
        }
1096
        $mask = Database::escape_string($mask);
1097
1098
        $tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
1099
        $tbl_cru = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
1100
        $sql = 'SELECT DISTINCT user.user_id, user.lastname, user.firstname, user.email, user.official_code
1101
                FROM ' . $tbl_user . ' user';
1102
        if (!api_is_platform_admin()) {
1103
            $sql .= ', ' . $tbl_cru . ' cru';
1104
        }
1105
1106
        $sql .= ' WHERE user.status = ' . STUDENT;
1107
        $sql .= ' AND (user.lastname LIKE '."'%" . $mask . "%'";
1108
        $sql .= ' OR user.firstname LIKE '."'%" . $mask . "%')";
1109
1110
        if (!api_is_platform_admin()) {
1111
            $sql .= ' AND user.user_id = cru.user_id AND
1112
                      cru.relation_type <> '.COURSE_RELATION_TYPE_RRHH.' AND
1113
                      cru.c_id in (
1114
                            SELECT c_id FROM '.$tbl_cru . '
1115
                            WHERE
1116
                                user_id = ' . api_get_user_id() . ' AND
1117
                                status = ' . COURSEMANAGER . '
1118
                        )
1119
                    ';
1120
        }
1121
1122
        $sql .= ' ORDER BY lastname, firstname';
1123
        if (api_is_western_name_order()) {
1124
            $sql .= ' ORDER BY firstname, lastname';
1125
        }
1126
1127
        $result = Database::query($sql);
1128
        $users = Database::store_result($result);
1129
1130
        return $users;
1131
    }
1132
1133
    /**
1134
     * @param int $linkId
1135
     * @param float $weight
1136
     */
1137
    public static function updateLinkWeight($linkId, $name, $weight)
1138
    {
1139
        $linkId = intval($linkId);
1140
        $weight = floatval($weight);
1141
        $course_id = api_get_course_int_id();
1142
1143
        AbstractLink::add_link_log($linkId, $name);
1144
        $table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
1145
1146
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1147
        $tbl_forum_thread = Database:: get_course_table(TABLE_FORUM_THREAD);
1148
        $tbl_work = Database:: get_course_table(TABLE_STUDENT_PUBLICATION);
1149
        $tbl_attendance = Database:: get_course_table(TABLE_ATTENDANCE);
1150
1151
        $sql = 'UPDATE '.$table_link.' SET weight = '."'".Database::escape_string($weight)."'".'
1152
                WHERE id = '.$linkId;
1153
1154
        Database::query($sql);
1155
1156
        // Update weight for attendance
1157
        $sql = 'SELECT ref_id FROM '.$table_link.'
1158
                WHERE id = '.$linkId.' AND type='.LINK_ATTENDANCE;
1159
1160
        $rs_attendance  = Database::query($sql);
1161 View Code Duplication
        if (Database::num_rows($rs_attendance) > 0) {
1162
            $row_attendance = Database::fetch_array($rs_attendance);
1163
            $sql = 'UPDATE '.$tbl_attendance.' SET attendance_weight ='.$weight.'
1164
                    WHERE c_id = '.$course_id.' AND  id = '.intval($row_attendance['ref_id']);
1165
            Database::query($sql);
1166
        }
1167
        // Update weight into forum thread
1168
        $sql = 'UPDATE '.$tbl_forum_thread.' SET thread_weight='.$weight.'
1169
                WHERE
1170
                    c_id = '.$course_id.' AND
1171
                    thread_id = (
1172
                        SELECT ref_id FROM '.$table_link.'
1173
                        WHERE id='.$linkId.' AND type='.LINK_FORUM_THREAD.'
1174
                    )
1175
                ';
1176
        Database::query($sql);
1177
        //Update weight into student publication(work)
1178
        $sql = 'UPDATE '.$tbl_work.' SET weight='.$weight.'
1179
                WHERE
1180
                    c_id = '.$course_id.' AND id = (
1181
                    SELECT ref_id FROM '.$table_link.'
1182
                    WHERE id='.$linkId.' AND type = '.LINK_STUDENTPUBLICATION.'
1183
                ) ';
1184
        Database::query($sql);
1185
    }
1186
1187
    /**
1188
     * @param int $id
1189
     * @param float $weight
1190
     */
1191
    public static function updateEvaluationWeight($id, $weight)
1192
    {
1193
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
1194
        $id = intval($id);
1195
        $evaluation = new Evaluation();
1196
        $evaluation->add_evaluation_log($id);
1197
        $sql = 'UPDATE '.$table_evaluation.'
1198
               SET weight = '."'".Database::escape_string($weight)."'".'
1199
               WHERE id = '.$id;
1200
        Database::query($sql);
1201
    }
1202
1203
    /**
1204
     *
1205
     * Get the achieved certificates for a user in courses
1206
     * @param int $userId The user id
1207
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1208
     * @return array
1209
     */
1210
    public static function getUserCertificatesInCourses($userId, $includeNonPublicCertificates = true)
1211
    {
1212
        $userId = intval($userId);
1213
        $courseList = [];
1214
1215
        $courses = CourseManager::get_courses_list_by_user_id($userId);
1216
1217
        foreach ($courses as $course) {
1218
            if (!$includeNonPublicCertificates) {
1219
                $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course['code']);
1220
1221
                if (empty($allowPublicCertificates)) {
1222
                    continue;
1223
                }
1224
            }
1225
1226
            $courseGradebookCategory = Category::load(null, null, $course['code']);
1227
1228
            if (empty($courseGradebookCategory)) {
1229
                continue;
1230
            }
1231
1232
            $courseGradebookId = $courseGradebookCategory[0]->get_id();
1233
1234
            $certificateInfo = GradebookUtils::get_certificate_by_user_id($courseGradebookId, $userId);
1235
1236
            if (empty($certificateInfo)) {
1237
                continue;
1238
            }
1239
1240
            $courseInfo = api_get_course_info_by_id($course['real_id']);
1241
1242
            $courseList[] = [
1243
                'course' => $courseInfo['title'],
1244
                'score' => $certificateInfo['score_certificate'],
1245
                'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1246
                'link' => api_get_path(WEB_PATH) . "certificates/index.php?id={$certificateInfo['id']}"
1247
            ];
1248
        }
1249
1250
        return $courseList;
1251
    }
1252
1253
    /**
1254
     * Get the achieved certificates for a user in course sessions
1255
     * @param int $userId The user id
1256
     * @param bool $includeNonPublicCertificates Whether include the non-plublic certificates
1257
     * @return array
1258
     */
1259
    public static function getUserCertificatesInSessions($userId, $includeNonPublicCertificates = true)
1260
    {
1261
        $userId = intval($userId);
1262
        $sessionList = [];
1263
1264
        $sessions = SessionManager::get_sessions_by_user($userId, true, true);
1265
1266
        foreach ($sessions as $session) {
1267
            if (empty($session['courses'])) {
1268
                continue;
1269
            }
1270
            $sessionCourses = SessionManager::get_course_list_by_session_id($session['session_id']);
1271
1272
            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...
1273
                if (!$includeNonPublicCertificates) {
1274
                    $allowPublicCertificates = api_get_course_setting('allow_public_certificates', $course['code']);
1275
1276
                    if (empty($allowPublicCertificates)) {
1277
                        continue;
1278
                    }
1279
                }
1280
1281
                $courseGradebookCategory = Category::load(
1282
                    null,
1283
                    null,
1284
                    $course['code'],
1285
                    null,
1286
                    null,
1287
                    $session['session_id']
1288
                );
1289
1290
                if (empty($courseGradebookCategory)) {
1291
                    continue;
1292
                }
1293
1294
                $courseGradebookId = $courseGradebookCategory[0]->get_id();
1295
1296
                $certificateInfo = GradebookUtils::get_certificate_by_user_id(
1297
                    $courseGradebookId,
1298
                    $userId
1299
                );
1300
1301
                if (empty($certificateInfo)) {
1302
                    continue;
1303
                }
1304
1305
                $sessionList[] = [
1306
                    'session' => $session['session_name'],
1307
                    'course' => $course['title'],
1308
                    'score' => $certificateInfo['score_certificate'],
1309
                    'date' => api_format_date($certificateInfo['created_at'], DATE_FORMAT_SHORT),
1310
                    'link' => api_get_path(WEB_PATH) . "certificates/index.php?id={$certificateInfo['id']}"
1311
                ];
1312
            }
1313
        }
1314
1315
        return $sessionList;
1316
    }
1317
1318
    /**
1319
     * @param int $userId
1320
     * @param array $cats
1321
     * @param bool $saveToFile
1322
     * @param bool $saveToHtmlFile
1323
     * @param array $studentList
1324
     * @param PDF $pdf
1325
     *
1326
     * @return string
1327
     */
1328
    public static function generateTable(
1329
        $userId,
1330
        $cats,
1331
        $saveToFile = false,
1332
        $saveToHtmlFile = false,
1333
        $studentList = array(),
1334
        $pdf = null
1335
    ) {
1336
        $courseInfo = api_get_course_info();
1337
        $userInfo = api_get_user_info($userId);
1338
1339
        $cat = $cats[0];
1340
1341
        $allcat = $cats[0]->get_subcategories(
1342
            $userId,
1343
            api_get_course_id(),
1344
            api_get_session_id()
1345
        );
1346
        $alleval = $cats[0]->get_evaluations($userId);
1347
        $alllink = $cats[0]->get_links($userId);
1348
1349
        $gradebooktable = new GradebookTable(
1350
            $cat,
1351
            $allcat,
1352
            $alleval,
1353
            $alllink,
1354
            null, // params
1355
            true, // $exportToPdf
1356
            false, // showteacher
1357
            $userId,
1358
            $studentList
1359
        );
1360
1361
        $gradebooktable->userId = $userId;
1362
1363 View Code Duplication
        if (api_is_allowed_to_edit()) {
1364
            $gradebooktable->td_attributes = [
1365
                4 => 'class=centered'
1366
            ];
1367
        } else {
1368
            $gradebooktable->td_attributes = [
1369
                3 => 'class=centered',
1370
                4 => 'class=centered',
1371
                5 => 'class=centered',
1372
                6 => 'class=centered',
1373
                7 => 'class=centered'
1374
            ];
1375
        }
1376
1377
        $table = $gradebooktable->return_table();
1378
        $graph = $gradebooktable->getGraph();
1379
1380
        $sessionName = api_get_session_name(api_get_session_id());
1381
        $sessionName = !empty($sessionName) ? " - $sessionName" : '';
1382
1383
        $params = array(
1384
            'pdf_title' => sprintf(get_lang('GradeFromX'), $courseInfo['department_name']),
1385
            'session_info' => '',
1386
            'course_info' => '',
1387
            'pdf_date' => '',
1388
            'course_code' => api_get_course_id(),
1389
            'add_signatures' => false,
1390
            'student_info' => $userInfo,
1391
            'show_grade_generated_date' => true,
1392
            'show_real_course_teachers' => false,
1393
            'show_teacher_as_myself' => false,
1394
            'orientation' => 'P'
1395
        );
1396
1397
        if (empty($pdf)) {
1398
            $pdf = new PDF('A4', $params['orientation'], $params);
1399
        }
1400
1401
        $pdf->params['student_info'] = $userInfo;
1402
1403
        $file = api_get_path(SYS_ARCHIVE_PATH).uniqid().'.html';
1404
1405
        $content =
1406
            $table.
1407
            $graph.
1408
            '<br />'.get_lang('Feedback').'<br />
1409
            <textarea rows="5" cols="100" ></textarea>';
1410
1411
        $address = api_get_setting('institution_address');
1412
        $phone = api_get_setting('administratorTelephone');
1413
        $address = str_replace('\n', '<br />', $address);
1414
1415
        $pdf->custom_header = array('html' => "<h5 align='right'>$address <br />$phone</h5>");
0 ignored issues
show
Documentation Bug introduced by
It seems like array('html' => "<h5 ali...} <br />{$phone}</h5>") of type array<string,?> is incompatible with the declared type string of property $custom_header.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1416
1417
        $result = $pdf->html_to_pdf_with_template(
1418
            $content,
1419
            $saveToFile,
1420
            $saveToHtmlFile
1421
        );
1422
1423
        if ($saveToHtmlFile) {
1424
            file_put_contents($file, $result);
1425
            return $file;
1426
        }
1427
1428
        return $file;
1429
    }
1430
1431
}
1432