Skill::getSkillRelItemsPerCourse()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 4
nop 2
dl 0
loc 17
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
5
use Chamilo\CoreBundle\Entity\Skill as SkillEntity;
6
use Chamilo\CoreBundle\Entity\SkillRelUser as SkillRelUserEntity;
7
use Chamilo\SkillBundle\Entity\SkillRelCourse;
8
use Chamilo\SkillBundle\Entity\SkillRelItem;
9
use Chamilo\SkillBundle\Entity\SkillRelItemRelUser;
10
use Chamilo\UserBundle\Entity\User;
11
use Fhaculty\Graph\Graph;
12
use Fhaculty\Graph\Vertex;
13
14
/**
15
 * Class SkillProfile.
16
 *
17
 * @todo break the file in different classes
18
 */
19
class SkillProfile extends Model
20
{
21
    public $columns = ['id', 'name', 'description'];
22
23
    /**
24
     * Constructor.
25
     */
26
    public function __construct()
27
    {
28
        $this->table = Database::get_main_table(TABLE_MAIN_SKILL_PROFILE);
29
        $this->table_rel_profile = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
30
    }
31
32
    /**
33
     * @return array
34
     */
35
    public function getProfiles()
36
    {
37
        $sql = "SELECT * FROM $this->table p
38
                INNER JOIN $this->table_rel_profile sp
39
                ON (p.id = sp.profile_id) ";
40
        $result = Database::query($sql);
41
        $profiles = Database::store_result($result, 'ASSOC');
42
43
        return $profiles;
44
    }
45
46
    /**
47
     * This function is for editing profile info from profile_id.
48
     *
49
     * @param int    $profileId
50
     * @param string $name
51
     * @param string $description
52
     *
53
     * @return bool
54
     */
55
    public function updateProfileInfo($profileId, $name, $description)
56
    {
57
        $profileId = (int) $profileId;
58
59
        if (empty($profileId)) {
60
            return false;
61
        }
62
63
        $name = Database::escape_string($name);
64
        $description = Database::escape_string($description);
65
66
        Database::update(
67
            $this->table,
68
            [
69
                'name' => html_filter($name),
70
                'description' => html_filter($description),
71
            ],
72
            ['id = ?' => $profileId]
73
        );
74
75
        return true;
76
    }
77
78
    /**
79
     * Call the save method of the parent class and the SkillRelProfile object.
80
     *
81
     * @param array $params
82
     * @param bool  $show_query Whether to show the query in parent save() method
83
     *
84
     * @return mixed Profile ID or false if incomplete params
85
     */
86
    public function save($params, $show_query = false)
87
    {
88
        if (!empty($params)) {
89
            $params['name'] = html_filter($params['name']);
90
            $params['description'] = html_filter($params['description']);
91
92
            $profile_id = parent::save($params, $show_query);
93
            if ($profile_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $profile_id of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
94
                $skill_rel_profile = new SkillRelProfile();
95
                if (isset($params['skills'])) {
96
                    foreach ($params['skills'] as $skill_id) {
97
                        $attributes = [
98
                            'skill_id' => $skill_id,
99
                            'profile_id' => $profile_id,
100
                        ];
101
                        $skill_rel_profile->save($attributes);
102
                    }
103
                }
104
105
                return $profile_id;
106
            }
107
        }
108
109
        return false;
110
    }
111
112
    /**
113
     * Delete a skill profile.
114
     *
115
     * @param int $id The skill profile id
116
     *
117
     * @return bool Whether delete a skill profile
118
     */
119
    public function delete($id)
120
    {
121
        Database::delete(
122
            $this->table_rel_profile,
123
            [
124
                'profile_id' => $id,
125
            ]
126
        );
127
128
        return parent::delete($id);
129
    }
130
}
131
132
/**
133
 * Class SkillRelProfile.
134
 */
135
class SkillRelProfile extends Model
136
{
137
    public $columns = ['id', 'skill_id', 'profile_id'];
138
139
    /**
140
     * Constructor.
141
     */
142
    public function __construct()
143
    {
144
        $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
145
        $this->tableProfile = Database::get_main_table(TABLE_MAIN_SKILL_PROFILE);
146
    }
147
148
    /**
149
     * @param int $profileId
150
     *
151
     * @return array
152
     */
153
    public function getSkillsByProfile($profileId)
154
    {
155
        $profileId = (int) $profileId;
156
        $skills = $this->get_all(['where' => ['profile_id = ? ' => $profileId]]);
157
        $return = [];
158
        if (!empty($skills)) {
159
            foreach ($skills as $skill_data) {
160
                $return[] = $skill_data['skill_id'];
161
            }
162
        }
163
164
        return $return;
165
    }
166
167
    /**
168
     * This function is for getting profile info from profile_id.
169
     *
170
     * @param int $profileId
171
     *
172
     * @return array
173
     */
174
    public function getProfileInfo($profileId)
175
    {
176
        $profileId = (int) $profileId;
177
        $sql = "SELECT * FROM $this->table p
178
                INNER JOIN $this->tableProfile pr
179
                ON (pr.id = p.profile_id)
180
                WHERE p.profile_id = ".$profileId;
181
        $result = Database::query($sql);
182
        $profileData = Database::fetch_array($result, 'ASSOC');
183
184
        return $profileData;
185
    }
186
}
187
188
/**
189
 * Class SkillRelSkill.
190
 */
191
class SkillRelSkill extends Model
192
{
193
    public $columns = ['skill_id', 'parent_id', 'relation_type', 'level'];
194
195
    /**
196
     * Constructor.
197
     */
198
    public function __construct()
199
    {
200
        $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_SKILL);
201
        $this->tableSkill = Database::get_main_table(TABLE_MAIN_SKILL);
202
    }
203
204
    /**
205
     * Gets an element.
206
     *
207
     * @param int $id
208
     *
209
     * @return array
210
     */
211
    public function getSkillInfo($id)
212
    {
213
        $id = (int) $id;
214
215
        if (empty($id)) {
216
            return [];
217
        }
218
219
        $result = Database::select(
220
            '*',
221
            $this->table,
222
            ['where' => ['skill_id = ?' => $id]],
223
            'first'
224
        );
225
226
        return $result;
227
    }
228
229
    /**
230
     * @param int  $skillId
231
     * @param bool $add_child_info
232
     *
233
     * @return array
234
     */
235
    public function getSkillParents($skillId, $add_child_info = true)
236
    {
237
        $skillId = (int) $skillId;
238
        $sql = 'SELECT child.* FROM '.$this->table.' child
239
                LEFT JOIN '.$this->table.' parent
240
                ON child.parent_id = parent.skill_id
241
                WHERE child.skill_id = '.$skillId.' ';
242
        $result = Database::query($sql);
243
        $skill = Database::store_result($result, 'ASSOC');
244
        $skill = isset($skill[0]) ? $skill[0] : null;
245
246
        $parents = [];
247
        if (!empty($skill)) {
248
            if ($skill['parent_id'] != null) {
249
                $parents = self::getSkillParents($skill['parent_id']);
0 ignored issues
show
Bug Best Practice introduced by
The method SkillRelSkill::getSkillParents() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

249
                /** @scrutinizer ignore-call */ 
250
                $parents = self::getSkillParents($skill['parent_id']);
Loading history...
250
            }
251
            if ($add_child_info) {
252
                $parents[] = $skill;
253
            }
254
        }
255
256
        return $parents;
257
    }
258
259
    /**
260
     * @param int $skillId
261
     *
262
     * @return array
263
     */
264
    public function getDirectParents($skillId)
265
    {
266
        $skillId = (int) $skillId;
267
        $sql = 'SELECT parent_id as skill_id
268
                FROM '.$this->table.'
269
                WHERE skill_id = '.$skillId;
270
        $result = Database::query($sql);
271
        $skill = Database::store_result($result, 'ASSOC');
272
        $skill = isset($skill[0]) ? $skill[0] : null;
273
        $parents = [];
274
        if (!empty($skill)) {
275
            $parents[] = $skill;
276
        }
277
278
        return $parents;
279
    }
280
281
    /**
282
     * @param int  $skill_id
283
     * @param bool $load_user_data
284
     * @param bool $user_id
285
     *
286
     * @return array
287
     */
288
    public function getChildren(
289
        $skill_id,
290
        $load_user_data = false,
291
        $user_id = false,
292
        $order = ''
293
    ) {
294
        $skill_id = (int) $skill_id;
295
        $sql = 'SELECT parent.* FROM '.$this->tableSkill.' skill
296
                INNER JOIN '.$this->table.' parent
297
                ON parent.id = skill.id
298
                WHERE parent_id = '.$skill_id.'
299
                ORDER BY skill.name ASC';
300
        $result = Database::query($sql);
301
        $skills = Database::store_result($result, 'ASSOC');
302
303
        $skill_obj = new Skill();
304
        $skill_rel_user = new SkillRelUser();
305
306
        if ($load_user_data) {
307
            $passed_skills = $skill_rel_user->getUserSkills($user_id);
308
            $done_skills = [];
309
            foreach ($passed_skills as $done_skill) {
310
                $done_skills[] = $done_skill['skill_id'];
311
            }
312
        }
313
314
        if (!empty($skills)) {
315
            foreach ($skills as &$skill) {
316
                $skill['data'] = $skill_obj->get($skill['skill_id']);
317
                if (isset($skill['data']) && !empty($skill['data'])) {
318
                    if (!empty($done_skills)) {
319
                        $skill['data']['passed'] = 0;
320
                        if (in_array($skill['skill_id'], $done_skills)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $done_skills does not seem to be defined for all execution paths leading up to this point.
Loading history...
321
                            $skill['data']['passed'] = 1;
322
                        }
323
                    }
324
                } else {
325
                    $skill = null;
326
                }
327
            }
328
        }
329
330
        return $skills;
331
    }
332
333
    /**
334
     * @param array $params
335
     *
336
     * @return bool
337
     */
338
    public function updateBySkill($params)
339
    {
340
        $result = Database::update(
341
            $this->table,
342
            $params,
343
            ['skill_id = ? ' => $params['skill_id']]
344
        );
345
        if ($result) {
346
            return true;
347
        }
348
349
        return false;
350
    }
351
352
    /**
353
     * @param int $skill_id
354
     * @param int $parent_id
355
     *
356
     * @return bool
357
     */
358
    public function relationExists($skill_id, $parent_id)
359
    {
360
        $result = $this->find(
361
            'all',
362
            [
363
                'where' => [
364
                    'skill_id = ? AND parent_id = ?' => [
365
                        $skill_id,
366
                        $parent_id,
367
                    ],
368
                ],
369
            ]
370
        );
371
372
        if (!empty($result)) {
373
            return true;
374
        }
375
376
        return false;
377
    }
378
}
379
380
/**
381
 * Class SkillRelGradebook.
382
 */
383
class SkillRelGradebook extends Model
384
{
385
    public $columns = ['id', 'gradebook_id', 'skill_id'];
386
387
    /**
388
     * SkillRelGradebook constructor.
389
     */
390
    public function __construct()
391
    {
392
        $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_GRADEBOOK);
393
    }
394
395
    /**
396
     * @param int $gradebookId
397
     * @param int $skillId
398
     *
399
     * @return bool
400
     */
401
    public function existsGradeBookSkill($gradebookId, $skillId)
402
    {
403
        $result = $this->find(
404
            'all',
405
            [
406
                'where' => [
407
                    'gradebook_id = ? AND skill_id = ?' => [
408
                        $gradebookId,
409
                        $skillId,
410
                    ],
411
                ],
412
            ]
413
        );
414
        if (!empty($result)) {
415
            return true;
416
        }
417
418
        return false;
419
    }
420
421
    /**
422
     * Gets an element.
423
     */
424
    public function getSkillInfo($skill_id, $gradebookId)
425
    {
426
        if (empty($skill_id)) {
427
            return [];
428
        }
429
        $result = Database::select(
430
            '*',
431
            $this->table,
432
            [
433
                'where' => [
434
                    'skill_id = ? AND gradebook_id = ? ' => [
435
                        $skill_id,
436
                        $gradebookId,
437
                    ],
438
                ],
439
            ],
440
            'first'
441
        );
442
443
        return $result;
444
    }
445
446
    /**
447
     * @param int   $skill_id
448
     * @param array $gradebook_list
449
     */
450
    public function updateGradeBookListBySkill($skill_id, $gradebook_list)
451
    {
452
        $original_gradebook_list = $this->find(
453
            'all',
454
            ['where' => ['skill_id = ?' => [$skill_id]]]
455
        );
456
        $gradebooks_to_remove = [];
457
        $gradebooks_to_add = [];
458
        $original_gradebook_list_ids = [];
459
460
        if (!empty($original_gradebook_list)) {
461
            foreach ($original_gradebook_list as $gradebook) {
462
                if (!in_array($gradebook['gradebook_id'], $gradebook_list)) {
463
                    $gradebooks_to_remove[] = $gradebook['id'];
464
                }
465
            }
466
            foreach ($original_gradebook_list as $gradebook_item) {
467
                $original_gradebook_list_ids[] = $gradebook_item['gradebook_id'];
468
            }
469
        }
470
471
        if (!empty($gradebook_list)) {
472
            foreach ($gradebook_list as $gradebook_id) {
473
                if (!in_array($gradebook_id, $original_gradebook_list_ids)) {
474
                    $gradebooks_to_add[] = $gradebook_id;
475
                }
476
            }
477
        }
478
479
        if (!empty($gradebooks_to_remove)) {
480
            foreach ($gradebooks_to_remove as $id) {
481
                $this->delete($id);
482
            }
483
        }
484
485
        if (!empty($gradebooks_to_add)) {
486
            foreach ($gradebooks_to_add as $gradebook_id) {
487
                $attributes = [
488
                    'skill_id' => $skill_id,
489
                    'gradebook_id' => $gradebook_id,
490
                ];
491
                $this->save($attributes);
492
            }
493
        }
494
    }
495
496
    /**
497
     * @param array $params
498
     *
499
     * @return bool|void
500
     */
501
    public function updateBySkill($params)
502
    {
503
        $skillInfo = $this->existsGradeBookSkill(
504
            $params['gradebook_id'],
505
            $params['skill_id']
506
        );
507
508
        if ($skillInfo) {
509
            return;
510
        } else {
511
            $result = $this->save($params);
512
        }
513
        if ($result) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $result of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
514
            return true;
515
        }
516
517
        return false;
518
    }
