MDL-64993 core_message: Add self-conversations to create_user generator
[moodle.git] / lib / badgeslib.php
blob4c1bb90ab8acf08dd408ea7f2b9b8a3fd0ed8a5c
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 global $CFG;
222 $criteriatypes = array();
224 if ($this->type == BADGE_TYPE_COURSE) {
225 $criteriatypes = array(
226 BADGE_CRITERIA_TYPE_OVERALL,
227 BADGE_CRITERIA_TYPE_MANUAL,
228 BADGE_CRITERIA_TYPE_COURSE,
229 BADGE_CRITERIA_TYPE_BADGE,
230 BADGE_CRITERIA_TYPE_ACTIVITY,
231 BADGE_CRITERIA_TYPE_COMPETENCY
233 } else if ($this->type == BADGE_TYPE_SITE) {
234 $criteriatypes = array(
235 BADGE_CRITERIA_TYPE_OVERALL,
236 BADGE_CRITERIA_TYPE_MANUAL,
237 BADGE_CRITERIA_TYPE_COURSESET,
238 BADGE_CRITERIA_TYPE_BADGE,
239 BADGE_CRITERIA_TYPE_PROFILE,
240 BADGE_CRITERIA_TYPE_COHORT,
241 BADGE_CRITERIA_TYPE_COMPETENCY
244 $alltypes = badges_list_criteria();
245 foreach ($criteriatypes as $index => $type) {
246 if (!isset($alltypes[$type])) {
247 unset($criteriatypes[$index]);
251 return $criteriatypes;
255 * Save/update badge information in 'badge' table only.
256 * Cannot be used for updating awards and criteria settings.
258 * @return bool Returns true on success.
260 public function save() {
261 global $DB;
263 $fordb = new stdClass();
264 foreach (get_object_vars($this) as $k => $v) {
265 $fordb->{$k} = $v;
267 unset($fordb->criteria);
269 $fordb->timemodified = time();
270 if ($DB->update_record_raw('badge', $fordb)) {
271 // Trigger event, badge updated.
272 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
273 $event = \core\event\badge_updated::create($eventparams);
274 $event->trigger();
275 return true;
276 } else {
277 throw new moodle_exception('error:save', 'badges');
278 return false;
283 * Creates and saves a clone of badge with all its properties.
284 * Clone is not active by default and has 'Copy of' attached to its name.
286 * @return int ID of new badge.
288 public function make_clone() {
289 global $DB, $USER, $PAGE;
291 $fordb = new stdClass();
292 foreach (get_object_vars($this) as $k => $v) {
293 $fordb->{$k} = $v;
296 $fordb->name = get_string('copyof', 'badges', $this->name);
297 $fordb->status = BADGE_STATUS_INACTIVE;
298 $fordb->usercreated = $USER->id;
299 $fordb->usermodified = $USER->id;
300 $fordb->timecreated = time();
301 $fordb->timemodified = time();
302 unset($fordb->id);
304 if ($fordb->notification > 1) {
305 $fordb->nextcron = badges_calculate_message_schedule($fordb->notification);
308 $criteria = $fordb->criteria;
309 unset($fordb->criteria);
311 if ($new = $DB->insert_record('badge', $fordb, true)) {
312 $newbadge = new badge($new);
314 // Copy badge image.
315 $fs = get_file_storage();
316 if ($file = $fs->get_file($this->get_context()->id, 'badges', 'badgeimage', $this->id, '/', 'f1.png')) {
317 if ($imagefile = $file->copy_content_to_temp()) {
318 badges_process_badge_image($newbadge, $imagefile);
322 // Copy badge criteria.
323 foreach ($this->criteria as $crit) {
324 $crit->make_clone($new);
327 // Copy endorsement.
328 $endorsement = $this->get_endorsement();
329 if ($endorsement) {
330 unset($endorsement->id);
331 $endorsement->badgeid = $new;
332 $newbadge->save_endorsement($endorsement);
335 // Copy alignments.
336 $alignments = $this->get_alignments();
337 foreach ($alignments as $alignment) {
338 unset($alignment->id);
339 $alignment->badgeid = $new;
340 $newbadge->save_alignment($alignment);
343 // Copy related badges.
344 $related = $this->get_related_badges(true);
345 if (!empty($related)) {
346 $newbadge->add_related_badges(array_keys($related));
349 // Trigger event, badge duplicated.
350 $eventparams = array('objectid' => $new, 'context' => $PAGE->context);
351 $event = \core\event\badge_duplicated::create($eventparams);
352 $event->trigger();
354 return $new;
355 } else {
356 throw new moodle_exception('error:clone', 'badges');
357 return false;
362 * Checks if badges is active.
363 * Used in badge award.
365 * @return bool A status indicating badge is active
367 public function is_active() {
368 if (($this->status == BADGE_STATUS_ACTIVE) ||
369 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
370 return true;
372 return false;
376 * Use to get the name of badge status.
379 public function get_status_name() {
380 return get_string('badgestatus_' . $this->status, 'badges');
384 * Use to set badge status.
385 * Only active badges can be earned/awarded/issued.
387 * @param int $status Status from BADGE_STATUS constants
389 public function set_status($status = 0) {
390 $this->status = $status;
391 $this->save();
392 if ($status == BADGE_STATUS_ACTIVE) {
393 // Trigger event, badge enabled.
394 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
395 $event = \core\event\badge_enabled::create($eventparams);
396 $event->trigger();
397 } else if ($status == BADGE_STATUS_INACTIVE) {
398 // Trigger event, badge disabled.
399 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
400 $event = \core\event\badge_disabled::create($eventparams);
401 $event->trigger();
406 * Checks if badges is locked.
407 * Used in badge award and editing.
409 * @return bool A status indicating badge is locked
411 public function is_locked() {
412 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
413 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
414 return true;
416 return false;
420 * Checks if badge has been awarded to users.
421 * Used in badge editing.
423 * @return bool A status indicating badge has been awarded at least once
425 public function has_awards() {
426 global $DB;
427 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
428 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
429 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
431 return $awarded;
435 * Gets list of users who have earned an instance of this badge.
437 * @return array An array of objects with information about badge awards.
439 public function get_awards() {
440 global $DB;
442 $awards = $DB->get_records_sql(
443 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
444 FROM {badge_issued} b INNER JOIN {user} u
445 ON b.userid = u.id
446 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
448 return $awards;
452 * Indicates whether badge has already been issued to a user.
455 public function is_issued($userid) {
456 global $DB;
457 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
461 * Issue a badge to user.
463 * @param int $userid User who earned the badge
464 * @param bool $nobake Not baking actual badges (for testing purposes)
466 public function issue($userid, $nobake = false) {
467 global $DB, $CFG;
469 $now = time();
470 $issued = new stdClass();
471 $issued->badgeid = $this->id;
472 $issued->userid = $userid;
473 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
474 $issued->dateissued = $now;
476 if ($this->can_expire()) {
477 $issued->dateexpire = $this->calculate_expiry($now);
478 } else {
479 $issued->dateexpire = null;
482 // Take into account user badges privacy settings.
483 // If none set, badges default visibility is set to public.
484 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
486 $result = $DB->insert_record('badge_issued', $issued, true);
488 if ($result) {
489 // Trigger badge awarded event.
490 $eventdata = array (
491 'context' => $this->get_context(),
492 'objectid' => $this->id,
493 'relateduserid' => $userid,
494 'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
496 \core\event\badge_awarded::create($eventdata)->trigger();
498 // Lock the badge, so that its criteria could not be changed any more.
499 if ($this->status == BADGE_STATUS_ACTIVE) {
500 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
503 // Update details in criteria_met table.
504 $compl = $this->get_criteria_completions($userid);
505 foreach ($compl as $c) {
506 $obj = new stdClass();
507 $obj->id = $c->id;
508 $obj->issuedid = $result;
509 $DB->update_record('badge_criteria_met', $obj, true);
512 if (!$nobake) {
513 // Bake a badge image.
514 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
516 // Notify recipients and badge creators.
517 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
523 * Reviews all badge criteria and checks if badge can be instantly awarded.
525 * @return int Number of awards
527 public function review_all_criteria() {
528 global $DB, $CFG;
529 $awards = 0;
531 // Raise timelimit as this could take a while for big web sites.
532 core_php_time_limit::raise();
533 raise_memory_limit(MEMORY_HUGE);
535 foreach ($this->criteria as $crit) {
536 // Overall criterion is decided when other criteria are reviewed.
537 if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
538 continue;
541 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
543 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
544 if ($this->type == BADGE_TYPE_SITE) {
545 $sql = "SELECT DISTINCT u.id, bi.badgeid
546 FROM {user} u
547 {$extrajoin}
548 LEFT JOIN {badge_issued} bi
549 ON u.id = bi.userid AND bi.badgeid = :badgeid
550 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
551 $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
552 $toearn = $DB->get_fieldset_sql($sql, $params);
553 } else {
554 // For course level badges, get all users who already earned the badge in this course.
555 // Then find the ones who are enrolled in the course and don't have a badge yet.
556 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
557 $wheresql = '';
558 $earnedparams = array();
559 if (!empty($earned)) {
560 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
561 $wheresql = ' WHERE u.id ' . $earnedsql;
563 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
564 $sql = "SELECT DISTINCT u.id
565 FROM {user} u
566 {$extrajoin}
567 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
568 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
569 $toearn = $DB->get_fieldset_sql($sql, $params);
572 foreach ($toearn as $uid) {
573 $reviewoverall = false;
574 if ($crit->review($uid, true)) {
575 $crit->mark_complete($uid);
576 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
577 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
578 $this->issue($uid);
579 $awards++;
580 } else {
581 $reviewoverall = true;
583 } else {
584 // Will be reviewed some other time.
585 $reviewoverall = false;
587 // Review overall if it is required.
588 if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
589 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
590 $this->issue($uid);
591 $awards++;
596 return $awards;
600 * Gets an array of completed criteria from 'badge_criteria_met' table.
602 * @param int $userid Completions for a user
603 * @return array Records of criteria completions
605 public function get_criteria_completions($userid) {
606 global $DB;
607 $completions = array();
608 $sql = "SELECT bcm.id, bcm.critid
609 FROM {badge_criteria_met} bcm
610 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
611 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
612 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
614 return $completions;
618 * Checks if badges has award criteria set up.
620 * @return bool A status indicating badge has at least one criterion
622 public function has_criteria() {
623 if (count($this->criteria) > 0) {
624 return true;
626 return false;
630 * Returns badge award criteria
632 * @return array An array of badge criteria
634 public function get_criteria() {
635 global $DB;
636 $criteria = array();
638 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
639 foreach ($records as $record) {
640 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
644 return $criteria;
648 * Get aggregation method for badge criteria
650 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
651 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
653 public function get_aggregation_method($criteriatype = 0) {
654 global $DB;
655 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
656 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
658 if (!$aggregation) {
659 return BADGE_CRITERIA_AGGREGATION_ALL;
662 return $aggregation;
666 * Checks if badge has expiry period or date set up.
668 * @return bool A status indicating badge can expire
670 public function can_expire() {
671 if ($this->expireperiod || $this->expiredate) {
672 return true;
674 return false;
678 * Calculates badge expiry date based on either expirydate or expiryperiod.
680 * @param int $timestamp Time of badge issue
681 * @return int A timestamp
683 public function calculate_expiry($timestamp) {
684 $expiry = null;
686 if (isset($this->expiredate)) {
687 $expiry = $this->expiredate;
688 } else if (isset($this->expireperiod)) {
689 $expiry = $timestamp + $this->expireperiod;
692 return $expiry;
696 * Checks if badge has manual award criteria set.
698 * @return bool A status indicating badge can be awarded manually
700 public function has_manual_award_criteria() {
701 foreach ($this->criteria as $criterion) {
702 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
703 return true;
706 return false;
710 * Fully deletes the badge or marks it as archived.
712 * @param $archive bool Achive a badge without actual deleting of any data.
714 public function delete($archive = true) {
715 global $DB;
717 if ($archive) {
718 $this->status = BADGE_STATUS_ARCHIVED;
719 $this->save();
721 // Trigger event, badge archived.
722 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
723 $event = \core\event\badge_archived::create($eventparams);
724 $event->trigger();
725 return;
728 $fs = get_file_storage();
730 // Remove all issued badge image files and badge awards.
731 // Cannot bulk remove area files here because they are issued in user context.
732 $awards = $this->get_awards();
733 foreach ($awards as $award) {
734 $usercontext = context_user::instance($award->userid);
735 $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
737 $DB->delete_records('badge_issued', array('badgeid' => $this->id));
739 // Remove all badge criteria.
740 $criteria = $this->get_criteria();
741 foreach ($criteria as $criterion) {
742 $criterion->delete();
745 // Delete badge images.
746 $badgecontext = $this->get_context();
747 $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
749 // Delete endorsements, alignments and related badges.
750 $DB->delete_records('badge_endorsement', array('badgeid' => $this->id));
751 $relatedsql = 'badgeid = :badgeid OR relatedbadgeid = :relatedbadgeid';
752 $relatedparams = array(
753 'badgeid' => $this->id,
754 'relatedbadgeid' => $this->id
756 $DB->delete_records_select('badge_related', $relatedsql, $relatedparams);
757 $DB->delete_records('badge_alignment', array('badgeid' => $this->id));
759 // Finally, remove badge itself.
760 $DB->delete_records('badge', array('id' => $this->id));
762 // Trigger event, badge deleted.
763 $eventparams = array('objectid' => $this->id,
764 'context' => $this->get_context(),
765 'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
767 $event = \core\event\badge_deleted::create($eventparams);
768 $event->trigger();
772 * Add multiple related badges.
774 * @param array $relatedids Id of badges.
776 public function add_related_badges($relatedids) {
777 global $DB;
778 $relatedbadges = array();
779 foreach ($relatedids as $relatedid) {
780 $relatedbadge = new stdClass();
781 $relatedbadge->badgeid = $this->id;
782 $relatedbadge->relatedbadgeid = $relatedid;
783 $relatedbadges[] = $relatedbadge;
785 $DB->insert_records('badge_related', $relatedbadges);
789 * Delete an related badge.
791 * @param int $relatedid Id related badge.
792 * @return bool A status for delete an related badge.
794 public function delete_related_badge($relatedid) {
795 global $DB;
796 $sql = "(badgeid = :badgeid AND relatedbadgeid = :relatedid) OR " .
797 "(badgeid = :relatedid2 AND relatedbadgeid = :badgeid2)";
798 $params = ['badgeid' => $this->id, 'badgeid2' => $this->id, 'relatedid' => $relatedid, 'relatedid2' => $relatedid];
799 return $DB->delete_records_select('badge_related', $sql, $params);
803 * Checks if badge has related badges.
805 * @return bool A status related badge.
807 public function has_related() {
808 global $DB;
809 $sql = "SELECT DISTINCT b.id
810 FROM {badge_related} br
811 JOIN {badge} b ON (br.relatedbadgeid = b.id OR br.badgeid = b.id)
812 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2) AND b.id != :badgeid3";
813 return $DB->record_exists_sql($sql, ['badgeid' => $this->id, 'badgeid2' => $this->id, 'badgeid3' => $this->id]);
817 * Get related badges of badge.
819 * @param bool $activeonly Do not get the inactive badges when is true.
820 * @return array Related badges information.
822 public function get_related_badges(bool $activeonly = false) {
823 global $DB;
825 $params = array('badgeid' => $this->id, 'badgeid2' => $this->id, 'badgeid3' => $this->id);
826 $query = "SELECT DISTINCT b.id, b.name, b.version, b.language, b.type
827 FROM {badge_related} br
828 JOIN {badge} b ON (br.relatedbadgeid = b.id OR br.badgeid = b.id)
829 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2) AND b.id != :badgeid3";
830 if ($activeonly) {
831 $query .= " AND b.status <> :status";
832 $params['status'] = BADGE_STATUS_INACTIVE;
834 $relatedbadges = $DB->get_records_sql($query, $params);
835 return $relatedbadges;
839 * Insert/update alignment information of badge.
841 * @param stdClass $alignment Data of a alignment.
842 * @param int $alignmentid ID alignment.
843 * @return bool|int A status/ID when insert or update data.
845 public function save_alignment($alignment, $alignmentid = 0) {
846 global $DB;
848 $record = $DB->record_exists('badge_alignment', array('id' => $alignmentid));
849 if ($record) {
850 $alignment->id = $alignmentid;
851 return $DB->update_record('badge_alignment', $alignment);
852 } else {
853 return $DB->insert_record('badge_alignment', $alignment, true);
858 * Delete a alignment of badge.
860 * @param int $alignmentid ID alignment.
861 * @return bool A status for delete a alignment.
863 public function delete_alignment($alignmentid) {
864 global $DB;
865 return $DB->delete_records('badge_alignment', array('badgeid' => $this->id, 'id' => $alignmentid));
869 * Get alignments of badge.
871 * @return array List content alignments.
873 public function get_alignments() {
874 global $DB;
875 return $DB->get_records('badge_alignment', array('badgeid' => $this->id));
879 * Get alignments of badge.
881 * @deprecated since Moodle 3.7 see MDL-63876
882 * @return array List content alignments.
884 public function get_alignment() {
885 debugging('Use of get_alignment is deprecated. Call get_alignments instead.', DEBUG_DEVELOPER);
887 return $this->get_alignments();
891 * Insert/update Endorsement information of badge.
893 * @param stdClass $endorsement Data of an endorsement.
894 * @return bool|int A status/ID when insert or update data.
896 public function save_endorsement($endorsement) {
897 global $DB;
898 $record = $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
899 if ($record) {
900 $endorsement->id = $record->id;
901 return $DB->update_record('badge_endorsement', $endorsement);
902 } else {
903 return $DB->insert_record('badge_endorsement', $endorsement, true);
908 * Get endorsement of badge.
910 * @return array|stdClass Endorsement information.
912 public function get_endorsement() {
913 global $DB;
914 return $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
918 * Markdown language support for criteria.
920 * @return string $output Markdown content to output.
922 public function markdown_badge_criteria() {
923 $agg = $this->get_aggregation_methods();
924 if (empty($this->criteria)) {
925 return get_string('nocriteria', 'badges');
927 $overalldescr = '';
928 $overall = $this->criteria[BADGE_CRITERIA_TYPE_OVERALL];
929 if (!empty($overall->description)) {
930 $overalldescr = format_text($overall->description, $overall->descriptionformat,
931 array('context' => $this->get_context())) . '\n';
933 // Get the condition string.
934 if (count($this->criteria) == 2) {
935 $condition = get_string('criteria_descr', 'badges');
936 } else {
937 $condition = get_string('criteria_descr_' . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
938 core_text::strtoupper($agg[$this->get_aggregation_method()]));
940 unset($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
941 $items = array();
942 // If only one criterion left, make sure its description goe to the top.
943 if (count($this->criteria) == 1) {
944 $c = reset($this->criteria);
945 if (!empty($c->description)) {
946 $overalldescr = $c->description . '\n';
948 if (count($c->params) == 1) {
949 $items[] = ' * ' . get_string('criteria_descr_single_' . $c->criteriatype, 'badges') .
950 $c->get_details();
951 } else {
952 $items[] = '* ' . get_string('criteria_descr_' . $c->criteriatype, 'badges',
953 core_text::strtoupper($agg[$this->get_aggregation_method($c->criteriatype)])) .
954 $c->get_details();
956 } else {
957 foreach ($this->criteria as $type => $c) {
958 $criteriadescr = '';
959 if (!empty($c->description)) {
960 $criteriadescr = $c->description;
962 if (count($c->params) == 1) {
963 $items[] = ' * ' . get_string('criteria_descr_single_' . $type, 'badges') .
964 $c->get_details() . $criteriadescr;
965 } else {
966 $items[] = '* ' . get_string('criteria_descr_' . $type, 'badges',
967 core_text::strtoupper($agg[$this->get_aggregation_method($type)])) .
968 $c->get_details() . $criteriadescr;
972 return strip_tags($overalldescr . $condition . html_writer::alist($items, array(), 'ul'));
976 * Define issuer information by format Open Badges specification version 2.
978 * @return array Issuer informations of the badge.
980 public function get_badge_issuer() {
981 $issuer = array();
982 $issuerurl = new moodle_url('/badges/badge_json.php', array('id' => $this->id, 'action' => 0));
983 $issuer['name'] = $this->issuername;
984 $issuer['url'] = $this->issuerurl;
985 $issuer['email'] = $this->issuercontact;
986 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
987 $issuer['id'] = $issuerurl->out(false);
988 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
989 return $issuer;
994 * Sends notifications to users about awarded badges.
996 * @param badge $badge Badge that was issued
997 * @param int $userid Recipient ID
998 * @param string $issued Unique hash of an issued badge
999 * @param string $filepathhash File path hash of an issued badge for attachments
1001 function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
1002 global $CFG, $DB;
1004 $admin = get_admin();
1005 $userfrom = new stdClass();
1006 $userfrom->id = $admin->id;
1007 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
1008 foreach (get_all_user_name_fields() as $addname) {
1009 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
1011 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
1012 $userfrom->maildisplay = true;
1014 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
1015 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
1017 $params = new stdClass();
1018 $params->badgename = $badge->name;
1019 $params->username = fullname($userto);
1020 $params->badgelink = $issuedlink;
1021 $message = badge_message_from_template($badge->message, $params);
1022 $plaintext = html_to_text($message);
1024 // Notify recipient.
1025 $eventdata = new \core\message\message();
1026 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
1027 $eventdata->component = 'moodle';
1028 $eventdata->name = 'badgerecipientnotice';
1029 $eventdata->userfrom = $userfrom;
1030 $eventdata->userto = $userto;
1031 $eventdata->notification = 1;
1032 $eventdata->subject = $badge->messagesubject;
1033 $eventdata->fullmessage = $plaintext;
1034 $eventdata->fullmessageformat = FORMAT_HTML;
1035 $eventdata->fullmessagehtml = $message;
1036 $eventdata->smallmessage = '';
1037 $eventdata->customdata = [
1038 'notificationiconurl' => moodle_url::make_pluginfile_url(
1039 $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
1040 'hash' => $issued,
1043 // Attach badge image if possible.
1044 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
1045 $fs = get_file_storage();
1046 $file = $fs->get_file_by_hash($filepathhash);
1047 $eventdata->attachment = $file;
1048 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
1050 message_send($eventdata);
1051 } else {
1052 message_send($eventdata);
1055 // Notify badge creator about the award if they receive notifications every time.
1056 if ($badge->notification == 1) {
1057 $userfrom = core_user::get_noreply_user();
1058 $userfrom->maildisplay = true;
1060 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
1061 $a = new stdClass();
1062 $a->user = fullname($userto);
1063 $a->link = $issuedlink;
1064 $creatormessage = get_string('creatorbody', 'badges', $a);
1065 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1067 $eventdata = new \core\message\message();
1068 $eventdata->courseid = $badge->courseid;
1069 $eventdata->component = 'moodle';
1070 $eventdata->name = 'badgecreatornotice';
1071 $eventdata->userfrom = $userfrom;
1072 $eventdata->userto = $creator;
1073 $eventdata->notification = 1;
1074 $eventdata->subject = $creatorsubject;
1075 $eventdata->fullmessage = html_to_text($creatormessage);
1076 $eventdata->fullmessageformat = FORMAT_HTML;
1077 $eventdata->fullmessagehtml = $creatormessage;
1078 $eventdata->smallmessage = '';
1079 $eventdata->customdata = [
1080 'notificationiconurl' => moodle_url::make_pluginfile_url(
1081 $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
1082 'hash' => $issued,
1085 message_send($eventdata);
1086 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
1091 * Caclulates date for the next message digest to badge creators.
1093 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
1094 * @return int Timestamp for next cron
1096 function badges_calculate_message_schedule($schedule) {
1097 $nextcron = 0;
1099 switch ($schedule) {
1100 case BADGE_MESSAGE_DAILY:
1101 $nextcron = time() + 60 * 60 * 24;
1102 break;
1103 case BADGE_MESSAGE_WEEKLY:
1104 $nextcron = time() + 60 * 60 * 24 * 7;
1105 break;
1106 case BADGE_MESSAGE_MONTHLY:
1107 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
1108 break;
1111 return $nextcron;
1115 * Replaces variables in a message template and returns text ready to be emailed to a user.
1117 * @param string $message Message body.
1118 * @return string Message with replaced values
1120 function badge_message_from_template($message, $params) {
1121 $msg = $message;
1122 foreach ($params as $key => $value) {
1123 $msg = str_replace("%$key%", $value, $msg);
1126 return $msg;
1130 * Get all badges.
1132 * @param int Type of badges to return
1133 * @param int Course ID for course badges
1134 * @param string $sort An SQL field to sort by
1135 * @param string $dir The sort direction ASC|DESC
1136 * @param int $page The page or records to return
1137 * @param int $perpage The number of records to return per page
1138 * @param int $user User specific search
1139 * @return array $badge Array of records matching criteria
1141 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
1142 global $DB;
1143 $records = array();
1144 $params = array();
1145 $where = "b.status != :deleted AND b.type = :type ";
1146 $params['deleted'] = BADGE_STATUS_ARCHIVED;
1148 $userfields = array('b.id, b.name, b.status');
1149 $usersql = "";
1150 if ($user != 0) {
1151 $userfields[] = 'bi.dateissued';
1152 $userfields[] = 'bi.uniquehash';
1153 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
1154 $params['userid'] = $user;
1155 $where .= " AND (b.status = 1 OR b.status = 3) ";
1157 $fields = implode(', ', $userfields);
1159 if ($courseid != 0 ) {
1160 $where .= "AND b.courseid = :courseid ";
1161 $params['courseid'] = $courseid;
1164 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
1165 $params['type'] = $type;
1167 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
1168 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1170 $badges = array();
1171 foreach ($records as $r) {
1172 $badge = new badge($r->id);
1173 $badges[$r->id] = $badge;
1174 if ($user != 0) {
1175 $badges[$r->id]->dateissued = $r->dateissued;
1176 $badges[$r->id]->uniquehash = $r->uniquehash;
1177 } else {
1178 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
1179 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
1180 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
1181 $badges[$r->id]->statstring = $badge->get_status_name();
1184 return $badges;
1188 * Get badges for a specific user.
1190 * @param int $userid User ID
1191 * @param int $courseid Badges earned by a user in a specific course
1192 * @param int $page The page or records to return
1193 * @param int $perpage The number of records to return per page
1194 * @param string $search A simple string to search for
1195 * @param bool $onlypublic Return only public badges
1196 * @return array of badges ordered by decreasing date of issue
1198 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
1199 global $CFG, $DB;
1201 $params = array(
1202 'userid' => $userid
1204 $sql = 'SELECT
1205 bi.uniquehash,
1206 bi.dateissued,
1207 bi.dateexpire,
1208 bi.id as issuedid,
1209 bi.visible,
1210 u.email,
1212 FROM
1213 {badge} b,
1214 {badge_issued} bi,
1215 {user} u
1216 WHERE b.id = bi.badgeid
1217 AND u.id = bi.userid
1218 AND bi.userid = :userid';
1220 if (!empty($search)) {
1221 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
1222 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
1224 if ($onlypublic) {
1225 $sql .= ' AND (bi.visible = 1) ';
1228 if (empty($CFG->badges_allowcoursebadges)) {
1229 $sql .= ' AND b.courseid IS NULL';
1230 } else if ($courseid != 0) {
1231 $sql .= ' AND (b.courseid = :courseid) ';
1232 $params['courseid'] = $courseid;
1234 $sql .= ' ORDER BY bi.dateissued DESC';
1235 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1237 return $badges;
1241 * Extends the course administration navigation with the Badges page
1243 * @param navigation_node $coursenode
1244 * @param object $course
1246 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
1247 global $CFG, $SITE;
1249 $coursecontext = context_course::instance($course->id);
1250 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
1251 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
1252 'moodle/badges:createbadge',
1253 'moodle/badges:awardbadge',
1254 'moodle/badges:configurecriteria',
1255 'moodle/badges:configuremessages',
1256 'moodle/badges:configuredetails',
1257 'moodle/badges:deletebadge'), $coursecontext);
1259 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
1260 $coursenode->add(get_string('coursebadges', 'badges'), null,
1261 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
1262 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
1264 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
1266 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
1267 navigation_node::TYPE_SETTING, null, 'coursebadges');
1269 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
1270 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
1272 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
1273 navigation_node::TYPE_SETTING, null, 'newbadge');
1279 * Triggered when badge is manually awarded.
1281 * @param object $data
1282 * @return boolean
1284 function badges_award_handle_manual_criteria_review(stdClass $data) {
1285 $criteria = $data->crit;
1286 $userid = $data->userid;
1287 $badge = new badge($criteria->badgeid);
1289 if (!$badge->is_active() || $badge->is_issued($userid)) {
1290 return true;
1293 if ($criteria->review($userid)) {
1294 $criteria->mark_complete($userid);
1296 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
1297 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
1298 $badge->issue($userid);
1302 return true;
1306 * Process badge image from form data
1308 * @param badge $badge Badge object
1309 * @param string $iconfile Original file
1311 function badges_process_badge_image(badge $badge, $iconfile) {
1312 global $CFG, $USER;
1313 require_once($CFG->libdir. '/gdlib.php');
1315 if (!empty($CFG->gdversion)) {
1316 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
1317 @unlink($iconfile);
1319 // Clean up file draft area after badge image has been saved.
1320 $context = context_user::instance($USER->id, MUST_EXIST);
1321 $fs = get_file_storage();
1322 $fs->delete_area_files($context->id, 'user', 'draft');
1327 * Print badge image.
1329 * @param badge $badge Badge object
1330 * @param stdClass $context
1331 * @param string $size
1333 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1334 $fsize = ($size == 'small') ? 'f2' : 'f1';
1336 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1337 // Appending a random parameter to image link to forse browser reload the image.
1338 $imageurl->param('refresh', rand(1, 10000));
1339 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
1341 return html_writer::empty_tag('img', $attributes);
1345 * Bake issued badge.
1347 * @param string $hash Unique hash of an issued badge.
1348 * @param int $badgeid ID of the original badge.
1349 * @param int $userid ID of badge recipient (optional).
1350 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1351 * @return string|url Returns either new file path hash or new file URL
1353 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1354 global $CFG, $USER;
1355 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
1357 $badge = new badge($badgeid);
1358 $badge_context = $badge->get_context();
1359 $userid = ($userid) ? $userid : $USER->id;
1360 $user_context = context_user::instance($userid);
1362 $fs = get_file_storage();
1363 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
1364 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
1365 $contents = $file->get_content();
1367 $filehandler = new PNG_MetaDataHandler($contents);
1368 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1369 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1370 // Add assertion URL tExt chunk.
1371 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1372 $fileinfo = array(
1373 'contextid' => $user_context->id,
1374 'component' => 'badges',
1375 'filearea' => 'userbadge',
1376 'itemid' => $badge->id,
1377 'filepath' => '/',
1378 'filename' => $hash . '.png',
1381 // Create a file with added contents.
1382 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1383 if ($pathhash) {
1384 return $newfile->get_pathnamehash();
1387 } else {
1388 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1389 return;
1393 // If file exists and we just need its path hash, return it.
1394 if ($pathhash) {
1395 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1396 return $file->get_pathnamehash();
1399 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1400 return $fileurl;
1404 * Returns external backpack settings and badges from this backpack.
1406 * This function first checks if badges for the user are cached and
1407 * tries to retrieve them from the cache. Otherwise, badges are obtained
1408 * through curl request to the backpack.
1410 * @param int $userid Backpack user ID.
1411 * @param boolean $refresh Refresh badges collection in cache.
1412 * @return null|object Returns null is there is no backpack or object with backpack settings.
1414 function get_backpack_settings($userid, $refresh = false) {
1415 global $DB;
1416 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
1418 // Try to get badges from cache first.
1419 $badgescache = cache::make('core', 'externalbadges');
1420 $out = $badgescache->get($userid);
1421 if ($out !== false && !$refresh) {
1422 return $out;
1424 // Get badges through curl request to the backpack.
1425 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1426 if ($record) {
1427 $backpack = new OpenBadgesBackpackHandler($record);
1428 $out = new stdClass();
1429 $out->backpackurl = $backpack->get_url();
1431 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1432 $out->totalcollections = count($collections);
1433 $out->totalbadges = 0;
1434 $out->badges = array();
1435 foreach ($collections as $collection) {
1436 $badges = $backpack->get_badges($collection->collectionid);
1437 if (isset($badges->badges)) {
1438 $out->badges = array_merge($out->badges, $badges->badges);
1439 $out->totalbadges += count($badges->badges);
1440 } else {
1441 $out->badges = array_merge($out->badges, array());
1444 } else {
1445 $out->totalbadges = 0;
1446 $out->totalcollections = 0;
1449 $badgescache->set($userid, $out);
1450 return $out;
1453 return null;
1457 * Download all user badges in zip archive.
1459 * @param int $userid ID of badge owner.
1461 function badges_download($userid) {
1462 global $CFG, $DB;
1463 $context = context_user::instance($userid);
1464 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1466 // Get list of files to download.
1467 $fs = get_file_storage();
1468 $filelist = array();
1469 foreach ($records as $issued) {
1470 $badge = new badge($issued->badgeid);
1471 // Need to make image name user-readable and unique using filename safe characters.
1472 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1473 $name = str_replace(' ', '_', $name);
1474 $name = clean_param($name, PARAM_FILE);
1475 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1476 $filelist[$name . '.png'] = $file;
1480 // Zip files and sent them to a user.
1481 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1482 $zipper = new zip_packer();
1483 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1484 send_temp_file($tempzip, 'badges.zip');
1485 } else {
1486 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1487 die;
1492 * Checks if badges can be pushed to external backpack.
1494 * @return string Code of backpack accessibility status.
1496 function badges_check_backpack_accessibility() {
1497 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
1498 // For behat sites, do not poll the remote badge site.
1499 // Behat sites should not be available, but we should pretend as though they are.
1500 return 'available';
1503 global $CFG;
1504 include_once $CFG->libdir . '/filelib.php';
1506 // Using fake assertion url to check whether backpack can access the web site.
1507 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1509 // Curl request to backpack baker.
1510 $curl = new curl();
1511 $options = array(
1512 'FRESH_CONNECT' => true,
1513 'RETURNTRANSFER' => true,
1514 'HEADER' => 0,
1515 'CONNECTTIMEOUT' => 2,
1517 $location = BADGE_BACKPACKURL . '/baker';
1518 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1520 $data = json_decode($out);
1521 if (!empty($curl->error)) {
1522 return 'curl-request-timeout';
1523 } else {
1524 if (isset($data->code) && $data->code == 'http-unreachable') {
1525 return 'http-unreachable';
1526 } else {
1527 return 'available';
1531 return false;
1535 * Checks if user has external backpack connected.
1537 * @param int $userid ID of a user.
1538 * @return bool True|False whether backpack connection exists.
1540 function badges_user_has_backpack($userid) {
1541 global $DB;
1542 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1546 * Handles what happens to the course badges when a course is deleted.
1548 * @param int $courseid course ID.
1549 * @return void.
1551 function badges_handle_course_deletion($courseid) {
1552 global $CFG, $DB;
1553 include_once $CFG->libdir . '/filelib.php';
1555 $systemcontext = context_system::instance();
1556 $coursecontext = context_course::instance($courseid);
1557 $fs = get_file_storage();
1559 // Move badges images to the system context.
1560 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1562 // Get all course badges.
1563 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1564 foreach ($badges as $badge) {
1565 // Archive badges in this course.
1566 $toupdate = new stdClass();
1567 $toupdate->id = $badge->id;
1568 $toupdate->type = BADGE_TYPE_SITE;
1569 $toupdate->courseid = null;
1570 $toupdate->status = BADGE_STATUS_ARCHIVED;
1571 $DB->update_record('badge', $toupdate);
1576 * Loads JS files required for backpack support.
1578 * @uses $CFG, $PAGE
1579 * @return void
1581 function badges_setup_backpack_js() {
1582 global $CFG, $PAGE;
1583 if (!empty($CFG->badges_allowexternalbackpack)) {
1584 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
1585 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
1586 $PAGE->requires->js('/badges/backpack.js', true);
1591 * Return all the enabled criteria types for this site.
1593 * @param boolean $enabled
1594 * @return array
1596 function badges_list_criteria($enabled = true) {
1597 global $CFG;
1599 $types = array(
1600 BADGE_CRITERIA_TYPE_OVERALL => 'overall',
1601 BADGE_CRITERIA_TYPE_ACTIVITY => 'activity',
1602 BADGE_CRITERIA_TYPE_MANUAL => 'manual',
1603 BADGE_CRITERIA_TYPE_SOCIAL => 'social',
1604 BADGE_CRITERIA_TYPE_COURSE => 'course',
1605 BADGE_CRITERIA_TYPE_COURSESET => 'courseset',
1606 BADGE_CRITERIA_TYPE_PROFILE => 'profile',
1607 BADGE_CRITERIA_TYPE_BADGE => 'badge',
1608 BADGE_CRITERIA_TYPE_COHORT => 'cohort',
1609 BADGE_CRITERIA_TYPE_COMPETENCY => 'competency',
1611 if ($enabled) {
1612 foreach ($types as $key => $type) {
1613 $class = 'award_criteria_' . $type;
1614 $file = $CFG->dirroot . '/badges/criteria/' . $class . '.php';
1615 if (file_exists($file)) {
1616 require_once($file);
1618 if (!$class::is_enabled()) {
1619 unset($types[$key]);
1624 return $types;
1628 * Check if any badge has records for competencies.
1630 * @param array $competencyids Array of competencies ids.
1631 * @return boolean Return true if competencies were found in any badge.
1633 function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1634 global $DB;
1636 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED);
1638 $sql = "SELECT DISTINCT bc.badgeid
1639 FROM {badge_criteria} bc
1640 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1641 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1642 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY;
1644 return $DB->record_exists_sql($sql, $params);
1648 * Creates single message for all notification and sends it out
1650 * @param object $badge A badge which is notified about.
1652 function badge_assemble_notification(stdClass $badge) {
1653 global $DB;
1655 $userfrom = core_user::get_noreply_user();
1656 $userfrom->maildisplay = true;
1658 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id))) {
1659 // Get badge creator.
1660 $creator = $DB->get_record('user', array('id' => $badge->creator), '*', MUST_EXIST);
1661 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1662 $creatormessage = '';
1664 // Put all messages in one digest.
1665 foreach ($msgs as $msg) {
1666 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash)), $badge->name);
1667 $recipient = $DB->get_record('user', array('id' => $msg->userid), '*', MUST_EXIST);
1669 $a = new stdClass();
1670 $a->user = fullname($recipient);
1671 $a->link = $issuedlink;
1672 $creatormessage .= get_string('creatorbody', 'badges', $a);
1673 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid, 'userid' => $msg->userid));
1676 // Create a message object.
1677 $eventdata = new \core\message\message();
1678 $eventdata->courseid = SITEID;
1679 $eventdata->component = 'moodle';
1680 $eventdata->name = 'badgecreatornotice';
1681 $eventdata->userfrom = $userfrom;
1682 $eventdata->userto = $creator;
1683 $eventdata->notification = 1;
1684 $eventdata->subject = $creatorsubject;
1685 $eventdata->fullmessage = format_text_email($creatormessage, FORMAT_HTML);
1686 $eventdata->fullmessageformat = FORMAT_PLAIN;
1687 $eventdata->fullmessagehtml = $creatormessage;
1688 $eventdata->smallmessage = $creatorsubject;
1690 message_send($eventdata);