Test Setup Failed
Push — master ( f71949...6c6bd7 )
by Julito
55:21
created

GradebookUtils::build_edit_icons_link()   C

Complexity

Conditions 9
Paths 18

Size

Total Lines 46
Code Lines 30

Duplication

Lines 41
Ratio 89.13 %

Importance

Changes 0
Metric Value
cc 9
eloc 30
nc 18
nop 2
dl 41
loc 46
rs 5.0942
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) . '
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces before double colon; 1 found

This check looks for references to static members where there are spaces between the name of the type and the actual member.

An example:

Certificate ::TRIPLEDES_CBC

will actually work, but is not very readable.

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