519
}
520
521
/**
522
 * Class SkillRelUser.
523
 */
524
class SkillRelUser extends Model
525
{
526
    public $columns = [
527
        'id',
528
        'user_id',
529
        'skill_id',
530
        'acquired_skill_at',
531
        'assigned_by',
532
        'course_id',
533
        'session_id',
534
    ];
535
536
    /**
537
     * Constructor.
538
     */
539
    public function __construct()
540
    {
541
        $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
542
    }
543
544
    /**
545
     * @param array $skill_list
546
     *
547
     * @return array
548
     */
549
    public function getUserBySkills($skill_list)
550
    {
551
        $users = [];
552
        if (!empty($skill_list)) {
553
            $skill_list = array_map('intval', $skill_list);
554
            $skill_list = implode("', '", $skill_list);
555
556
            $sql = "SELECT user_id FROM {$this->table}
557
                    WHERE skill_id IN ('$skill_list') ";
558
559
            $result = Database::query($sql);
560
            $users = Database::store_result($result, 'ASSOC');
561
        }
562
563
        return $users;
564
    }
565
566
    /**
567
     * Get the achieved skills for the user.
568
     *
569
     * @param int $userId
570
     * @param int $courseId  Optional. The course id
571
     * @param int $sessionId Optional. The session id
572
     *
573
     * @return array The skill list. Otherwise return false
574
     */
575
    public function getUserSkills($userId, $courseId = 0, $sessionId = 0)
576
    {
577
        if (empty($userId)) {
578
            return [];
579
        }
580
581
        $courseId = (int) $courseId;
582
        $sessionId = $sessionId ? (int) $sessionId : null;
583
        $whereConditions = [
584
            'user_id = ? ' => (int) $userId,
585
        ];
586
587
        if ($sessionId > 0) {
588
            $whereConditions['AND course_id = ? '] = $courseId;
589
            $whereConditions['AND session_id = ? '] = $sessionId;
590
        } else {
591
            $whereConditions['AND course_id = ? AND session_id is NULL'] = $courseId;
592
        }
593
594
        $result = Database::select(
595
            'skill_id',
596
            $this->table,
597
            [
598
                'where' => $whereConditions,
599
            ],
600
            'all'
601
        );
602
603
        return $result;
604
    }
605
606
    /**
607
     * Get the relation data between user and skill.
608
     *
609
     * @param int $userId    The user id
610
     * @param int $skillId   The skill id
611
     * @param int $courseId  Optional. The course id
612
     * @param int $sessionId Optional. The session id
613
     *
614
     * @return array The relation data. Otherwise return false
615
     */
616
    public function getByUserAndSkill($userId, $skillId, $courseId = 0, $sessionId = 0)
617
    {
618
        $sql = "SELECT * FROM {$this->table} WHERE user_id = %d AND skill_id = %d ";
619
620
        if ($courseId > 0) {
621
            $sql .= "AND course_id = %d ".api_get_session_condition($sessionId, true);
622
        }
623
624
        $sql = sprintf(
625
            $sql,
626
            $userId,
627
            $skillId,
628
            $courseId
629
        );
630
631
        $result = Database::query($sql);
632
633
        return Database::fetch_assoc($result);
634
    }
635
636
    /**
637
     * Delete a user skill by course.
638
     *
639
     * @param int $userId
640
     * @param int $courseId
641
     * @param int $sessionId
642
     */
643
    public function deleteUserSkill($userId, $courseId, $sessionId = 0)
644
    {
645
        $whereSession = ($sessionId ? " AND session_id = $sessionId" : " AND session_id IS NULL");
646
        $sql = "DELETE FROM {$this->table}
647
                WHERE
648
                      user_id = $userId AND
649
                      course_id = $courseId
650
                      $whereSession";
651
652
        Database::query($sql);
653
    }
654
655
    /**
656
     * Get the URL for the issue.
657
     *
658
     * @return string
659
     */
660
    public static function getIssueUrl(SkillRelUserEntity $skillIssue)
661
    {
662
        return api_get_path(WEB_PATH)."badge/{$skillIssue->getId()}";
663
    }
664
665
    /**
666
     * Get the URL for the All issues page.
667
     *
668
     * @return string
669
     */
670
    public static function getIssueUrlAll(SkillRelUserEntity $skillIssue)
671
    {
672
        return api_get_path(WEB_PATH)."skill/{$skillIssue->getSkill()->getId()}/user/{$skillIssue->getUser()->getId()}";
673
    }
674
675
    /**
676
     * Get the URL for the assertion.
677
     *
678
     * @return string
679
     */
680
    public static function getAssertionUrl(SkillRelUserEntity $skillIssue)
681
    {
682
        $url = api_get_path(WEB_CODE_PATH).'badge/assertion.php?';
683
684
        $url .= http_build_query([
685
            'user' => $skillIssue->getUser()->getId(),
686
            'skill' => $skillIssue->getSkill()->getId(),
687
            'course' => $skillIssue->getCourse() ? $skillIssue->getCourse()->getId() : 0,
688
            'session' => $skillIssue->getSession() ? $skillIssue->getSession()->getId() : 0,
689
        ]);
690
691
        return $url;
692
    }
693
}
694
695
/**
696
 * Class Skill.
697
 */
