Passed
Push — master ( 05e539...3ba91c )
by Julito
08:20
created

Evaluation::get_icon_name()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\GradebookEvaluation;
5
use ChamiloSession as Session;
6
7
/**
8
 * Class Evaluation.
9
 */
10
class Evaluation implements GradebookItem
11
{
12
    public $studentList;
13
    /** @var GradebookEvaluation */
14
    public $entity;
15
    private $id;
16
    private $name;
17
    private $description;
18
    private $user_id;
19
    private $course_code;
20
    /** @var Category */
21
    private $category;
22
    private $created_at;
23
    private $weight;
24
    private $eval_max;
25
    private $visible;
26
    private $courseId;
27
    private $sessionId;
28
29
    /**
30
     * Construct.
31
     */
32
    public function __construct()
33
    {
34
    }
35
36
    /**
37
     * @return Category
38
     */
39
    public function getCategory()
40
    {
41
        return $this->category;
42
    }
43
44
    /**
45
     * @param Category $category
46
     */
47
    public function setCategory($category)
48
    {
49
        $this->category = $category;
50
    }
51
52
    /**
53
     * @return int
54
     */
55
    public function get_category_id()
56
    {
57
        return $this->category->get_id();
58
    }
59
60
    /**
61
     * @param int $category_id
62
     */
63
    public function set_category_id($category_id)
64
    {
65
        $categories = Category::load($category_id);
66
        if (isset($categories[0])) {
67
            $this->setCategory($categories[0]);
68
        }
69
    }
70
71
    /**
72
     * @return int
73
     */
74
    public function get_id()
75
    {
76
        return (int) $this->id;
77
    }
78
79
    /**
80
     * @return string
81
     */
82
    public function get_name()
83
    {
84
        return $this->name;
85
    }
86
87
    /**
88
     * @return string
89
     */
90
    public function get_description()
91
    {
92
        return $this->description;
93
    }
94
95
    public function get_user_id()
96
    {
97
        return $this->user_id;
98
    }
99
100
    public function get_course_code()
101
    {
102
        return $this->course_code;
103
    }
104
105
    /**
106
     * @return int
107
     */
108
    public function getSessionId()
109
    {
110
        return $this->sessionId;
111
    }
112
113
    /**
114
     * @param int $sessionId
115
     */
116
    public function setSessionId($sessionId)
117
    {
118
        $this->sessionId = (int) $sessionId;
119
    }
120
121
    public function set_session_id($sessionId)
122
    {
123
        $this->setSessionId($sessionId);
124
    }
125
    public function get_date()
126
    {
127
        return $this->created_at;
128
    }
129
130
    public function get_weight()
131
    {
132
        return $this->weight;
133
    }
134
135
    public function get_max()
136
    {
137
        return $this->eval_max;
138
    }
139
140
    public function get_type()
141
    {
142
        return $this->type;
143
    }
144
145
    public function is_visible()
146
    {
147
        return $this->visible;
148
    }
149
150
    public function get_locked()
151
    {
152
        return $this->locked;
153
    }
154
155
    public function is_locked()
156
    {
157
        return isset($this->locked) && 1 == $this->locked ? true : false;
158
    }
159
160
    public function set_id($id)
161
    {
162
        $this->id = (int) $id;
163
    }
164
165
    public function set_name($name)
166
    {
167
        $this->name = $name;
168
    }
169
170
    public function set_description($description)
171
    {
172
        $this->description = $description;
173
    }
174
175
    public function set_user_id($user_id)
176
    {
177
        $this->user_id = $user_id;
178
    }
179
180
    public function getCourseId()
181
    {
182
        return $this->courseId;
183
    }
184
185
    public function set_course_code($course_code)
186
    {
187
        $this->course_code = $course_code;
188
    }
189
190
    public function set_date($date)
191
    {
192
        $this->created_at = $date;
193
    }
194
195
    public function set_weight($weight)
196
    {
197
        $this->weight = $weight;
198
    }
199
200
    public function set_max($max)
201
    {
202
        $this->eval_max = $max;
203
    }
204
205
    public function set_visible($visible)
206
    {
207
        $this->visible = $visible;
208
    }
209
210
    public function set_type($type)
211
    {
212
        $this->type = $type;
213
    }
214
215
    public function set_locked($locked)
216
    {
217
        $this->locked = $locked;
218
    }
219
220
    /**
221
     * Retrieve evaluations and return them as an array of Evaluation objects.
222
     *
223
     * @param int    $id          evaluation id
224
     * @param int    $user_id     user id (evaluation owner)
225
     * @param string $course_code course code
226
     * @param int    $category_id parent category
227
     * @param int    $visible     visible
228
     *
229
     * @return array
230
     */
231
    public static function load(
232
        $id = null,
233
        $user_id = null,
234
        $course_code = null,
235
        $category_id = null,
236
        $visible = null,
237
        $locked = null
238
    ) {
239
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
240
        $sql = 'SELECT * FROM '.$table;
241
        $paramcount = 0;
242
243
        if (isset($id)) {
244
            $sql .= ' WHERE id = '.intval($id);
245
            $paramcount++;
246
        }
247
248
        if (isset($user_id)) {
249
            if (0 != $paramcount) {
250
                $sql .= ' AND';
251
            } else {
252
                $sql .= ' WHERE';
253
            }
254
            $sql .= ' user_id = '.intval($user_id);
255
            $paramcount++;
256
        }
257
258
        if (isset($course_code) && '-1' != $course_code) {
259
            $courseInfo = api_get_course_info($course_code);
260
            if ($courseInfo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $courseInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
261
                if (0 != $paramcount) {
262
                    $sql .= ' AND';
263
                } else {
264
                    $sql .= ' WHERE';
265
                }
266
                $sql .= " c_id = '".$courseInfo['real_id']."'";
267
                $paramcount++;
268
            }
269
        }
270
271
        if (isset($category_id)) {
272
            if (0 != $paramcount) {
273
                $sql .= ' AND';
274
            } else {
275
                $sql .= ' WHERE';
276
            }
277
            $sql .= ' category_id = '.intval($category_id);
278
            $paramcount++;
279
        }
280
281
        if (isset($visible)) {
282
            if (0 != $paramcount) {
283
                $sql .= ' AND';
284
            } else {
285
                $sql .= ' WHERE';
286
            }
287
            $sql .= ' visible = '.intval($visible);
288
            $paramcount++;
289
        }
290
291
        if (isset($locked)) {
292
            if (0 != $paramcount) {
293
                $sql .= ' AND';
294
            } else {
295
                $sql .= ' WHERE';
296
            }
297
            $sql .= ' locked = '.intval($locked);
298
        }
299
300
        $result = Database::query($sql);
301
302
        return self::create_evaluation_objects_from_sql_result($result);
303
    }
304
305
    /**
306
     * Insert this evaluation into the database.
307
     */
308
    public function add()
309
    {
310
        if (isset($this->name) &&
311
            isset($this->user_id) &&
312
            isset($this->weight) &&
313
            isset($this->eval_max) &&
314
            isset($this->visible)
315
        ) {
316
            if (empty($this->type)) {
317
                $this->type = 'evaluation';
318
            }
319
            $em = Database::getManager();
320
321
            $evaluation = new GradebookEvaluation();
322
            $evaluation
323
                ->setDescription($this->description)
324
                ->setCourse(api_get_course_entity())
325
                ->setName($this->get_name())
326
                ->setCategoryId($this->get_category_id())
327
                ->setUser(api_get_user_entity($this->get_user_id()))
328
                ->setWeight(api_float_val($this->get_weight()))
329
                ->setMax($this->get_max())
330
                ->setVisible($this->is_visible())
331
                ->setType($this->type)
332
            ;
333
            $em->persist($evaluation);
334
            $em->flush();
335
            $this->set_id($evaluation->getId());
336
        }
337
338
        return false;
339
    }
340
341
    /**
342
     * @param int $id
343
     */
344
    public function addEvaluationLog($id)
345
    {
346
        if (!empty($id)) {
347
            $tbl_grade_evaluations = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
348
            $tbl_grade_linkeval_log = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG);
349
            $eval = new Evaluation();
350
            $dateobject = $eval->load($id, null, null, null, null);
351
            $arreval = get_object_vars($dateobject[0]);
352
            if (!empty($arreval['id'])) {
353
                $sql = 'SELECT weight from '.$tbl_grade_evaluations.'
354
                        WHERE id='.$arreval['id'];
355
                $rs = Database::query($sql);
356
                $row_old_weight = Database::fetch_array($rs, 'ASSOC');
357
                $current_date = api_get_utc_datetime();
358
                $params = [
359
                    'id_linkeval_log' => $arreval['id'],
360
                    'name' => $arreval['name'],
361
                    'description' => $arreval['description'],
362
                    'created_at' => $current_date,
363
                    'weight' => $row_old_weight['weight'],
364
                    'visible' => $arreval['visible'],
365
                    'type' => 'evaluation',
366
                    'user_id_log' => api_get_user_id(),
367
                ];
368
                Database::insert($tbl_grade_linkeval_log, $params);
369
            }
370
        }
371
    }
