MDL-68430 filter_mathjaxloader: update default CDN to 2.7.8
[moodle.git] / lib / badgeslib.php
blob3a70bb2ee39c73a1197bad76716d81c0a929e628
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 $tomorrow = new DateTime("1 day", core_date::get_server_timezone_object());
1070 $nextcron = $tomorrow->getTimestamp();
1071 break;
1072 case BADGE_MESSAGE_WEEKLY:
1073 $nextweek = new DateTime("1 week", core_date::get_server_timezone_object());
1074 $nextcron = $nextweek->getTimestamp();
1075 break;
1076 case BADGE_MESSAGE_MONTHLY:
1077 $nextmonth = new DateTime("1 month", core_date::get_server_timezone_object());
1078 $nextcron = $nextmonth->getTimestamp();
1079 break;
1082 return $nextcron;
1086 * Replaces variables in a message template and returns text ready to be emailed to a user.
1088 * @param string $message Message body.
1089 * @return string Message with replaced values
1091 function badge_message_from_template($message, $params) {
1092 $msg = $message;
1093 foreach ($params as $key => $value) {
1094 $msg = str_replace("%$key%", $value, $msg);
1097 return $msg;
1101 * Get all badges.
1103 * @param int Type of badges to return
1104 * @param int Course ID for course badges
1105 * @param string $sort An SQL field to sort by
1106 * @param string $dir The sort direction ASC|DESC
1107 * @param int $page The page or records to return
1108 * @param int $perpage The number of records to return per page
1109 * @param int $user User specific search
1110 * @return array $badge Array of records matching criteria
1112 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
1113 global $DB;
1114 $records = array();
1115 $params = array();
1116 $where = "b.status != :deleted AND b.type = :type ";
1117 $params['deleted'] = BADGE_STATUS_ARCHIVED;
1119 $userfields = array('b.id, b.name, b.status');
1120 $usersql = "";
1121 if ($user != 0) {
1122 $userfields[] = 'bi.dateissued';
1123 $userfields[] = 'bi.uniquehash';
1124 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
1125 $params['userid'] = $user;
1126 $where .= " AND (b.status = 1 OR b.status = 3) ";
1128 $fields = implode(', ', $userfields);
1130 if ($courseid != 0 ) {
1131 $where .= "AND b.courseid = :courseid ";
1132 $params['courseid'] = $courseid;
1135 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
1136 $params['type'] = $type;
1138 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
1139 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1141 $badges = array();
1142 foreach ($records as $r) {
1143 $badge = new badge($r->id);
1144 $badges[$r->id] = $badge;
1145 if ($user != 0) {
1146 $badges[$r->id]->dateissued = $r->dateissued;
1147 $badges[$r->id]->uniquehash = $r->uniquehash;
1148 } else {
1149 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
1150 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
1151 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
1152 $badges[$r->id]->statstring = $badge->get_status_name();
1155 return $badges;
1159 * Get badges for a specific user.
1161 * @param int $userid User ID
1162 * @param int $courseid Badges earned by a user in a specific course
1163 * @param int $page The page or records to return
1164 * @param int $perpage The number of records to return per page
1165 * @param string $search A simple string to search for
1166 * @param bool $onlypublic Return only public badges
1167 * @return array of badges ordered by decreasing date of issue
1169 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
1170 global $CFG, $DB;
1172 $params = array(
1173 'userid' => $userid
1175 $sql = 'SELECT
1176 bi.uniquehash,
1177 bi.dateissued,
1178 bi.dateexpire,
1179 bi.id as issuedid,
1180 bi.visible,
1181 u.email,
1183 FROM
1184 {badge} b,
1185 {badge_issued} bi,
1186 {user} u
1187 WHERE b.id = bi.badgeid
1188 AND u.id = bi.userid
1189 AND bi.userid = :userid';
1191 if (!empty($search)) {
1192 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
1193 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
1195 if ($onlypublic) {
1196 $sql .= ' AND (bi.visible = 1) ';
1199 if (empty($CFG->badges_allowcoursebadges)) {
1200 $sql .= ' AND b.courseid IS NULL';
1201 } else if ($courseid != 0) {
1202 $sql .= ' AND (b.courseid = :courseid) ';
1203 $params['courseid'] = $courseid;
1205 $sql .= ' ORDER BY bi.dateissued DESC';
1206 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1208 return $badges;
1212 * Extends the course administration navigation with the Badges page
1214 * @param navigation_node $coursenode
1215 * @param object $course
1217 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
1218 global $CFG, $SITE;
1220 $coursecontext = context_course::instance($course->id);
1221 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
1222 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
1223 'moodle/badges:createbadge',
1224 'moodle/badges:awardbadge',
1225 'moodle/badges:configurecriteria',
1226 'moodle/badges:configuremessages',
1227 'moodle/badges:configuredetails',
1228 'moodle/badges:deletebadge'), $coursecontext);
1230 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
1231 $coursenode->add(get_string('coursebadges', 'badges'), null,
1232 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
1233 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
1235 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
1237 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
1238 navigation_node::TYPE_SETTING, null, 'coursebadges');
1240 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
1241 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
1243 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
1244 navigation_node::TYPE_SETTING, null, 'newbadge');
1250 * Triggered when badge is manually awarded.
1252 * @param object $data
1253 * @return boolean
1255 function badges_award_handle_manual_criteria_review(stdClass $data) {
1256 $criteria = $data->crit;
1257 $userid = $data->userid;
1258 $badge = new badge($criteria->badgeid);
1260 if (!$badge->is_active() || $badge->is_issued($userid)) {
1261 return true;
1264 if ($criteria->review($userid)) {
1265 $criteria->mark_complete($userid);
1267 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
1268 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
1269 $badge->issue($userid);
1273 return true;
1277 * Process badge image from form data
1279 * @param badge $badge Badge object
1280 * @param string $iconfile Original file
1282 function badges_process_badge_image(badge $badge, $iconfile) {
1283 global $CFG, $USER;
1284 require_once($CFG->libdir. '/gdlib.php');
1286 if (!empty($CFG->gdversion)) {
1287 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
1288 @unlink($iconfile);
1290 // Clean up file draft area after badge image has been saved.
1291 $context = context_user::instance($USER->id, MUST_EXIST);
1292 $fs = get_file_storage();
1293 $fs->delete_area_files($context->id, 'user', 'draft');
1298 * Print badge image.
1300 * @param badge $badge Badge object
1301 * @param stdClass $context
1302 * @param string $size
1304 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1305 $fsize = ($size == 'small') ? 'f2' : 'f1';
1307 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1308 // Appending a random parameter to image link to forse browser reload the image.
1309 $imageurl->param('refresh', rand(1, 10000));
1310 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
1312 return html_writer::empty_tag('img', $attributes);
1316 * Bake issued badge.
1318 * @param string $hash Unique hash of an issued badge.
1319 * @param int $badgeid ID of the original badge.
1320 * @param int $userid ID of badge recipient (optional).
1321 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1322 * @return string|url Returns either new file path hash or new file URL
1324 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1325 global $CFG, $USER;
1326 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
1328 $badge = new badge($badgeid);
1329 $badge_context = $badge->get_context();
1330 $userid = ($userid) ? $userid : $USER->id;
1331 $user_context = context_user::instance($userid);
1333 $fs = get_file_storage();
1334 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
1335 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
1336 $contents = $file->get_content();
1338 $filehandler = new PNG_MetaDataHandler($contents);
1339 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1340 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1341 // Add assertion URL tExt chunk.
1342 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1343 $fileinfo = array(
1344 'contextid' => $user_context->id,
1345 'component' => 'badges',
1346 'filearea' => 'userbadge',
1347 'itemid' => $badge->id,
1348 'filepath' => '/',
1349 'filename' => $hash . '.png',
1352 // Create a file with added contents.
1353 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1354 if ($pathhash) {
1355 return $newfile->get_pathnamehash();
1358 } else {
1359 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1360 return;
1364 // If file exists and we just need its path hash, return it.
1365 if ($pathhash) {
1366 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1367 return $file->get_pathnamehash();
1370 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1371 return $fileurl;
1375 * Returns external backpack settings and badges from this backpack.
1377 * This function first checks if badges for the user are cached and
1378 * tries to retrieve them from the cache. Otherwise, badges are obtained
1379 * through curl request to the backpack.
1381 * @param int $userid Backpack user ID.
1382 * @param boolean $refresh Refresh badges collection in cache.
1383 * @return null|object Returns null is there is no backpack or object with backpack settings.
1385 function get_backpack_settings($userid, $refresh = false) {
1386 global $DB;
1387 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
1389 // Try to get badges from cache first.
1390 $badgescache = cache::make('core', 'externalbadges');
1391 $out = $badgescache->get($userid);
1392 if ($out !== false && !$refresh) {
1393 return $out;
1395 // Get badges through curl request to the backpack.
1396 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1397 if ($record) {
1398 $backpack = new OpenBadgesBackpackHandler($record);
1399 $out = new stdClass();
1400 $out->backpackurl = $backpack->get_url();
1402 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1403 $out->totalcollections = count($collections);
1404 $out->totalbadges = 0;
1405 $out->badges = array();
1406 foreach ($collections as $collection) {
1407 $badges = $backpack->get_badges($collection->collectionid);
1408 if (isset($badges->badges)) {
1409 $out->badges = array_merge($out->badges, $badges->badges);
1410 $out->totalbadges += count($badges->badges);
1411 } else {
1412 $out->badges = array_merge($out->badges, array());
1415 } else {
1416 $out->totalbadges = 0;
1417 $out->totalcollections = 0;
1420 $badgescache->set($userid, $out);
1421 return $out;
1424 return null;
1428 * Download all user badges in zip archive.
1430 * @param int $userid ID of badge owner.
1432 function badges_download($userid) {
1433 global $CFG, $DB;
1434 $context = context_user::instance($userid);
1435 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1437 // Get list of files to download.
1438 $fs = get_file_storage();
1439 $filelist = array();
1440 foreach ($records as $issued) {
1441 $badge = new badge($issued->badgeid);
1442 // Need to make image name user-readable and unique using filename safe characters.
1443 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1444 $name = str_replace(' ', '_', $name);
1445 $name = clean_param($name, PARAM_FILE);
1446 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1447 $filelist[$name . '.png'] = $file;
1451 // Zip files and sent them to a user.
1452 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1453 $zipper = new zip_packer();
1454 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1455 send_temp_file($tempzip, 'badges.zip');
1456 } else {
1457 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1458 die;
1463 * Checks if badges can be pushed to external backpack.
1465 * @return string Code of backpack accessibility status.
1467 function badges_check_backpack_accessibility() {
1468 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
1469 // For behat sites, do not poll the remote badge site.
1470 // Behat sites should not be available, but we should pretend as though they are.
1471 return 'available';
1474 global $CFG;
1475 include_once $CFG->libdir . '/filelib.php';
1477 // Using fake assertion url to check whether backpack can access the web site.
1478 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1480 // Curl request to backpack baker.
1481 $curl = new curl();
1482 $options = array(
1483 'FRESH_CONNECT' => true,
1484 'RETURNTRANSFER' => true,
1485 'HEADER' => 0,
1486 'CONNECTTIMEOUT' => 2,
1488 $location = BADGE_BACKPACKURL . '/baker';
1489 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1491 $data = json_decode($out);
1492 if (!empty($curl->error)) {
1493 return 'curl-request-timeout';
1494 } else {
1495 if (isset($data->code) && $data->code == 'http-unreachable') {
1496 return 'http-unreachable';
1497 } else {
1498 return 'available';
1502 return false;
1506 * Checks if user has external backpack connected.
1508 * @param int $userid ID of a user.
1509 * @return bool True|False whether backpack connection exists.
1511 function badges_user_has_backpack($userid) {
1512 global $DB;
1513 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1517 * Handles what happens to the course badges when a course is deleted.
1519 * @param int $courseid course ID.
1520 * @return void.
1522 function badges_handle_course_deletion($courseid) {
1523 global $CFG, $DB;
1524 include_once $CFG->libdir . '/filelib.php';
1526 $systemcontext = context_system::instance();
1527 $coursecontext = context_course::instance($courseid);
1528 $fs = get_file_storage();
1530 // Move badges images to the system context.
1531 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1533 // Get all course badges.
1534 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1535 foreach ($badges as $badge) {
1536 // Archive badges in this course.
1537 $toupdate = new stdClass();
1538 $toupdate->id = $badge->id;
1539 $toupdate->type = BADGE_TYPE_SITE;
1540 $toupdate->courseid = null;
1541 $toupdate->status = BADGE_STATUS_ARCHIVED;
1542 $DB->update_record('badge', $toupdate);
1547 * Loads JS files required for backpack support.
1549 * @uses $CFG, $PAGE
1550 * @return void
1552 function badges_setup_backpack_js() {
1553 global $CFG, $PAGE;
1554 if (!empty($CFG->badges_allowexternalbackpack)) {
1555 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
1556 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
1557 $PAGE->requires->js('/badges/backpack.js', true);