698
class Skill extends Model
699
{
700
    public $columns = [
701
        'id',
702
        'name',
703
        'description',
704
        'access_url_id',
705
        'short_code',
706
        'icon',
707
        'criteria',
708
    ];
709
    public $required = ['name'];
710
711
    /** Array of colours by depth, for the coffee wheel. Each depth has 4 col */
712
    /*var $colours = array(
713
      0 => array('#f9f0ab', '#ecc099', '#e098b0', '#ebe378'),
714
      1 => array('#d5dda1', '#4a5072', '#8dae43', '#72659d'),
715
      2 => array('#b28647', '#2e6093', '#393e64', '#1e8323'),
716
      3 => array('#9f6652', '#9f6652', '#9f6652', '#9f6652'),
717
      4 => array('#af643c', '#af643c', '#af643c', '#af643c'),
718
      5 => array('#72659d', '#72659d', '#72659d', '#72659d'),
719
      6 => array('#8a6e9e', '#8a6e9e', '#8a6e9e', '#8a6e9e'),
720
      7 => array('#92538c', '#92538c', '#92538c', '#92538c'),
721
      8 => array('#2e6093', '#2e6093', '#2e6093', '#2e6093'),
722
      9 => array('#3a5988', '#3a5988', '#3a5988', '#3a5988'),
723
     10 => array('#393e64', '#393e64', '#393e64', '#393e64'),
724
    );*/
725
    public function __construct()
726
    {
727
        $this->table = Database::get_main_table(TABLE_MAIN_SKILL);
728
        $this->table_user = Database::get_main_table(TABLE_MAIN_USER);
729
        $this->table_skill_rel_gradebook = Database::get_main_table(TABLE_MAIN_SKILL_REL_GRADEBOOK);
730
        $this->table_skill_rel_user = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
731
        $this->table_course = Database::get_main_table(TABLE_MAIN_COURSE);
732
        $this->table_skill_rel_skill = Database::get_main_table(TABLE_MAIN_SKILL_REL_SKILL);
733
        $this->table_gradebook = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
734
        $this->sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
735
    }
736
737
    /**
738
     * Gets an element.
739
     *
740
     * @param int $id
741
     *
742
     * @return array|mixed
743
     */
744
    public function get($id)
745
    {
746
        $result = parent::get($id);
747
        if (empty($result)) {
748
            return [];
749
        }
750
751
        $path = api_get_path(WEB_UPLOAD_PATH).'badges/';
752
        if (!empty($result['icon'])) {
753
            $iconSmall = sprintf(
754
                '%s-small.png',
755
                sha1($result['name'])
756
            );
757
758
            $iconBig = sprintf(
759
                '%s.png',
760
                sha1($result['name'])
761
            );
762
763
            $iconMini = $path.$iconSmall;
764
            $iconSmall = $path.$iconSmall;
765
            $iconBig = $path.$iconBig;
766
        } else {
767
            $iconMini = Display::returnIconPath('badges-default.png', ICON_SIZE_MEDIUM);
768
            $iconSmall = Display::returnIconPath('badges-default.png', ICON_SIZE_BIG);
769
            $iconBig = Display::returnIconPath('badges-default.png', ICON_SIZE_HUGE);
770
        }
771
772
        $result['icon_mini'] = $iconMini;
773
        $result['icon_small'] = $iconSmall;
774
        $result['icon_big'] = $iconBig;
775
776
        $result['img_mini'] = Display::img($iconBig, $result['name'], ['width' => ICON_SIZE_MEDIUM]);
777
        $result['img_big'] = Display::img($iconBig, $result['name']);
778
        $result['img_small'] = Display::img($iconSmall, $result['name']);
779
        $result['name'] = self::translateName($result['name']);
780
        $result['short_code'] = self::translateCode($result['short_code']);
781
782
        return $result;
783
    }
784
785
    /**
786
     * @param array  $skills
787
     * @param string $imageSize     mini|small|big
788
     * @param bool   $addDivWrapper
789
     *
790
     * @return string
791
     */
792
    public function processSkillList($skills, $imageSize = '', $addDivWrapper = true)
793
    {
794
        if (empty($skills)) {
795
            return '';
796
        }
797
798
        if (empty($imageSize)) {
799
            $imageSize = 'img_small';
800
        } else {
801
            $imageSize = "img_$imageSize";
802
        }
803
804
        $html = '';
805
        if ($addDivWrapper) {
806
            $html = '<div class="scrollbar-inner badges-sidebar">';
807
        }
808
        $html .= '<ul class="list-unstyled list-badges">';
809
        foreach ($skills as $skill) {
810
            if (isset($skill['data'])) {
811
                $skill = $skill['data'];
812
            }
813
            $html .= '<li class="thumbnail">';
814
            $item = $skill[$imageSize];
815
            $item .= '<div class="caption">
816
                        <p class="text-center">'.$skill['name'].'</p>
817
                      </div>';
818
            if (isset($skill['url'])) {
819
                $html .= Display::url($item, $skill['url'], ['target' => '_blank']);
820
            } else {
821
                $html .= $item;
822
            }
823
            $html .= '</li>';
824
        }
825
        $html .= '</ul>';
826
827
        if ($addDivWrapper) {
828
            $html .= '</div>';
829
        }
830
831
        return $html;
832
    }
833
834
    /**
835
     * @param $skills
836
     * @param string $imageSize mini|small|big
837
     * @param string $style
838
     * @param bool   $showBadge
839
     * @param bool   $showTitle
840
     *
841
     * @return string
842
     */
843
    public function processSkillListSimple($skills, $imageSize = '', $style = '', $showBadge = true, $showTitle = true)
844
    {
845
        if (empty($skills)) {
846
            return '';
847
        }
848
849
        $isHierarchicalTable = api_get_configuration_value('table_of_hierarchical_skill_presentation');
850
851
        if (empty($imageSize)) {
852
            $imageSize = 'img_small';
853
        } else {
854
            $imageSize = "img_$imageSize";
855
        }
856
857
        $html = '';
858
        foreach ($skills as $skill) {
859
            if (isset($skill['data'])) {
860
                $skill = $skill['data'];
861
            }
862
863
            $item = '';
864
            if ($showBadge) {
865
                $item = '<div class="item">'.$skill[$imageSize].'</div>';
866
            }
867
868
            $name = '<div class="caption">'.$skill['name'].'</div>';
869
            if (!empty($skill['short_code'])) {
870
                $name = $skill['short_code'];
871
            }
872
873
            if (!$isHierarchicalTable) {
874
                //$item .= '<br />';
875
            }
876
877
            if ($showTitle) {
878
                $item .= $name;
879
            }
880
881
            if (isset($skill['url'])) {
882
                $html .= Display::url($item, $skill['url'], ['target' => '_blank', 'style' => $style]);
883
            } else {
884
                $html .= Display::url($item, '#', ['target' => '_blank', 'style' => $style]);
885
            }
886
        }
887
888
        return $html;
889
    }
890
891
    /**
892
     * @param int $id
893
     *
894
     * @return array
895
     */
896
    public function getSkillInfo($id)
897
    {
898
        $skillRelSkill = new SkillRelSkill();
899
        $skillInfo = $this->get($id);
900
        if (!empty($skillInfo)) {
901
            $skillInfo['extra'] = $skillRelSkill->getSkillInfo($id);
902
            $skillInfo['gradebooks'] = $this->getGradebooksBySkill($id);
903
        }
904
905
        return $skillInfo;
906
    }
907
908
    /**
909
     * @param array $skill_list
910
     *
911
     * @return array
912
     */
913
    public function getSkillsInfo($skill_list)
914
    {
915
        $skill_list = array_map('intval', $skill_list);
916
        $skill_list = implode("', '", $skill_list);
917
918
        $sql = "SELECT * FROM {$this->table}
919
                WHERE id IN ('$skill_list') ";
920
921
        $result = Database::query($sql);
922
        $skills = Database::store_result($result, 'ASSOC');
923
924
        foreach ($skills as &$skill) {
925
            if (!$skill['icon']) {
926
                continue;
927
            }
928
929
            $skill['icon_small'] = sprintf(
930
                'badges/%s-small.png',
931
                sha1($skill['name'])
932
            );
933
            $skill['name'] = self::translateName($skill['name']);
934
            $skill['short_code'] = self::translateCode($skill['short_code']);
935
        }
936
937
        return $skills;
938
    }
939
940
    /**
941
     * @param bool $load_user_data
942
     * @param bool $user_id
943
     * @param int  $id
944
     * @param int  $parent_id
945
     *
946
     * @return array
947
     */
948
    public function get_all(
949
        $load_user_data = false,
950
        $user_id = false,
951
        $id = null,
952
        $parent_id = null
953
    ) {
954
        $id_condition = '';
955
        if (!empty($id)) {
956
            $id = (int) $id;
957
            $id_condition = " WHERE s.id = $id";
958
        }
959
960
        if (!empty($parent_id)) {
961
            $parent_id = (int) $parent_id;
962
            if (empty($id_condition)) {
963
                $id_condition = " WHERE ss.parent_id = $parent_id";
964
            } else {
965
                $id_condition = " AND ss.parent_id = $parent_id";
966
            }
967
        }
968
969
        $sql = "SELECT
970
                    s.id,
971
                    s.name,
972
                    s.description,
973
                    ss.parent_id,
974
                    ss.relation_type,
975
                    s.icon,
976
                    s.short_code,
977
                    s.status
978
                FROM {$this->table} s
979
                INNER JOIN {$this->table_skill_rel_skill} ss
980
                ON (s.id = ss.skill_id) $id_condition
981
                ORDER BY ss.id, ss.parent_id";
982
983
        $result = Database::query($sql);
984
        $skills = [];
985
        $webPath = api_get_path(WEB_UPLOAD_PATH);
986
        if (Database::num_rows($result)) {
987
            while ($row = Database::fetch_array($result, 'ASSOC')) {
988
                $skillInfo = self::get($row['id']);
0 ignored issues
show
Bug Best Practice introduced by
The method Skill::get() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

988
                /** @scrutinizer ignore-call */ 
989
                $skillInfo = self::get($row['id']);
Loading history...
989
990
                $row['img_mini'] = $skillInfo['img_mini'];
991
                $row['img_big'] = $skillInfo['img_big'];
992
                $row['img_small'] = $skillInfo['img_small'];
993
994
                $row['name'] = self::translateName($row['name']);
995
                $row['short_code'] = self::translateCode($row['short_code']);
996
                $skillRelSkill = new SkillRelSkill();
997
                $parents = $skillRelSkill->getSkillParents($row['id']);
998
                $row['level'] = count($parents) - 1;
999
                $row['gradebooks'] = $this->getGradebooksBySkill($row['id']);
1000
                $skills[$row['id']] = $row;
1001
            }
1002
        }
1003
1004
        // Load all children of the parent_id
1005
        if (!empty($skills) && !empty($parent_id)) {
1006
            foreach ($skills as $skill) {
1007
                $children = self::get_all($load_user_data, $user_id, $id, $skill['id']);
0 ignored issues
show
Bug Best Practice introduced by
The method Skill::get_all() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1007
                /** @scrutinizer ignore-call */ 
1008
                $children = self::get_all($load_user_data, $user_id, $id, $skill['id']);
Loading history...
1008
                if (!empty($children)) {
1009
                    //$skills = array_merge($skills, $children);
1010
                    $skills = $skills + $children;
1011
                }
1012
            }
1013
        }
1014
1015
        return $skills;
1016
    }
1017
1018
    /**
1019
     * @param int $skill_id
1020
     *
1021
     * @return array|resource
1022
     */
1023
    public function getGradebooksBySkill($skill_id)
1024
    {
1025
        $skill_id = (int) $skill_id;
1026
        $sql = "SELECT g.* FROM {$this->table_gradebook} g
1027
                INNER JOIN {$this->table_skill_rel_gradebook} sg
1028
                ON g.id = sg.gradebook_id
1029
                WHERE sg.skill_id = $skill_id";
1030
        $result = Database::query($sql);
1031
        $result = Database::store_result($result, 'ASSOC');
1032
1033
        return $result;
1034
    }
1035
1036
    /**
1037
     * Get one level children.
1038
     *
1039
     * @param int  $skill_id
1040
     * @param bool $load_user_data
1041
     *
1042
     * @return array
1043
     */
1044
    public function getChildren($skill_id, $load_user_data = false)
1045
    {
1046
        $skillRelSkill = new SkillRelSkill();
1047
        if ($load_user_data) {
1048
            $user_id = api_get_user_id();
1049
            $skills = $skillRelSkill->getChildren($skill_id, true, $user_id);
1050
        } else {
1051
            $skills = $skillRelSkill->getChildren($skill_id);
1052
        }
1053
1054
        return $skills;
1055
    }
1056
1057
    /**
1058
     * Get all children of the current node (recursive).
1059
     *
1060
     * @param int $skillId
1061
     *
1062
     * @return array
1063
     */
1064
    public function getAllChildren($skillId)
1065
    {
1066
        $skillRelSkill = new SkillRelSkill();
1067
        $children = $skillRelSkill->getChildren($skillId);
1068
        foreach ($children as $child) {
1069
            $subChildren = $this->getAllChildren($child['id']);
1070
        }
1071
1072
        if (!empty($subChildren)) {
1073
            $children = array_merge($children, $subChildren);
1074
        }
1075
1076
        return $children;
1077
    }
1078
1079
    /**
1080
     * Gets all parents from from the wanted skill.
1081
     */
1082
    public function get_parents($skillId)
1083
    {
1084
        $skillRelSkill = new SkillRelSkill();
1085
        $skills = $skillRelSkill->getSkillParents($skillId, true);
1086
        foreach ($skills as &$skill) {
1087
            $skill['data'] = $this->get($skill['skill_id']);
1088
        }
1089
1090
        return $skills;
1091
    }
1092
1093
    /**
1094
     * All direct parents.
1095
     *
1096
     * @param int $skillId
1097
     *
1098
     * @return array
1099
     */
1100
    public function getDirectParents($skillId)
1101
    {
1102
        $skillRelSkill = new SkillRelSkill();
1103
        $skills = $skillRelSkill->getDirectParents($skillId, true);
1104
        if (!empty($skills)) {
1105
            foreach ($skills as &$skill) {
1106
                $skillData = $this->get($skill['skill_id']);
1107
                if (empty($skillData)) {
1108
                    continue;
1109
                }
1110
                $skill['data'] = $skillData;
1111
                $skill_info2 = $skillRelSkill->getSkillInfo($skill['skill_id']);
1112
                $parentId = isset($skill_info2['parent_id']) ? isset($skill_info2['parent_id']) : 0;
1113
                $skill['data']['parent_id'] = $parentId;
1114
            }
1115
1116
            return $skills;
1117
        }
1118
1119
        return [];
1120
    }
1121
1122
    /**
1123
     * Adds a new skill.
1124
     *
1125
     * @param array $params
1126
     *
1127
     * @return bool|null
1128
     */
1129
    public function add($params)
1130
    {
1131
        if (!isset($params['parent_id'])) {
1132
            $params['parent_id'] = 1;
1133
        }
1134
1135
        if (!is_array($params['parent_id'])) {
1136
            $params['parent_id'] = [$params['parent_id']];
1137
        }
1138
1139
        $skillRelSkill = new SkillRelSkill();
1140
        $skillRelGradebook = new SkillRelGradebook();
1141
1142
        // Saving name, description
1143
        $skill_id = $this->save($params);
1144
        if ($skill_id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $skill_id of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1145
            // Saving skill_rel_skill (parent_id, relation_type)
1146
            foreach ($params['parent_id'] as $parent_id) {
1147
                $relation_exists = $skillRelSkill->relationExists($skill_id, $parent_id);
1148
                if (!$relation_exists) {
1149
                    $attributes = [
1150
                        'skill_id' => $skill_id,
1151
                        'parent_id' => $parent_id,
1152
                        'relation_type' => isset($params['relation_type']) ? $params['relation_type'] : 0,
1153
                        //'level'         => $params['level'],
1154
                    ];
1155
                    $skillRelSkill->save($attributes);
1156
                }
1157
            }
1158
1159
            if (!empty($params['gradebook_id'])) {
1160
                foreach ($params['gradebook_id'] as $gradebook_id) {
1161
                    $attributes = [];
1162
                    $attributes['gradebook_id'] = $gradebook_id;
1163
                    $attributes['skill_id'] = $skill_id;
1164
                    $skillRelGradebook->save($attributes);
1165
                }
1166
            }
1167
1168
            return $skill_id;
1169
        }
1170
1171
        return null;
1172
    }
1173
1174
    /**
1175
     * @param int      $userId
1176
     * @param Category $category
1177
     * @param int      $courseId
1178
     * @param int      $sessionId
1179
     *
1180
     * @return bool
1181
     */
1182
    public function addSkillToUser(
1183
        $userId,
1184
        $category,
1185
        $courseId,
1186
        $sessionId
1187
    ) {
1188
        $skill_gradebook = new SkillRelGradebook();
1189
        $skill_rel_user = new SkillRelUser();
1190
1191
        if (empty($category)) {
1192
            return false;
1193
        }
1194
1195
        $enableGradeSubCategorySkills = (true === api_get_configuration_value('gradebook_enable_subcategory_skills_independant_assignement'));
1196
        // Load subcategories
1197
        if (empty($category->get_parent_id())) {
1198
            $subCategories = $category->get_subcategories(
1199
                $userId,
1200
                $category->get_course_code(),
1201
                $category->get_session_id()
1202
            );
1203
            $scoreSubCategories = $this->getSubCategoryResultScore($category, $userId);
1204
            if (!empty($subCategories)) {
1205
                /** @var Category $subCategory */
1206
                foreach ($subCategories as $subCategory) {
1207
                    $scoreChecked = true;
1208
                    if (!empty($scoreSubCategories[$subCategory->get_id()])) {
1209
                        $resultScore = $scoreSubCategories[$subCategory->get_id()];
1210
                        $scoreChecked = ($resultScore['user_score'] >= $resultScore['min_score']);
1211
                    }
1212
                    if ($scoreChecked) {
1213
                        $this->addSkillToUser($userId, $subCategory, $courseId, $sessionId);
1214
                    }
1215
                }
1216
            }
1217
        }
1218
1219
        $gradebookId = $category->get_id();
1220
        $skill_gradebooks = $skill_gradebook->get_all(['where' => ['gradebook_id = ?' => $gradebookId]]);
1221
1222
        // It checks if gradebook is passed to add the skill
1223
        if ($enableGradeSubCategorySkills) {
1224
            $userFinished = Category::userFinishedCourse(
1225
                $userId,
1226
                $category,
1227
                true
1228
            );
1229
            if (!$userFinished) {
1230
                return false;
1231
            }
1232
        }
1233
1234
        if (!empty($skill_gradebooks)) {
1235
            foreach ($skill_gradebooks as $skill_gradebook) {
1236
                $hasSkill = $this->userHasSkill(
1237
                    $userId,
1238
                    $skill_gradebook['skill_id'],
1239
                    $courseId,
1240
                    $sessionId
1241
                );
1242
1243
                if (!$hasSkill) {
1244
                    $params = [
1245
                        'user_id' => $userId,
1246
                        'skill_id' => $skill_gradebook['skill_id'],
1247
                        'acquired_skill_at' => api_get_utc_datetime(),
1248
                        'course_id' => (int) $courseId,
1249
                        'session_id' => $sessionId ? (int) $sessionId : null,
1250
                    ];
1251
1252
                    $skill_rel_user->save($params);
1253
1254
                    // It sends notifications about user skills from gradebook
1255
                    $badgeAssignationNotification = api_get_configuration_value('badge_assignation_notification');
1256
                    if ($badgeAssignationNotification) {
1257
                        $entityManager = Database::getManager();
1258
                        $skillRepo = $entityManager->getRepository('ChamiloCoreBundle:Skill');
1259
                        $skill = $skillRepo->find($skill_gradebook['skill_id']);
1260
                        if ($skill) {
1261
                            $user = api_get_user_entity($userId);
1262
                            $url = api_get_path(WEB_PATH)."skill/{$skill_gradebook['skill_id']}/user/{$userId}";
1263
                            $message = sprintf(
1264
                                get_lang('YouXHaveAchievedTheSkillYToSeeFollowLinkZ'),
1265
                                $user->getFirstname(),
1266
                                $skill->getName(),
1267
                                Display::url($url, $url, ['target' => '_blank'])
1268
                            );
1269
                            MessageManager::send_message(
1270
                                $user->getId(),
1271
                                get_lang('YouHaveAchievedANewSkill'),
1272
                                $message
1273
                            );
1274
                        }
1275
                    }
1276
                }
1277
            }
1278
        }
1279
1280
        return true;
1281
    }
1282
1283
    /**
1284
     * Get the results of user in a subCategory.
1285
     *
1286
     * @param $category
1287
     * @param $userId
1288
     *
1289
     * @return array
1290
     */
1291
    public function getSubCategoryResultScore($category, $userId)
1292
    {
1293
        $scoreSubCategories = [];
1294
        if (true === api_get_configuration_value('gradebook_enable_subcategory_skills_independant_assignement')) {
1295
            $subCategories = $category->get_subcategories(
1296
                $userId,
1297
                $category->get_course_code(),
1298
                $category->get_session_id()
1299
            );
1300
            $alleval = $category->get_evaluations($userId, false, $category->get_course_code(),
1301
                $category->get_session_id());
1302
            $alllink = $category->get_links($userId, true, $category->get_course_code(), $category->get_session_id());
1303
            $datagen = new GradebookDataGenerator($subCategories, $alleval, $alllink);
1304
            $gradeResult = $datagen->get_data();
1305
            foreach ($gradeResult as $data) {
1306
                /** @var AbstractLink $item */
1307
                $item = $data[0];
1308
                if (Category::class === get_class($item)) {
1309
                    $scoreSubCategories[$item->get_id()]['min_score'] = $item->getCertificateMinScore();
0 ignored issues
show
Bug introduced by
The method getCertificateMinScore() does not exist on AbstractLink. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1309
                    /** @scrutinizer ignore-call */ 
1310
                    $scoreSubCategories[$item->get_id()]['min_score'] = $item->getCertificateMinScore();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1310
                    $scoreSubCategories[$item->get_id()]['user_score'] = round($data['result_score'][0]);
1311
                }
1312
            }
1313
        }
1314
1315
        return $scoreSubCategories;
1316
    }
1317
1318
    /* Deletes a skill */
1319
    public function delete($skill_id)
1320
    {
1321
        /*$params = array('skill_id' => $skill_id);
1322
1323
        $skillRelSkill     = new SkillRelSkill();
1324
        $skills = $skillRelSkill->get_all(array('where'=>array('skill_id = ?' =>$skill_id)));
1325
1326
        $skill_rel_profile     = new SkillRelProfile();
1327
        $skillRelGradebook = new SkillRelGradebook();
1328
        $skill_rel_user     = new SkillRelUser();
1329
1330
        $this->delete($skill_id);
1331
1332
        $skillRelGradebook->delete($params);*/
1333
    }
1334
1335
    /**
1336
     * @param array $params
1337
     */
1338
    public function edit($params)
1339
    {
1340
        if (!isset($params['parent_id'])) {
1341
            $params['parent_id'] = 1;
1342
        }
1343
1344
        $params['gradebook_id'] = isset($params['gradebook_id']) ? $params['gradebook_id'] : [];
1345
1346
        $skillRelSkill = new SkillRelSkill();
1347
        $skillRelGradebook = new SkillRelGradebook();
1348
1349
        // Saving name, description
1350
        $this->update($params);
1351
        $skillId = $params['id'];
1352
1353
        if ($skillId) {
1354
            // Saving skill_rel_skill (parent_id, relation_type)
1355
            if (!is_array($params['parent_id'])) {
1356
                $params['parent_id'] = [$params['parent_id']];
1357
            }
1358
1359
            // Cannot change parent of root
1360
            if ($skillId == 1) {
1361
                $params['parent_id'] = 0;
1362
            }
1363
1364
            foreach ($params['parent_id'] as $parent_id) {
1365
                $relation_exists = $skillRelSkill->relationExists($skillId, $parent_id);
1366
                if (!$relation_exists) {
1367
                    $attributes = [
1368
                        'skill_id' => $skillId,
1369
                        'parent_id' => $parent_id,
1370
                        'relation_type' => $params['relation_type'],
1371
                        //'level'         => $params['level'],
1372
                    ];
1373
                    $skillRelSkill->updateBySkill($attributes);
1374
                }
1375
            }
1376
1377
            $skillRelGradebook->updateGradeBookListBySkill(
1378
                $skillId,
1379
                $params['gradebook_id']
1380
            );
1381
1382
            return $skillId;
1383
        }
1384
1385
        return null;
1386
    }
1387
1388
    /**
1389
     * Get user's skills.
1390
     *
1391
     * @param int  $userId
1392
     * @param bool $getSkillData
1393
     * @param int  $courseId
1394
     * @param int  $sessionId
1395
     *
1396
     * @return array
1397
     */
1398
    public function getUserSkills($userId, $getSkillData = false, $courseId = 0, $sessionId = 0)
1399
    {
1400
        $userId = (int) $userId;
1401
        $courseId = (int) $courseId;
1402
        $sessionId = (int) $sessionId;
1403
1404
        $courseCondition = '';
1405
        if (!empty($courseId)) {
1406
            $courseCondition = " AND course_id = $courseId ";
1407
        }
1408
1409
        $sessionCondition = '';
1410
        if (!empty($sessionId)) {
1411
            $sessionCondition = " AND course_id = $sessionId ";
1412
        }
1413
1414
        $sql = 'SELECT DISTINCT
1415
                    s.id,
1416
                    s.name,
1417
                    s.icon,
1418
                    u.id as issue,
1419
                    u.acquired_skill_at,
1420
                    u.course_id
1421
                FROM '.$this->table_skill_rel_user.' u
1422
                INNER JOIN '.$this->table.' s
1423
                ON u.skill_id = s.id
1424
                WHERE
1425
                    user_id = '.$userId.' '.$sessionCondition.' '.$courseCondition;
1426
1427
        $result = Database::query($sql);
1428
        $skills = Database::store_result($result, 'ASSOC');
1429
        $skillList = [];
1430
        if (!empty($skills)) {
1431
            foreach ($skills as $skill) {
1432
                if ($getSkillData) {
1433
                    $skillData = $this->get($skill['id']);
1434
                    $skillData['url'] = api_get_path(WEB_PATH).'badge/'.$skill['id'].'/user/'.$userId;
1435
                    $skillList[$skill['id']] = array_merge($skill, $skillData);
1436
                } else {
1437
                    $skillList[$skill['id']] = $skill['id'];
1438
                }
1439
            }
1440
        }
1441
1442
        return $skillList;
1443
    }
1444
1445
    /**
1446
     * @param array $skills
1447
     * @param int   $level
1448
     *
1449
     * @return string
1450
     */
1451
    public function processVertex(Vertex $vertex, $skills = [], $level = 0)
1452
    {
1453
        $isHierarchicalTable = api_get_configuration_value('table_of_hierarchical_skill_presentation');
1454
        $subTable = '';
1455
        if ($vertex->getVerticesEdgeTo()->count() > 0) {
1456
            if ($isHierarchicalTable) {
1457
                $subTable .= '<ul>';
1458
            }
1459
            foreach ($vertex->getVerticesEdgeTo() as $subVertex) {
1460
                $data = $subVertex->getAttribute('graphviz.data');
1461
                $passed = in_array($data['id'], array_keys($skills));
1462
                $transparency = '';
1463
                if ($passed === false) {
1464
                    // @todo use css class
1465
                    $transparency = 'opacity: 0.4; filter: alpha(opacity=40);';
1466
                }
1467
1468
                if ($isHierarchicalTable) {
1469
                    $label = $this->processSkillListSimple([$data], 'mini', $transparency);
1470
                    $subTable .= '<li>'.$label;
1471
                    $subTable .= $this->processVertex($subVertex, $skills, $level + 1);
1472
                    $subTable .= '</li>';
1473
                } else {
1474
                    $imageSize = 'mini';
1475
                    if ($level == 2) {
1476
                        $imageSize = 'small';
1477
                    }
1478
                    $showTitle = true;
1479
                    if ($level > 2) {
1480
                        $showTitle = false;
1481
                    }
1482
1483
                    $label = $this->processSkillListSimple([$data], $imageSize, $transparency, true, $showTitle);
1484
                    $subTable .= '<div class="thumbnail" style="float:left; margin-right:5px; ">';
1485
                    $subTable .= '<div style="'.$transparency.'">';
1486
1487
                    $subTable .= '<div style="text-align: center">';
1488
                    $subTable .= $label;
1489
                    $subTable .= '</div>';
1490
1491
                    $subTable .= '</div>';
1492
                    $subTable .= $this->processVertex($subVertex, $skills, $level + 1);
1493
                    $subTable .= '</div>';
1494
                }
1495
            }
1496
1497
            if ($isHierarchicalTable) {
1498
                $subTable .= '</ul>';
1499
            }
1500
        }
1501
1502
        return $subTable;
1503
    }
1504
1505
    /**
1506
     * @param int  $userId
1507
     * @param int  $courseId
1508
     * @param int  $sessionId
1509
     * @param bool $addTitle
1510
     *
1511
     * @return array
1512
     */
1513
    public function getUserSkillsTable($userId, $courseId = 0, $sessionId = 0, $addTitle = true)
1514
    {
1515
        $skills = $this->getUserSkills($userId, true, $courseId, $sessionId);
1516
        $courseTempList = [];
1517
        $tableRows = [];
1518
        $skillParents = [];
1519
        foreach ($skills as $resultData) {
1520
            $parents = $this->get_parents($resultData['id']);
1521
            foreach ($parents as $parentData) {
1522
                $parentData['passed'] = in_array($parentData['id'], array_keys($skills));
1523
                if ($parentData['passed'] && isset($skills[$parentData['id']]['url'])) {
1524
                    $parentData['data']['url'] = $skills[$parentData['id']]['url'];
1525
                }
1526
                $skillParents[$resultData['id']][$parentData['id']] = $parentData;
1527
            }
1528
        }
1529
1530
        foreach ($skills as $resultData) {
1531
            $courseId = $resultData['course_id'];
1532
            if (!empty($courseId)) {
1533
                if (isset($courseTempList[$courseId])) {
1534
                    $courseInfo = $courseTempList[$courseId];
1535
                } else {
1536
                    $courseInfo = api_get_course_info_by_id($courseId);
1537
                    $courseTempList[$courseId] = $courseInfo;
1538
                }
1539
            } else {
1540
                $courseInfo = [];
1541
            }
1542
            $tableRow = [
1543
                'skill_badge' => $resultData['img_small'],
1544
                'skill_name' => self::translateName($resultData['name']),
1545
                'short_code' => $resultData['short_code'],
1546
                'skill_url' => $resultData['url'],
1547
                'achieved_at' => api_get_local_time($resultData['acquired_skill_at']),
1548
                'course_image' => '',
1549
                'course_name' => '',
1550
            ];
1551
1552
            if (!empty($courseInfo)) {
1553
                $tableRow['course_image'] = $courseInfo['course_image'];
1554
                $tableRow['course_name'] = $courseInfo['title'];
1555
            }
1556
            $tableRows[] = $tableRow;
1557
        }
1558
1559
        $isHierarchicalTable = api_get_configuration_value('table_of_hierarchical_skill_presentation');
1560
        $allowLevels = api_get_configuration_value('skill_levels_names');
1561
1562
        $tableResult = '<div id="skillList">';
1563
        if ($isHierarchicalTable) {
1564
            $tableResult = '<div class="table-responsive">';
1565
        }
1566
1567
        if ($addTitle) {
1568
            $tableResult .= Display::page_subheader(get_lang('AchievedSkills'));
1569
            $tableResult .= '<div class="skills-badges">';
1570
        }
1571
1572
        if (!empty($skillParents)) {
1573
            if (empty($allowLevels)) {
1574
                $tableResult .= $this->processSkillListSimple($skills);
1575
            } else {
1576
                $graph = new Graph();
1577
                $graph->setAttribute('graphviz.graph.rankdir', 'LR');
1578
                foreach ($skillParents as $skillId => $parentList) {
1579
                    $old = null;
1580
                    foreach ($parentList as $parent) {
1581
                        if ($graph->hasVertex($parent['id'])) {
1582
                            $current = $graph->getVertex($parent['id']);
1583
                        } else {
1584
                            $current = $graph->createVertex($parent['id']);
1585
                            $current->setAttribute('graphviz.data', $parent['data']);
1586
                        }
1587
1588
                        if (!empty($old)) {
1589
                            if ($graph->hasVertex($old['id'])) {
1590
                                $nextVertex = $graph->getVertex($old['id']);
1591
                            } else {
1592
                                $nextVertex = $graph->createVertex($old['id']);
1593
                                $nextVertex->setAttribute('graphviz.data', $old['data']);
1594
                            }
1595
1596
                            if (!$nextVertex->hasEdgeTo($current)) {
1597
                                $nextVertex->createEdgeTo($current);
1598
                            }
1599
                        }
1600
                        $old = $parent;
1601
                    }
1602
                }
1603
1604
                if ($isHierarchicalTable) {
1605
                    $table = '<table class ="table table-bordered">';
1606
                    // Getting "root" vertex
1607
                    $root = $graph->getVertex(1);
1608
                    $table .= '<tr>';
1609
                    /** @var Vertex $vertex */
1610
                    foreach ($root->getVerticesEdgeTo() as $vertex) {
1611
                        $data = $vertex->getAttribute('graphviz.data');
1612
1613
                        $passed = in_array($data['id'], array_keys($skills));
1614
                        $transparency = '';
1615
                        if ($passed === false) {
1616
                            // @todo use a css class
1617
                            $transparency = 'opacity: 0.4; filter: alpha(opacity=40);';
1618
                        }
1619
1620
                        $label = $this->processSkillListSimple([$data], 'mini', $transparency);
1621
                        $table .= '<td >';
1622
1623
                        $table .= '<div class="skills_chart"> <ul><li>'.$label;
1624
                        $table .= $this->processVertex($vertex, $skills);
1625
                        $table .= '</ul></li></div>';
1626
                        $table .= '</td>';
1627
                    }
1628
                    $table .= '</tr></table>';
1629
                } else {
1630
                    // Getting "root" vertex
1631
                    $root = $graph->getVertex(1);
1632
                    $table = '';
1633
                    /** @var Vertex $vertex */
1634
                    foreach ($root->getVerticesEdgeTo() as $vertex) {
1635
                        $data = $vertex->getAttribute('graphviz.data');
1636
1637
                        $passed = in_array($data['id'], array_keys($skills));
1638
                        $transparency = '';
1639
                        if ($passed === false) {
1640
                            // @todo use a css class
1641
                            $transparency = 'opacity: 0.4; filter: alpha(opacity=40);';
1642
                        }
1643
1644
                        $label = $this->processSkillListSimple([$data], 'mini', $transparency, false);
1645
1646
                        $skillTable = $this->processVertex($vertex, $skills, 2);
1647
                        $table .= "<h3>$label</h3>";
1648
1649
                        if (!empty($skillTable)) {
1650
                            $table .= '<table class ="table table-bordered">';
1651
                            $table .= '<tr>';
1652
                            $table .= '<td>';
1653
                            $table .= '<div>';
1654
                            $table .= $skillTable;
1655
                            $table .= '</div>';
1656
                            $table .= '</td>';
1657
                            $table .= '</tr></table>';
1658
                        }
1659
                    }
1660
                }
1661
1662
                $tableResult .= $table;
1663
            }
1664
        } else {
1665
            $tableResult .= get_lang('WithoutAchievedSkills');
1666
        }
1667
1668
        if ($addTitle) {
1669
            $tableResult .= '</div>';
1670
        }
1671
        $tableResult .= '</div>';
1672
1673
        return [
1674
            'skills' => $tableRows,
1675
            'table' => $tableResult,
1676
        ];
1677
    }
1678
1679
    /**
1680
     * @param int  $user_id
1681
     * @param int  $skill_id
1682
     * @param bool $return_flat_array
1683
     * @param bool $add_root
1684
     *
1685
     * @return array|null
1686
     */
1687
    public function getSkillsTree(
1688
        $user_id = null,
1689
        $skill_id = null,
1690
        $return_flat_array = false,
1691
        $add_root = false
1692
    ) {
1693
        if ($skill_id == 1) {
1694
            $skill_id = 0;
1695
        }
1696
        if (isset($user_id) && !empty($user_id)) {
1697
            $skills = $this->get_all(true, $user_id, null, $skill_id);
1698
        } else {
1699
            $skills = $this->get_all(false, false, null, $skill_id);
1700
        }
1701
1702
        $original_skill = $this->list = $skills;
1703
1704
        // Show 1 item
1705
        if (!empty($skill_id)) {
1706
            if ($add_root) {
1707
                if (!empty($skill_id)) {
1708
                    // Default root node
1709
                    $skills[1] = [
1710
                        'id' => '1',
1711
                        'name' => get_lang('Root'),
1712
                        'parent_id' => '0',
1713
                        'status' => 1,
1714
                    ];
1715
                    $skillInfo = $this->getSkillInfo($skill_id);
1716
1717
                    // 2nd node
1718
                    $skills[$skill_id] = $skillInfo;
1719
                    // Uncomment code below to hide the searched skill
1720
                    $skills[$skill_id]['data']['parent_id'] = $skillInfo['extra']['parent_id'];
1721
                    $skills[$skill_id]['parent_id'] = 1;
1722
                }
1723
            }
1724
        }
1725
1726
        $refs = [];
1727
        $skills_tree = null;
1728
1729
        // Create references for all nodes
1730
        $flat_array = [];
1731
        $family = [];
1732
        if (!empty($skills)) {
1733
            foreach ($skills as &$skill) {
1734
                if ($skill['parent_id'] == 0) {
1735
                    $skill['parent_id'] = 'root';
1736
                }
1737
1738
                // because except main keys (id, name, children) others keys
1739
                // are not saved while in the space tree
1740
                $skill['data'] = ['parent_id' => $skill['parent_id']];
1741
1742
                // If a short code was defined, send the short code to replace
1743
                // skill name (to shorten the text in the wheel)
1744
                if (!empty($skill['short_code']) &&
1745
                    api_get_setting('show_full_skill_name_on_skill_wheel') === 'false'
1746
                ) {
1747
                    $skill['data']['short_code'] = $skill['short_code'];
1748
                }
1749
1750
                $skill['data']['name'] = $skill['name'];
1751
                $skill['data']['status'] = $skill['status'];
1752
1753
                // In order to paint all members of a family with the same color
1754
                if (empty($skill_id)) {
1755
                    if ($skill['parent_id'] == 1) {
1756
                        $family[$skill['id']] = $this->getAllChildren($skill['id']);
1757
                    }
1758
                } else {
1759
                    if ($skill['parent_id'] == $skill_id) {
1760
                        $family[$skill['id']] = $this->getAllChildren($skill['id']);
1761
                    }
1762
                    /*if ($skill_id == $skill['id']) {
1763
                        $skill['parent_id'] = 1;
1764
                    }*/
1765
                }
1766
1767
                if (!isset($skill['data']['real_parent_id'])) {
1768
                    $skill['data']['real_parent_id'] = $skill['parent_id'];
1769
                }
1770
1771
                // User achieved the skill (depends in the gradebook with certification)
1772
                $skill['data']['achieved'] = false;
1773
                if ($user_id) {
1774
                    $skill['data']['achieved'] = $this->userHasSkill(
1775
                        $user_id,
1776
                        $skill['id']
1777
                    );
1778
                }
1779
1780
                // Check if the skill has related gradebooks
1781
                $skill['data']['skill_has_gradebook'] = false;
1782
                if (isset($skill['gradebooks']) && !empty($skill['gradebooks'])) {
1783
                    $skill['data']['skill_has_gradebook'] = true;
1784
                }
1785
                $refs[$skill['id']] = &$skill;
1786
                $flat_array[$skill['id']] = &$skill;
1787
            }
1788
1789
            // Checking family value
1790
1791
            $family_id = 1;
1792
            $new_family_array = [];
1793
            foreach ($family as $main_family_id => $family_items) {
1794
                if (!empty($family_items)) {
1795
                    foreach ($family_items as $item) {
1796
                        $new_family_array[$item['id']] = $family_id;
1797
                    }
1798
                }
1799
                $new_family_array[$main_family_id] = $family_id;
1800
                $family_id++;
1801
            }
1802
1803
            if (empty($original_skill)) {
1804
                $refs['root']['children'][0] = $skills[1];
1805
                $skills[$skill_id]['data']['family_id'] = 1;
1806
                $refs['root']['children'][0]['children'][0] = $skills[$skill_id];
1807
                $flat_array[$skill_id] = $skills[$skill_id];
1808
            } else {
1809
                // Moving node to the children index of their parents
1810
                foreach ($skills as $my_skill_id => &$skill) {
1811
                    if (isset($new_family_array[$skill['id']])) {
1812
                        $skill['data']['family_id'] = $new_family_array[$skill['id']];
1813
                    }
1814
                    $refs[$skill['parent_id']]['children'][] = &$skill;
1815
                    $flat_array[$my_skill_id] = $skill;
1816
                }
1817
            }
1818
1819
            $skills_tree = [
1820
                'name' => get_lang('SkillRootName'),
1821
                'id' => 'root',
1822
                'children' => $refs['root']['children'],
1823
                'data' => [],
1824
            ];
1825
        }
1826
1827
        if ($return_flat_array) {
1828
            return $flat_array;
1829
        }
1830
        unset($skills);
1831
1832
        return $skills_tree;
1833
    }
1834
1835
    /**
1836
     * Get skills tree as a simplified JSON structure.
1837
     *
1838
     * @param int user id
1839
     * @param int skill id
1840
     * @param bool return a flat array or not
1841
     * @param int depth of the skills
1842
     *
1843
     * @return string json
1844
     */
1845
    public function getSkillsTreeToJson(
1846
        $user_id = null,
1847
        $skill_id = null,
1848
        $return_flat_array = false,
1849
        $main_depth = 2
1850
    ) {
1851
        $tree = $this->getSkillsTree(
1852
            $user_id,
1853
            $skill_id,
1854
            $return_flat_array,
1855
            true
1856
        );
1857
        $simple_tree = [];
1858
        if (!empty($tree['children'])) {
1859
            foreach ($tree['children'] as $element) {
1860
                $children = [];
1861
                if (isset($element['children'])) {
1862
                    $children = $this->getSkillToJson($element['children'], 1, $main_depth);
1863
                }
1864
                $simple_tree[] = [
1865
                    'name' => $element['name'],
1866
                    'children' => $children,
1867
                ];
1868
            }
1869
        }
1870
1871
        return json_encode($simple_tree[0]['children']);
1872
    }
1873
1874
    /**
1875
     * Get JSON element.
1876
     *
1877
     * @param array $subtree
1878
     * @param int   $depth
1879
     * @param int   $max_depth
1880
     *
1881
     * @return array|null
1882
     */
1883
    public function getSkillToJson($subtree, $depth = 1, $max_depth = 2)
1884
    {
1885
        $simple_sub_tree = [];
1886
        if (is_array($subtree)) {
1887
            $counter = 1;
1888
            foreach ($subtree as $elem) {
1889
                $tmp = [];
1890
                $tmp['name'] = $elem['name'];
1891
                $tmp['id'] = $elem['id'];
1892
                $tmp['isSearched'] = self::isSearched($elem['id']);
1893
1894
                if (isset($elem['children']) && is_array($elem['children'])) {
1895
                    $tmp['children'] = $this->getSkillToJson(
1896
                        $elem['children'],
1897
                        $depth + 1,
1898
                        $max_depth
1899
                    );
1900
                }
1901
1902
                if ($depth > $max_depth) {
1903
                    continue;
1904
                }
1905
1906
                $tmp['depth'] = $depth;
1907
                $tmp['counter'] = $counter;
1908
                $counter++;
1909
1910
                if (isset($elem['data']) && is_array($elem['data'])) {
1911
                    foreach ($elem['data'] as $key => $item) {
1912
                        $tmp[$key] = $item;
1913
                    }
1914
                }
1915
                $simple_sub_tree[] = $tmp;
1916
            }
1917
1918
            return $simple_sub_tree;
1919
        }
1920
1921
        return null;
1922
    }
1923
1924
    /**
1925
     * @param int $user_id
1926
     *
1927
     * @return bool
1928
     */
1929
    public function getUserSkillRanking($user_id)
1930
    {
1931
        $user_id = (int) $user_id;
1932
        $sql = "SELECT count(skill_id) count
1933
                FROM {$this->table} s
1934
                INNER JOIN {$this->table_skill_rel_user} su
1935
                ON (s.id = su.skill_id)
1936
                WHERE user_id = $user_id";
1937
        $result = Database::query($sql);
1938
        if (Database::num_rows($result)) {
1939
            $result = Database::fetch_row($result);
1940
1941
            return $result[0];
1942
        }
1943
1944
        return false;
1945
    }
1946
1947
    /**
1948
     * @param $start
1949
     * @param $limit
1950
     * @param $sidx
1951
     * @param $sord
1952
     * @param $where_condition
1953
     *
1954
     * @return array
1955
     */
1956
    public function getUserListSkillRanking(
1957
        $start,
1958
        $limit,
1959
        $sidx,
1960
        $sord,
1961
        $where_condition
1962
    ) {
1963
        $start = (int) $start;
1964
        $limit = (int) $limit;
1965
1966
        /*  ORDER BY $sidx $sord */
1967
        $sql = "SELECT *, @rownum:=@rownum+1 rank FROM (
1968
                    SELECT u.user_id, firstname, lastname, count(username) skills_acquired
1969
                    FROM {$this->table} s INNER JOIN {$this->table_skill_rel_user} su ON (s.id = su.skill_id)
1970
                    INNER JOIN {$this->table_user} u ON u.user_id = su.user_id, (SELECT @rownum:=0) r
1971
                    WHERE 1=1 $where_condition
1972
                    GROUP BY username
1973
                    ORDER BY skills_acquired desc
1974
                    LIMIT $start , $limit)  AS T1, (SELECT @rownum:=0) r";
1975
        $result = Database::query($sql);
1976
        if (Database::num_rows($result)) {
1977
            return Database::store_result($result, 'ASSOC');
1978
        }
1979
1980
        return [];
1981
    }