372
373
    /**
374
     * Update the properties of this evaluation in the database.
375
     */
376
    public function save()
377
    {
378
        $tbl_grade_evaluations = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
379
        $sql = 'UPDATE '.$tbl_grade_evaluations
380
            ." SET name = '".Database::escape_string($this->get_name())."'"
381
            .', description = ';
382
        if (isset($this->description)) {
383
            $sql .= "'".Database::escape_string($this->get_description())."'";
384
        } else {
385
            $sql .= 'null';
386
        }
387
        $sql .= ', user_id = '.intval($this->get_user_id())
388
            .', c_id = ';
389
        if (isset($this->courseId)) {
390
            $sql .= "'".Database::escape_string($this->getCourseId())."'";
391
        } else {
392
            $sql .= 'null';
393
        }
394
        $sql .= ', category_id = ';
395
        if (isset($this->category)) {
396
            $sql .= intval($this->get_category_id());
397
        } else {
398
            $sql .= 'null';
399
        }
400
        $sql .= ', weight = "'.Database::escape_string($this->get_weight()).'" '
401
            .', max = '.intval($this->get_max())
402
            .', visible = '.intval($this->is_visible())
403
            .' WHERE id = '.intval($this->id);
404
        //recorded history
405
406
        $eval_log = new Evaluation();
407
        $eval_log->addEvaluationLog($this->id);
408
        Database::query($sql);
409
    }
