MDL-63876 competencies: Use direct URL
[moodle.git] / lib / badgeslib.php
CommitLineData
27806552
YB
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Contains classes, functions and constants used in badges.
19 *
20 * @package core
21 * @subpackage badges
22 * @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @author Yuliya Bozhko <yuliya.bozhko@totaralms.com>
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29/* Include required award criteria library. */
30require_once($CFG->dirroot . '/badges/criteria/award_criteria.php');
31
32/*
33 * Number of records per page.
34*/
35define('BADGE_PERPAGE', 50);
36
37/*
38 * Badge award criteria aggregation method.
39 */
40define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
41
42/*
43 * Badge award criteria aggregation method.
44 */
45define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
46
47/*
48 * Inactive badge means that this badge cannot be earned and has not been awarded
49 * yet. Its award criteria can be changed.
50 */
51define('BADGE_STATUS_INACTIVE', 0);
52
53/*
54 * Active badge means that this badge can we earned, but it has not been awarded
55 * yet. Can be deactivated for the purpose of changing its criteria.
56 */
57define('BADGE_STATUS_ACTIVE', 1);
58
59/*
60 * Inactive badge can no longer be earned, but it has been awarded in the past and
61 * therefore its criteria cannot be changed.
62 */
63define('BADGE_STATUS_INACTIVE_LOCKED', 2);
64
65/*
66 * Active badge means that it can be earned and has already been awarded to users.
67 * Its criteria cannot be changed any more.
68 */
69define('BADGE_STATUS_ACTIVE_LOCKED', 3);
70
71/*
72 * Archived badge is considered deleted and can no longer be earned and is not
73 * displayed in the list of all badges.
74 */
75define('BADGE_STATUS_ARCHIVED', 4);
76
77/*
78 * Badge type for site badges.
79 */
80define('BADGE_TYPE_SITE', 1);
81
82/*
83 * Badge type for course badges.
84 */
85define('BADGE_TYPE_COURSE', 2);
86
87/*
88 * Badge messaging schedule options.
89 */
90define('BADGE_MESSAGE_NEVER', 0);
91define('BADGE_MESSAGE_ALWAYS', 1);
92define('BADGE_MESSAGE_DAILY', 2);
93define('BADGE_MESSAGE_WEEKLY', 3);
94define('BADGE_MESSAGE_MONTHLY', 4);
95
343534a8
YB
96/*
97 * URL of backpack. Currently only the Open Badges backpack is supported.
98 */
4d0ebdeb 99define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
343534a8 100
5a1ea828
SA
101/*
102 * Open Badges specifications.
103 */
104define('OPEN_BADGES_V1', 1);
105define('OPEN_BADGES_V2', 2);
106
d363a5c2
TT
107/*
108 * Only use for Open Badges 2.0 specification
109 */
110define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
111define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
112define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
113define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
114define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
115define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
116
27806552
YB
117/**
118 * Class that represents badge.
119 *
120 */
121class badge {
122 /** @var int Badge id */
123 public $id;
124
125 /** Values from the table 'badge' */
126 public $name;
127 public $description;
128 public $timecreated;
129 public $timemodified;
130 public $usercreated;
131 public $usermodified;
27806552
YB
132 public $issuername;
133 public $issuerurl;
134 public $issuercontact;
135 public $expiredate;
136 public $expireperiod;
137 public $type;
138 public $courseid;
139 public $message;
140 public $messagesubject;
141 public $attachment;
142 public $notification;
143 public $status = 0;
144 public $nextcron;
145
d363a5c2
TT
146 /** @var string control version of badge */
147 public $version;
148
149 /** @var string language code */
150 public $language;
151
152 /** @var string name image author */
153 public $imageauthorname;
154
155 /** @var string email image author */
156 public $imageauthoremail;
157
158 /** @var string url image author */
159 public $imageauthorurl;
160
161 /** @var string image caption */
162 public $imagecaption;
163
27806552
YB
164 /** @var array Badge criteria */
165 public $criteria = array();
166
167 /**
168 * Constructs with badge details.
169 *
170 * @param int $badgeid badge ID.
171 */
172 public function __construct($badgeid) {
173 global $DB;
174 $this->id = $badgeid;
175
176 $data = $DB->get_record('badge', array('id' => $badgeid));
177
178 if (empty($data)) {
179 print_error('error:nosuchbadge', 'badges', $badgeid);
180 }
181
182 foreach ((array)$data as $field => $value) {
183 if (property_exists($this, $field)) {
184 $this->{$field} = $value;
185 }
186 }
187
188 $this->criteria = self::get_criteria();
189 }
190
191 /**
192 * Use to get context instance of a badge.
193 * @return context instance.
194 */
195 public function get_context() {
196 if ($this->type == BADGE_TYPE_SITE) {
197 return context_system::instance();
198 } else if ($this->type == BADGE_TYPE_COURSE) {
199 return context_course::instance($this->courseid);
200 } else {
201 debugging('Something is wrong...');
202 }
203 }
204
205 /**
206 * Return array of aggregation methods
207 * @return array
208 */
209 public static function get_aggregation_methods() {
210 return array(
211 BADGE_CRITERIA_AGGREGATION_ALL => get_string('all', 'badges'),
212 BADGE_CRITERIA_AGGREGATION_ANY => get_string('any', 'badges'),
213 );
214 }
215
216 /**
217 * Return array of accepted criteria types for this badge
218 * @return array
219 */
220 public function get_accepted_criteria() {
221 $criteriatypes = array();
222
223 if ($this->type == BADGE_TYPE_COURSE) {
224 $criteriatypes = array(
225 BADGE_CRITERIA_TYPE_OVERALL,
226 BADGE_CRITERIA_TYPE_MANUAL,
227 BADGE_CRITERIA_TYPE_COURSE,
a7370e0d 228 BADGE_CRITERIA_TYPE_BADGE,
f94786e0
DW
229 BADGE_CRITERIA_TYPE_ACTIVITY,
230 BADGE_CRITERIA_TYPE_COMPETENCY
27806552
YB
231 );
232 } else if ($this->type == BADGE_TYPE_SITE) {
233 $criteriatypes = array(
234 BADGE_CRITERIA_TYPE_OVERALL,
235 BADGE_CRITERIA_TYPE_MANUAL,
236 BADGE_CRITERIA_TYPE_COURSESET,
a7370e0d 237 BADGE_CRITERIA_TYPE_BADGE,
27806552 238 BADGE_CRITERIA_TYPE_PROFILE,
abc07b53 239 BADGE_CRITERIA_TYPE_COHORT,
f94786e0 240 BADGE_CRITERIA_TYPE_COMPETENCY
27806552
YB
241 );
242 }
243
244 return $criteriatypes;
245 }
246
247 /**
248 * Save/update badge information in 'badge' table only.
249 * Cannot be used for updating awards and criteria settings.
250 *
251 * @return bool Returns true on success.
252 */
253 public function save() {
254 global $DB;
255
256 $fordb = new stdClass();
257 foreach (get_object_vars($this) as $k => $v) {
258 $fordb->{$k} = $v;
259 }
260 unset($fordb->criteria);
261
262 $fordb->timemodified = time();
263 if ($DB->update_record_raw('badge', $fordb)) {
a0e13871
SB
264 // Trigger event, badge updated.
265 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
266 $event = \core\event\badge_updated::create($eventparams);
267 $event->trigger();
27806552
YB
268 return true;
269 } else {
270 throw new moodle_exception('error:save', 'badges');
271 return false;
272 }
273 }
274
275 /**
276 * Creates and saves a clone of badge with all its properties.
277 * Clone is not active by default and has 'Copy of' attached to its name.
278 *
279 * @return int ID of new badge.
280 */
281 public function make_clone() {
a0e13871 282 global $DB, $USER, $PAGE;
27806552
YB
283
284 $fordb = new stdClass();
285 foreach (get_object_vars($this) as $k => $v) {
286 $fordb->{$k} = $v;
287 }
288
289 $fordb->name = get_string('copyof', 'badges', $this->name);
290 $fordb->status = BADGE_STATUS_INACTIVE;
27806552
YB
291 $fordb->usercreated = $USER->id;
292 $fordb->usermodified = $USER->id;
293 $fordb->timecreated = time();
294 $fordb->timemodified = time();
295 unset($fordb->id);
296
297 if ($fordb->notification > 1) {
298 $fordb->nextcron = badges_calculate_message_schedule($fordb->notification);
299 }
300
301 $criteria = $fordb->criteria;
302 unset($fordb->criteria);
303
304 if ($new = $DB->insert_record('badge', $fordb, true)) {
305 $newbadge = new badge($new);
306
307 // Copy badge image.
308 $fs = get_file_storage();
309 if ($file = $fs->get_file($this->get_context()->id, 'badges', 'badgeimage', $this->id, '/', 'f1.png')) {
310 if ($imagefile = $file->copy_content_to_temp()) {
311 badges_process_badge_image($newbadge, $imagefile);
312 }
313 }
314
315 // Copy badge criteria.
316 foreach ($this->criteria as $crit) {
317 $crit->make_clone($new);
318 }
319
a0e13871
SB
320 // Trigger event, badge duplicated.
321 $eventparams = array('objectid' => $new, 'context' => $PAGE->context);
322 $event = \core\event\badge_duplicated::create($eventparams);
323 $event->trigger();
324
27806552
YB
325 return $new;
326 } else {
327 throw new moodle_exception('error:clone', 'badges');
328 return false;
329 }
330 }
331
332 /**
333 * Checks if badges is active.
334 * Used in badge award.
335 *
336 * @return bool A status indicating badge is active
337 */
338 public function is_active() {
339 if (($this->status == BADGE_STATUS_ACTIVE) ||
340 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
341 return true;
342 }
343 return false;
344 }
345
346 /**
347 * Use to get the name of badge status.
348 *
349 */
350 public function get_status_name() {
351 return get_string('badgestatus_' . $this->status, 'badges');
352 }
353
354 /**
355 * Use to set badge status.
356 * Only active badges can be earned/awarded/issued.
357 *
358 * @param int $status Status from BADGE_STATUS constants
359 */
360 public function set_status($status = 0) {
361 $this->status = $status;
362 $this->save();
a0e13871
SB
363 if ($status == BADGE_STATUS_ACTIVE) {
364 // Trigger event, badge enabled.
365 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
366 $event = \core\event\badge_enabled::create($eventparams);
367 $event->trigger();
368 } else if ($status == BADGE_STATUS_INACTIVE) {
369 // Trigger event, badge disabled.
370 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
371 $event = \core\event\badge_disabled::create($eventparams);
372 $event->trigger();
373 }
27806552
YB
374 }
375
376 /**
377 * Checks if badges is locked.
378 * Used in badge award and editing.
379 *
380 * @return bool A status indicating badge is locked
381 */
382 public function is_locked() {
383 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
384 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
385 return true;
386 }
387 return false;
388 }
389
390 /**
391 * Checks if badge has been awarded to users.
392 * Used in badge editing.
393 *
394 * @return bool A status indicating badge has been awarded at least once
395 */
396 public function has_awards() {
397 global $DB;
e477ec0a
YB
398 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
399 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
400 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
401
402 return $awarded;
27806552
YB
403 }
404
405 /**
406 * Gets list of users who have earned an instance of this badge.
407 *
408 * @return array An array of objects with information about badge awards.
409 */
410 public function get_awards() {
411 global $DB;
412
413 $awards = $DB->get_records_sql(
414 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
415 FROM {badge_issued} b INNER JOIN {user} u
416 ON b.userid = u.id
7f964cfd 417 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
27806552
YB
418
419 return $awards;
420 }
421
422 /**
423 * Indicates whether badge has already been issued to a user.
424 *
425 */
426 public function is_issued($userid) {
427 global $DB;
428 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
429 }
430
431 /**
432 * Issue a badge to user.
433 *
434 * @param int $userid User who earned the badge
435 * @param bool $nobake Not baking actual badges (for testing purposes)
436 */
437 public function issue($userid, $nobake = false) {
438 global $DB, $CFG;
439
440 $now = time();
441 $issued = new stdClass();
442 $issued->badgeid = $this->id;
443 $issued->userid = $userid;
444 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
445 $issued->dateissued = $now;
446
447 if ($this->can_expire()) {
448 $issued->dateexpire = $this->calculate_expiry($now);
449 } else {
450 $issued->dateexpire = null;
451 }
452
e2805314
YB
453 // Take into account user badges privacy settings.
454 // If none set, badges default visibility is set to public.
455 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
27806552
YB
456
457 $result = $DB->insert_record('badge_issued', $issued, true);
458
459 if ($result) {
483cfd76 460 // Trigger badge awarded event.
4ae5ecbe
SL
461 $eventdata = array (
462 'context' => $this->get_context(),
463 'objectid' => $this->id,
464 'relateduserid' => $userid,
2ec274f5 465 'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
4ae5ecbe
SL
466 );
467 \core\event\badge_awarded::create($eventdata)->trigger();
483cfd76 468
27806552
YB
469 // Lock the badge, so that its criteria could not be changed any more.
470 if ($this->status == BADGE_STATUS_ACTIVE) {
471 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
472 }
473
474 // Update details in criteria_met table.
475 $compl = $this->get_criteria_completions($userid);
476 foreach ($compl as $c) {
477 $obj = new stdClass();
478 $obj->id = $c->id;
479 $obj->issuedid = $result;
480 $DB->update_record('badge_criteria_met', $obj, true);
481 }
482
483 if (!$nobake) {
484 // Bake a badge image.
485 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
486
487 // Notify recipients and badge creators.
f007e899 488 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
27806552
YB
489 }
490 }
491 }
492
493 /**
494 * Reviews all badge criteria and checks if badge can be instantly awarded.
495 *
496 * @return int Number of awards
497 */
498 public function review_all_criteria() {
499 global $DB, $CFG;
500 $awards = 0;
501
502 // Raise timelimit as this could take a while for big web sites.
3ef7279f 503 core_php_time_limit::raise();
27806552
YB
504 raise_memory_limit(MEMORY_HUGE);
505
c8d2f392
YB
506 foreach ($this->criteria as $crit) {
507 // Overall criterion is decided when other criteria are reviewed.
508 if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
509 continue;
510 }
511
512 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
f94786e0 513
c8d2f392
YB
514 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
515 if ($this->type == BADGE_TYPE_SITE) {
516 $sql = "SELECT DISTINCT u.id, bi.badgeid
27806552 517 FROM {user} u
c8d2f392 518 {$extrajoin}
27806552
YB
519 LEFT JOIN {badge_issued} bi
520 ON u.id = bi.userid AND bi.badgeid = :badgeid
c8d2f392
YB
521 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
522 $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
523 $toearn = $DB->get_fieldset_sql($sql, $params);
524 } else {
525 // For course level badges, get all users who already earned the badge in this course.
526 // Then find the ones who are enrolled in the course and don't have a badge yet.
527 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
528 $wheresql = '';
529 $earnedparams = array();
530 if (!empty($earned)) {
531 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
532 $wheresql = ' WHERE u.id ' . $earnedsql;
533 }
534 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
5f92c736 535 $sql = "SELECT DISTINCT u.id
c8d2f392
YB
536 FROM {user} u
537 {$extrajoin}
538 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
539 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
540 $toearn = $DB->get_fieldset_sql($sql, $params);
541 }
27806552 542
c8d2f392
YB
543 foreach ($toearn as $uid) {
544 $reviewoverall = false;
545 if ($crit->review($uid, true)) {
546 $crit->mark_complete($uid);
547 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
548 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
549 $this->issue($uid);
550 $awards++;
27806552 551 } else {
c8d2f392 552 $reviewoverall = true;
27806552 553 }
c8d2f392
YB
554 } else {
555 // Will be reviewed some other time.
556 $reviewoverall = false;
557 }
558 // Review overall if it is required.
559 if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
560 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
561 $this->issue($uid);
562 $awards++;
27806552 563 }
27806552
YB
564 }
565 }
566
567 return $awards;
568 }
569
570 /**
571 * Gets an array of completed criteria from 'badge_criteria_met' table.
572 *
573 * @param int $userid Completions for a user
574 * @return array Records of criteria completions
575 */
576 public function get_criteria_completions($userid) {
577 global $DB;
578 $completions = array();
579 $sql = "SELECT bcm.id, bcm.critid
580 FROM {badge_criteria_met} bcm
581 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
582 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
583 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
584
585 return $completions;
586 }
587
588 /**
589 * Checks if badges has award criteria set up.
590 *
591 * @return bool A status indicating badge has at least one criterion
592 */
593 public function has_criteria() {
594 if (count($this->criteria) > 0) {
595 return true;
596 }
597 return false;
598 }
599
600 /**
601 * Returns badge award criteria
602 *
603 * @return array An array of badge criteria
604 */
605 public function get_criteria() {
606 global $DB;
607 $criteria = array();
608
609 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
610 foreach ($records as $record) {
611 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
612 }
613 }
614
615 return $criteria;
616 }
617
618 /**
619 * Get aggregation method for badge criteria
620 *
621 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
622 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
623 */
624 public function get_aggregation_method($criteriatype = 0) {
625 global $DB;
626 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
627 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
628
629 if (!$aggregation) {
630 return BADGE_CRITERIA_AGGREGATION_ALL;
631 }
632
633 return $aggregation;
634 }
635
636 /**
637 * Checks if badge has expiry period or date set up.
638 *
639 * @return bool A status indicating badge can expire
640 */
641 public function can_expire() {
642 if ($this->expireperiod || $this->expiredate) {
643 return true;
644 }
645 return false;
646 }
647
648 /**
649 * Calculates badge expiry date based on either expirydate or expiryperiod.
650 *
651 * @param int $timestamp Time of badge issue
652 * @return int A timestamp
653 */
654 public function calculate_expiry($timestamp) {
655 $expiry = null;
656
657 if (isset($this->expiredate)) {
658 $expiry = $this->expiredate;
659 } else if (isset($this->expireperiod)) {
660 $expiry = $timestamp + $this->expireperiod;
661 }
662
663 return $expiry;
664 }
665
666 /**
667 * Checks if badge has manual award criteria set.
668 *
669 * @return bool A status indicating badge can be awarded manually
670 */
671 public function has_manual_award_criteria() {
672 foreach ($this->criteria as $criterion) {
673 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
674 return true;
675 }
676 }
677 return false;
678 }
679
680 /**
455d13b7
YB
681 * Fully deletes the badge or marks it as archived.
682 *
683 * @param $archive bool Achive a badge without actual deleting of any data.
27806552 684 */
455d13b7
YB
685 public function delete($archive = true) {
686 global $DB;
687
688 if ($archive) {
689 $this->status = BADGE_STATUS_ARCHIVED;
690 $this->save();
a0e13871
SB
691
692 // Trigger event, badge archived.
693 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
694 $event = \core\event\badge_archived::create($eventparams);
695 $event->trigger();
455d13b7
YB
696 return;
697 }
698
699 $fs = get_file_storage();
700
701 // Remove all issued badge image files and badge awards.
702 // Cannot bulk remove area files here because they are issued in user context.
703 $awards = $this->get_awards();
704 foreach ($awards as $award) {
705 $usercontext = context_user::instance($award->userid);
706 $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
707 }
708 $DB->delete_records('badge_issued', array('badgeid' => $this->id));
709
710 // Remove all badge criteria.
711 $criteria = $this->get_criteria();
712 foreach ($criteria as $criterion) {
713 $criterion->delete();
714 }
715
716 // Delete badge images.
717 $badgecontext = $this->get_context();
718 $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
719
e8bfd9b4 720 // Delete endorsements, alignments and related badges.
5a1ea828 721 $DB->delete_records('badge_endorsement', array('badgeid' => $this->id));
9639cb48
JP
722 $relatedsql = 'badgeid = :badgeid OR relatedbadgeid = :relatedbadgeid';
723 $relatedparams = array(
724 'badgeid' => $this->id,
725 'relatedbadgeid' => $this->id
726 );
727 $DB->delete_records_select('badge_related', $relatedsql, $relatedparams);
e8bfd9b4 728 $DB->delete_records('badge_alignment', array('badgeid' => $this->id));
5a1ea828 729
455d13b7
YB
730 // Finally, remove badge itself.
731 $DB->delete_records('badge', array('id' => $this->id));
a0e13871
SB
732
733 // Trigger event, badge deleted.
734 $eventparams = array('objectid' => $this->id,
735 'context' => $this->get_context(),
736 'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
737 );
738 $event = \core\event\badge_deleted::create($eventparams);
739 $event->trigger();
27806552 740 }
d363a5c2
TT
741
742 /**
743 * Add multiple related badges.
744 *
745 * @param array $relatedids Id of badges.
746 */
747 public function add_related_badges($relatedids) {
748 global $DB;
749 $relatedbadges = array();
750 foreach ($relatedids as $relatedid) {
751 $relatedbadge = new stdClass();
752 $relatedbadge->badgeid = $this->id;
753 $relatedbadge->relatedbadgeid = $relatedid;
754 $relatedbadges[] = $relatedbadge;
755 }
756 $DB->insert_records('badge_related', $relatedbadges);
757 }
758
759 /**
760 * Delete an related badge.
761 *
762 * @param int $relatedid Id related badge.
763 * @return bool A status for delete an related badge.
764 */
765 public function delete_related_badge($relatedid) {
766 global $DB;
1dee827c
JD
767 $sql = "(badgeid = :badgeid AND relatedbadgeid = :relatedid) OR " .
768 "(badgeid = :relatedid2 AND relatedbadgeid = :badgeid2)";
769 $params = ['badgeid' => $this->id, 'badgeid2' => $this->id, 'relatedid' => $relatedid, 'relatedid2' => $relatedid];
770 return $DB->delete_records_select('badge_related', $sql, $params);
d363a5c2
TT
771 }
772
773 /**
774 * Checks if badge has related badges.
775 *
776 * @return bool A status related badge.
777 */
778 public function has_related() {
779 global $DB;
1dee827c
JD
780 $sql = "SELECT DISTINCT b.id
781 FROM {badge_related} br
782 JOIN {badge} b ON (br.relatedbadgeid = b.id OR br.badgeid = b.id)
783 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2) AND b.id != :badgeid3";
784 return $DB->record_exists_sql($sql, ['badgeid' => $this->id, 'badgeid2' => $this->id, 'badgeid3' => $this->id]);
d363a5c2
TT
785 }
786
787 /**
788 * Get related badges of badge.
789 *
790 * @param bool $activeonly Do not get the inactive badges when is true.
791 * @return array Related badges information.
792 */
793 public function get_related_badges(bool $activeonly = false) {
794 global $DB;
795
1dee827c
JD
796 $params = array('badgeid' => $this->id, 'badgeid2' => $this->id, 'badgeid3' => $this->id);
797 $query = "SELECT DISTINCT b.id, b.name, b.version, b.language, b.type
d363a5c2 798 FROM {badge_related} br
1dee827c
JD
799 JOIN {badge} b ON (br.relatedbadgeid = b.id OR br.badgeid = b.id)
800 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2) AND b.id != :badgeid3";
d363a5c2
TT
801 if ($activeonly) {
802 $query .= " AND b.status <> :status";
803 $params['status'] = BADGE_STATUS_INACTIVE;
804 }
805 $relatedbadges = $DB->get_records_sql($query, $params);
806 return $relatedbadges;
807 }
808
809 /**
e8bfd9b4 810 * Insert/update alignment information of badge.
d363a5c2 811 *
e8bfd9b4
DW
812 * @param stdClass $alignment Data of a alignment.
813 * @param int $alignmentid ID alignment.
d363a5c2
TT
814 * @return bool|int A status/ID when insert or update data.
815 */
816 public function save_alignment($alignment, $alignmentid = 0) {
817 global $DB;
818
e8bfd9b4 819 $record = $DB->record_exists('badge_alignment', array('id' => $alignmentid));
d363a5c2
TT
820 if ($record) {
821 $alignment->id = $alignmentid;
e8bfd9b4 822 return $DB->update_record('badge_alignment', $alignment);
d363a5c2 823 } else {
e8bfd9b4 824 return $DB->insert_record('badge_alignment', $alignment, true);
d363a5c2
TT
825 }
826 }
827
828 /**
e8bfd9b4 829 * Delete a alignment of badge.
d363a5c2 830 *
e8bfd9b4
DW
831 * @param int $alignmentid ID alignment.
832 * @return bool A status for delete a alignment.
d363a5c2 833 */
5a1ea828 834 public function delete_alignment($alignmentid) {
d363a5c2 835 global $DB;
e8bfd9b4 836 return $DB->delete_records('badge_alignment', array('badgeid' => $this->id, 'id' => $alignmentid));
d363a5c2
TT
837 }
838
839 /**
e8bfd9b4 840 * Get alignments of badge.
d363a5c2 841 *
e8bfd9b4 842 * @return array List content alignments.
d363a5c2 843 */
f94786e0 844 public function get_alignments() {
d363a5c2 845 global $DB;
e8bfd9b4 846 return $DB->get_records('badge_alignment', array('badgeid' => $this->id));
d363a5c2
TT
847 }
848
849 /**
850 * Insert/update Endorsement information of badge.
851 *
852 * @param stdClass $endorsement Data of an endorsement.
853 * @return bool|int A status/ID when insert or update data.
854 */
855 public function save_endorsement($endorsement) {
856 global $DB;
857 $record = $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
858 if ($record) {
859 $endorsement->id = $record->id;
860 return $DB->update_record('badge_endorsement', $endorsement);
861 } else {
862 return $DB->insert_record('badge_endorsement', $endorsement, true);
863 }
864 }
865
866 /**
867 * Get endorsement of badge.
868 *
869 * @return array|stdClass Endorsement information.
870 */
871 public function get_endorsement() {
872 global $DB;
873 return $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
874 }
875
876 /**
877 * Markdown language support for criteria.
878 *
879 * @return string $output Markdown content to output.
880 */
881 public function markdown_badge_criteria() {
882 $agg = $this->get_aggregation_methods();
883 if (empty($this->criteria)) {
884 return get_string('nocriteria', 'badges');
885 }
886 $overalldescr = '';
887 $overall = $this->criteria[BADGE_CRITERIA_TYPE_OVERALL];
888 if (!empty($overall->description)) {
889 $overalldescr = format_text($overall->description, $overall->descriptionformat,
890 array('context' => $this->get_context())) . '\n';
891 }
892 // Get the condition string.
893 if (count($this->criteria) == 2) {
894 $condition = get_string('criteria_descr', 'badges');
895 } else {
896 $condition = get_string('criteria_descr_' . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
897 core_text::strtoupper($agg[$this->get_aggregation_method()]));
898 }
899 unset($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
900 $items = array();
901 // If only one criterion left, make sure its description goe to the top.
902 if (count($this->criteria) == 1) {
903 $c = reset($this->criteria);
904 if (!empty($c->description)) {
905 $overalldescr = $c->description . '\n';
906 }
907 if (count($c->params) == 1) {
908 $items[] = ' * ' . get_string('criteria_descr_single_' . $c->criteriatype, 'badges') .
909 $c->get_details();
910 } else {
911 $items[] = '* ' . get_string('criteria_descr_' . $c->criteriatype, 'badges',
912 core_text::strtoupper($agg[$this->get_aggregation_method($c->criteriatype)])) .
913 $c->get_details();
914 }
915 } else {
916 foreach ($this->criteria as $type => $c) {
917 $criteriadescr = '';
918 if (!empty($c->description)) {
919 $criteriadescr = $c->description;
920 }
921 if (count($c->params) == 1) {
922 $items[] = ' * ' . get_string('criteria_descr_single_' . $type, 'badges') .
923 $c->get_details() . $criteriadescr;
924 } else {
925 $items[] = '* ' . get_string('criteria_descr_' . $type, 'badges',
926 core_text::strtoupper($agg[$this->get_aggregation_method($type)])) .
927 $c->get_details() . $criteriadescr;
928 }
929 }
930 }
931 return strip_tags($overalldescr . $condition . html_writer::alist($items, array(), 'ul'));
932 }
933
934 /**
935 * Define issuer information by format Open Badges specification version 2.
936 *
937 * @return array Issuer informations of the badge.
938 */
939 public function get_badge_issuer() {
940 $issuer = array();
941 $issuerurl = new moodle_url('/badges/badge_json.php', array('id' => $this->id, 'action' => 0));
942 $issuer['name'] = $this->issuername;
943 $issuer['url'] = $this->issuerurl;
944 $issuer['email'] = $this->issuercontact;
945 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
946 $issuer['id'] = $issuerurl->out(false);
947 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
948 return $issuer;
949 }
27806552
YB
950}
951
952/**
953 * Sends notifications to users about awarded badges.
954 *
955 * @param badge $badge Badge that was issued
956 * @param int $userid Recipient ID
957 * @param string $issued Unique hash of an issued badge
958 * @param string $filepathhash File path hash of an issued badge for attachments
959 */
960function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
961 global $CFG, $DB;
962
963 $admin = get_admin();
964 $userfrom = new stdClass();
965 $userfrom->id = $admin->id;
966 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
a327f25e
AG
967 foreach (get_all_user_name_fields() as $addname) {
968 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
969 }
27806552 970 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
27806552
YB
971 $userfrom->maildisplay = true;
972
973 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
974 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
975
976 $params = new stdClass();
977 $params->badgename = $badge->name;
978 $params->username = fullname($userto);
979 $params->badgelink = $issuedlink;
980 $message = badge_message_from_template($badge->message, $params);
1f258cd8 981 $plaintext = html_to_text($message);
27806552 982
f5d17c14 983 // Notify recipient.
cc350fd9 984 $eventdata = new \core\message\message();
f593e827 985 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
f5d17c14
YB
986 $eventdata->component = 'moodle';
987 $eventdata->name = 'badgerecipientnotice';
988 $eventdata->userfrom = $userfrom;
989 $eventdata->userto = $userto;
990 $eventdata->notification = 1;
991 $eventdata->subject = $badge->messagesubject;
992 $eventdata->fullmessage = $plaintext;
1f258cd8 993 $eventdata->fullmessageformat = FORMAT_HTML;
f5d17c14 994 $eventdata->fullmessagehtml = $message;
1f258cd8 995 $eventdata->smallmessage = '';
f5d17c14
YB
996
997 // Attach badge image if possible.
998 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
27806552
YB
999 $fs = get_file_storage();
1000 $file = $fs->get_file_by_hash($filepathhash);
f5d17c14
YB
1001 $eventdata->attachment = $file;
1002 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
1003
1004 message_send($eventdata);
27806552 1005 } else {
f5d17c14 1006 message_send($eventdata);
27806552
YB
1007 }
1008
1009 // Notify badge creator about the award if they receive notifications every time.
1010 if ($badge->notification == 1) {
f5d17c14
YB
1011 $userfrom = core_user::get_noreply_user();
1012 $userfrom->maildisplay = true;
1013
27806552
YB
1014 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
1015 $a = new stdClass();
1016 $a->user = fullname($userto);
1017 $a->link = $issuedlink;
1018 $creatormessage = get_string('creatorbody', 'badges', $a);
1019 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1020
cc350fd9
AD
1021 $eventdata = new \core\message\message();
1022 $eventdata->courseid = $badge->courseid;
27806552 1023 $eventdata->component = 'moodle';
f5d17c14 1024 $eventdata->name = 'badgecreatornotice';
27806552
YB
1025 $eventdata->userfrom = $userfrom;
1026 $eventdata->userto = $creator;
1027 $eventdata->notification = 1;
1028 $eventdata->subject = $creatorsubject;
1f258cd8
YB
1029 $eventdata->fullmessage = html_to_text($creatormessage);
1030 $eventdata->fullmessageformat = FORMAT_HTML;
f5d17c14 1031 $eventdata->fullmessagehtml = $creatormessage;
1f258cd8 1032 $eventdata->smallmessage = '';
27806552
YB
1033
1034 message_send($eventdata);
1035 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
1036 }
1037}
1038
1039/**
1040 * Caclulates date for the next message digest to badge creators.
1041 *
1042 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
1043 * @return int Timestamp for next cron
1044 */
1045function badges_calculate_message_schedule($schedule) {
1046 $nextcron = 0;
1047
1048 switch ($schedule) {
1049 case BADGE_MESSAGE_DAILY:
1050 $nextcron = time() + 60 * 60 * 24;
1051 break;
1052 case BADGE_MESSAGE_WEEKLY:
1053 $nextcron = time() + 60 * 60 * 24 * 7;
1054 break;
1055 case BADGE_MESSAGE_MONTHLY:
1056 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
1057 break;
1058 }
1059
1060 return $nextcron;
1061}
1062
1063/**
1064 * Replaces variables in a message template and returns text ready to be emailed to a user.
1065 *
1066 * @param string $message Message body.
1067 * @return string Message with replaced values
1068 */
1069function badge_message_from_template($message, $params) {
1070 $msg = $message;
1071 foreach ($params as $key => $value) {
1072 $msg = str_replace("%$key%", $value, $msg);
1073 }
1074
1075 return $msg;
1076}
1077
1078/**
1079 * Get all badges.
1080 *
1081 * @param int Type of badges to return
1082 * @param int Course ID for course badges
1083 * @param string $sort An SQL field to sort by
1084 * @param string $dir The sort direction ASC|DESC
1085 * @param int $page The page or records to return
1086 * @param int $perpage The number of records to return per page
1087 * @param int $user User specific search
1088 * @return array $badge Array of records matching criteria
1089 */
1090function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
1091 global $DB;
1092 $records = array();
1093 $params = array();
1094 $where = "b.status != :deleted AND b.type = :type ";
1095 $params['deleted'] = BADGE_STATUS_ARCHIVED;
1096
1097 $userfields = array('b.id, b.name, b.status');
1098 $usersql = "";
1099 if ($user != 0) {
1100 $userfields[] = 'bi.dateissued';
1101 $userfields[] = 'bi.uniquehash';
1102 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
1103 $params['userid'] = $user;
1104 $where .= " AND (b.status = 1 OR b.status = 3) ";
1105 }
1106 $fields = implode(', ', $userfields);
1107
1108 if ($courseid != 0 ) {
1109 $where .= "AND b.courseid = :courseid ";
1110 $params['courseid'] = $courseid;
1111 }
1112
1113 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
1114 $params['type'] = $type;
1115
1116 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
1117 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1118
1119 $badges = array();
1120 foreach ($records as $r) {
1121 $badge = new badge($r->id);
1122 $badges[$r->id] = $badge;
1123 if ($user != 0) {
1124 $badges[$r->id]->dateissued = $r->dateissued;
1125 $badges[$r->id]->uniquehash = $r->uniquehash;
1126 } else {
7f964cfd
YB
1127 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
1128 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
1129 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
27806552
YB
1130 $badges[$r->id]->statstring = $badge->get_status_name();
1131 }
1132 }
1133 return $badges;
1134}
1135
1136/**
1137 * Get badges for a specific user.
1138 *
1139 * @param int $userid User ID
1140 * @param int $courseid Badges earned by a user in a specific course
1141 * @param int $page The page or records to return
1142 * @param int $perpage The number of records to return per page
1143 * @param string $search A simple string to search for
1144 * @param bool $onlypublic Return only public badges
1145 * @return array of badges ordered by decreasing date of issue
1146 */
1147function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
b4846b88 1148 global $CFG, $DB;
27806552 1149
d237385e
SH
1150 $params = array(
1151 'userid' => $userid
1152 );
27806552
YB
1153 $sql = 'SELECT
1154 bi.uniquehash,
1155 bi.dateissued,
1156 bi.dateexpire,
1157 bi.id as issuedid,
1158 bi.visible,
1159 u.email,
1160 b.*
1161 FROM
1162 {badge} b,
1163 {badge_issued} bi,
1164 {user} u
1165 WHERE b.id = bi.badgeid
1166 AND u.id = bi.userid
d237385e 1167 AND bi.userid = :userid';
27806552
YB
1168
1169 if (!empty($search)) {
d237385e
SH
1170 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
1171 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
27806552
YB
1172 }
1173 if ($onlypublic) {
1174 $sql .= ' AND (bi.visible = 1) ';
1175 }
1176
b4846b88
AO
1177 if (empty($CFG->badges_allowcoursebadges)) {
1178 $sql .= ' AND b.courseid IS NULL';
1179 } else if ($courseid != 0) {
d237385e
SH
1180 $sql .= ' AND (b.courseid = :courseid) ';
1181 $params['courseid'] = $courseid;
27806552
YB
1182 }
1183 $sql .= ' ORDER BY bi.dateissued DESC';
1184 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1185
1186 return $badges;
1187}
1188
27806552
YB
1189/**
1190 * Extends the course administration navigation with the Badges page
1191 *
1192 * @param navigation_node $coursenode
1193 * @param object $course
1194 */
1195function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
1196 global $CFG, $SITE;
1197
1198 $coursecontext = context_course::instance($course->id);
1199 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
a72c2cd6
YB
1200 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
1201 'moodle/badges:createbadge',
1202 'moodle/badges:awardbadge',
1203 'moodle/badges:configurecriteria',
1204 'moodle/badges:configuremessages',
1205 'moodle/badges:configuredetails',
1206 'moodle/badges:deletebadge'), $coursecontext);
27806552 1207
a72c2cd6
YB
1208 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
1209 $coursenode->add(get_string('coursebadges', 'badges'), null,
1210 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
1211 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
27806552 1212
a72c2cd6 1213 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
27806552 1214
a72c2cd6
YB
1215 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
1216 navigation_node::TYPE_SETTING, null, 'coursebadges');
19a9f2ea 1217
a72c2cd6
YB
1218 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
1219 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
19a9f2ea 1220
a72c2cd6
YB
1221 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
1222 navigation_node::TYPE_SETTING, null, 'newbadge');
27806552
YB
1223 }
1224 }
1225}
1226
27806552
YB
1227/**
1228 * Triggered when badge is manually awarded.
1229 *
1230 * @param object $data
1231 * @return boolean
1232 */
1233function badges_award_handle_manual_criteria_review(stdClass $data) {
1234 $criteria = $data->crit;
1235 $userid = $data->userid;
1236 $badge = new badge($criteria->badgeid);
1237
1238 if (!$badge->is_active() || $badge->is_issued($userid)) {
1239 return true;
1240 }
1241
1242 if ($criteria->review($userid)) {
1243 $criteria->mark_complete($userid);
1244
1245 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
1246 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
1247 $badge->issue($userid);
1248 }
1249 }
1250
1251 return true;
1252}
1253
1254/**
1255 * Process badge image from form data
1256 *
1257 * @param badge $badge Badge object
1258 * @param string $iconfile Original file
1259 */
1260function badges_process_badge_image(badge $badge, $iconfile) {
1261 global $CFG, $USER;
1262 require_once($CFG->libdir. '/gdlib.php');
1263
1264 if (!empty($CFG->gdversion)) {
cda2a827 1265 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
27806552
YB
1266 @unlink($iconfile);
1267
1268 // Clean up file draft area after badge image has been saved.
1269 $context = context_user::instance($USER->id, MUST_EXIST);
1270 $fs = get_file_storage();
1271 $fs->delete_area_files($context->id, 'user', 'draft');
1272 }
1273}
1274
1275/**
1276 * Print badge image.
1277 *
1278 * @param badge $badge Badge object
1279 * @param stdClass $context
1280 * @param string $size
1281 */
1282function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1283 $fsize = ($size == 'small') ? 'f2' : 'f1';
1284
1285 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1286 // Appending a random parameter to image link to forse browser reload the image.
b143259e
YB
1287 $imageurl->param('refresh', rand(1, 10000));
1288 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
27806552
YB
1289
1290 return html_writer::empty_tag('img', $attributes);
1291}
1292
1293/**
1294 * Bake issued badge.
1295 *
1296 * @param string $hash Unique hash of an issued badge.
1297 * @param int $badgeid ID of the original badge.
1298 * @param int $userid ID of badge recipient (optional).
1299 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1300 * @return string|url Returns either new file path hash or new file URL
1301 */
1302function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1303 global $CFG, $USER;
1fcf0ca8 1304 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
27806552
YB
1305
1306 $badge = new badge($badgeid);
1307 $badge_context = $badge->get_context();
1308 $userid = ($userid) ? $userid : $USER->id;
1309 $user_context = context_user::instance($userid);
1310
1311 $fs = get_file_storage();
1312 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
49b464f8 1313 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
27806552
YB
1314 $contents = $file->get_content();
1315
1316 $filehandler = new PNG_MetaDataHandler($contents);
1317 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1318 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1319 // Add assertion URL tExt chunk.
1320 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1321 $fileinfo = array(
1322 'contextid' => $user_context->id,
1323 'component' => 'badges',
1324 'filearea' => 'userbadge',
1325 'itemid' => $badge->id,
1326 'filepath' => '/',
1327 'filename' => $hash . '.png',
1328 );
1329
1330 // Create a file with added contents.
1331 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1332 if ($pathhash) {
1333 return $newfile->get_pathnamehash();
1334 }
1335 }
1336 } else {
be2b37cf
Y
1337 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1338 return;
27806552
YB
1339 }
1340 }
1341
f5d17c14
YB
1342 // If file exists and we just need its path hash, return it.
1343 if ($pathhash) {
1344 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1345 return $file->get_pathnamehash();
1346 }
1347
27806552
YB
1348 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1349 return $fileurl;
1350}
1351
1352/**
e2805314 1353 * Returns external backpack settings and badges from this backpack.
27806552 1354 *
2d3c0fae
YB
1355 * This function first checks if badges for the user are cached and
1356 * tries to retrieve them from the cache. Otherwise, badges are obtained
1357 * through curl request to the backpack.
1358 *
27806552 1359 * @param int $userid Backpack user ID.
2d3c0fae 1360 * @param boolean $refresh Refresh badges collection in cache.
27806552
YB
1361 * @return null|object Returns null is there is no backpack or object with backpack settings.
1362 */
2d3c0fae 1363function get_backpack_settings($userid, $refresh = false) {
27806552 1364 global $DB;
1fcf0ca8 1365 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
27806552 1366
2d3c0fae
YB
1367 // Try to get badges from cache first.
1368 $badgescache = cache::make('core', 'externalbadges');
1369 $out = $badgescache->get($userid);
1370 if ($out !== false && !$refresh) {
1371 return $out;
1372 }
1373 // Get badges through curl request to the backpack.
e2805314 1374 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
27806552
YB
1375 if ($record) {
1376 $backpack = new OpenBadgesBackpackHandler($record);
1377 $out = new stdClass();
1378 $out->backpackurl = $backpack->get_url();
e2805314
YB
1379
1380 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1381 $out->totalcollections = count($collections);
1382 $out->totalbadges = 0;
1383 $out->badges = array();
1384 foreach ($collections as $collection) {
1385 $badges = $backpack->get_badges($collection->collectionid);
1386 if (isset($badges->badges)) {
1387 $out->badges = array_merge($out->badges, $badges->badges);
a763bb05 1388 $out->totalbadges += count($badges->badges);
e2805314
YB
1389 } else {
1390 $out->badges = array_merge($out->badges, array());
1391 }
1392 }
1393 } else {
1394 $out->totalbadges = 0;
1395 $out->totalcollections = 0;
1396 }
1397
2d3c0fae 1398 $badgescache->set($userid, $out);
27806552
YB
1399 return $out;
1400 }
1401
1402 return null;
1403}
1404
1405/**
1406 * Download all user badges in zip archive.
1407 *
1408 * @param int $userid ID of badge owner.
1409 */
1410function badges_download($userid) {
1411 global $CFG, $DB;
1412 $context = context_user::instance($userid);
1413 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1414
1415 // Get list of files to download.
1416 $fs = get_file_storage();
1417 $filelist = array();
1418 foreach ($records as $issued) {
1419 $badge = new badge($issued->badgeid);
1420 // Need to make image name user-readable and unique using filename safe characters.
1421 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1422 $name = str_replace(' ', '_', $name);
d77a6026 1423 $name = clean_param($name, PARAM_FILE);
27806552
YB
1424 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1425 $filelist[$name . '.png'] = $file;
1426 }
1427 }
1428
1429 // Zip files and sent them to a user.
1430 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1431 $zipper = new zip_packer();
1432 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1433 send_temp_file($tempzip, 'badges.zip');
1434 } else {
62fef3cf
YB
1435 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1436 die;
27806552
YB
1437 }
1438}
1439
27806552
YB
1440/**
1441 * Checks if badges can be pushed to external backpack.
1442 *
1443 * @return string Code of backpack accessibility status.
1444 */
1445function badges_check_backpack_accessibility() {
389aad6e
AN
1446 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
1447 // For behat sites, do not poll the remote badge site.
1448 // Behat sites should not be available, but we should pretend as though they are.
1449 return 'available';
1450 }
1451
27806552
YB
1452 global $CFG;
1453 include_once $CFG->libdir . '/filelib.php';
1454
1455 // Using fake assertion url to check whether backpack can access the web site.
1456 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1457
343534a8 1458 // Curl request to backpack baker.
27806552
YB
1459 $curl = new curl();
1460 $options = array(
1461 'FRESH_CONNECT' => true,
1462 'RETURNTRANSFER' => true,
27806552 1463 'HEADER' => 0,
dd4a197e 1464 'CONNECTTIMEOUT' => 2,
27806552 1465 );
4d0ebdeb 1466 $location = BADGE_BACKPACKURL . '/baker';
27806552
YB
1467 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1468
1469 $data = json_decode($out);
1470 if (!empty($curl->error)) {
1471 return 'curl-request-timeout';
1472 } else {
1473 if (isset($data->code) && $data->code == 'http-unreachable') {
1474 return 'http-unreachable';
1475 } else {
1476 return 'available';
1477 }
1478 }
1479
1480 return false;
1481}
e2805314
YB
1482
1483/**
1484 * Checks if user has external backpack connected.
1485 *
1486 * @param int $userid ID of a user.
1487 * @return bool True|False whether backpack connection exists.
1488 */
1489function badges_user_has_backpack($userid) {
1490 global $DB;
1491 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1492}
7deff81f
YB
1493
1494/**
1495 * Handles what happens to the course badges when a course is deleted.
1496 *
1497 * @param int $courseid course ID.
1498 * @return void.
1499 */
1500function badges_handle_course_deletion($courseid) {
1501 global $CFG, $DB;
1502 include_once $CFG->libdir . '/filelib.php';
1503
1504 $systemcontext = context_system::instance();
1505 $coursecontext = context_course::instance($courseid);
1506 $fs = get_file_storage();
1507
1508 // Move badges images to the system context.
1509 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1510
1511 // Get all course badges.
1512 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1513 foreach ($badges as $badge) {
1514 // Archive badges in this course.
1515 $toupdate = new stdClass();
1516 $toupdate->id = $badge->id;
1517 $toupdate->type = BADGE_TYPE_SITE;
1518 $toupdate->courseid = null;
1519 $toupdate->status = BADGE_STATUS_ARCHIVED;
1520 $DB->update_record('badge', $toupdate);
1521 }
1522}
2c910861
YB
1523
1524/**
1525 * Loads JS files required for backpack support.
1526 *
1527 * @uses $CFG, $PAGE
1528 * @return void
1529 */
1530function badges_setup_backpack_js() {
1531 global $CFG, $PAGE;
1532 if (!empty($CFG->badges_allowexternalbackpack)) {
1533 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
4d0ebdeb 1534 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
2c910861
YB
1535 $PAGE->requires->js('/badges/backpack.js', true);
1536 }
1537}