1982
1983
    /**
1984
     * @return int
1985
     */
1986
    public function getUserListSkillRankingCount()
1987
    {
1988
        $sql = "SELECT count(*) FROM (
1989
                    SELECT count(distinct 1)
1990
                    FROM {$this->table} s
1991
                    INNER JOIN {$this->table_skill_rel_user} su
1992
                    ON (s.id = su.skill_id)
1993
                    INNER JOIN {$this->table_user} u
1994
                    ON u.user_id = su.user_id
1995
                    GROUP BY username
1996
                 ) as T1";
1997
        $result = Database::query($sql);
1998
        if (Database::num_rows($result)) {
1999
            $result = Database::fetch_row($result);
2000
2001
            return $result[0];
2002
        }
2003
2004
        return 0;
2005
    }
2006
2007
    /**
2008
     * @param string $courseCode
2009
     *
2010
     * @return int
2011
     */
2012
    public function getCountSkillsByCourse($courseCode)
2013
    {
2014
        $courseCode = Database::escape_string($courseCode);
2015
        $sql = "SELECT count(skill_id) as count
2016
                FROM {$this->table_gradebook} g
2017
                INNER JOIN {$this->table_skill_rel_gradebook} sg
2018
                ON g.id = sg.gradebook_id
2019
                WHERE course_code = '$courseCode'";
2020
2021
        $result = Database::query($sql);
2022
        if (Database::num_rows($result)) {
2023
            $result = Database::fetch_row($result);
2024
2025
            return $result[0];
2026
        }
2027
2028
        return 0;
2029
    }