410
411
    /**
412
     * Delete this evaluation from the database.
413
     */
414
    public function delete()
415
    {
416
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
417
        $sql = 'DELETE FROM '.$table.'
418
                WHERE id = '.$this->get_id();
419
        Database::query($sql);
420
    }
421
422
    /**
423
     * Check if an evaluation name (with the same parent category) already exists.
424
     *
425
     * @param string $name to check (if not given, the name property of this object will be checked)
426
     * @param $parent parent category
427
     *
428
     * @return bool
429
     */
430
    public function does_name_exist($name, $parent)
431
    {
432
        if (!isset($name)) {
433
            $name = $this->name;
434
            $parent = $this->category;
435
        }
436
        $tbl_grade_evaluations = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
437
        $sql = "SELECT count(id) AS number
438
                FROM $tbl_grade_evaluations
439
                WHERE name = '".Database::escape_string($name)."'";
440
441
        if (api_is_allowed_to_edit()) {
442
            $parent = Category::load($parent);
443
            $courseId = $parent[0]->getCourseId();
444
            if (isset($courseId) && !empty($courseId)) {
445
                $table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
446
                $sql .= ' AND user_id IN (
447
					 SELECT user_id FROM '.$table.'
448
					 WHERE
449
						c_id = '.$courseId.' AND
450
						status = '.COURSEMANAGER.'
451
					)';
452
            } else {
453
                $sql .= ' AND user_id = '.api_get_user_id();
454
            }
455
        } else {
456
            $sql .= ' AND user_id = '.api_get_user_id();
457
        }
