Passed
Push — 1.11.x ( bce6cd...c146d9 )
by Angel Fernando Quiroz
12:25
created

main/badge/issued.php (1 issue)

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\SkillRelUser;
5
use Chamilo\CoreBundle\Entity\SkillRelUserComment;
6
use SkillRelUser as SkillRelUserManager;
7
8
/**
9
 * Show information about the issued badge.
10
 *
11
 * @author Angel Fernando Quiroz Campos <[email protected]>
12
 * @author José Loguercio Silva <[email protected]>
13
 */
14
require_once __DIR__.'/../inc/global.inc.php';
15
16
$issue = isset($_REQUEST['issue']) ? (int) $_REQUEST['issue'] : 0;
17
18
if (empty($issue)) {
19
    api_not_allowed(true);
20
}
21
22
$entityManager = Database::getManager();
23
/** @var SkillRelUser $skillIssue */
24
$skillIssue = $entityManager->find('ChamiloCoreBundle:SkillRelUser', $issue);
25
26
if (!$skillIssue) {
27
    Display::addFlash(
28
        Display::return_message(
29
            get_lang('SkillNotFound'),
30
            'warning'
31
        )
32
    );
33
    header('Location: '.api_get_path(WEB_PATH));
34
    exit;
35
}
36
37
$skillRepo = $entityManager->getRepository('ChamiloCoreBundle:Skill');
38
$skillLevelRepo = $entityManager->getRepository('ChamiloSkillBundle:Level');
39
40
$user = $skillIssue->getUser();
41
$skill = $skillIssue->getSkill();
42
43
if (!$user || !$skill) {
44
    Display::addFlash(
45
        Display::return_message(get_lang('NoResults'), 'warning')
46
    );
47
48
    header('Location: '.api_get_path(WEB_PATH));
49
    exit;
50
}
51
52
if (!Skill::isToolAvailable()) {
53
    api_not_allowed(true);
54
}
55
56
$showLevels = api_get_configuration_value('hide_skill_levels') === false;
57
58
$skillInfo = [
59
    'id' => $skill->getId(),
60
    'name' => $skill->getName(),
61
    'short_code' => $skill->getShortCode(),
62
    'description' => $skill->getDescription(),
63
    'criteria' => $skill->getCriteria(),
64
    'badge_image' => Skill::getWebIconPath($skill),
65
    'courses' => [],
66
];
67
68
$titleContent = sprintf(get_lang('IHaveObtainedSkillXOnY'), $skillInfo['name'], api_get_setting('siteName'));
69
70
// Open Graph Markup
71
$htmlHeadXtra[] = "
72
    <meta property='og:type' content='article' />
73
    <meta property='og:title' content='".$titleContent."' />
74
    <meta property='og:url' content='".api_get_path(WEB_PATH)."badge/".$issue."' />
75
    <meta property='og:description' content='".$skillInfo['description']."' />
76
    <meta property='og:image' content='".$skillInfo['badge_image']."' />