2030
2031
    /**
2032
     * @param int $skillId
2033
     *
2034
     * @return array
2035
     */
2036
    public function getCoursesBySkill($skillId)
2037
    {
2038
        $skillId = (int) $skillId;
2039
        $sql = "SELECT c.title, c.code
2040
                FROM {$this->table_gradebook} g
2041
                INNER JOIN {$this->table_skill_rel_gradebook} sg
2042
                ON g.id = sg.gradebook_id
2043
                INNER JOIN {$this->table_course} c
2044
                ON c.code = g.course_code
2045
                WHERE sg.skill_id = $skillId
2046
                AND (g.session_id IS NULL OR g.session_id = 0)";
2047
        $result = Database::query($sql);
2048
2049
        return Database::store_result($result, 'ASSOC');
2050
    }
2051
2052
    /**
2053
     * Check if the user has the skill.
2054
     *
2055
     * @param int $userId    The user id
2056
     * @param int $skillId   The skill id
2057
     * @param int $courseId  Optional. The course id
2058
     * @param int $sessionId Optional. The session id
2059
     *
2060
     * @return bool Whether the user has the skill return true. Otherwise return false
2061
     */
2062
    public function userHasSkill($userId, $skillId, $courseId = 0, $sessionId = 0)
2063
    {
2064
        $courseId = (int) $courseId;
2065
        $sessionId = (int) $sessionId;
2066
2067
        $whereConditions = [
2068
            'user_id = ? ' => (int) $userId,
2069
            'AND skill_id = ? ' => (int) $skillId,
2070
        ];
2071
2072
        if ($courseId > 0) {
2073
            if ($sessionId) {
2074
                $whereConditions['AND course_id = ? '] = $courseId;
2075
                $whereConditions['AND session_id = ? '] = $sessionId;
2076
            } else {
2077
                $whereConditions['AND course_id = ? AND session_id is NULL'] = $courseId;
2078
            }
2079
        }
2080
2081
        $result = Database::select(
2082
            'COUNT(1) AS qty',
2083
            $this->table_skill_rel_user,
2084
            [
2085
                'where' => $whereConditions,
2086
            ],
2087
            'first'
2088
        );
2089
2090
        if ($result != false) {
2091
            if ($result['qty'] > 0) {
2092
                return true;
2093
            }
2094
        }
2095
2096
        return false;
2097
    }
2098
2099
    /**
2100
     * Check if a skill is searched.
2101
     *
2102
     * @param int $id The skill id
2103
     *
2104
     * @return bool Whether el skill is searched return true. Otherwise return false
2105
     */
2106
    public static function isSearched($id)
2107
    {
2108
        $id = (int) $id;
2109
2110
        if (empty($id)) {
2111
            return false;
2112
        }
2113
2114
        $skillRelProfileTable = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
2115
2116
        $result = Database::select(
2117
            'COUNT( DISTINCT `skill_id`) AS qty',
2118
            $skillRelProfileTable,
2119
            [
2120
                'where' => [
2121
                    'skill_id = ?' => $id,
2122
                ],
2123
            ],
2124
            'first'
2125
        );
2126
2127
        if ($result === false) {
2128
            return false;
2129
        }
2130
2131
        if ($result['qty'] > 0) {
2132
            return true;
2133
        }
2134
2135
        return false;
2136
    }
2137
2138
    /**
2139
     * Get the achieved skills by course.
2140
     *
2141
     * @param int $courseId The course id
2142
     *
2143
     * @return array The skills list
2144
     */
2145
    public function listAchievedByCourse($courseId)
2146
    {
2147
        $courseId = (int) $courseId;
2148
2149
        if ($courseId == 0) {
2150
            return [];
2151
        }
2152
2153
        $list = [];
2154
2155
        $sql = "SELECT
2156
                    course.id c_id,
2157
                    course.title c_name,
2158
                    course.directory c_directory,
2159
                    user.user_id,
2160
                    user.lastname,
2161
                    user.firstname,
2162
                    user.username,
2163
                    skill.id skill_id,
2164
                    skill.name skill_name,
2165
                    sru.acquired_skill_at
2166
                FROM {$this->table_skill_rel_user} AS sru
2167
                INNER JOIN {$this->table_course}
2168
                ON sru.course_id = course.id
2169
                INNER JOIN {$this->table_user}
2170
                ON sru.user_id = user.user_id
2171
                INNER JOIN {$this->table}
2172
                ON sru.skill_id = skill.id
2173
                WHERE course.id = $courseId";
2174
2175
        $result = Database::query($sql);
2176
2177
        while ($row = Database::fetch_assoc($result)) {
2178
            $row['skill_name'] = self::translateName($row['skill_name']);
2179
            $list[] = $row;
2180
        }
2181
2182
        return $list;
2183
    }