458
459
        if (!isset($parent)) {
460
            $sql .= ' AND category_id is null';
461
        } else {
462
            $sql .= ' AND category_id = '.intval($parent);
463
        }
464
        $result = Database::query($sql);
465
        $number = Database::fetch_row($result);
466
467
        return 0 != $number[0];
468
    }
469
470
    /**
471
     * Are there any results for this evaluation yet ?
472
     * The 'max' property should not be changed then.
473
     *
474
     * @return bool
475
     */
476
    public function has_results()
477
    {
478
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
479
        $sql = 'SELECT count(id) AS number
480
                FROM '.$table.'
481
                WHERE evaluation_id = '.intval($this->get_id());
482
        $result = Database::query($sql);
483
        $number = Database::fetch_row($result);
484
485
        return 0 != $number[0];
486
    }
487
488
    /**
489
     * Delete all results for this evaluation.
490
     */
491
    public function delete_results()
492
    {
493
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
494
        $sql = 'DELETE FROM '.$table.'
495
                WHERE evaluation_id = '.$this->get_id();
496
        Database::query($sql);
497
    }
498
499
    /**
500
     * Delete this evaluation and all underlying results.
501
     */
502
    public function delete_with_results()
503
    {
504
        $this->delete_results();
505
        $this->delete();
506
    }
507
508
    /**
509
     * Check if the given score is possible for this evaluation.
510
     */
511
    public function is_valid_score($score)
512
    {
513
        return is_numeric($score) && $score >= 0 && $score <= $this->eval_max;
514
    }
515
516
    /**
517
     * Calculate the score of this evaluation.
518
     *
519
     * @param int    $studentId (default: all students who have results for this eval - then the average is returned)
520
     * @param string $type      (best, average, ranking)
521
     *
522
     * @return array (score, max) if student is given
523
     *               array (sum of scores, number of scores) otherwise
524
     *               or null if no scores available
525
     */
526
    public function calc_score($studentId = null, $type = null)
527
    {
528
        $allowStats = api_get_configuration_value('allow_gradebook_stats');
529
        if ($allowStats) {
530
            $evaluation = $this->entity;
531
            if (!empty($evaluation)) {
532
                $weight = $evaluation->getMax();
533
                switch ($type) {
534
                    case 'best':
535
                        $bestResult = $evaluation->getBestScore();
536
                        $result = [$bestResult, $weight];
537
538
                        return $result;
539
                        break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
540
                    case 'average':
541
                        $count = count($evaluation->getUserScoreList());
542
                        if (empty($count)) {
543
                            $result = [0, $weight];
544
545
                            return $result;
546
                        }
547
548
                        $sumResult = array_sum($evaluation->getUserScoreList());
549
                        $result = [$sumResult / $count, $weight];
550
551
                        return $result;
552
                        break;
553
                    case 'ranking':
554
                        $ranking = AbstractLink::getCurrentUserRanking($studentId, $evaluation->getUserScoreList());
555
556
                        return $ranking;
557
                        break;
558
                    default:
559
                        $weight = $evaluation->getMax();
560
                        if (!empty($studentId)) {
561
                            $scoreList = $evaluation->getUserScoreList();
562
                            $result = [0, $weight];
563
                            if (isset($scoreList[$studentId])) {
564
                                $result = [$scoreList[$studentId], $weight];
565
                            }
566
567
                            return $result;
568
                        } else {
569
                            $studentCount = count($evaluation->getUserScoreList());
570
                            $sumResult = array_sum($evaluation->getUserScoreList());
571
                            $result = [$sumResult, $studentCount];
572
                        }
573
574
                        return $result;
575
                        break;
576
                }
577
            }
578
        }
579
580
        $useSession = true;
581
        if (isset($studentId) && empty($type)) {
582
            $key = 'result_score_student_list_'.api_get_course_int_id().'_'.api_get_session_id().'_'.$this->id.'_'.$studentId;
583
            $data = Session::read('calc_score');
584
            $results = isset($data[$key]) ? $data[$key] : null;
585
586
            if (false == $useSession) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
587
                $results = null;
588
            }
589
            $results = null;
590
            if (empty($results)) {
591
                $results = Result::load(null, $studentId, $this->id);
592
                Session::write('calc_score', [$key => $results]);
593
            }
594
595
            $score = null;
596
            if (!empty($results)) {
597
                /** @var Result $res */
598
                foreach ($results as $res) {
599
                    $score = $res->get_score();
600
                    }
601
            }
602
603
            return [$score, $this->get_max()];
604
        } else {
605
            $count = 0;
606
            $sum = 0;
607
            $bestResult = 0;
608
            $weight = 0;
609
            $sumResult = 0;
610
611
            $key = 'result_score_student_list_'.api_get_course_int_id().'_'.api_get_session_id().'_'.$this->id;
612
            $data = Session::read('calc_score');
613
            $allResults = isset($data[$key]) ? $data[$key] : null;
614
            if (false == $useSession) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
615
                $allResults = null;
616
            }
