weekly release 3.6.5+
[moodle.git] / lib / badgeslib.php
blobf1acbda292f9a57d7e82086a7d221dadccc64cd2
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.
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/>.
17 /**
18 * Contains classes, functions and constants used in badges.
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>
27 defined('MOODLE_INTERNAL') || die();
29 /* Include required award criteria library. */
30 require_once($CFG->dirroot . '/badges/criteria/award_criteria.php');
33 * Number of records per page.
35 define('BADGE_PERPAGE', 50);
38 * Badge award criteria aggregation method.
40 define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
43 * Badge award criteria aggregation method.
45 define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
48 * Inactive badge means that this badge cannot be earned and has not been awarded
49 * yet. Its award criteria can be changed.
51 define('BADGE_STATUS_INACTIVE', 0);
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.
57 define('BADGE_STATUS_ACTIVE', 1);
60 * Inactive badge can no longer be earned, but it has been awarded in the past and
61 * therefore its criteria cannot be changed.
63 define('BADGE_STATUS_INACTIVE_LOCKED', 2);
66 * Active badge means that it can be earned and has already been awarded to users.
67 * Its criteria cannot be changed any more.
69 define('BADGE_STATUS_ACTIVE_LOCKED', 3);
72 * Archived badge is considered deleted and can no longer be earned and is not
73 * displayed in the list of all badges.
75 define('BADGE_STATUS_ARCHIVED', 4);
78 * Badge type for site badges.
80 define('BADGE_TYPE_SITE', 1);
83 * Badge type for course badges.
85 define('BADGE_TYPE_COURSE', 2);
88 * Badge messaging schedule options.
90 define('BADGE_MESSAGE_NEVER', 0);
91 define('BADGE_MESSAGE_ALWAYS', 1);
92 define('BADGE_MESSAGE_DAILY', 2);
93 define('BADGE_MESSAGE_WEEKLY', 3);
94 define('BADGE_MESSAGE_MONTHLY', 4);
97 * URL of backpack. Currently only the Open Badges backpack is supported.
99 define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
102 * Open Badges specifications.
104 define('OPEN_BADGES_V1', 1);
105 define('OPEN_BADGES_V2', 2);
108 * Only use for Open Badges 2.0 specification
110 define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
111 define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
112 define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
113 define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
114 define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
115 define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
118 * Class that represents badge.
121 class badge {
122 /** @var int Badge id */
123 public $id;
125 /** Values from the table 'badge' */
126 public $name;
127 public $description;
128 public $timecreated;
129 public $timemodified;
130 public $usercreated;
131 public $usermodified;
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;
146 /** @var string control version of badge */
147 public $version;
149 /** @var string language code */
150 public $language;
152 /** @var string name image author */
153 public $imageauthorname;
155 /** @var string email image author */
156 public $imageauthoremail;
158 /** @var string url image author */
159 public $imageauthorurl;
161 /** @var string image caption */
162 public $imagecaption;
164 /** @var array Badge criteria */
165 public $criteria = array();
168 * Constructs with badge details.
170 * @param int $badgeid badge ID.
172 public function __construct($badgeid) {
173 global $DB;
174 $this->id = $badgeid;
176 $data = $DB->get_record('badge', array('id' => $badgeid));
178 if (empty($data)) {
179 print_error('error:nosuchbadge', 'badges', $badgeid);
182 foreach ((array)$data as $field => $value) {
183 if (property_exists($this, $field)) {
184 $this->{$field} = $value;
188 $this->criteria = self::get_criteria();
192 * Use to get context instance of a badge.
193 * @return context instance.
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...');
206 * Return array of aggregation methods
207 * @return array
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'),
217 * Return array of accepted criteria types for this badge
218 * @return array
220 public function get_accepted_criteria() {
221 $criteriatypes = array();
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,
228 BADGE_CRITERIA_TYPE_BADGE,
229 BADGE_CRITERIA_TYPE_ACTIVITY
231 } else if ($this->type == BADGE_TYPE_SITE) {
232 $criteriatypes = array(
233 BADGE_CRITERIA_TYPE_OVERALL,
234 BADGE_CRITERIA_TYPE_MANUAL,
235 BADGE_CRITERIA_TYPE_COURSESET,
236 BADGE_CRITERIA_TYPE_BADGE,
237 BADGE_CRITERIA_TYPE_PROFILE,
238 BADGE_CRITERIA_TYPE_COHORT,
242 return $criteriatypes;
246 * Save/update badge information in 'badge' table only.
247 * Cannot be used for updating awards and criteria settings.
249 * @return bool Returns true on success.
251 public function save() {
252 global $DB;
254 $fordb = new stdClass();
255 foreach (get_object_vars($this) as $k => $v) {
256 $fordb->{$k} = $v;
258 unset($fordb->criteria);
260 $fordb->timemodified = time();
261 if ($DB->update_record_raw('badge', $fordb)) {
262 // Trigger event, badge updated.
263 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
264 $event = \core\event\badge_updated::create($eventparams);
265 $event->trigger();
266 return true;
267 } else {
268 throw new moodle_exception('error:save', 'badges');
269 return false;
274 * Creates and saves a clone of badge with all its properties.
275 * Clone is not active by default and has 'Copy of' attached to its name.
277 * @return int ID of new badge.
279 public function make_clone() {
280 global $DB, $USER, $PAGE;
282 $fordb = new stdClass();
283 foreach (get_object_vars($this) as $k => $v) {
284 $fordb->{$k} = $v;
287 $fordb->name = get_string('copyof', 'badges', $this->name);
288 $fordb->status = BADGE_STATUS_INACTIVE;
289 $fordb->usercreated = $USER->id;
290 $fordb->usermodified = $USER->id;
291 $fordb->timecreated = time();
292 $fordb->timemodified = time();
293 unset($fordb->id);
295 if ($fordb->notification > 1) {
296 $fordb->nextcron = badges_calculate_message_schedule($fordb->notification);
299 $criteria = $fordb->criteria;
300 unset($fordb->criteria);
302 if ($new = $DB->insert_record('badge', $fordb, true)) {
303 $newbadge = new badge($new);
305 // Copy badge image.
306 $fs = get_file_storage();
307 if ($file = $fs->get_file($this->get_context()->id, 'badges', 'badgeimage', $this->id, '/', 'f1.png')) {
308 if ($imagefile = $file->copy_content_to_temp()) {
309 badges_process_badge_image($newbadge, $imagefile);
313 // Copy badge criteria.
314 foreach ($this->criteria as $crit) {
315 $crit->make_clone($new);
318 // Copy endorsement.
319 $endorsement = $this->get_endorsement();
320 if ($endorsement) {
321 unset($endorsement->id);
322 $endorsement->badgeid = $new;
323 $newbadge->save_endorsement($endorsement);
326 // Copy alignments.
327 $alignments = $this->get_alignments();
328 foreach ($alignments as $alignment) {
329 unset($alignment->id);
330 $alignment->badgeid = $new;
331 $newbadge->save_alignment($alignment);
334 // Copy related badges.
335 $related = $this->get_related_badges(true);
336 if (!empty($related)) {
337 $newbadge->add_related_badges(array_keys($related));
340 // Trigger event, badge duplicated.
341 $eventparams = array('objectid' => $new, 'context' => $PAGE->context);
342 $event = \core\event\badge_duplicated::create($eventparams);
343 $event->trigger();
345 return $new;
346 } else {
347 throw new moodle_exception('error:clone', 'badges');
348 return false;
353 * Checks if badges is active.
354 * Used in badge award.
356 * @return bool A status indicating badge is active
358 public function is_active() {
359 if (($this->status == BADGE_STATUS_ACTIVE) ||
360 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
361 return true;
363 return false;
367 * Use to get the name of badge status.
370 public function get_status_name() {
371 return get_string('badgestatus_' . $this->status, 'badges');
375 * Use to set badge status.
376 * Only active badges can be earned/awarded/issued.
378 * @param int $status Status from BADGE_STATUS constants
380 public function set_status($status = 0) {
381 $this->status = $status;
382 $this->save();
383 if ($status == BADGE_STATUS_ACTIVE) {
384 // Trigger event, badge enabled.
385 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
386 $event = \core\event\badge_enabled::create($eventparams);
387 $event->trigger();
388 } else if ($status == BADGE_STATUS_INACTIVE) {
389 // Trigger event, badge disabled.
390 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
391 $event = \core\event\badge_disabled::create($eventparams);
392 $event->trigger();
397 * Checks if badges is locked.
398 * Used in badge award and editing.
400 * @return bool A status indicating badge is locked
402 public function is_locked() {
403 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
404 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
405 return true;
407 return false;
411 * Checks if badge has been awarded to users.
412 * Used in badge editing.
414 * @return bool A status indicating badge has been awarded at least once
416 public function has_awards() {
417 global $DB;
418 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
419 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
420 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
422 return $awarded;
426 * Gets list of users who have earned an instance of this badge.
428 * @return array An array of objects with information about badge awards.
430 public function get_awards() {
431 global $DB;
433 $awards = $DB->get_records_sql(
434 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
435 FROM {badge_issued} b INNER JOIN {user} u
436 ON b.userid = u.id
437 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
439 return $awards;
443 * Indicates whether badge has already been issued to a user.
446 public function is_issued($userid) {
447 global $DB;
448 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
452 * Issue a badge to user.
454 * @param int $userid User who earned the badge
455 * @param bool $nobake Not baking actual badges (for testing purposes)
457 public function issue($userid, $nobake = false) {
458 global $DB, $CFG;
460 $now = time();
461 $issued = new stdClass();
462 $issued->badgeid = $this->id;
463 $issued->userid = $userid;
464 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
465 $issued->dateissued = $now;
467 if ($this->can_expire()) {
468 $issued->dateexpire = $this->calculate_expiry($now);
469 } else {
470 $issued->dateexpire = null;
473 // Take into account user badges privacy settings.
474 // If none set, badges default visibility is set to public.
475 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
477 $result = $DB->insert_record('badge_issued', $issued, true);
479 if ($result) {
480 // Trigger badge awarded event.
481 $eventdata = array (
482 'context' => $this->get_context(),
483 'objectid' => $this->id,
484 'relateduserid' => $userid,
485 'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
487 \core\event\badge_awarded::create($eventdata)->trigger();
489 // Lock the badge, so that its criteria could not be changed any more.
490 if ($this->status == BADGE_STATUS_ACTIVE) {
491 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
494 // Update details in criteria_met table.
495 $compl = $this->get_criteria_completions($userid);
496 foreach ($compl as $c) {
497 $obj = new stdClass();
498 $obj->id = $c->id;
499 $obj->issuedid = $result;
500 $DB->update_record('badge_criteria_met', $obj, true);
503 if (!$nobake) {
504 // Bake a badge image.
505 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
507 // Notify recipients and badge creators.
508 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
514 * Reviews all badge criteria and checks if badge can be instantly awarded.
516 * @return int Number of awards
518 public function review_all_criteria() {
519 global $DB, $CFG;
520 $awards = 0;
522 // Raise timelimit as this could take a while for big web sites.
523 core_php_time_limit::raise();
524 raise_memory_limit(MEMORY_HUGE);
526 foreach ($this->criteria as $crit) {
527 // Overall criterion is decided when other criteria are reviewed.
528 if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
529 continue;
532 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
533 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
534 if ($this->type == BADGE_TYPE_SITE) {
535 $sql = "SELECT DISTINCT u.id, bi.badgeid
536 FROM {user} u
537 {$extrajoin}
538 LEFT JOIN {badge_issued} bi
539 ON u.id = bi.userid AND bi.badgeid = :badgeid
540 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
541 $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
542 $toearn = $DB->get_fieldset_sql($sql, $params);
543 } else {
544 // For course level badges, get all users who already earned the badge in this course.
545 // Then find the ones who are enrolled in the course and don't have a badge yet.
546 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
547 $wheresql = '';
548 $earnedparams = array();
549 if (!empty($earned)) {
550 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
551 $wheresql = ' WHERE u.id ' . $earnedsql;
553 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
554 $sql = "SELECT DISTINCT u.id
555 FROM {user} u
556 {$extrajoin}
557 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
558 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
559 $toearn = $DB->get_fieldset_sql($sql, $params);
562 foreach ($toearn as $uid) {
563 $reviewoverall = false;
564 if ($crit->review($uid, true)) {
565 $crit->mark_complete($uid);
566 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
567 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
568 $this->issue($uid);
569 $awards++;
570 } else {
571 $reviewoverall = true;
573 } else {
574 // Will be reviewed some other time.
575 $reviewoverall = false;
577 // Review overall if it is required.
578 if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
579 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
580 $this->issue($uid);
581 $awards++;
586 return $awards;
590 * Gets an array of completed criteria from 'badge_criteria_met' table.
592 * @param int $userid Completions for a user
593 * @return array Records of criteria completions
595 public function get_criteria_completions($userid) {
596 global $DB;
597 $completions = array();
598 $sql = "SELECT bcm.id, bcm.critid
599 FROM {badge_criteria_met} bcm
600 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
601 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
602 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
604 return $completions;
608 * Checks if badges has award criteria set up.
610 * @return bool A status indicating badge has at least one criterion
612 public function has_criteria() {
613 if (count($this->criteria) > 0) {
614 return true;
616 return false;
620 * Returns badge award criteria
622 * @return array An array of badge criteria
624 public function get_criteria() {
625 global $DB;
626 $criteria = array();
628 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
629 foreach ($records as $record) {
630 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
634 return $criteria;
638 * Get aggregation method for badge criteria
640 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
641 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
643 public function get_aggregation_method($criteriatype = 0) {
644 global $DB;
645 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
646 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
648 if (!$aggregation) {
649 return BADGE_CRITERIA_AGGREGATION_ALL;
652 return $aggregation;
656 * Checks if badge has expiry period or date set up.
658 * @return bool A status indicating badge can expire
660 public function can_expire() {
661 if ($this->expireperiod || $this->expiredate) {
662 return true;
664 return false;
668 * Calculates badge expiry date based on either expirydate or expiryperiod.
670 * @param int $timestamp Time of badge issue
671 * @return int A timestamp
673 public function calculate_expiry($timestamp) {
674 $expiry = null;
676 if (isset($this->expiredate)) {
677 $expiry = $this->expiredate;
678 } else if (isset($this->expireperiod)) {
679 $expiry = $timestamp + $this->expireperiod;
682 return $expiry;
686 * Checks if badge has manual award criteria set.
688 * @return bool A status indicating badge can be awarded manually
690 public function has_manual_award_criteria() {
691 foreach ($this->criteria as $criterion) {
692 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
693 return true;
696 return false;
700 * Fully deletes the badge or marks it as archived.
702 * @param $archive bool Achive a badge without actual deleting of any data.
704 public function delete($archive = true) {
705 global $DB;
707 if ($archive) {
708 $this->status = BADGE_STATUS_ARCHIVED;
709 $this->save();
711 // Trigger event, badge archived.
712 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
713 $event = \core\event\badge_archived::create($eventparams);
714 $event->trigger();
715 return;
718 $fs = get_file_storage();
720 // Remove all issued badge image files and badge awards.
721 // Cannot bulk remove area files here because they are issued in user context.
722 $awards = $this->get_awards();
723 foreach ($awards as $award) {
724 $usercontext = context_user::instance($award->userid);
725 $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
727 $DB->delete_records('badge_issued', array('badgeid' => $this->id));
729 // Remove all badge criteria.
730 $criteria = $this->get_criteria();
731 foreach ($criteria as $criterion) {
732 $criterion->delete();
735 // Delete badge images.
736 $badgecontext = $this->get_context();
737 $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
739 // Delete endorsements, competencies and related badges.
740 $DB->delete_records('badge_endorsement', array('badgeid' => $this->id));
741 $relatedsql = 'badgeid = :badgeid OR relatedbadgeid = :relatedbadgeid';
742 $relatedparams = array(
743 'badgeid' => $this->id,
744 'relatedbadgeid' => $this->id
746 $DB->delete_records_select('badge_related', $relatedsql, $relatedparams);
747 $DB->delete_records('badge_competencies', array('badgeid' => $this->id));
749 // Finally, remove badge itself.
750 $DB->delete_records('badge', array('id' => $this->id));
752 // Trigger event, badge deleted.
753 $eventparams = array('objectid' => $this->id,
754 'context' => $this->get_context(),
755 'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
757 $event = \core\event\badge_deleted::create($eventparams);
758 $event->trigger();
762 * Add multiple related badges.
764 * @param array $relatedids Id of badges.
766 public function add_related_badges($relatedids) {
767 global $DB;
768 $relatedbadges = array();
769 foreach ($relatedids as $relatedid) {
770 $relatedbadge = new stdClass();
771 $relatedbadge->badgeid = $this->id;
772 $relatedbadge->relatedbadgeid = $relatedid;
773 $relatedbadges[] = $relatedbadge;
775 $DB->insert_records('badge_related', $relatedbadges);
779 * Delete an related badge.
781 * @param int $relatedid Id related badge.
782 * @return bool A status for delete an related badge.
784 public function delete_related_badge($relatedid) {
785 global $DB;
786 $sql = "(badgeid = :badgeid AND relatedbadgeid = :relatedid) OR " .
787 "(badgeid = :relatedid2 AND relatedbadgeid = :badgeid2)";
788 $params = ['badgeid' => $this->id, 'badgeid2' => $this->id, 'relatedid' => $relatedid, 'relatedid2' => $relatedid];
789 return $DB->delete_records_select('badge_related', $sql, $params);
793 * Checks if badge has related badges.
795 * @return bool A status related badge.
797 public function has_related() {
798 global $DB;
799 $sql = "SELECT DISTINCT b.id
800 FROM {badge_related} br
801 JOIN {badge} b ON (br.relatedbadgeid = b.id OR br.badgeid = b.id)
802 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2) AND b.id != :badgeid3";
803 return $DB->record_exists_sql($sql, ['badgeid' => $this->id, 'badgeid2' => $this->id, 'badgeid3' => $this->id]);
807 * Get related badges of badge.
809 * @param bool $activeonly Do not get the inactive badges when is true.
810 * @return array Related badges information.
812 public function get_related_badges(bool $activeonly = false) {
813 global $DB;
815 $params = array('badgeid' => $this->id, 'badgeid2' => $this->id, 'badgeid3' => $this->id);
816 $query = "SELECT DISTINCT b.id, b.name, b.version, b.language, b.type
817 FROM {badge_related} br
818 JOIN {badge} b ON (br.relatedbadgeid = b.id OR br.badgeid = b.id)
819 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2) AND b.id != :badgeid3";
820 if ($activeonly) {
821 $query .= " AND b.status <> :status";
822 $params['status'] = BADGE_STATUS_INACTIVE;
824 $relatedbadges = $DB->get_records_sql($query, $params);
825 return $relatedbadges;
829 * Insert/update competency alignment information of badge.
831 * @param stdClass $alignment Data of a competency alignment.
832 * @param int $alignmentid ID competency alignment.
833 * @return bool|int A status/ID when insert or update data.
835 public function save_alignment($alignment, $alignmentid = 0) {
836 global $DB;
838 $record = $DB->record_exists('badge_competencies', array('id' => $alignmentid));
839 if ($record) {
840 $alignment->id = $alignmentid;
841 return $DB->update_record('badge_competencies', $alignment);
842 } else {
843 return $DB->insert_record('badge_competencies', $alignment, true);
848 * Delete a competency alignment of badge.
850 * @param int $alignmentid ID competency alignment.
851 * @return bool A status for delete a competency alignment.
853 public function delete_alignment($alignmentid) {
854 global $DB;
855 return $DB->delete_records('badge_competencies', array('badgeid' => $this->id, 'id' => $alignmentid));
859 * Get competencies of badge.
861 * @return array List content competencies.
863 public function get_alignments() {
864 global $DB;
865 return $DB->get_records('badge_competencies', array('badgeid' => $this->id));
869 * Insert/update Endorsement information of badge.
871 * @param stdClass $endorsement Data of an endorsement.
872 * @return bool|int A status/ID when insert or update data.
874 public function save_endorsement($endorsement) {
875 global $DB;
876 $record = $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
877 if ($record) {
878 $endorsement->id = $record->id;
879 return $DB->update_record('badge_endorsement', $endorsement);
880 } else {
881 return $DB->insert_record('badge_endorsement', $endorsement, true);
886 * Get endorsement of badge.
888 * @return array|stdClass Endorsement information.
890 public function get_endorsement() {
891 global $DB;
892 return $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
896 * Markdown language support for criteria.
898 * @return string $output Markdown content to output.
900 public function markdown_badge_criteria() {
901 $agg = $this->get_aggregation_methods();
902 if (empty($this->criteria)) {
903 return get_string('nocriteria', 'badges');
905 $overalldescr = '';
906 $overall = $this->criteria[BADGE_CRITERIA_TYPE_OVERALL];
907 if (!empty($overall->description)) {
908 $overalldescr = format_text($overall->description, $overall->descriptionformat,
909 array('context' => $this->get_context())) . '\n';
911 // Get the condition string.
912 if (count($this->criteria) == 2) {
913 $condition = get_string('criteria_descr', 'badges');
914 } else {
915 $condition = get_string('criteria_descr_' . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
916 core_text::strtoupper($agg[$this->get_aggregation_method()]));
918 unset($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
919 $items = array();
920 // If only one criterion left, make sure its description goe to the top.
921 if (count($this->criteria) == 1) {
922 $c = reset($this->criteria);
923 if (!empty($c->description)) {
924 $overalldescr = $c->description . '\n';
926 if (count($c->params) == 1) {
927 $items[] = ' * ' . get_string('criteria_descr_single_' . $c->criteriatype, 'badges') .
928 $c->get_details();
929 } else {
930 $items[] = '* ' . get_string('criteria_descr_' . $c->criteriatype, 'badges',
931 core_text::strtoupper($agg[$this->get_aggregation_method($c->criteriatype)])) .
932 $c->get_details();
934 } else {
935 foreach ($this->criteria as $type => $c) {
936 $criteriadescr = '';
937 if (!empty($c->description)) {
938 $criteriadescr = $c->description;
940 if (count($c->params) == 1) {
941 $items[] = ' * ' . get_string('criteria_descr_single_' . $type, 'badges') .
942 $c->get_details() . $criteriadescr;
943 } else {
944 $items[] = '* ' . get_string('criteria_descr_' . $type, 'badges',
945 core_text::strtoupper($agg[$this->get_aggregation_method($type)])) .
946 $c->get_details() . $criteriadescr;
950 return strip_tags($overalldescr . $condition . html_writer::alist($items, array(), 'ul'));
954 * Define issuer information by format Open Badges specification version 2.
956 * @return array Issuer informations of the badge.
958 public function get_badge_issuer() {
959 $issuer = array();
960 $issuerurl = new moodle_url('/badges/badge_json.php', array('id' => $this->id, 'action' => 0));
961 $issuer['name'] = $this->issuername;
962 $issuer['url'] = $this->issuerurl;
963 $issuer['email'] = $this->issuercontact;
964 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
965 $issuer['id'] = $issuerurl->out(false);
966 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
967 return $issuer;
972 * Sends notifications to users about awarded badges.
974 * @param badge $badge Badge that was issued
975 * @param int $userid Recipient ID
976 * @param string $issued Unique hash of an issued badge
977 * @param string $filepathhash File path hash of an issued badge for attachments
979 function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
980 global $CFG, $DB;
982 $admin = get_admin();
983 $userfrom = new stdClass();
984 $userfrom->id = $admin->id;
985 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
986 foreach (get_all_user_name_fields() as $addname) {
987 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
989 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
990 $userfrom->maildisplay = true;
992 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
993 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
995 $params = new stdClass();
996 $params->badgename = $badge->name;
997 $params->username = fullname($userto);
998 $params->badgelink = $issuedlink;
999 $message = badge_message_from_template($badge->message, $params);
1000 $plaintext = html_to_text($message);
1002 // Notify recipient.
1003 $eventdata = new \core\message\message();
1004 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
1005 $eventdata->component = 'moodle';
1006 $eventdata->name = 'badgerecipientnotice';
1007 $eventdata->userfrom = $userfrom;
1008 $eventdata->userto = $userto;
1009 $eventdata->notification = 1;
1010 $eventdata->subject = $badge->messagesubject;
1011 $eventdata->fullmessage = $plaintext;
1012 $eventdata->fullmessageformat = FORMAT_HTML;
1013 $eventdata->fullmessagehtml = $message;
1014 $eventdata->smallmessage = '';
1016 // Attach badge image if possible.
1017 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
1018 $fs = get_file_storage();
1019 $file = $fs->get_file_by_hash($filepathhash);
1020 $eventdata->attachment = $file;
1021 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
1023 message_send($eventdata);
1024 } else {
1025 message_send($eventdata);
1028 // Notify badge creator about the award if they receive notifications every time.
1029 if ($badge->notification == 1) {
1030 $userfrom = core_user::get_noreply_user();
1031 $userfrom->maildisplay = true;
1033 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
1034 $a = new stdClass();
1035 $a->user = fullname($userto);
1036 $a->link = $issuedlink;
1037 $creatormessage = get_string('creatorbody', 'badges', $a);
1038 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1040 $eventdata = new \core\message\message();
1041 $eventdata->courseid = $badge->courseid;
1042 $eventdata->component = 'moodle';
1043 $eventdata->name = 'badgecreatornotice';
1044 $eventdata->userfrom = $userfrom;
1045 $eventdata->userto = $creator;
1046 $eventdata->notification = 1;
1047 $eventdata->subject = $creatorsubject;
1048 $eventdata->fullmessage = html_to_text($creatormessage);
1049 $eventdata->fullmessageformat = FORMAT_HTML;
1050 $eventdata->fullmessagehtml = $creatormessage;
1051 $eventdata->smallmessage = '';
1053 message_send($eventdata);
1054 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
1059 * Caclulates date for the next message digest to badge creators.
1061 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
1062 * @return int Timestamp for next cron
1064 function badges_calculate_message_schedule($schedule) {
1065 $nextcron = 0;
1067 switch ($schedule) {
1068 case BADGE_MESSAGE_DAILY:
1069 $nextcron = time() + 60 * 60 * 24;
1070 break;
1071 case BADGE_MESSAGE_WEEKLY:
1072 $nextcron = time() + 60 * 60 * 24 * 7;
1073 break;
1074 case BADGE_MESSAGE_MONTHLY:
1075 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
1076 break;
1079 return $nextcron;
1083 * Replaces variables in a message template and returns text ready to be emailed to a user.
1085 * @param string $message Message body.
1086 * @return string Message with replaced values
1088 function badge_message_from_template($message, $params) {
1089 $msg = $message;
1090 foreach ($params as $key => $value) {
1091 $msg = str_replace("%$key%", $value, $msg);
1094 return $msg;
1098 * Get all badges.
1100 * @param int Type of badges to return
1101 * @param int Course ID for course badges
1102 * @param string $sort An SQL field to sort by
1103 * @param string $dir The sort direction ASC|DESC
1104 * @param int $page The page or records to return
1105 * @param int $perpage The number of records to return per page
1106 * @param int $user User specific search
1107 * @return array $badge Array of records matching criteria
1109 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
1110 global $DB;
1111 $records = array();
1112 $params = array();
1113 $where = "b.status != :deleted AND b.type = :type ";
1114 $params['deleted'] = BADGE_STATUS_ARCHIVED;
1116 $userfields = array('b.id, b.name, b.status');
1117 $usersql = "";
1118 if ($user != 0) {
1119 $userfields[] = 'bi.dateissued';
1120 $userfields[] = 'bi.uniquehash';
1121 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
1122 $params['userid'] = $user;
1123 $where .= " AND (b.status = 1 OR b.status = 3) ";
1125 $fields = implode(', ', $userfields);
1127 if ($courseid != 0 ) {
1128 $where .= "AND b.courseid = :courseid ";
1129 $params['courseid'] = $courseid;
1132 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
1133 $params['type'] = $type;
1135 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
1136 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1138 $badges = array();
1139 foreach ($records as $r) {
1140 $badge = new badge($r->id);
1141 $badges[$r->id] = $badge;
1142 if ($user != 0) {
1143 $badges[$r->id]->dateissued = $r->dateissued;
1144 $badges[$r->id]->uniquehash = $r->uniquehash;
1145 } else {
1146 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
1147 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
1148 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
1149 $badges[$r->id]->statstring = $badge->get_status_name();
1152 return $badges;
1156 * Get badges for a specific user.
1158 * @param int $userid User ID
1159 * @param int $courseid Badges earned by a user in a specific course
1160 * @param int $page The page or records to return
1161 * @param int $perpage The number of records to return per page
1162 * @param string $search A simple string to search for
1163 * @param bool $onlypublic Return only public badges
1164 * @return array of badges ordered by decreasing date of issue
1166 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
1167 global $CFG, $DB;
1169 $params = array(
1170 'userid' => $userid
1172 $sql = 'SELECT
1173 bi.uniquehash,
1174 bi.dateissued,
1175 bi.dateexpire,
1176 bi.id as issuedid,
1177 bi.visible,
1178 u.email,
1180 FROM
1181 {badge} b,
1182 {badge_issued} bi,
1183 {user} u
1184 WHERE b.id = bi.badgeid
1185 AND u.id = bi.userid
1186 AND bi.userid = :userid';
1188 if (!empty($search)) {
1189 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
1190 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
1192 if ($onlypublic) {
1193 $sql .= ' AND (bi.visible = 1) ';
1196 if (empty($CFG->badges_allowcoursebadges)) {
1197 $sql .= ' AND b.courseid IS NULL';
1198 } else if ($courseid != 0) {
1199 $sql .= ' AND (b.courseid = :courseid) ';
1200 $params['courseid'] = $courseid;
1202 $sql .= ' ORDER BY bi.dateissued DESC';
1203 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1205 return $badges;
1209 * Extends the course administration navigation with the Badges page
1211 * @param navigation_node $coursenode
1212 * @param object $course
1214 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
1215 global $CFG, $SITE;
1217 $coursecontext = context_course::instance($course->id);
1218 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
1219 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
1220 'moodle/badges:createbadge',
1221 'moodle/badges:awardbadge',
1222 'moodle/badges:configurecriteria',
1223 'moodle/badges:configuremessages',
1224 'moodle/badges:configuredetails',
1225 'moodle/badges:deletebadge'), $coursecontext);
1227 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
1228 $coursenode->add(get_string('coursebadges', 'badges'), null,
1229 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
1230 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
1232 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
1234 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
1235 navigation_node::TYPE_SETTING, null, 'coursebadges');
1237 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
1238 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
1240 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
1241 navigation_node::TYPE_SETTING, null, 'newbadge');
1247 * Triggered when badge is manually awarded.
1249 * @param object $data
1250 * @return boolean
1252 function badges_award_handle_manual_criteria_review(stdClass $data) {
1253 $criteria = $data->crit;
1254 $userid = $data->userid;
1255 $badge = new badge($criteria->badgeid);
1257 if (!$badge->is_active() || $badge->is_issued($userid)) {
1258 return true;
1261 if ($criteria->review($userid)) {
1262 $criteria->mark_complete($userid);
1264 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
1265 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
1266 $badge->issue($userid);
1270 return true;
1274 * Process badge image from form data
1276 * @param badge $badge Badge object
1277 * @param string $iconfile Original file
1279 function badges_process_badge_image(badge $badge, $iconfile) {
1280 global $CFG, $USER;
1281 require_once($CFG->libdir. '/gdlib.php');
1283 if (!empty($CFG->gdversion)) {
1284 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
1285 @unlink($iconfile);
1287 // Clean up file draft area after badge image has been saved.
1288 $context = context_user::instance($USER->id, MUST_EXIST);
1289 $fs = get_file_storage();
1290 $fs->delete_area_files($context->id, 'user', 'draft');
1295 * Print badge image.
1297 * @param badge $badge Badge object
1298 * @param stdClass $context
1299 * @param string $size
1301 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1302 $fsize = ($size == 'small') ? 'f2' : 'f1';
1304 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1305 // Appending a random parameter to image link to forse browser reload the image.
1306 $imageurl->param('refresh', rand(1, 10000));
1307 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
1309 return html_writer::empty_tag('img', $attributes);
1313 * Bake issued badge.
1315 * @param string $hash Unique hash of an issued badge.
1316 * @param int $badgeid ID of the original badge.
1317 * @param int $userid ID of badge recipient (optional).
1318 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1319 * @return string|url Returns either new file path hash or new file URL
1321 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1322 global $CFG, $USER;
1323 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
1325 $badge = new badge($badgeid);
1326 $badge_context = $badge->get_context();
1327 $userid = ($userid) ? $userid : $USER->id;
1328 $user_context = context_user::instance($userid);
1330 $fs = get_file_storage();
1331 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
1332 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
1333 $contents = $file->get_content();
1335 $filehandler = new PNG_MetaDataHandler($contents);
1336 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1337 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1338 // Add assertion URL tExt chunk.
1339 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1340 $fileinfo = array(
1341 'contextid' => $user_context->id,
1342 'component' => 'badges',
1343 'filearea' => 'userbadge',
1344 'itemid' => $badge->id,
1345 'filepath' => '/',
1346 'filename' => $hash . '.png',
1349 // Create a file with added contents.
1350 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1351 if ($pathhash) {
1352 return $newfile->get_pathnamehash();
1355 } else {
1356 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1357 return;
1361 // If file exists and we just need its path hash, return it.
1362 if ($pathhash) {
1363 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1364 return $file->get_pathnamehash();
1367 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1368 return $fileurl;
1372 * Returns external backpack settings and badges from this backpack.
1374 * This function first checks if badges for the user are cached and
1375 * tries to retrieve them from the cache. Otherwise, badges are obtained
1376 * through curl request to the backpack.
1378 * @param int $userid Backpack user ID.
1379 * @param boolean $refresh Refresh badges collection in cache.
1380 * @return null|object Returns null is there is no backpack or object with backpack settings.
1382 function get_backpack_settings($userid, $refresh = false) {
1383 global $DB;
1384 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
1386 // Try to get badges from cache first.
1387 $badgescache = cache::make('core', 'externalbadges');
1388 $out = $badgescache->get($userid);
1389 if ($out !== false && !$refresh) {
1390 return $out;
1392 // Get badges through curl request to the backpack.
1393 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1394 if ($record) {
1395 $backpack = new OpenBadgesBackpackHandler($record);
1396 $out = new stdClass();
1397 $out->backpackurl = $backpack->get_url();
1399 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1400 $out->totalcollections = count($collections);
1401 $out->totalbadges = 0;
1402 $out->badges = array();
1403 foreach ($collections as $collection) {
1404 $badges = $backpack->get_badges($collection->collectionid);
1405 if (isset($badges->badges)) {
1406 $out->badges = array_merge($out->badges, $badges->badges);
1407 $out->totalbadges += count($badges->badges);
1408 } else {
1409 $out->badges = array_merge($out->badges, array());
1412 } else {
1413 $out->totalbadges = 0;
1414 $out->totalcollections = 0;
1417 $badgescache->set($userid, $out);
1418 return $out;
1421 return null;
1425 * Download all user badges in zip archive.
1427 * @param int $userid ID of badge owner.
1429 function badges_download($userid) {
1430 global $CFG, $DB;
1431 $context = context_user::instance($userid);
1432 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1434 // Get list of files to download.
1435 $fs = get_file_storage();
1436 $filelist = array();
1437 foreach ($records as $issued) {
1438 $badge = new badge($issued->badgeid);
1439 // Need to make image name user-readable and unique using filename safe characters.
1440 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1441 $name = str_replace(' ', '_', $name);
1442 $name = clean_param($name, PARAM_FILE);
1443 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1444 $filelist[$name . '.png'] = $file;
1448 // Zip files and sent them to a user.
1449 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1450 $zipper = new zip_packer();
1451 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1452 send_temp_file($tempzip, 'badges.zip');
1453 } else {
1454 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1455 die;
1460 * Checks if badges can be pushed to external backpack.
1462 * @return string Code of backpack accessibility status.
1464 function badges_check_backpack_accessibility() {
1465 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
1466 // For behat sites, do not poll the remote badge site.
1467 // Behat sites should not be available, but we should pretend as though they are.
1468 return 'available';
1471 global $CFG;
1472 include_once $CFG->libdir . '/filelib.php';
1474 // Using fake assertion url to check whether backpack can access the web site.
1475 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1477 // Curl request to backpack baker.
1478 $curl = new curl();
1479 $options = array(
1480 'FRESH_CONNECT' => true,
1481 'RETURNTRANSFER' => true,
1482 'HEADER' => 0,
1483 'CONNECTTIMEOUT' => 2,
1485 $location = BADGE_BACKPACKURL . '/baker';
1486 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1488 $data = json_decode($out);
1489 if (!empty($curl->error)) {
1490 return 'curl-request-timeout';
1491 } else {
1492 if (isset($data->code) && $data->code == 'http-unreachable') {
1493 return 'http-unreachable';
1494 } else {
1495 return 'available';
1499 return false;
1503 * Checks if user has external backpack connected.
1505 * @param int $userid ID of a user.
1506 * @return bool True|False whether backpack connection exists.
1508 function badges_user_has_backpack($userid) {
1509 global $DB;
1510 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1514 * Handles what happens to the course badges when a course is deleted.
1516 * @param int $courseid course ID.
1517 * @return void.
1519 function badges_handle_course_deletion($courseid) {
1520 global $CFG, $DB;
1521 include_once $CFG->libdir . '/filelib.php';
1523 $systemcontext = context_system::instance();
1524 $coursecontext = context_course::instance($courseid);
1525 $fs = get_file_storage();
1527 // Move badges images to the system context.
1528 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1530 // Get all course badges.
1531 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1532 foreach ($badges as $badge) {
1533 // Archive badges in this course.
1534 $toupdate = new stdClass();
1535 $toupdate->id = $badge->id;
1536 $toupdate->type = BADGE_TYPE_SITE;
1537 $toupdate->courseid = null;
1538 $toupdate->status = BADGE_STATUS_ARCHIVED;
1539 $DB->update_record('badge', $toupdate);
1544 * Loads JS files required for backpack support.
1546 * @uses $CFG, $PAGE
1547 * @return void
1549 function badges_setup_backpack_js() {
1550 global $CFG, $PAGE;
1551 if (!empty($CFG->badges_allowexternalbackpack)) {
1552 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
1553 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
1554 $PAGE->requires->js('/badges/backpack.js', true);