2184
2185
    /**
2186
     * Get the users list who achieved a skill.
2187
     *
2188
     * @param int $skillId The skill id
2189
     *
2190
     * @return array The users list
2191
     */
2192
    public function listUsersWhoAchieved($skillId)
2193
    {
2194
        $skillId = (int) $skillId;
2195
2196
        if ($skillId == 0) {
2197
            return [];
2198
        }
2199
2200
        $list = [];
2201
        $sql = "SELECT
2202
                    course.id c_id,
2203
                    course.title c_name,
2204
                    course.directory c_directory,
2205
                    user.user_id,
2206
                    user.lastname,
2207
                    user.firstname,
2208
                    user.username,
2209
                    skill.id skill_id,
2210
                    skill.name skill_name,
2211
                    sru.acquired_skill_at
2212
                FROM {$this->table_skill_rel_user} AS sru
2213
                INNER JOIN {$this->table_course}
2214
                ON sru.course_id = course.id
2215
                INNER JOIN {$this->table_user}
2216
                ON sru.user_id = user.user_id
2217
                INNER JOIN {$this->table}
2218
                ON sru.skill_id = skill.id
2219
                WHERE skill.id = $skillId ";
2220
2221
        $result = Database::query($sql);
2222
        while ($row = Database::fetch_assoc($result)) {
2223
            $row['skill_name'] = self::translateName($row['skill_name']);
2224
            $list[] = $row;
2225
        }
2226
2227
        return $list;
2228
    }
2229
2230
    /**
2231
     * Get the session list where the user can achieve a skill.
2232
     *
2233
     * @param int $skillId The skill id
2234
     *
2235
     * @return array
2236
     */
2237
    public function getSessionsBySkill($skillId)
2238
    {
2239
        $skillId = (int) $skillId;
2240
2241
        $sql = "SELECT s.id, s.name
2242
                FROM {$this->table_gradebook} g
2243
                INNER JOIN {$this->table_skill_rel_gradebook} sg
2244
                ON g.id = sg.gradebook_id
2245
                INNER JOIN {$this->sessionTable} s
2246
                ON g.session_id = s.id
2247
                WHERE sg.skill_id = $skillId
2248
                AND g.session_id > 0";
2249
2250
        $result = Database::query($sql);
2251
2252
        return Database::store_result($result, 'ASSOC');
2253
    }
2254
2255
    /**
2256
     * Check if the $fromUser can comment the $toUser skill issue.
2257
     *
2258
     * @param User $fromUser
2259
     * @param User $toUser
2260
     *
2261
     * @return bool
2262
     */
2263
    public static function userCanAddFeedbackToUser($fromUser, $toUser)
2264
    {
2265
        if (api_is_platform_admin()) {
2266
            return true;
2267
        }
2268
2269
        $userRepo = UserManager::getRepository();
2270
        $fromUserStatus = $fromUser->getStatus();
2271
2272
        switch ($fromUserStatus) {
2273
            case SESSIONADMIN:
2274
                if (api_get_setting('allow_session_admins_to_manage_all_sessions') === 'true') {
2275
                    if ($toUser->getCreatorId() === $fromUser->getId()) {
2276
                        return true;
2277
                    }
2278
                }
2279
2280
                $sessionAdmins = $userRepo->getSessionAdmins($toUser);
2281
2282
                foreach ($sessionAdmins as $sessionAdmin) {
2283
                    if ($sessionAdmin->getId() !== $fromUser->getId()) {
2284
                        continue;
2285
                    }
2286
2287
                    return true;
2288
                }
2289
                break;
2290
            case STUDENT_BOSS:
2291
                $studentBosses = $userRepo->getStudentBosses($toUser);
2292
                foreach ($studentBosses as $studentBoss) {
2293
                    if ($studentBoss->getId() !== $fromUser->getId()) {
2294
                        continue;
2295
                    }
2296
2297
                    return true;
2298
                }
2299
                break;
2300
            case DRH:
2301
                return UserManager::is_user_followed_by_drh(
2302
                    $toUser->getId(),
2303
                    $fromUser->getId()
2304
                );
2305
        }
2306
2307
        return false;
2308
    }
2309
2310
    /**
2311
     * If $studentId is set then check if current user has the right to see
2312
     * the page.
2313
     *
2314
     * @param int  $studentId check if current user has access to see $studentId
2315
     * @param bool $blockPage raise a api_not_allowed()
2316
     *
2317
     * @return bool
2318
     */
2319
    public static function isAllowed($studentId = 0, $blockPage = true)
2320
    {
2321
        $allowHR = api_get_setting('allow_hr_skills_management') === 'true';
2322
2323
        if (self::isToolAvailable()) {
2324
            if (api_is_platform_admin(false, $allowHR)) {
2325
                return true;
2326
            }
2327
2328
            if (!empty($studentId)) {
2329
                $currentUserId = api_get_user_id();
2330
                if ((int) $currentUserId === (int) $studentId) {
2331
                    return true;
2332
                }
2333
2334
                $haveAccess = self::hasAccessToUserSkill(
2335
                    $currentUserId,
2336
                    $studentId
2337
                );
2338
2339
                if ($haveAccess) {
2340
                    return true;
2341
                }
2342
            }
2343
        }
2344
2345
        if ($blockPage) {
2346
            api_not_allowed(true);
2347
        }
2348
2349
        return false;
2350
    }
2351
2352
    /**
2353
     * @return bool
2354
     */
2355
    public static function isToolAvailable()
2356
    {
2357
        $allowTool = api_get_setting('allow_skills_tool');
2358
2359
        if ($allowTool === 'true') {
2360
            return true;
2361
        }
2362
2363
        return false;
2364
    }
2365
2366
    /**
2367
     * @param int $currentUserId
2368
     * @param int $studentId
2369
     *
2370
     * @return bool
2371
     */
2372
    public static function hasAccessToUserSkill($currentUserId, $studentId)
2373
    {
2374
        if (self::isToolAvailable()) {
2375
            if (api_is_platform_admin()) {
2376
                return true;
2377
            }
2378
2379
            $currentUserId = (int) $currentUserId;
2380
            $studentId = (int) $studentId;
2381
2382
            if ($currentUserId === $studentId) {
2383
                return true;
2384
            }
2385
2386
            if (api_is_student_boss()) {
2387
                $isBoss = UserManager::userIsBossOfStudent($currentUserId, $studentId);
2388
                if ($isBoss) {
2389
                    return true;
2390
                }
2391
            }
2392
2393
            $allow = api_get_configuration_value('allow_private_skills');
2394
            if ($allow === true) {
2395
                if (api_is_teacher()) {
2396
                    return UserManager::isTeacherOfStudent(
2397
                        $currentUserId,
2398
                        $studentId
2399
                    );
2400
                }
2401
2402
                if (api_is_drh()) {
2403
                    return UserManager::is_user_followed_by_drh(
2404
                        $studentId,
2405
                        $currentUserId
2406
                    );
2407
                }
2408
            }
2409
        }
2410
2411
        return false;
2412
    }
2413
2414
    /**
2415
     * Get skills.
2416
     *
2417
     * @param int $userId
2418
     * @param int level
2419
     *
2420
     * @return array
2421
     */
2422
    public function getStudentSkills($userId, $level = 0)
2423
    {
2424
        $userId = (int) $userId;
2425
2426
        $sql = "SELECT s.id, s.name, sru.acquired_skill_at
2427
                FROM {$this->table} s
2428
                INNER JOIN {$this->table_skill_rel_user} sru
2429
                ON s.id = sru.skill_id
2430
                WHERE sru.user_id = $userId";
2431
2432
        $result = Database::query($sql);
2433
2434
        $skills = [];
2435
        foreach ($result as $item) {
2436
            if (empty($level)) {
2437
                $skills[] = [
2438
                    'name' => self::translateName($item['name']),
2439
                    'acquired_skill_at' => $item['acquired_skill_at'],
2440
                ];
2441
            } else {
2442
                $parents = self::get_parents($item['id']);
0 ignored issues
show
Bug Best Practice introduced by
The method Skill::get_parents() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2442
                /** @scrutinizer ignore-call */ 
2443
                $parents = self::get_parents($item['id']);
Loading history...
2443
                // +2 because it takes into account the root
2444
                if (count($parents) == $level + 1) {
2445
                    $skills[] = [
2446
                        'name' => self::translateName($item['name']),
2447
                        'acquired_skill_at' => $item['acquired_skill_at'],
2448
                    ];
2449
                }
2450
            }
2451
        }
2452
2453
        return $skills;
2454
    }
2455
2456
    /**
2457
     * @param string $name
2458
     *
2459
     * @return string
2460
     */
2461
    public static function translateName($name)
2462
    {
2463
        $variable = ChamiloApi::getLanguageVar($name, 'Skill');
2464
2465
        return isset($GLOBALS[$variable]) ? $GLOBALS[$variable] : $name;
2466
    }
2467
2468
    /**
2469
     * @param string $code
2470
     *
2471
     * @return mixed|string
2472
     */
2473
    public static function translateCode($code)
2474
    {
2475
        if (empty($code)) {
2476
            return '';
2477
        }
2478
2479
        $variable = ChamiloApi::getLanguageVar($code, 'SkillCode');
2480
2481
        return isset($GLOBALS[$variable]) ? $GLOBALS[$variable] : $code;
2482
    }
2483
2484
    /**
2485
     * @param array $skillInfo
2486
     *
2487
     * @return array
2488
     */
2489
    public function setForm(FormValidator &$form, $skillInfo = [])
2490
    {
2491
        $allSkills = $this->get_all();
2492
        $objGradebook = new Gradebook();
2493
2494
        $isAlreadyRootSkill = false;
2495
        foreach ($allSkills as $checkedSkill) {
2496
            if (intval($checkedSkill['parent_id']) > 0) {
2497
                $isAlreadyRootSkill = true;
2498
                break;
2499
            }
2500
        }
2501
2502
        $skillList = $isAlreadyRootSkill ? [] : [0 => get_lang('None')];
2503
2504
        foreach ($allSkills as $skill) {
2505
            if (isset($skillInfo['id']) && $skill['id'] == $skillInfo['id']) {
2506
                continue;
2507
            }
2508
2509
            $skillList[$skill['id']] = $skill['name'];
2510
        }
2511
2512
        $allGradeBooks = $objGradebook->find('all');
2513
2514
        // This procedure is for check if there is already a Skill with no Parent (Root by default)
2515
        $gradeBookList = [];
2516
        foreach ($allGradeBooks as $gradebook) {
2517
            $gradeBookList[$gradebook['id']] = $gradebook['name'];
2518
        }
2519
2520
        $translateUrl = api_get_path(WEB_CODE_PATH).'admin/skill_translate.php?';
2521
        $translateNameButton = '';
2522
        $translateCodeButton = '';
2523
        $skillId = null;
2524
        if (!empty($skillInfo)) {
2525
            $skillId = $skillInfo['id'];
2526
            $translateNameUrl = $translateUrl.http_build_query(['skill' => $skillId, 'action' => 'name']);
2527
            $translateCodeUrl = $translateUrl.http_build_query(['skill' => $skillId, 'action' => 'code']);
2528
            $translateNameButton = Display::toolbarButton(
2529
                get_lang('TranslateThisTerm'),
2530
                $translateNameUrl,
2531
                'language',
2532
                'link'
2533
            );
2534
            $translateCodeButton = Display::toolbarButton(
2535
                get_lang('TranslateThisTerm'),
2536
                $translateCodeUrl,
2537
                'language',
2538
                'link'
2539
            );
2540
        }
2541
2542
        $form->addText('name', [get_lang('Name'), $translateNameButton], true, ['id' => 'name']);
2543
        $form->addText('short_code', [get_lang('ShortCode'), $translateCodeButton], false, ['id' => 'short_code']);
2544
2545
        // Cannot change parent of root
2546
        if ($skillId != 1) {
2547
            $form->addSelect('parent_id', get_lang('Parent'), $skillList, ['id' => 'parent_id']);
2548
        }
2549
2550
        $form->addSelect(
2551
            'gradebook_id',
2552
            [get_lang('Gradebook'), get_lang('WithCertificate')],
2553
            $gradeBookList,
2554
            ['id' => 'gradebook_id', 'multiple' => 'multiple', 'size' => 10]
2555
        );
2556
        $form->addTextarea('description', get_lang('Description'), ['id' => 'description', 'rows' => 7]);
2557
        $form->addTextarea('criteria', get_lang('CriteriaToEarnTheBadge'), ['id' => 'criteria', 'rows' => 7]);
2558
2559
        // EXTRA FIELDS
2560
        $extraField = new ExtraField('skill');
2561
        $returnParams = $extraField->addElements($form, $skillId);
2562
2563
        if (empty($skillInfo)) {
2564
            $form->addButtonCreate(get_lang('Add'));
2565
        } else {
2566
            $form->addButtonUpdate(get_lang('Update'));
2567
            $form->addHidden('id', $skillInfo['id']);
2568
        }
2569
2570
        return $returnParams;
2571
    }
2572
2573
    /**
2574
     * @return string
2575
     */
2576
    public function getToolBar()
2577
    {
2578
        $toolbar = Display::url(
2579
            Display::return_icon(
2580
                'back.png',
2581
                get_lang('ManageSkills'),
2582
                null,
2583
                ICON_SIZE_MEDIUM
2584
            ),
2585
            api_get_path(WEB_CODE_PATH).'admin/skill_list.php'
2586
        );
2587
        $actions = '<div class="actions">'.$toolbar.'</div>';
2588
2589
        return $actions;
2590
    }
2591
2592
    /**
2593
     * @param SkillRelItemRelUser $skillRelItemRelUser
2594
     */
2595
    public static function getUserSkillStatusLabel(SkillRelItem $skillRelItem, SkillRelItemRelUser $skillRelItemRelUser = null, bool $addHeader = true, int $userId = 0): string
