Issues (2160)

main/badge/issued_all.php (3 issues)

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\SkillRelUser;
0 ignored issues
show
This use statement conflicts with another class in this namespace, SkillRelUser. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
use Chamilo\CoreBundle\Entity\SkillRelUserComment;
6
use SkillRelUser as SkillRelUserManager;
7
use Symfony\Component\HttpFoundation\Request as HttpRequest;
0 ignored issues
show
This use statement conflicts with another class in this namespace, HttpRequest. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
9
/**
10
 * Show information about all issued badges with same skill by user.
11
 *
12
 * @author José Loguercio Silva <[email protected]>
13
 */
14
require_once __DIR__.'/../inc/global.inc.php';
15
16
$httpRequest = HttpRequest::createFromGlobals();
17
18
$userId = $httpRequest->query->getInt('user');
19
$skillId = $httpRequest->query->getInt('skill');
20
21
if (!$userId || !$skillId) {
22
    api_not_allowed(true);
23
}
24
25
Skill::isAllowed($userId);
26
27
$em = Database::getManager();
28
$user = api_get_user_entity($userId);
29
$skill = $em->find('ChamiloCoreBundle:Skill', $skillId);
30
$currentUserId = api_get_user_id();
31
32
if (!$user || !$skill) {
0 ignored issues
show
$user is of type Chamilo\UserBundle\Entity\User, thus it always evaluated to true.
Loading history...
33
    Display::addFlash(
34
        Display::return_message(get_lang('NoResults'), 'error')
35
    );
36
37
    header('Location: '.api_get_path(WEB_PATH));
38
    exit;
39
}
40
41
$skillRepo = $em->getRepository('ChamiloCoreBundle:Skill');
42
$skillUserRepo = $em->getRepository('ChamiloCoreBundle:SkillRelUser');
43
$skillLevelRepo = $em->getRepository('ChamiloSkillBundle:Level');
44
45
$userSkills = $skillUserRepo->findBy([
46
    'user' => $user,
47
    'skill' => $skill,
48
]);
49
50
$userInfo = [
51
    'id' => $user->getId(),
52
    'complete_name' => UserManager::formatUserFullName($user),
53
];
54
55
$skillInfo = [
56
    'id' => $skill->getId(),
57
    'name' => $skill->getName(),
58
    'short_code' => $skill->getShortCode(),
59
    'description' => $skill->getDescription(),
60
    'criteria' => $skill->getCriteria(),
61
    'badge_image' => Skill::getWebIconPath($skill),
62
    'courses' => [],
63
];
64
65
$allUserBadges = [];
66
/** @var SkillRelUser $skillIssue */
67
foreach ($userSkills as $index => $skillIssue) {
68
    $currentUser = api_get_user_entity($currentUserId);
69
    $allowDownloadExport = $currentUser ? $currentUser->getId() === $user->getId() : false;
70
    $allowComment = $currentUser ? Skill::userCanAddFeedbackToUser($currentUser, $user) : false;
71
    $skillIssueDate = api_get_local_time($skillIssue->getAcquiredSkillAt());
72
    $currentSkillLevel = get_lang('NoLevelAcquiredYet');
73
    if ($skillIssue->getAcquiredLevel()) {
74
        $currentSkillLevel = $skillLevelRepo->find(['id' => $skillIssue->getAcquiredLevel()])->getName();
75
    }
76
    $argumentationAuthor = api_get_user_info($skillIssue->getArgumentationAuthorId());
77
78
    $tempDate = DateTime::createFromFormat('Y-m-d H:i:s', $skillIssueDate);
79
    $linkedinOrganizationId = api_get_configuration_value('linkedin_organization_id');
80
    if (($linkedinOrganizationId === false)) {
81
        $linkedinOrganizationId = null;
82
    }
83
84
    $skillIssueInfo = [
85
        'id' => $skillIssue->getId(),
86
        'datetime' => api_format_date($skillIssueDate, DATE_TIME_FORMAT_SHORT),
87
        'year' => $tempDate->format('Y'),
88
        'month' => $tempDate->format('m'),
89
        'linkedin_organization_id' => $linkedinOrganizationId,
90
        'acquired_level' => $currentSkillLevel,
91
        'argumentation_author_id' => $skillIssue->getArgumentationAuthorId(),
92
        'argumentation_author_name' => api_get_person_name(
93
            $argumentationAuthor['firstname'],
94
            $argumentationAuthor['lastname']
95
        ),
96
        'argumentation' => Security::remove_XSS($skillIssue->getArgumentation()),
97
        'source_name' => $skillIssue->getSourceName(),
98
        'user_id' => $skillIssue->getUser()->getId(),
99
        'user_complete_name' => UserManager::formatUserFullName($skillIssue->getUser()),
100
        'skill_id' => $skillIssue->getSkill()->getId(),
101
        'skill_badge_image' => Skill::getWebIconPath($skillIssue->getSkill()),
102
        'skill_name' => $skillIssue->getSkill()->getName(),
103
        'skill_short_code' => $skillIssue->getSkill()->getShortCode(),
104
        'skill_description' => $skillIssue->getSkill()->getDescription(),
105
        'skill_criteria' => $skillIssue->getSkill()->getCriteria(),
106
        'badge_assertion' => SkillRelUserManager::getAssertionUrl($skillIssue),
107
        'comments' => [],
108
        'feedback_average' => $skillIssue->getAverage(),
109
    ];
110
111
    $skillIssueComments = $skillIssue->getComments(true);
112
113
    $userId = $skillIssueInfo['user_id'];
114
    $skillId = $skillIssueInfo['skill_id'];
115
116
    foreach ($skillIssueComments as $comment) {
117
        $commentDate = api_get_local_time($comment->getFeedbackDateTime());
118
        $skillIssueInfo['comments'][] = [
119
            'text' => $comment->getFeedbackText(),
120
            'value' => $comment->getFeedbackValue(),
121
            'giver_complete_name' => UserManager::formatUserFullName($comment->getFeedbackGiver()),
122
            'datetime' => api_format_date($commentDate, DATE_TIME_FORMAT_SHORT),
123
        ];
124
    }
125
126
    $acquiredLevel = [];
127
    $profile = $skillRepo->find($skillId)->getProfile();
128
129
    if (!$profile) {
130
        $skillRelSkill = new SkillRelSkill();
131
        $parents = $skillRelSkill->getSkillParents($skillId);
132
133
        krsort($parents);
134
135
        foreach ($parents as $parent) {
136
            $skillParentId = $parent['skill_id'];
137
            $profile = $skillRepo->find($skillParentId)->getProfile();
138
139
            if ($profile) {
140
                break;
141
            }
142
143
            if (!$profile && $parent['parent_id'] == 0) {
144
                $profile = $skillLevelRepo->findAll();
145
                $profile = !empty($profile) ? $profile[0] : [];
146
            }
147
        }
148
    }
149
150
    if ($profile) {
151
        $profileId = $profile->getId();
152
        $levels = $skillLevelRepo->findBy([
153
            'profile' => $profileId,
154
        ]);
155
156
        foreach ($levels as $level) {
157
            $profileLevels[$level->getPosition()][$level->getId()] = $level->getName();
158
        }
159
160
        ksort($profileLevels); // Sort the array by Position.
161
162
        foreach ($profileLevels as $profileLevel) {
163
            $profileId = key($profileLevel);
164
            $acquiredLevel[$profileId] = $profileLevel[$profileId];
165
        }
166
    }
167
168
    $formAcquiredLevel = new FormValidator(
169
        'acquired_level'.$skillIssue->getId(),
170
        'post',
171
        SkillRelUserManager::getIssueUrlAll($skillIssue)
172
    );
173
    $formAcquiredLevel->addSelect('acquired_level', get_lang('AcquiredLevel'), $acquiredLevel);
174
    $formAcquiredLevel->addHidden('user', $skillIssue->getUser()->getId());
175
    $formAcquiredLevel->addHidden('issue', $skillIssue->getId());
176
    $formAcquiredLevel->addButtonSend(get_lang('Save'));
177
178
    if ($formAcquiredLevel->validate() && $allowComment) {
179
        $values = $formAcquiredLevel->exportValues();
180
181
        $level = $skillLevelRepo->find($values['acquired_level']);
182
        $skillIssue->setAcquiredLevel($level);
183
184
        $em->persist($skillIssue);
185
        $em->flush();
186
187
        header('Location: '.SkillRelUserManager::getIssueUrlAll($skillIssue));
188
        exit;
189
    }
190
191
    $form = new FormValidator(
192
        'comment'.$skillIssue->getId(),
193
        'post',
194
        SkillRelUserManager::getIssueUrlAll($skillIssue)
195
    );
196
    $form->addTextarea('comment', get_lang('NewComment'), ['rows' => 4]);
197
    $form->applyFilter('comment', 'trim');
198
    $form->addRule('comment', get_lang('ThisFieldIsRequired'), 'required');
199
    $form->addSelect(
200
        'value',
201
        [get_lang('Value'), get_lang('RateTheSkillInPractice')],
202
        ['-', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
203
    );
204
    $form->addHidden('user', $skillIssue->getUser()->getId());
205
    $form->addHidden('issue', $skillIssue->getId());
206
    $form->addButtonSend(get_lang('Send'));
207
208
    if ($form->validate() && $allowComment) {
209
        $values = $form->exportValues();
210
211
        $skillUserComment = new SkillRelUserComment();
212
        $skillUserComment
213
            ->setFeedbackDateTime(new DateTime())
214
            ->setFeedbackGiver($currentUser)
215
            ->setFeedbackText($values['comment'])
216
            ->setFeedbackValue($values['value'] ? $values['value'] : null)
217
            ->setSkillRelUser($skillIssue);
218
219
        $em->persist($skillUserComment);
220
        $em->flush();
221
222
        header('Location: '.SkillRelUserManager::getIssueUrlAll($skillIssue));
223
        exit;
224
    }
225
226
    $badgeInfoError = '';
227
    $personalBadge = '';
228
229
    if ($allowDownloadExport) {
230
        $backpack = 'https://backpack.openbadges.org/';
231
        $configBackpack = api_get_setting('openbadges_backpack');
232
233
        if (0 !== strcmp($backpack, $configBackpack)) {
234
            $backpack = $configBackpack;
235
            if (substr($backpack, -1) !== '/') {
236
                $backpack .= '/';
237
            }
238
        }
239
240
        $htmlHeadXtra[] = '<script src="'.$backpack.'issuer.js"></script>';
241
        $objSkill = new Skill();
242
        $assertionUrl = $skillIssueInfo['badge_assertion'];
243
        $skills = $objSkill->get($skillId);
244
        $unbakedBadge = api_get_path(SYS_UPLOAD_PATH)."badges/".$skills['icon'];
245
        if (!is_file($unbakedBadge)) {
246
            $unbakedBadge = api_get_path(WEB_CODE_PATH).'img/icons/128/badges-default.png';
247
        }
248
249
        $unbakedBadge = file_get_contents($unbakedBadge);
250
        $badgeInfoError = false;
251
        $personalBadge = "";
252
        $png = new PNGImageBaker($unbakedBadge);
253
254
        if ($png->checkChunks("tEXt", "openbadges")) {
255
            $bakedInfo = $png->addChunk("tEXt", "openbadges", $assertionUrl);
256
            $bakedBadge = UserManager::getUserPathById($userId, "system");
257
            $bakedBadge = $bakedBadge.'badges';
258
            if (!file_exists($bakedBadge)) {
259
                mkdir($bakedBadge, api_get_permissions_for_new_directories(), true);
260
            }
261
            $skillRelUserId = $skillIssueInfo['id'];
262
            if (!file_exists($bakedBadge."/badge_".$skillRelUserId)) {
263
                file_put_contents($bakedBadge."/badge_".$skillRelUserId.".png", $bakedInfo);
264
            }
265
266
            //Process to validate a baked badge
267
            $badgeContent = file_get_contents($bakedBadge."/badge_".$skillRelUserId.".png");
268
            $verifyBakedBadge = $png->extractBadgeInfo($badgeContent);
269
            if (!is_array($verifyBakedBadge)) {
270
                $badgeInfoError = true;
271
            }
272
273
            if (!$badgeInfoError) {
274
                $personalBadge = UserManager::getUserPathById($userId, "web");
275
                $personalBadge = $personalBadge."badges/badge_".$skillRelUserId.".png";
276
            }
277
        }
278
    }
279
280
    $allUserBadges[$index]['issue_info'] = $skillIssueInfo;
281
    $allUserBadges[$index]['allow_comment'] = $allowComment;
282
    $allUserBadges[$index]['allow_download_export'] = $allowDownloadExport;
283
    $allUserBadges[$index]['comment_form'] = $form->returnForm();
284
    $allUserBadges[$index]['acquired_level_form'] = $formAcquiredLevel->returnForm();
285
    $allUserBadges[$index]['badge_error'] = $badgeInfoError;
286
    $allUserBadges[$index]['personal_badge'] = $personalBadge;
287
}
288
289
$template = new Template(get_lang('IssuedBadgeInformation'));
290
$template->assign('user_badges', $allUserBadges);
291
$template->assign('show_level', api_get_configuration_value('hide_skill_levels') == false);
292
293
$content = $template->fetch(
294
    $template->get_template('skill/issued_all.tpl')
295
);
296
297
$template->assign('header', get_lang('IssuedBadgeInformation'));
298
$template->assign('content', $content);
299
$template->display_one_col_template();
300