617
618
            if (empty($allResults)) {
619
                $allResults = Result::load(null, null, $this->id);
620
                Session::write($key, $allResults);
621
            }
622
623
            $students = [];
624
            /** @var Result $res */
625
            foreach ($allResults as $res) {
626
                $score = $res->get_score();
627
                if (!empty($score) || '0' == $score) {
628
                    $count++;
629
                    $sum += $score / $this->get_max();
630
                    $sumResult += $score;
631
                    if ($score > $bestResult) {
632
                        $bestResult = $score;
633
                    }
634
                    $weight = $this->get_max();
635
                }
636
                $students[$res->get_user_id()] = $score;
637
            }
638
639
            if (empty($count)) {
640
                return [null, null];
641
            }
642
643
            switch ($type) {
644
                case 'best':
645
                    return [$bestResult, $weight];
646
                    break;
647
                case 'average':
648
                    return [$sumResult / $count, $weight];
649
                    break;
650
                case 'ranking':
651
                    $students = [];
652
                    /** @var Result $res */
653
                    foreach ($allResults as $res) {
654
                        $score = $res->get_score();
655
                        $students[$res->get_user_id()] = $score;
656
                    }
657
658
                    return AbstractLink::getCurrentUserRanking($studentId, $students);
659
                    break;
660
                default:
661
                    return [$sum, $count];
662
                    break;
663
            }
664
        }
665
    }
666
667
    /**
668
     * Generate an array of possible categories where this evaluation can be moved to.
669
     * Notice: its own parent will be included in the list: it's up to the frontend
670
     * to disable this element.
671
     *
672
     * @return array 2-dimensional array - every element contains 3 subelements (id, name, level)
673
     */
674
    public function get_target_categories()
675
    {
676
        // - course independent evaluation
677
        //   -> movable to root or other course independent categories
678
        // - evaluation inside a course
679
        //   -> movable to root, independent categories or categories inside the course
680
        $user = api_is_platform_admin() ? null : api_get_user_id();
681
        $targets = [];
682
        $level = 0;
683
        $root = [0, get_lang('Main folder'), $level];
684
        $targets[] = $root;
685
686
        if (isset($this->courseId) && !empty($this->courseId)) {
687
            $crscats = Category::load(null, null, $this->course_code, 0);
688
            foreach ($crscats as $cat) {
689
                $targets[] = [$cat->get_id(), $cat->get_name(), $level + 1];
690
                $targets = $this->addTargetSubcategories($targets, $level + 1, $cat->get_id());
691
            }
692
        }
693
694
        $indcats = Category::load(null, $user, 0, 0);
695
        foreach ($indcats as $cat) {
696
            $targets[] = [$cat->get_id(), $cat->get_name(), $level + 1];
697
            $targets = $this->addTargetSubcategories(
698
                $targets,
699
                $level + 1,
700
                $cat->get_id()
701
            );
702
        }
703
704
        return $targets;
705
    }
706
707
    /**
708
     * Move this evaluation to the given category.
709
     * If this evaluation moves from inside a course to outside,
710
     * its course code is also changed.
711
     */
712
    public function move_to_cat($cat)
713
    {
714
        $this->set_category_id($cat->get_id());
715
        if ($this->get_course_code() != $cat->get_course_code()) {
716
            $this->set_course_code($cat->get_course_code());
717
        }
718
        $this->save();
719
    }