77
";
78
79
$currentUserId = api_get_user_id();
80
$currentUser = api_get_user_entity($currentUserId);
81
$allowExport = $currentUser ? $currentUser->getId() === $user->getId() : false;
82
83
$allowComment = $currentUser ? Skill::userCanAddFeedbackToUser($currentUser, $user) : false;
84
$skillIssueDate = api_get_local_time($skillIssue->getAcquiredSkillAt());
85
$currentSkillLevel = get_lang('NoLevelAcquiredYet');
86
if ($skillIssue->getAcquiredLevel()) {
87
    $currentSkillLevel = $skillLevelRepo->find(['id' => $skillIssue->getAcquiredLevel()])->getName();
88
}
89
90
$author = api_get_user_info($skillIssue->getArgumentationAuthorId());
91
$tempDate = DateTime::createFromFormat('Y-m-d H:i:s', $skillIssueDate);
92
$linkedinOrganizationId = api_get_configuration_value('linkedin_organization_id');
93
if (($linkedinOrganizationId === false)) {
94
    $linkedinOrganizationId = null;
95
}
96
97
$skillIssueInfo = [
98
    'id' => $skillIssue->getId(),
99
    'datetime' => api_format_date($skillIssueDate, DATE_TIME_FORMAT_SHORT),
100
    'year' => $tempDate->format('Y'),
101
    'month' => $tempDate->format('m'),
102
    'linkedin_organization_id' => $linkedinOrganizationId,
103
    'acquired_level' => $currentSkillLevel,
104
    'argumentation_author_id' => $skillIssue->getArgumentationAuthorId(),
105
    'argumentation_author_name' => $author['complete_name'],
106
    'argumentation' => $skillIssue->getArgumentation(),
107
    'source_name' => $skillIssue->getSourceName(),
108
    'user_id' => $skillIssue->getUser()->getId(),
109
    'user_complete_name' => UserManager::formatUserFullName($skillIssue->getUser()),
110
    'skill_id' => $skillIssue->getSkill()->getId(),
111
    'skill_badge_image' => Skill::getWebIconPath($skillIssue->getSkill()),
112
    'skill_name' => $skillIssue->getSkill()->getName(),
113
    'skill_short_code' => $skillIssue->getSkill()->getShortCode(),
114
    'skill_description' => $skillIssue->getSkill()->getDescription(),
115
    'skill_criteria' => $skillIssue->getSkill()->getCriteria(),
116
    'badge_assertion' => SkillRelUserManager::getAssertionUrl($skillIssue),
117
    'comments' => [],
118
    'feedback_average' => $skillIssue->getAverage(),
0 ignored issues
show
The method getAverage() does not exist on SkillRelUser. ( Ignorable by Annotation )

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

118
    'feedback_average' => $skillIssue->/** @scrutinizer ignore-call */ getAverage(),

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...
119
];
120
121
$skillIssueComments = $skillIssue->getComments(true);
122
123
$userId = $skillIssueInfo['user_id'];
124
$skillId = $skillIssueInfo['skill_id'];
125
126
/** @var SkillRelUserComment $comment */
127
foreach ($skillIssueComments as $comment) {
128
    $commentDate = api_get_local_time($comment->getFeedbackDateTime());
129
    $skillIssueInfo['comments'][] = [
130
        'text' => $comment->getFeedbackText(),
131
        'value' => $comment->getFeedbackValue(),
132
        'giver_complete_name' => UserManager::formatUserFullName($comment->getFeedbackGiver()),
133
        'datetime' => api_format_date($commentDate, DATE_TIME_FORMAT_SHORT),
134
    ];
135
}
136
137
$acquiredLevel = [];
138
$profile = $skillRepo->find($skillId)->getProfile();
139
140
if (!$profile) {
141
    $skillRelSkill = new SkillRelSkill();
142
    $parents = $skillRelSkill->getSkillParents($skillId);
143
144
    krsort($parents);
145
146
    foreach ($parents as $parent) {
147
        $skillParentId = $parent['skill_id'];
148
        $profile = $skillRepo->find($skillParentId)->getProfile();
149
150
        if ($profile) {
151
            break;
152
        }
153
154
        if (!$profile && $parent['parent_id'] == 0) {
155
            $profile = $skillLevelRepo->findAll();
156
            if ($profile) {
157
                $profile = $profile[0];
158
            }
159
        }
160
    }
161
}
162
163
if ($profile) {
164
    $profileId = $profile->getId();
165
    $levels = $skillLevelRepo->findBy([
166
        'profile' => $profileId,
167
    ]);
168
169
    $profileLevels = [];
170
    foreach ($levels as $level) {
171
        $profileLevels[$level->getPosition()][$level->getId()] = $level->getName();
172
    }
173
174
    ksort($profileLevels); // Sort the array by Position.
175
    foreach ($profileLevels as $profileLevel) {
176
        $profileId = key($profileLevel);
177
        $acquiredLevel[$profileId] = $profileLevel[$profileId];
178
    }
179
}
180
181
$allowToEdit = Skill::isAllowed($user->getId(), false);
182
183
if ($showLevels && $allowToEdit) {
184
    $formAcquiredLevel = new FormValidator('acquired_level');
185
    $formAcquiredLevel->addSelect('acquired_level', get_lang('AcquiredLevel'), $acquiredLevel);
186
    $formAcquiredLevel->addHidden('user', $skillIssue->getUser()->getId());
187
    $formAcquiredLevel->addHidden('issue', $skillIssue->getId());
188
    $formAcquiredLevel->addButtonSave(get_lang('Save'));
189
190
    if ($formAcquiredLevel->validate() && $allowComment) {
191
        $values = $formAcquiredLevel->exportValues();
192
        $level = $skillLevelRepo->find($values['acquired_level']);
193
        $skillIssue->setAcquiredLevel($level);
194
195
        $entityManager->persist($skillIssue);
196
        $entityManager->flush();
197
        Display::addFlash(Display::return_message(get_lang('Saved')));
198
199
        header('Location: '.SkillRelUserManager::getIssueUrl($skillIssue));
200
        exit;
201
    }
202
}
203
204
$form = new FormValidator('comment');
205
$form->addTextarea('comment', get_lang('NewComment'), ['rows' => 4]);
206
$form->applyFilter('comment', 'trim');
207
$form->addRule('comment', get_lang('ThisFieldIsRequired'), 'required');
208
$form->addSelect(
209
    'value',
210
    [get_lang('Value'), get_lang('RateTheSkillInPractice')],
211
    ['-', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
212
);
213
$form->addHidden('user', $skillIssue->getUser()->getId());
214
$form->addHidden('issue', $skillIssue->getId());
215
$form->addButtonSend(get_lang('Send'));
216
217
if ($form->validate() && $allowComment && $allowToEdit) {
218
    $values = $form->exportValues();
219
    $skillUserComment = new SkillRelUserComment();
220
    $skillUserComment
221
        ->setFeedbackDateTime(new DateTime())
222
        ->setFeedbackGiver($currentUser)
223
        ->setFeedbackText($values['comment'])
224
        ->setFeedbackValue($values['value'] ? $values['value'] : null)
225
        ->setSkillRelUser($skillIssue)
226
    ;
227
228
    $entityManager->persist($skillUserComment);
229
    $entityManager->flush();
230
    Display::addFlash(Display::return_message(get_lang('Added')));
231
232
    header('Location: '.SkillRelUserManager::getIssueUrl($skillIssue));
233
    exit;
234
}
235
236
$badgeInfoError = '';
237
$personalBadge = '';
238
if ($allowExport) {
239
    $backpack = 'https://backpack.openbadges.org/';
240
    $configBackpack = api_get_setting('openbadges_backpack');
241
242
    if (0 !== strcmp($backpack, $configBackpack)) {
243
        $backpack = $configBackpack;
244
        if (substr($backpack, -1) !== '/') {
245
            $backpack .= '/';
246
        }
247
    }
248
249
    $htmlHeadXtra[] = '<script src="'.$backpack.'issuer.js"></script>';
250
    $objSkill = new Skill();
251
    $assertionUrl = $skillIssueInfo['badge_assertion'];
252
    $skills = $objSkill->get($skillId);
253
    $unbakedBadge = api_get_path(SYS_UPLOAD_PATH).'badges/'.$skills['icon'];
254
    if (!is_file($unbakedBadge)) {
255
        $unbakedBadge = api_get_path(SYS_CODE_PATH).'img/icons/128/badges-default.png';
256
    }
257
258
    $unbakedBadge = file_get_contents($unbakedBadge);
259
    $badgeInfoError = false;
260
    $personalBadge = '';
261
    $png = new PNGImageBaker($unbakedBadge);
262
263
    if ($png->checkChunks("tEXt", "openbadges")) {
264
        $bakedInfo = $png->addChunk("tEXt", "openbadges", $assertionUrl);
265
        $bakedBadge = UserManager::getUserPathById($userId, "system");
266
        $bakedBadge = $bakedBadge.'badges';
267
        if (!file_exists($bakedBadge)) {
268
            mkdir($bakedBadge, api_get_permissions_for_new_directories(), true);
269
        }
270
        $skillRelUserId = $skillIssueInfo['id'];
271
        if (!file_exists($bakedBadge."/badge_".$skillRelUserId)) {
272
            file_put_contents($bakedBadge."/badge_".$skillRelUserId.".png", $bakedInfo);
273
        }
274
275
        // Process to validate a baked badge
276
        $badgeContent = file_get_contents($bakedBadge."/badge_".$skillRelUserId.".png");
277
        $verifyBakedBadge = $png->extractBadgeInfo($badgeContent);
278
        if (!is_array($verifyBakedBadge)) {
279
            $badgeInfoError = true;
280
        }
281
282
        if (!$badgeInfoError) {
283
            $personalBadge = UserManager::getUserPathById($userId, 'web');
284
            $personalBadge = $personalBadge."badges/badge_".$skillRelUserId.".png";
285
        }
286
    }
287
}
288
289
$template = new Template(get_lang('IssuedBadgeInformation'));
290
$template->assign('issue_info', $skillIssueInfo);
291
$template->assign('allow_comment', $allowComment);
292
$template->assign('allow_export', $allowExport);
293
294
$commentForm = '';
295
if ($allowComment && $allowToEdit) {
296
    $commentForm = $form->returnForm();
297
}
298
$template->assign('comment_form', $commentForm);
299
300
$levelForm = '';
301
if ($showLevels && $allowToEdit) {
302
    $levelForm = $formAcquiredLevel->returnForm();
303
}
304
$template->assign('acquired_level_form', $levelForm);
305
$template->assign('badge_error', $badgeInfoError);
306
$template->assign('personal_badge', $personalBadge);
307
$template->assign('show_level', $showLevels);
308
$content = $template->fetch($template->get_template('skill/issued.tpl'));
309
$template->assign('header', get_lang('IssuedBadgeInformation'));
310
$template->assign('content', $content);
311
$template->display_one_col_template();
312