2596
    {
2597
        if (empty($skillRelItem)) {
2598
            return '';
2599
        }
2600
        $type = 'success';
2601
        if (empty($skillRelItemRelUser)) {
2602
            $type = '';
2603
        }
2604
        $label = '';
2605
        $skill = $skillRelItem->getSkill();
2606
        if ($addHeader) {
2607
            $label .= '<span id="skill-'.$skill->getId().'-'.$userId.'" class="user_skill" style="cursor:pointer">';
2608
        }
2609
        $label .= Display::label($skill->getName(), $type);
2610
        if ($addHeader) {
2611
            $label .= '</span>&nbsp;';
2612
        }
2613
2614
        return $label;
2615
    }
2616
2617
    /**
2618
     * Attach a list of skills (skill_rel_item) potentially assigned to a user to the given form.
2619
     *
2620
     * @param int  $typeId    see ITEM_TYPE_* constants
2621
     * @param bool $addHeader Whether to show the 'Skills' title for this block
2622
     */
2623
    public static function addSkillsToUserForm(FormValidator $form, int $typeId, int $itemId, int $userId, int $resultId = 0, bool $addHeader = false): void
2624
    {
2625
        $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
2626
        if ($allowSkillInTools && !empty($typeId) && !empty($itemId) && !empty($userId)) {
2627
            $em = Database::getManager();
2628
            $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
2629
                ['itemId' => $itemId, 'itemType' => $typeId]
2630
            );
2631
2632
            $skillRelUser = new SkillRelUser();
2633
            $skillUserList = $skillRelUser->getUserSkills($userId);
2634
            if (!empty($skillUserList)) {
2635
                $skillUserList = array_column($skillUserList, 'skill_id');
2636
            }
2637
2638
            $skills = '';
2639
            /** @var SkillRelItem $skillRelItem */
2640
            foreach ($items as $skillRelItem) {
2641
                $criteria = [
2642
                    'user' => $userId,
2643
                    'skillRelItem' => $skillRelItem,
2644
                ];
2645
                $skillRelItemRelUser = $em->getRepository('ChamiloSkillBundle:SkillRelItemRelUser')->findOneBy($criteria);
2646
                $skills .= self::getUserSkillStatusLabel($skillRelItem, $skillRelItemRelUser, true, $userId);
2647
            }
2648
2649
            if (!empty($skills)) {
2650
                $url = api_get_path(WEB_AJAX_PATH).'skill.ajax.php?a=update_skill_rel_user&'.api_get_cidreq();
2651
                $params = [
2652
                    'item_id' => $itemId,
2653
                    'type_id' => $typeId,
2654
                    'user_id' => $userId,
2655
                    'course_id' => api_get_course_int_id(),
2656
                    'session_id' => api_get_session_id(),
2657
                    'result_id' => $resultId,
2658
                ];
2659
                $params = json_encode($params);
2660
                if ($addHeader) {
2661
                    $form->addHtml(Display::page_subheader2(get_lang('Skills')));
2662
                }
2663
2664
                $skillId = $skillRelItem->getSkill()->getId();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $skillRelItem seems to be defined by a foreach iteration on line 2640. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
2665
                $elementId = 'skill-'.$skillId.'-'.$userId;
2666
                $html = '
2667
                <script>
2668
                    $(function() {
2669
                        $("#'.$elementId.'").on("click", function() {
2670
                            var params = '.$params.';
2671
                            $.ajax({
2672
                                type: "GET",
2673
                                async: false,
2674
                                data: params,
2675
                                url: "'.$url.'&skill_id="+'.$skillId.',
2676
                                success: function(result) {
2677
                                    $("#'.$elementId.'.user_skill").html(result);
2678
                                }
2679
                            });
2680
                        });
2681
                    });
2682
                </script>
2683
                ';
2684
                $form->addHtml($html);
2685
                $form->addLabel(get_lang('Skills'), $skills);
2686
                if ($addHeader) {
2687
                    $form->addHtml('<br />');
2688
                }
2689
            }
2690
        }
2691
    }
2692
2693
    /**
2694
     * Shows a list of skills (skill_rel_item) potentially assigned to a user
2695
     * to the given form, with AJAX action on click to save the assignment.
2696
     * Assigned skills appear in a different colour.
2697
     *
2698
     * @param int  $typeId    see ITEM_TYPE_* constants
2699
     * @param bool $addHeader Whether to show the 'Skills' title for this block
2700
     */
2701
    public static function getAddSkillsToUserBlock(int $typeId, int $itemId, int $userId, int $resultId = 0, bool $addHeader = false): string
2702
    {
2703
        $block = '';
2704
        $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
2705
        if ($allowSkillInTools && !empty($typeId) && !empty($itemId) && !empty($userId)) {
2706
            $em = Database::getManager();
2707
            $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
2708
                ['itemId' => $itemId, 'itemType' => $typeId]
2709
            );
2710
2711
            $skills = '';
2712
            /** @var SkillRelItem $skillRelItem */
2713
            foreach ($items as $skillRelItem) {
2714
                $criteria = [
2715
                    'user' => $userId,
2716
                    'skillRelItem' => $skillRelItem,
2717
                ];
2718
                $skillRelItemRelUser = $em->getRepository('ChamiloSkillBundle:SkillRelItemRelUser')->findOneBy($criteria);
2719
                $skills .= self::getUserSkillStatusLabel($skillRelItem, $skillRelItemRelUser, true, $userId);
2720
            }
2721
            $block .= $skills;
2722
2723
            if (!empty($skills)) {
2724
                $url = api_get_path(WEB_AJAX_PATH).'skill.ajax.php?a=update_skill_rel_user&'.api_get_cidreq();
2725
                $params = [
2726
                    'item_id' => $itemId,
2727
                    'type_id' => $typeId,
2728
                    'user_id' => $userId,
2729
                    'course_id' => api_get_course_int_id(),
2730
                    'session_id' => api_get_session_id(),
2731
                    'result_id' => $resultId,
2732
                ];
2733
                $params = json_encode($params);
2734
                if ($addHeader) {
2735
                    $block .= Display::page_subheader2(get_lang('Skills'));
2736
                }
2737
2738
                $skillId = $skillRelItem->getSkill()->getId();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $skillRelItem seems to be defined by a foreach iteration on line 2713. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
2739
                $elementId = 'skill-'.$skillId.'-'.$userId;
2740
                $html = '
2741
                <script>
2742
                    $(function() {
2743
                        $("#'.$elementId.'").on("click", function() {
2744
                            var params = '.$params.';
2745
                            $.ajax({
2746
                                type: "GET",
2747
                                async: false,
2748
                                data: params,
2749
                                url: "'.$url.'&skill_id="+'.$skillId.',
2750
                                success: function(result) {
2751
                                    $("#'.$elementId.'.user_skill").html(result);
2752
                                }
2753
                            });
2754
                        });
2755
                    });
2756
                </script>
2757
                ';
2758
                $block .= $html;
2759
                //$block .= $form->addLabel(get_lang('Skills'), $skills);
2760
                if ($addHeader) {
2761
                    $block .= '<br />';
2762
                }
2763
            }
2764
        }
2765
2766
        return $block;
2767
    }
2768
2769
    /**
2770
     * Add skills select ajax for an item (exercise, lp).
2771
     *
2772
     * @param int $courseId
2773
     * @param int $sessionId
2774
     * @param int $typeId    see ITEM_TYPE_* constants
2775
     * @param int $itemId
2776
     *
2777
     * @throws Exception
2778
     *
2779
     * @return array
2780
     */
2781
    public static function addSkillsToForm(FormValidator $form, $courseId, $sessionId, $typeId, $itemId = 0)
2782
    {
2783
        $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
2784
        if (!$allowSkillInTools) {
2785
            return [];
2786
        }
2787
2788
        if (empty($sessionId)) {
2789
            $sessionId = null;
2790
        }
2791
2792
        $em = Database::getManager();
2793
        $skillRelCourseRepo = $em->getRepository('ChamiloSkillBundle:SkillRelCourse');
2794
        $items = $skillRelCourseRepo->findBy(['course' => $courseId, 'session' => $sessionId]);
2795
2796
        $skills = [];
2797
        /** @var \Chamilo\SkillBundle\Entity\SkillRelCourse $skillRelCourse */
2798
        foreach ($items as $skillRelCourse) {
2799
            $skills[] = $skillRelCourse->getSkill();
2800
        }
2801
2802
        $selectedSkills = [];
2803
        if (!empty($itemId)) {
2804
            $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
2805
                ['itemId' => $itemId, 'itemType' => $typeId]
2806
            );
2807
            /** @var SkillRelItem $skillRelItem */
2808
            foreach ($items as $skillRelItem) {
2809
                $selectedSkills[] = $skillRelItem->getSkill()->getId();
2810
            }
2811
        }
2812
2813
        self::skillsToCheckbox($form, $skills, $courseId, $sessionId, $selectedSkills);
2814
2815
        return $skills;
2816
    }
2817
2818
    /**
2819
     * @param int $courseId
2820
     * @param int $sessionId
2821
     *
2822
     * @return array
2823
     */
2824
    public static function getSkillRelItemsPerCourse($courseId, $sessionId = null)
2825
    {
2826
        $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
2827
        $skills = [];
2828
2829
        if (empty($sessionId)) {
2830
            $sessionId = null;
2831
        }
2832
2833
        if ($allowSkillInTools) {
2834
            $em = Database::getManager();
2835
            $skills = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
2836
                ['courseId' => $courseId, 'sessionId' => $sessionId]
2837
            );
2838
        }
2839
2840
        return $skills;
2841
    }
2842
2843
    /**
2844
     * @param int $itemId
2845
     * @param int $itemType
2846
     *
2847
     * @return array
2848
     */
2849
    public static function getItemInfo($itemId, $itemType)
2850
    {
2851
        $itemInfo = [];
2852
        $itemId = (int) $itemId;
2853
        $itemType = (int) $itemType;
2854
        $em = Database::getManager();
2855
2856
        switch ($itemType) {
2857
            case ITEM_TYPE_EXERCISE:
2858
                /** @var \Chamilo\CourseBundle\Entity\CQuiz $item */
2859
                $item = $em->getRepository('ChamiloCourseBundle:CQuiz')->find($itemId);
2860
                if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\CourseBundle\Entity\CQuiz, thus it always evaluated to true.
Loading history...
2861
                    $itemInfo['name'] = $item->getTitle();
2862
                }
2863
                break;
2864
            case ITEM_TYPE_HOTPOTATOES:
2865
                break;
2866
            case ITEM_TYPE_LINK:
2867
                /** @var \Chamilo\CourseBundle\Entity\CLink $item */
2868
                $item = $em->getRepository('ChamiloCourseBundle:CLink')->find($itemId);
2869
                if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\CourseBundle\Entity\CLink, thus it always evaluated to true.
Loading history...
2870
                    $itemInfo['name'] = $item->getTitle();
2871
                }
2872
                break;
2873
            case ITEM_TYPE_LEARNPATH:
2874
                /** @var \Chamilo\CourseBundle\Entity\CLp $item */
2875
                $item = $em->getRepository('ChamiloCourseBundle:CLp')->find($itemId);
2876
                if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\CourseBundle\Entity\CLp, thus it always evaluated to true.
Loading history...
2877
                    $itemInfo['name'] = $item->getName();
2878
                }
2879
                break;
2880
            case ITEM_TYPE_GRADEBOOK:
2881
                break;
2882
            case ITEM_TYPE_STUDENT_PUBLICATION:
2883
                /** @var \Chamilo\CourseBundle\Entity\CStudentPublication $item */
2884
                $item = $em->getRepository('ChamiloCourseBundle:CStudentPublication')->find($itemId);
2885
                if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\CourseBundle\Entity\CStudentPublication, thus it always evaluated to true.
Loading history...
2886
                    $itemInfo['name'] = $item->getTitle();
2887
                }
2888
                break;
2889
            //ITEM_TYPE_FORUM', 7);
2890
            case ITEM_TYPE_ATTENDANCE:
2891
                /** @var \Chamilo\CourseBundle\Entity\CAttendance $item */
2892
                $item = $em->getRepository('ChamiloCourseBundle:CAttendance')->find($itemId);
2893
                if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\CourseBundle\Entity\CAttendance, thus it always evaluated to true.
Loading history...
2894
                    $itemInfo['name'] = $item->getName();
2895
                }
2896
                break;
2897
            case ITEM_TYPE_SURVEY:
2898
                /** @var \Chamilo\CourseBundle\Entity\CSurvey $item */
2899
                $item = $em->getRepository('ChamiloCourseBundle:CSurvey')->find($itemId);
2900
                if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\CourseBundle\Entity\CSurvey, thus it always evaluated to true.
Loading history...
2901
                    $itemInfo['name'] = strip_tags($item->getTitle());
2902
                }
2903
                break;
2904
            case ITEM_TYPE_FORUM_THREAD:
2905
                /** @var \Chamilo\CourseBundle\Entity\CForumThread $item */
2906
                $item = $em->getRepository('ChamiloCourseBundle:CForumThread')->find($itemId);
2907
                if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\CourseBundle\Entity\CForumThread, thus it always evaluated to true.
Loading history...
2908
                    $itemInfo['name'] = $item->getThreadTitle();
2909
                }
2910
                break;
2911
        }
2912
2913
        return $itemInfo;
2914
    }
2915
2916
    /**
2917
     * @param int $typeId
2918
     * @param int $itemId
2919
     *
2920
     * @return array
2921
     */
2922
    public static function getSkillRelItems($typeId, $itemId)
2923
    {
2924
        $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
2925
        $skills = [];
2926
        if ($allowSkillInTools) {
2927
            $em = Database::getManager();
2928
            $skills = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
2929
                ['itemId' => $itemId, 'itemType' => $typeId]
2930
            );
2931
        }
2932
2933
        return $skills;
2934
    }
2935
2936
    /**
2937
     * @param int $typeId
2938
     * @param int $itemId
2939
     *
2940
     * @return string
2941
     */
2942
    public static function getSkillRelItemsToString($typeId, $itemId)
2943
    {
2944
        $skills = self::getSkillRelItems($typeId, $itemId);
2945
        $skillToString = '';
2946
        if (!empty($skills)) {
2947
            /** @var SkillRelItem $skillRelItem */
2948
            $skillList = [];
2949
            foreach ($skills as $skillRelItem) {
2950
                $skillList[] = Display::label($skillRelItem->getSkill()->getName(), 'success');
2951
            }
2952
            $skillToString = '&nbsp;'.implode(' ', $skillList);
2953
        }
2954
2955
        return $skillToString;
2956
    }