720
721
    /**
722
     * Retrieve evaluations where a student has results for
723
     * and return them as an array of Evaluation objects.
724
     *
725
     * @param int $cat_id  parent category (use 'null' to retrieve them in all categories)
726
     * @param int $stud_id student id
727
     *
728
     * @return array
729
     */
730
    public static function get_evaluations_with_result_for_student($cat_id = null, $stud_id)
731
    {
732
        $tbl_grade_evaluations = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
733
        $tbl_grade_results = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
734
735
        $sql = 'SELECT * FROM '.$tbl_grade_evaluations.'
736
                WHERE id IN (
737
                    SELECT evaluation_id FROM '.$tbl_grade_results.'
738
                    WHERE user_id = '.intval($stud_id).' AND score IS NOT NULL
739
                )';
740
        if (!api_is_allowed_to_edit()) {
741
            $sql .= ' AND visible = 1';
742
        }
743
        if (isset($cat_id)) {
744
            $sql .= ' AND category_id = '.intval($cat_id);
745
        } else {
746
            $sql .= ' AND category_id >= 0';
747
        }
748
749
        $result = Database::query($sql);
750
        $alleval = self::create_evaluation_objects_from_sql_result($result);
751
752
        return $alleval;
753
    }
754
755
    /**
756
     * Get a list of students that do not have a result record for this evaluation.
757
     *
758
     * @param string $first_letter_user
759
     *
760
     * @return array
761
     */
762
    public function get_not_subscribed_students($first_letter_user = '')
763
    {
764
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
765
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
766
767
        $sql = "SELECT user_id,lastname,firstname,username
768
                FROM $tbl_user
769
                WHERE
770
                    lastname LIKE '".Database::escape_string($first_letter_user)."%' AND
771
                    status = ".STUDENT." AND user_id NOT IN (
772
                        SELECT user_id FROM $table
773
                        WHERE evaluation_id = ".$this->get_id()."
774
                    )
775
                ORDER BY lastname";
776
777
        $result = Database::query($sql);
778
        $users = Database::store_result($result);
779
780
        return $users;
781
    }
782
783
    /**
784
     * Find evaluations by name.
785
     *
786
     * @param string $name_mask search string
787
     *
788
     * @return array evaluation objects matching the search criterium
789
     *
790
     * @todo can be written more efficiently using a new (but very complex) sql query
791
     */
792
    public static function findEvaluations($name_mask, $selectcat)
793
    {
794
        $rootcat = Category::load($selectcat);
795
        $evals = $rootcat[0]->get_evaluations(
796
            (api_is_allowed_to_create_course() ? null : api_get_user_id()),
797
            true
798
        );
799
        $foundevals = [];
800
        foreach ($evals as $eval) {
801
            if (!(false === api_strpos(api_strtolower($eval->get_name()), api_strtolower($name_mask)))) {
802
                $foundevals[] = $eval;
803
            }
804
        }
805
806
        return $foundevals;
807
    }
808
809
    public function get_item_type()
810
    {
811
        return 'E';
812
    }
813
814
    public function get_icon_name()
815
    {
816
        return $this->has_results() ? 'evalnotempty' : 'evalempty';
817
    }
818
819
    /**
820
     * Locks an evaluation, only one who can unlock it is the platform administrator.
821
     *
822
     * @param int locked 1 or unlocked 0
823
     */
824
    public function lock($locked)
825
    {
826
        $table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
827
        $sql = "UPDATE $table_evaluation
828
                SET locked = '".intval($locked)."'
829
                WHERE id='".$this->get_id()."'";
830
        Database::query($sql);
831
    }
832
833
    public function check_lock_permissions()
834
    {
835
        if (api_is_platform_admin()) {
836
            return true;
837
        } else {
838
            if ($this->is_locked()) {
839
                api_not_allowed();
840
            }
841
        }
842
    }
843
844
    public function delete_linked_data()
845
    {
846
    }
847
848
    /**
849
     * @return mixed
850
     */
851
    public function getStudentList()
