2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Contains classes, functions and constants used in 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.
122 /** @var int Badge id */
125 /** Values from the table 'badge' */
129 public $timemodified;
131 public $usermodified;
134 public $issuercontact;
136 public $expireperiod;
140 public $messagesubject;
142 public $notification;
146 /** @var string control version of badge */
149 /** @var string language code */
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) {
174 $this->id = $badgeid;
176 $data = $DB->get_record('badge', array('id' => $badgeid));
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);
201 debugging('Something is wrong...');
206 * Return array of aggregation methods
209 public static function get_aggregation_methods() {
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
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() {
254 $fordb = new stdClass();
255 foreach (get_object_vars($this) as $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);
268 throw new moodle_exception('error:save', 'badges');
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) {
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();
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);
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 // Trigger event, badge duplicated.
319 $eventparams = array('objectid' => $new, 'context' => $PAGE->context);
320 $event = \core\event\badge_duplicated::create($eventparams);
325 throw new moodle_exception('error:clone', 'badges');
331 * Checks if badges is active.
332 * Used in badge award.
334 * @return bool A status indicating badge is active
336 public function is_active() {
337 if (($this->status == BADGE_STATUS_ACTIVE) ||
338 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
345 * Use to get the name of badge status.
348 public function get_status_name() {
349 return get_string('badgestatus_' . $this->status, 'badges');
353 * Use to set badge status.
354 * Only active badges can be earned/awarded/issued.
356 * @param int $status Status from BADGE_STATUS constants
358 public function set_status($status = 0) {
359 $this->status = $status;
361 if ($status == BADGE_STATUS_ACTIVE) {
362 // Trigger event, badge enabled.
363 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
364 $event = \core\event\badge_enabled::create($eventparams);
366 } else if ($status == BADGE_STATUS_INACTIVE) {
367 // Trigger event, badge disabled.
368 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
369 $event = \core\event\badge_disabled::create($eventparams);
375 * Checks if badges is locked.
376 * Used in badge award and editing.
378 * @return bool A status indicating badge is locked
380 public function is_locked() {
381 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
382 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
389 * Checks if badge has been awarded to users.
390 * Used in badge editing.
392 * @return bool A status indicating badge has been awarded at least once
394 public function has_awards() {
396 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
397 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
398 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
404 * Gets list of users who have earned an instance of this badge.
406 * @return array An array of objects with information about badge awards.
408 public function get_awards() {
411 $awards = $DB->get_records_sql(
412 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
413 FROM {badge_issued} b INNER JOIN {user} u
415 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
421 * Indicates whether badge has already been issued to a user.
424 public function is_issued($userid) {
426 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
430 * Issue a badge to user.
432 * @param int $userid User who earned the badge
433 * @param bool $nobake Not baking actual badges (for testing purposes)
435 public function issue($userid, $nobake = false) {
439 $issued = new stdClass();
440 $issued->badgeid = $this->id;
441 $issued->userid = $userid;
442 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
443 $issued->dateissued = $now;
445 if ($this->can_expire()) {
446 $issued->dateexpire = $this->calculate_expiry($now);
448 $issued->dateexpire = null;
451 // Take into account user badges privacy settings.
452 // If none set, badges default visibility is set to public.
453 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
455 $result = $DB->insert_record('badge_issued', $issued, true);
458 // Trigger badge awarded event.
460 'context' => $this->get_context(),
461 'objectid' => $this->id,
462 'relateduserid' => $userid,
463 'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
465 \core\event\badge_awarded::create($eventdata)->trigger();
467 // Lock the badge, so that its criteria could not be changed any more.
468 if ($this->status == BADGE_STATUS_ACTIVE) {
469 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
472 // Update details in criteria_met table.
473 $compl = $this->get_criteria_completions($userid);
474 foreach ($compl as $c) {
475 $obj = new stdClass();
477 $obj->issuedid = $result;
478 $DB->update_record('badge_criteria_met', $obj, true);
482 // Bake a badge image.
483 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
485 // Notify recipients and badge creators.
486 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
492 * Reviews all badge criteria and checks if badge can be instantly awarded.
494 * @return int Number of awards
496 public function review_all_criteria() {
500 // Raise timelimit as this could take a while for big web sites.
501 core_php_time_limit::raise();
502 raise_memory_limit(MEMORY_HUGE);
504 foreach ($this->criteria as $crit) {
505 // Overall criterion is decided when other criteria are reviewed.
506 if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
510 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
511 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
512 if ($this->type == BADGE_TYPE_SITE) {
513 $sql = "SELECT DISTINCT u.id, bi.badgeid
516 LEFT JOIN {badge_issued} bi
517 ON u.id = bi.userid AND bi.badgeid = :badgeid
518 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
519 $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
520 $toearn = $DB->get_fieldset_sql($sql, $params);
522 // For course level badges, get all users who already earned the badge in this course.
523 // Then find the ones who are enrolled in the course and don't have a badge yet.
524 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
526 $earnedparams = array();
527 if (!empty($earned)) {
528 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
529 $wheresql = ' WHERE u.id ' . $earnedsql;
531 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
532 $sql = "SELECT DISTINCT u.id
535 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
536 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
537 $toearn = $DB->get_fieldset_sql($sql, $params);
540 foreach ($toearn as $uid) {
541 $reviewoverall = false;
542 if ($crit->review($uid, true)) {
543 $crit->mark_complete($uid);
544 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
545 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
549 $reviewoverall = true;
552 // Will be reviewed some other time.
553 $reviewoverall = false;
555 // Review overall if it is required.
556 if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
557 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
568 * Gets an array of completed criteria from 'badge_criteria_met' table.
570 * @param int $userid Completions for a user
571 * @return array Records of criteria completions
573 public function get_criteria_completions($userid) {
575 $completions = array();
576 $sql = "SELECT bcm.id, bcm.critid
577 FROM {badge_criteria_met} bcm
578 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
579 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
580 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
586 * Checks if badges has award criteria set up.
588 * @return bool A status indicating badge has at least one criterion
590 public function has_criteria() {
591 if (count($this->criteria) > 0) {
598 * Returns badge award criteria
600 * @return array An array of badge criteria
602 public function get_criteria() {
606 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
607 foreach ($records as $record) {
608 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
616 * Get aggregation method for badge criteria
618 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
619 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
621 public function get_aggregation_method($criteriatype = 0) {
623 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
624 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
627 return BADGE_CRITERIA_AGGREGATION_ALL;
634 * Checks if badge has expiry period or date set up.
636 * @return bool A status indicating badge can expire
638 public function can_expire() {
639 if ($this->expireperiod || $this->expiredate) {
646 * Calculates badge expiry date based on either expirydate or expiryperiod.
648 * @param int $timestamp Time of badge issue
649 * @return int A timestamp
651 public function calculate_expiry($timestamp) {
654 if (isset($this->expiredate)) {
655 $expiry = $this->expiredate;
656 } else if (isset($this->expireperiod)) {
657 $expiry = $timestamp + $this->expireperiod;
664 * Checks if badge has manual award criteria set.
666 * @return bool A status indicating badge can be awarded manually
668 public function has_manual_award_criteria() {
669 foreach ($this->criteria as $criterion) {
670 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
678 * Fully deletes the badge or marks it as archived.
680 * @param $archive bool Achive a badge without actual deleting of any data.
682 public function delete($archive = true) {
686 $this->status = BADGE_STATUS_ARCHIVED;
689 // Trigger event, badge archived.
690 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
691 $event = \core\event\badge_archived::create($eventparams);
696 $fs = get_file_storage();
698 // Remove all issued badge image files and badge awards.
699 // Cannot bulk remove area files here because they are issued in user context.
700 $awards = $this->get_awards();
701 foreach ($awards as $award) {
702 $usercontext = context_user::instance($award->userid);
703 $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
705 $DB->delete_records('badge_issued', array('badgeid' => $this->id));
707 // Remove all badge criteria.
708 $criteria = $this->get_criteria();
709 foreach ($criteria as $criterion) {
710 $criterion->delete();
713 // Delete badge images.
714 $badgecontext = $this->get_context();
715 $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
717 // Delete endorsements, competencies and related badges.
718 $DB->delete_records('badge_endorsement', array('badgeid' => $this->id));
719 $relatedsql = 'badgeid = :badgeid OR relatedbadgeid = :relatedbadgeid';
720 $relatedparams = array(
721 'badgeid' => $this->id,
722 'relatedbadgeid' => $this->id
724 $DB->delete_records_select('badge_related', $relatedsql, $relatedparams);
725 $DB->delete_records('badge_competencies', array('badgeid' => $this->id));
727 // Finally, remove badge itself.
728 $DB->delete_records('badge', array('id' => $this->id));
730 // Trigger event, badge deleted.
731 $eventparams = array('objectid' => $this->id,
732 'context' => $this->get_context(),
733 'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
735 $event = \core\event\badge_deleted::create($eventparams);
740 * Add multiple related badges.
742 * @param array $relatedids Id of badges.
744 public function add_related_badges($relatedids) {
746 $relatedbadges = array();
747 foreach ($relatedids as $relatedid) {
748 $relatedbadge = new stdClass();
749 $relatedbadge->badgeid = $this->id;
750 $relatedbadge->relatedbadgeid = $relatedid;
751 $relatedbadges[] = $relatedbadge;
753 $DB->insert_records('badge_related', $relatedbadges);
757 * Delete an related badge.
759 * @param int $relatedid Id related badge.
760 * @return bool A status for delete an related badge.
762 public function delete_related_badge($relatedid) {
764 $sql = "(badgeid = :badgeid AND relatedbadgeid = :relatedid) OR " .
765 "(badgeid = :relatedid2 AND relatedbadgeid = :badgeid2)";
766 $params = ['badgeid' => $this->id, 'badgeid2' => $this->id, 'relatedid' => $relatedid, 'relatedid2' => $relatedid];
767 return $DB->delete_records_select('badge_related', $sql, $params);
771 * Checks if badge has related badges.
773 * @return bool A status related badge.
775 public function has_related() {
777 $sql = "SELECT DISTINCT b.id
778 FROM {badge_related} br
779 JOIN {badge} b ON (br.relatedbadgeid = b.id OR br.badgeid = b.id)
780 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2) AND b.id != :badgeid3";
781 return $DB->record_exists_sql($sql, ['badgeid' => $this->id, 'badgeid2' => $this->id, 'badgeid3' => $this->id]);
785 * Get related badges of badge.
787 * @param bool $activeonly Do not get the inactive badges when is true.
788 * @return array Related badges information.
790 public function get_related_badges(bool $activeonly = false) {
793 $params = array('badgeid' => $this->id, 'badgeid2' => $this->id, 'badgeid3' => $this->id);
794 $query = "SELECT DISTINCT b.id, b.name, b.version, b.language, b.type
795 FROM {badge_related} br
796 JOIN {badge} b ON (br.relatedbadgeid = b.id OR br.badgeid = b.id)
797 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2) AND b.id != :badgeid3";
799 $query .= " AND b.status <> :status";
800 $params['status'] = BADGE_STATUS_INACTIVE;
802 $relatedbadges = $DB->get_records_sql($query, $params);
803 return $relatedbadges;
807 * Insert/update competency alignment information of badge.
809 * @param stdClass $alignment Data of a competency alignment.
810 * @param int $alignmentid ID competency alignment.
811 * @return bool|int A status/ID when insert or update data.
813 public function save_alignment($alignment, $alignmentid = 0) {
816 $record = $DB->record_exists('badge_competencies', array('id' => $alignmentid));
818 $alignment->id = $alignmentid;
819 return $DB->update_record('badge_competencies', $alignment);
821 return $DB->insert_record('badge_competencies', $alignment, true);
826 * Delete a competency alignment of badge.
828 * @param int $alignmentid ID competency alignment.
829 * @return bool A status for delete a competency alignment.
831 public function delete_alignment($alignmentid) {
833 return $DB->delete_records('badge_competencies', array('badgeid' => $this->id, 'id' => $alignmentid));
837 * Get competencies of badge.
839 * @return array List content competencies.
841 public function get_alignment() {
843 return $DB->get_records('badge_competencies', array('badgeid' => $this->id));
847 * Insert/update Endorsement information of badge.
849 * @param stdClass $endorsement Data of an endorsement.
850 * @return bool|int A status/ID when insert or update data.
852 public function save_endorsement($endorsement) {
854 $record = $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
856 $endorsement->id = $record->id;
857 return $DB->update_record('badge_endorsement', $endorsement);
859 return $DB->insert_record('badge_endorsement', $endorsement, true);
864 * Get endorsement of badge.
866 * @return array|stdClass Endorsement information.
868 public function get_endorsement() {
870 return $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
874 * Markdown language support for criteria.
876 * @return string $output Markdown content to output.
878 public function markdown_badge_criteria() {
879 $agg = $this->get_aggregation_methods();
880 if (empty($this->criteria)) {
881 return get_string('nocriteria', 'badges');
884 $overall = $this->criteria[BADGE_CRITERIA_TYPE_OVERALL];
885 if (!empty($overall->description)) {
886 $overalldescr = format_text($overall->description, $overall->descriptionformat,
887 array('context' => $this->get_context())) . '\n';
889 // Get the condition string.
890 if (count($this->criteria) == 2) {
891 $condition = get_string('criteria_descr', 'badges');
893 $condition = get_string('criteria_descr_' . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
894 core_text::strtoupper($agg[$this->get_aggregation_method()]));
896 unset($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
898 // If only one criterion left, make sure its description goe to the top.
899 if (count($this->criteria) == 1) {
900 $c = reset($this->criteria);
901 if (!empty($c->description)) {
902 $overalldescr = $c->description . '\n';
904 if (count($c->params) == 1) {
905 $items[] = ' * ' . get_string('criteria_descr_single_' . $c->criteriatype, 'badges') .
908 $items[] = '* ' . get_string('criteria_descr_' . $c->criteriatype, 'badges',
909 core_text::strtoupper($agg[$this->get_aggregation_method($c->criteriatype)])) .
913 foreach ($this->criteria as $type => $c) {
915 if (!empty($c->description)) {
916 $criteriadescr = $c->description;
918 if (count($c->params) == 1) {
919 $items[] = ' * ' . get_string('criteria_descr_single_' . $type, 'badges') .
920 $c->get_details() . $criteriadescr;
922 $items[] = '* ' . get_string('criteria_descr_' . $type, 'badges',
923 core_text::strtoupper($agg[$this->get_aggregation_method($type)])) .
924 $c->get_details() . $criteriadescr;
928 return strip_tags($overalldescr . $condition . html_writer::alist($items, array(), 'ul'));
932 * Define issuer information by format Open Badges specification version 2.
934 * @return array Issuer informations of the badge.
936 public function get_badge_issuer() {
938 $issuerurl = new moodle_url('/badges/badge_json.php', array('id' => $this->id, 'action' => 0));
939 $issuer['name'] = $this->issuername;
940 $issuer['url'] = $this->issuerurl;
941 $issuer['email'] = $this->issuercontact;
942 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
943 $issuer['id'] = $issuerurl->out(false);
944 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
950 * Sends notifications to users about awarded badges.
952 * @param badge $badge Badge that was issued
953 * @param int $userid Recipient ID
954 * @param string $issued Unique hash of an issued badge
955 * @param string $filepathhash File path hash of an issued badge for attachments
957 function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
960 $admin = get_admin();
961 $userfrom = new stdClass();
962 $userfrom->id = $admin->id;
963 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
964 foreach (get_all_user_name_fields() as $addname) {
965 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
967 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
968 $userfrom->maildisplay = true;
970 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
971 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
973 $params = new stdClass();
974 $params->badgename = $badge->name;
975 $params->username = fullname($userto);
976 $params->badgelink = $issuedlink;
977 $message = badge_message_from_template($badge->message, $params);
978 $plaintext = html_to_text($message);
981 $eventdata = new \core\message\message();
982 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
983 $eventdata->component = 'moodle';
984 $eventdata->name = 'badgerecipientnotice';
985 $eventdata->userfrom = $userfrom;
986 $eventdata->userto = $userto;
987 $eventdata->notification = 1;
988 $eventdata->subject = $badge->messagesubject;
989 $eventdata->fullmessage = $plaintext;
990 $eventdata->fullmessageformat = FORMAT_HTML;
991 $eventdata->fullmessagehtml = $message;
992 $eventdata->smallmessage = '';
994 // Attach badge image if possible.
995 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
996 $fs = get_file_storage();
997 $file = $fs->get_file_by_hash($filepathhash);
998 $eventdata->attachment = $file;
999 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
1001 message_send($eventdata);
1003 message_send($eventdata);
1006 // Notify badge creator about the award if they receive notifications every time.
1007 if ($badge->notification == 1) {
1008 $userfrom = core_user::get_noreply_user();
1009 $userfrom->maildisplay = true;
1011 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
1012 $a = new stdClass();
1013 $a->user = fullname($userto);
1014 $a->link = $issuedlink;
1015 $creatormessage = get_string('creatorbody', 'badges', $a);
1016 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1018 $eventdata = new \core\message\message();
1019 $eventdata->courseid = $badge->courseid;
1020 $eventdata->component = 'moodle';
1021 $eventdata->name = 'badgecreatornotice';
1022 $eventdata->userfrom = $userfrom;
1023 $eventdata->userto = $creator;
1024 $eventdata->notification = 1;
1025 $eventdata->subject = $creatorsubject;
1026 $eventdata->fullmessage = html_to_text($creatormessage);
1027 $eventdata->fullmessageformat = FORMAT_HTML;
1028 $eventdata->fullmessagehtml = $creatormessage;
1029 $eventdata->smallmessage = '';
1031 message_send($eventdata);
1032 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
1037 * Caclulates date for the next message digest to badge creators.
1039 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
1040 * @return int Timestamp for next cron
1042 function badges_calculate_message_schedule($schedule) {
1045 switch ($schedule) {
1046 case BADGE_MESSAGE_DAILY:
1047 $nextcron = time() + 60 * 60 * 24;
1049 case BADGE_MESSAGE_WEEKLY:
1050 $nextcron = time() + 60 * 60 * 24 * 7;
1052 case BADGE_MESSAGE_MONTHLY:
1053 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
1061 * Replaces variables in a message template and returns text ready to be emailed to a user.
1063 * @param string $message Message body.
1064 * @return string Message with replaced values
1066 function badge_message_from_template($message, $params) {
1068 foreach ($params as $key => $value) {
1069 $msg = str_replace("%$key%", $value, $msg);
1078 * @param int Type of badges to return
1079 * @param int Course ID for course badges
1080 * @param string $sort An SQL field to sort by
1081 * @param string $dir The sort direction ASC|DESC
1082 * @param int $page The page or records to return
1083 * @param int $perpage The number of records to return per page
1084 * @param int $user User specific search
1085 * @return array $badge Array of records matching criteria
1087 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
1091 $where = "b.status != :deleted AND b.type = :type ";
1092 $params['deleted'] = BADGE_STATUS_ARCHIVED;
1094 $userfields = array('b.id, b.name, b.status');
1097 $userfields[] = 'bi.dateissued';
1098 $userfields[] = 'bi.uniquehash';
1099 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
1100 $params['userid'] = $user;
1101 $where .= " AND (b.status = 1 OR b.status = 3) ";
1103 $fields = implode(', ', $userfields);
1105 if ($courseid != 0 ) {
1106 $where .= "AND b.courseid = :courseid ";
1107 $params['courseid'] = $courseid;
1110 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
1111 $params['type'] = $type;
1113 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
1114 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1117 foreach ($records as $r) {
1118 $badge = new badge($r->id);
1119 $badges[$r->id] = $badge;
1121 $badges[$r->id]->dateissued = $r->dateissued;
1122 $badges[$r->id]->uniquehash = $r->uniquehash;
1124 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
1125 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
1126 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
1127 $badges[$r->id]->statstring = $badge->get_status_name();
1134 * Get badges for a specific user.
1136 * @param int $userid User ID
1137 * @param int $courseid Badges earned by a user in a specific course
1138 * @param int $page The page or records to return
1139 * @param int $perpage The number of records to return per page
1140 * @param string $search A simple string to search for
1141 * @param bool $onlypublic Return only public badges
1142 * @return array of badges ordered by decreasing date of issue
1144 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
1162 WHERE b.id = bi.badgeid
1163 AND u.id = bi.userid
1164 AND bi.userid = :userid';
1166 if (!empty($search)) {
1167 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
1168 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
1171 $sql .= ' AND (bi.visible = 1) ';
1174 if (empty($CFG->badges_allowcoursebadges)) {
1175 $sql .= ' AND b.courseid IS NULL';
1176 } else if ($courseid != 0) {
1177 $sql .= ' AND (b.courseid = :courseid) ';
1178 $params['courseid'] = $courseid;
1180 $sql .= ' ORDER BY bi.dateissued DESC';
1181 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1187 * Extends the course administration navigation with the Badges page
1189 * @param navigation_node $coursenode
1190 * @param object $course
1192 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
1195 $coursecontext = context_course::instance($course->id);
1196 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
1197 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
1198 'moodle/badges:createbadge',
1199 'moodle/badges:awardbadge',
1200 'moodle/badges:configurecriteria',
1201 'moodle/badges:configuremessages',
1202 'moodle/badges:configuredetails',
1203 'moodle/badges:deletebadge'), $coursecontext);
1205 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
1206 $coursenode->add(get_string('coursebadges', 'badges'), null,
1207 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
1208 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
1210 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
1212 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
1213 navigation_node::TYPE_SETTING, null, 'coursebadges');
1215 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
1216 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
1218 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
1219 navigation_node::TYPE_SETTING, null, 'newbadge');
1225 * Triggered when badge is manually awarded.
1227 * @param object $data
1230 function badges_award_handle_manual_criteria_review(stdClass $data) {
1231 $criteria = $data->crit;
1232 $userid = $data->userid;
1233 $badge = new badge($criteria->badgeid);
1235 if (!$badge->is_active() || $badge->is_issued($userid)) {
1239 if ($criteria->review($userid)) {
1240 $criteria->mark_complete($userid);
1242 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
1243 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
1244 $badge->issue($userid);
1252 * Process badge image from form data
1254 * @param badge $badge Badge object
1255 * @param string $iconfile Original file
1257 function badges_process_badge_image(badge $badge, $iconfile) {
1259 require_once($CFG->libdir. '/gdlib.php');
1261 if (!empty($CFG->gdversion)) {
1262 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
1265 // Clean up file draft area after badge image has been saved.
1266 $context = context_user::instance($USER->id, MUST_EXIST);
1267 $fs = get_file_storage();
1268 $fs->delete_area_files($context->id, 'user', 'draft');
1273 * Print badge image.
1275 * @param badge $badge Badge object
1276 * @param stdClass $context
1277 * @param string $size
1279 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1280 $fsize = ($size == 'small') ? 'f2' : 'f1';
1282 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1283 // Appending a random parameter to image link to forse browser reload the image.
1284 $imageurl->param('refresh', rand(1, 10000));
1285 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
1287 return html_writer::empty_tag('img', $attributes);
1291 * Bake issued badge.
1293 * @param string $hash Unique hash of an issued badge.
1294 * @param int $badgeid ID of the original badge.
1295 * @param int $userid ID of badge recipient (optional).
1296 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1297 * @return string|url Returns either new file path hash or new file URL
1299 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1301 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
1303 $badge = new badge($badgeid);
1304 $badge_context = $badge->get_context();
1305 $userid = ($userid) ? $userid : $USER->id;
1306 $user_context = context_user::instance($userid);
1308 $fs = get_file_storage();
1309 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
1310 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
1311 $contents = $file->get_content();
1313 $filehandler = new PNG_MetaDataHandler($contents);
1314 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1315 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1316 // Add assertion URL tExt chunk.
1317 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1319 'contextid' => $user_context->id,
1320 'component' => 'badges',
1321 'filearea' => 'userbadge',
1322 'itemid' => $badge->id,
1324 'filename' => $hash . '.png',
1327 // Create a file with added contents.
1328 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1330 return $newfile->get_pathnamehash();
1334 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1339 // If file exists and we just need its path hash, return it.
1341 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1342 return $file->get_pathnamehash();
1345 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1350 * Returns external backpack settings and badges from this backpack.
1352 * This function first checks if badges for the user are cached and
1353 * tries to retrieve them from the cache. Otherwise, badges are obtained
1354 * through curl request to the backpack.
1356 * @param int $userid Backpack user ID.
1357 * @param boolean $refresh Refresh badges collection in cache.
1358 * @return null|object Returns null is there is no backpack or object with backpack settings.
1360 function get_backpack_settings($userid, $refresh = false) {
1362 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
1364 // Try to get badges from cache first.
1365 $badgescache = cache::make('core', 'externalbadges');
1366 $out = $badgescache->get($userid);
1367 if ($out !== false && !$refresh) {
1370 // Get badges through curl request to the backpack.
1371 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1373 $backpack = new OpenBadgesBackpackHandler($record);
1374 $out = new stdClass();
1375 $out->backpackurl = $backpack->get_url();
1377 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1378 $out->totalcollections = count($collections);
1379 $out->totalbadges = 0;
1380 $out->badges = array();
1381 foreach ($collections as $collection) {
1382 $badges = $backpack->get_badges($collection->collectionid);
1383 if (isset($badges->badges)) {
1384 $out->badges = array_merge($out->badges, $badges->badges);
1385 $out->totalbadges += count($badges->badges);
1387 $out->badges = array_merge($out->badges, array());
1391 $out->totalbadges = 0;
1392 $out->totalcollections = 0;
1395 $badgescache->set($userid, $out);
1403 * Download all user badges in zip archive.
1405 * @param int $userid ID of badge owner.
1407 function badges_download($userid) {
1409 $context = context_user::instance($userid);
1410 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1412 // Get list of files to download.
1413 $fs = get_file_storage();
1414 $filelist = array();
1415 foreach ($records as $issued) {
1416 $badge = new badge($issued->badgeid);
1417 // Need to make image name user-readable and unique using filename safe characters.
1418 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1419 $name = str_replace(' ', '_', $name);
1420 $name = clean_param($name, PARAM_FILE);
1421 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1422 $filelist[$name . '.png'] = $file;
1426 // Zip files and sent them to a user.
1427 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1428 $zipper = new zip_packer();
1429 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1430 send_temp_file($tempzip, 'badges.zip');
1432 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1438 * Checks if badges can be pushed to external backpack.
1440 * @return string Code of backpack accessibility status.
1442 function badges_check_backpack_accessibility() {
1443 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
1444 // For behat sites, do not poll the remote badge site.
1445 // Behat sites should not be available, but we should pretend as though they are.
1450 include_once $CFG->libdir . '/filelib.php';
1452 // Using fake assertion url to check whether backpack can access the web site.
1453 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1455 // Curl request to backpack baker.
1458 'FRESH_CONNECT' => true,
1459 'RETURNTRANSFER' => true,
1461 'CONNECTTIMEOUT' => 2,
1463 $location = BADGE_BACKPACKURL . '/baker';
1464 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1466 $data = json_decode($out);
1467 if (!empty($curl->error)) {
1468 return 'curl-request-timeout';
1470 if (isset($data->code) && $data->code == 'http-unreachable') {
1471 return 'http-unreachable';
1481 * Checks if user has external backpack connected.
1483 * @param int $userid ID of a user.
1484 * @return bool True|False whether backpack connection exists.
1486 function badges_user_has_backpack($userid) {
1488 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1492 * Handles what happens to the course badges when a course is deleted.
1494 * @param int $courseid course ID.
1497 function badges_handle_course_deletion($courseid) {
1499 include_once $CFG->libdir . '/filelib.php';
1501 $systemcontext = context_system::instance();
1502 $coursecontext = context_course::instance($courseid);
1503 $fs = get_file_storage();
1505 // Move badges images to the system context.
1506 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1508 // Get all course badges.
1509 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1510 foreach ($badges as $badge) {
1511 // Archive badges in this course.
1512 $toupdate = new stdClass();
1513 $toupdate->id = $badge->id;
1514 $toupdate->type = BADGE_TYPE_SITE;
1515 $toupdate->courseid = null;
1516 $toupdate->status = BADGE_STATUS_ARCHIVED;
1517 $DB->update_record('badge', $toupdate);
1522 * Loads JS files required for backpack support.
1527 function badges_setup_backpack_js() {
1529 if (!empty($CFG->badges_allowexternalbackpack)) {
1530 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
1531 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
1532 $PAGE->requires->js('/badges/backpack.js', true);
1537 * Creates single message for all notification and sends it out
1539 * @param object $badge A badge which is notified about.
1541 function badge_assemble_notification(stdClass $badge) {
1544 $userfrom = core_user::get_noreply_user();
1545 $userfrom->maildisplay = true;
1547 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id))) {
1548 // Get badge creator.
1549 $creator = $DB->get_record('user', array('id' => $badge->creator), '*', MUST_EXIST);
1550 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1551 $creatormessage = '';
1553 // Put all messages in one digest.
1554 foreach ($msgs as $msg) {
1555 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash)), $badge->name);
1556 $recipient = $DB->get_record('user', array('id' => $msg->userid), '*', MUST_EXIST);
1558 $a = new stdClass();
1559 $a->user = fullname($recipient);
1560 $a->link = $issuedlink;
1561 $creatormessage .= get_string('creatorbody', 'badges', $a);
1562 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid, 'userid' => $msg->userid));
1565 // Create a message object.
1566 $eventdata = new \core\message\message();
1567 $eventdata->courseid = SITEID;
1568 $eventdata->component = 'moodle';
1569 $eventdata->name = 'badgecreatornotice';
1570 $eventdata->userfrom = $userfrom;
1571 $eventdata->userto = $creator;
1572 $eventdata->notification = 1;
1573 $eventdata->subject = $creatorsubject;
1574 $eventdata->fullmessage = format_text_email($creatormessage, FORMAT_HTML);
1575 $eventdata->fullmessageformat = FORMAT_PLAIN;
1576 $eventdata->fullmessagehtml = $creatormessage;
1577 $eventdata->smallmessage = $creatorsubject;
1579 message_send($eventdata);