2957
2958
    /**
2959
     * @param int $itemId
2960
     * @param int $typeId
2961
     */
2962
    public static function deleteSkillsFromItem($itemId, $typeId)
2963
    {
2964
        $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
2965
        if ($allowSkillInTools) {
2966
            $itemId = (int) $itemId;
2967
            $typeId = (int) $typeId;
2968
2969
            $em = Database::getManager();
2970
            // Delete old ones
2971
            $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
2972
                ['itemId' => $itemId, 'itemType' => $typeId]
2973
            );
2974
2975
            /** @var SkillRelItem $skillRelItem */
2976
            foreach ($items as $skillRelItem) {
2977
                $em->remove($skillRelItem);
2978
            }
2979
            $em->flush();
2980
        }
2981
    }
2982
2983
    /**
2984
     * Builds a list of skills attributable to this course+session in a checkbox input list for FormValidator.
2985
     *
2986
     * @param     $courseId
2987
     * @param int $sessionId
2988
     *
2989
     * @return array
2990
     */
2991
    public static function setSkillsToCourse(FormValidator $form, $courseId, $sessionId = 0)
2992
    {
2993
        $courseId = (int) $courseId;
2994
        $sessionId = (int) $sessionId;
2995
2996
        $form->addHidden('course_id', $courseId);
2997
        $form->addHidden('session_id', $sessionId);
2998
2999
        if (empty($sessionId)) {
3000
            $sessionId = null;
3001
        }
3002
3003
        $em = Database::getManager();
3004
        $skillRelCourseRepo = $em->getRepository('ChamiloSkillBundle:SkillRelCourse');
3005
        $items = $skillRelCourseRepo->findBy(['course' => $courseId, 'session' => $sessionId]);
3006
3007
        $skillsIdList = [];
3008
        $skills = [];
3009
        /** @var \Chamilo\SkillBundle\Entity\SkillRelCourse $skillRelCourse */
3010
        foreach ($items as $skillRelCourse) {
3011
            $skillId = $skillRelCourse->getSkill()->getId();
3012
            $skills[] = $skillRelCourse->getSkill();
3013
            $skillsIdList[] = $skillId;
3014
        }
3015
3016
        $group = self::skillsToCheckbox($form, $skills, $courseId, $sessionId, $skillsIdList);
3017
        $group->freeze();
3018
3019
        return [];
3020
    }
3021
3022
    /**
3023
     * Show a list of skills attributable to this course+session in a checkbox input list for FormValidator.
3024
     *
3025
     * @param       $skills
3026
     * @param       $courseId
3027
     * @param       $sessionId
3028
     * @param array $selectedSkills
3029
     *
3030
     * @return HTML_QuickForm_Element|HTML_QuickForm_group
3031
     */
3032
    public static function skillsToCheckbox(FormValidator $form, $skills, $courseId, $sessionId, $selectedSkills = [])
3033
    {
3034
        $em = Database::getManager();
3035
        $skillRelItemRepo = $em->getRepository('ChamiloSkillBundle:SkillRelItem');
3036
        $skillList = [];
3037
        /** @var \Chamilo\CoreBundle\Entity\Skill $skill */
3038
        foreach ($skills as $skill) {
3039
            $skillList[$skill->getId()] = $skill->getName();
3040
        }
3041
3042
        if (!empty($skillList)) {
3043
            asort($skillList);
3044
        }
3045
3046
        if (empty($sessionId)) {
3047
            $sessionId = null;
3048
        }
3049
3050
        $elements = [];
3051
        foreach ($skillList as $skillId => $skill) {
3052
            $countLabel = '';
3053
            $skillRelItemCount = $skillRelItemRepo->count(
3054
                ['skill' => $skillId, 'courseId' => $courseId, 'sessionId' => $sessionId]
3055
            );
3056
            if (!empty($skillRelItemCount)) {
3057
                $countLabel = '&nbsp;'.Display::badge($skillRelItemCount, 'info');
3058
            }
3059
3060
            $element = $form->createElement(
3061
                'checkbox',
3062
                "skills[$skillId]",
3063
                null,
3064
                $skill.$countLabel
3065
            );
3066
3067
            if (in_array($skillId, $selectedSkills)) {
3068
                $element->setValue(1);
3069
            }
3070
3071
            $elements[] = $element;
3072
        }
3073
3074
        return $form->addGroup($elements, '', get_lang('Skills'));
3075
    }
3076
3077
    /**
3078
     * Relate skill with an item (exercise, gradebook, lp, etc).
3079
     *
3080
     * @return bool
3081
     */
3082
    public static function saveSkillsToCourseFromForm(FormValidator $form)
3083
    {
3084
        $skills = (array) $form->getSubmitValue('skills');
3085
        $courseId = (int) $form->getSubmitValue('course_id');
3086
        $sessionId = (int) $form->getSubmitValue('session_id');
3087
3088
        if (!empty($skills)) {
3089
            $skills = array_keys($skills);
3090
        }
3091
3092
        return self::saveSkillsToCourse($skills, $courseId, $sessionId);
3093
    }
3094
3095
    /**
3096
     * @param array $skills
3097
     * @param int   $courseId
3098
     * @param int   $sessionId
3099
     *
3100
     * @return bool
3101
     */
3102
    public static function saveSkillsToCourse($skills, $courseId, $sessionId)
3103
    {
3104
        $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
3105
        if (!$allowSkillInTools) {
3106
            return false;
3107
        }
3108
3109
        $em = Database::getManager();
3110
        $sessionId = empty($sessionId) ? null : (int) $sessionId;
3111
3112
        $course = api_get_course_entity($courseId);
3113
        if (empty($course)) {
3114
            return false;
3115
        }
3116
3117
        $session = null;
3118
        if (!empty($sessionId)) {
3119
            $session = api_get_session_entity($sessionId);
3120
            $courseExistsInSession = SessionManager::sessionHasCourse($sessionId, $course->getCode());
3121
            if (!$courseExistsInSession) {
3122
                return false;
3123
            }
3124
        }
3125
3126
        // Delete old ones
3127
        $items = $em->getRepository('ChamiloSkillBundle:SkillRelCourse')->findBy(
3128
            ['course' => $courseId, 'session' => $sessionId]
3129
        );
3130
3131
        if (!empty($items)) {
3132
            /** @var SkillRelCourse $item */
3133
            foreach ($items as $item) {
3134
                if (!in_array($item->getSkill()->getId(), $skills)) {
3135
                    $em->remove($item);
3136
                }
3137
            }
3138
            $em->flush();
3139
        }
3140
3141
        // Add new one
3142
        if (!empty($skills)) {
3143
            foreach ($skills as $skillId) {
3144
                $item = (new SkillRelCourse())
3145
                    ->setCourse($course)
3146
                    ->setSession($session)
3147
                ;
3148
3149
                /** @var SkillEntity $skill */
3150
                $skill = $em->getRepository('ChamiloCoreBundle:Skill')->find($skillId);
3151
                if ($skill) {
3152
                    if (!$skill->hasCourseAndSession($item)) {
3153
                        $skill->addToCourse($item);
3154
                        $em->persist($skill);
3155
                    }
3156
                }
3157
            }
3158
            $em->flush();
3159
        }
3160
3161
        return true;
3162
    }
3163
3164
    /**
3165
     * Relate skill with an item (exercise, gradebook, lp, etc).
3166
     *
3167
     * @param FormValidator $form
3168
     * @param int           $typeId
3169
     * @param int           $itemId
3170
     */
3171
    public static function saveSkills($form, $typeId, $itemId)
3172
    {
3173
        $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
3174
        if ($allowSkillInTools) {
3175
            $userId = api_get_user_id();
3176
            $courseId = api_get_course_int_id();
3177
            if (empty($courseId)) {
3178
                $courseId = null;
3179
            }
3180
            $sessionId = api_get_session_id();
3181
            if (empty($sessionId)) {
3182
                $sessionId = null;
3183
            }
3184
3185
            $em = Database::getManager();
3186
            $skills = (array) $form->getSubmitValue('skills');
3187
3188
            $skillRelItemRelUserRepo = $em->getRepository('ChamiloSkillBundle:SkillRelItemRelUser');
3189
3190
            // Delete old ones
3191
            $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
3192
                ['itemId' => $itemId, 'itemType' => $typeId]
3193
            );
3194
3195
            if (!empty($items)) {
3196
                /** @var SkillRelItem $skillRelItem */
3197
                foreach ($items as $skillRelItem) {
3198
                    $skill = $skillRelItem->getSkill();
3199
                    $skillId = $skill->getId();
3200
                    $skillRelItemId = $skillRelItem->getId();
3201
                    if (!in_array($skillId, $skills)) {
3202
                        // Check if SkillRelItemRelUser is empty
3203
                        /** @var SkillRelItem[] $skillRelItemList */
3204
                        $skillRelItemRelUserList = $skillRelItemRelUserRepo->findBy(['skillRelItem' => $skillRelItemId]);
3205
                        if (empty($skillRelItemRelUserList)) {
3206
                            $em->remove($skillRelItem);
3207
                        } else {
3208
                            /** @var \Chamilo\SkillBundle\Entity\SkillRelItemRelUser $skillRelItemRelUser */
3209
                            foreach ($skillRelItemRelUserList as $skillRelItemRelUser) {
3210
                                Display::addFlash(
3211
                                    Display::return_message(
3212
                                        get_lang('CannotDeleteSkillBlockedByUser').'<br />'.
3213
                                        get_lang('User').': '.UserManager::formatUserFullName($skillRelItemRelUser->getUser()).'<br />'.
3214
                                        get_lang('Skill').': '.$skillRelItemRelUser->getSkillRelItem()->getSkill()->getName(),
3215
                                        'warning',
3216
                                        false
3217
                                    )
3218
                                );
3219
                            }
3220
                        }
3221
                    }
3222
                }
3223
                $em->flush();
3224
            }
3225
3226
            // Add new one
3227
            if (!empty($skills)) {
3228
                $skills = array_keys($skills);
3229
                $skillRepo = $em->getRepository('ChamiloCoreBundle:Skill');
3230
3231
                foreach ($skills as $skillId) {
3232
                    /** @var SkillEntity $skill */
3233
                    $skill = $skillRepo->find($skillId);
3234
                    if (null !== $skill) {
3235
                        if (!$skill->hasItem($typeId, $itemId)) {
3236
                            $skillRelItem = (new SkillRelItem())
3237
                                ->setItemType($typeId)
3238
                                ->setItemId($itemId)
3239
                                ->setCourseId($courseId)
3240
                                ->setSessionId($sessionId)
3241
                                ->setCreatedBy($userId)
3242
                                ->setUpdatedBy($userId)
3243
                            ;
3244
                            $skill->addItem($skillRelItem);
3245
                            $em->persist($skill);
3246
                            $em->persist($skillRelItem);
3247
                            $em->flush();
3248
                        }
3249
                    }
3250
                }
3251
            }
3252
        }
3253
    }
3254
3255
    /**
3256
     * Get the icon (badge image) URL.
3257
     *
3258
     * @param bool $getSmall Optional. Allow get the small image
3259
     *
3260
     * @return string
3261
     */
3262
    public static function getWebIconPath(SkillEntity $skill, $getSmall = false)
3263
    {
3264
        if ($getSmall) {
3265
            if (empty($skill->getIcon())) {
3266
                return \Display::return_icon('badges-default.png', null, null, ICON_SIZE_BIG, null, true);
3267
            }
3268
3269
            return api_get_path(WEB_UPLOAD_PATH).'badges/'.sha1($skill->getName()).'-small.png';
3270
        }
3271
3272
        if (empty($skill->getIcon())) {
3273
            return \Display::return_icon('badges-default.png', null, null, ICON_SIZE_HUGE, null, true);
3274
        }
3275
3276
        return api_get_path(WEB_UPLOAD_PATH)."badges/{$skill->getIcon()}";
3277
    }
3278
3279
    /**
3280
     * @param User                             $user
3281
     * @param \Chamilo\CoreBundle\Entity\Skill $skill
3282
     * @param int                              $levelId
3283
     * @param string                           $argumentation
3284
     * @param int                              $authorId
3285
     *
3286
     * @throws \Doctrine\ORM\OptimisticLockException
3287
     *
3288
     * @return SkillRelUserEntity
3289
     */
3290
    public function addSkillToUserBadge($user, $skill, $levelId, $argumentation, $authorId)
3291
    {
3292
        $showLevels = false === api_get_configuration_value('hide_skill_levels');
3293
        $badgeAssignationNotification = api_get_configuration_value('badge_assignation_notification');
3294
3295
        $entityManager = Database::getManager();
3296
3297
        $skillUserRepo = $entityManager->getRepository('ChamiloCoreBundle:SkillRelUser');
3298
3299
        $criteria = ['user' => $user, 'skill' => $skill];
3300
        $result = $skillUserRepo->findOneBy($criteria);
3301
3302
        if (!empty($result)) {
3303
            return false;
3304
        }
3305
        $skillLevelRepo = $entityManager->getRepository('ChamiloSkillBundle:Level');
3306
3307
        $skillUser = new SkillRelUserEntity();
3308
        $skillUser->setUser($user);
3309
        $skillUser->setSkill($skill);
3310
3311
        if ($showLevels && !empty($levelId)) {
3312
            $level = $skillLevelRepo->find($levelId);
3313
            $skillUser->setAcquiredLevel($level);
3314
        }
3315
3316
        $skillUser->setArgumentation($argumentation);
3317
        $skillUser->setArgumentationAuthorId($authorId);
3318
        $skillUser->setAcquiredSkillAt(new DateTime());
3319
        $skillUser->setAssignedBy(0);
3320
3321
        $entityManager->persist($skillUser);
3322
        $entityManager->flush();
3323
3324
        if ($badgeAssignationNotification) {
3325
            $url = SkillRelUser::getIssueUrlAll($skillUser);
3326
3327
            $message = sprintf(
3328
                get_lang('YouXHaveAchievedTheSkillYToSeeFollowLinkZ'),
3329
                $user->getFirstname(),
3330
                $skill->getName(),
3331
                Display::url($url, $url, ['target' => '_blank'])
3332
            );
3333
3334
            MessageManager::send_message(
3335
                $user->getId(),
3336
                get_lang('YouHaveAchievedANewSkill'),
3337
                $message
3338
            );
3339
        }
3340
3341
        return $skillUser;
3342
    }
3343
}
3344