852
    {
853
        return $this->studentList;
854
    }
855
856
    /**
857
     * @param $list
858
     */
859
    public function setStudentList($list)
860
    {
861
        $this->studentList = $list;
862
    }
863
864
    /**
865
     * @param int $evaluationId
866
     */
867
    public static function generateStats($evaluationId)
868
    {
869
        $allowStats = api_get_configuration_value('allow_gradebook_stats');
870
        if ($allowStats) {
871
            $evaluation = self::load($evaluationId);
872
873
            $results = Result::load(null, null, $evaluationId);
874
            $sumResult = 0;
875
            $bestResult = 0;
876
            $average = 0;
877
            $scoreList = [];
878
879
            if (!empty($results)) {
880
                /** @var Result $result */
881
                foreach ($results as $result) {
882
                    $score = $result->get_score();
883
                    $scoreList[$result->get_user_id()] = $score;
884
                    $sumResult += $score;
885
                    if ($score > $bestResult) {
886
                        $bestResult = $score;
887
                    }
888
                }
889
                $average = $sumResult / count($results);
890
            }
891
892
            /** @var Evaluation $evaluation */
893
            $evaluation = $evaluation[0];
894
            $evaluation = $evaluation->entity;
895
            $evaluation
896
                ->setBestScore($bestResult)
897
                ->setAverageScore($average)
898
                ->setUserScoreList($scoreList)
899
            ;
900
901
            $em = Database::getManager();
902
            $em->persist($evaluation);
903
            $em->flush();
904
        }
905
    }
906
907
    /**
908
     * @param int $courseId
909
     *
910
     * @return Evaluation
911
     */
912
    public function setCourseId($courseId)
913
    {
914
        $this->courseId = $courseId;
915
916
        return $this;
917
    }
918
919
    /**
920
     * @param array $result
921
     *
922
     * @return array
923
     */
924
    private static function create_evaluation_objects_from_sql_result($result)
925
    {
926
        $alleval = [];
927
        $allow = api_get_configuration_value('allow_gradebook_stats');
928
        if ($allow) {
929
            $em = Database::getManager();
930
            $repo = $em->getRepository(GradebookEvaluation::class);
931
        }
932
933
        if (Database::num_rows($result)) {
934
            while ($data = Database::fetch_array($result)) {
935
                $eval = new Evaluation();
936
                $eval->set_id($data['id']);
937
                $eval->set_name($data['name']);
938
                $eval->set_description($data['description']);
939
                $eval->set_user_id($data['user_id']);
940
                $eval->setCourseId($data['c_id']);
941
                $courseInfo = api_get_course_info_by_id($data['c_id']);
942
                $eval->set_course_code($courseInfo['code']);
943
                $eval->set_category_id($data['category_id']);
944
                $eval->set_date(api_get_local_time($data['created_at']));
945
                $eval->set_weight($data['weight']);
946
                $eval->set_max($data['max']);
947
                $eval->set_visible($data['visible']);
948
                $eval->set_type($data['type']);
949
                $eval->set_locked($data['locked']);
950
                $eval->setSessionId(api_get_session_id());
951
952
                if ($allow) {
953
                    $eval->entity = $repo->find($data['id']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $repo does not seem to be defined for all execution paths leading up to this point.
Loading history...
954
                }
955
956
                $alleval[] = $eval;
957
            }
958
        }
959
960
        return $alleval;
961
    }
962
963
    /**
964
     * Internal function used by get_target_categories().
965
     *
966
     * @param array $targets
967
     * @param int   $level
968
     * @param int   $categoryId
969
     *
970
     * @return array
971
     */
972
    private function addTargetSubcategories($targets, $level, $categoryId)
973
    {
974
        $subcats = Category::load(null, null, null, $categoryId);
975
        foreach ($subcats as $cat) {
976
            $targets[] = [$cat->get_id(), $cat->get_name(), $level + 1];
977
            $targets = $this->addTargetSubcategories(
978
                $targets,
979
                $level + 1,
980
                $cat->get_id()
981
            );
982
        }
983
984
        return $targets;
985
    }
986
}
987