Merge branch 'MDL-62945-master' of https://github.com/HuongNV13/moodle
[moodle.git] / lib / badgeslib.php
blobddbdbfb1b62413d1e78e1e403470a10cd5f46cec
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 * Class that represents badge.
105 class badge {
106 /** @var int Badge id */
107 public $id;
109 /** Values from the table 'badge' */
110 public $name;
111 public $description;
112 public $timecreated;
113 public $timemodified;
114 public $usercreated;
115 public $usermodified;
116 public $issuername;
117 public $issuerurl;
118 public $issuercontact;
119 public $expiredate;
120 public $expireperiod;
121 public $type;
122 public $courseid;
123 public $message;
124 public $messagesubject;
125 public $attachment;
126 public $notification;
127 public $status = 0;
128 public $nextcron;
130 /** @var array Badge criteria */
131 public $criteria = array();
134 * Constructs with badge details.
136 * @param int $badgeid badge ID.
138 public function __construct($badgeid) {
139 global $DB;
140 $this->id = $badgeid;
142 $data = $DB->get_record('badge', array('id' => $badgeid));
144 if (empty($data)) {
145 print_error('error:nosuchbadge', 'badges', $badgeid);
148 foreach ((array)$data as $field => $value) {
149 if (property_exists($this, $field)) {
150 $this->{$field} = $value;
154 $this->criteria = self::get_criteria();
158 * Use to get context instance of a badge.
159 * @return context instance.
161 public function get_context() {
162 if ($this->type == BADGE_TYPE_SITE) {
163 return context_system::instance();
164 } else if ($this->type == BADGE_TYPE_COURSE) {
165 return context_course::instance($this->courseid);
166 } else {
167 debugging('Something is wrong...');
172 * Return array of aggregation methods
173 * @return array
175 public static function get_aggregation_methods() {
176 return array(
177 BADGE_CRITERIA_AGGREGATION_ALL => get_string('all', 'badges'),
178 BADGE_CRITERIA_AGGREGATION_ANY => get_string('any', 'badges'),
183 * Return array of accepted criteria types for this badge
184 * @return array
186 public function get_accepted_criteria() {
187 $criteriatypes = array();
189 if ($this->type == BADGE_TYPE_COURSE) {
190 $criteriatypes = array(
191 BADGE_CRITERIA_TYPE_OVERALL,
192 BADGE_CRITERIA_TYPE_MANUAL,
193 BADGE_CRITERIA_TYPE_COURSE,
194 BADGE_CRITERIA_TYPE_BADGE,
195 BADGE_CRITERIA_TYPE_ACTIVITY
197 } else if ($this->type == BADGE_TYPE_SITE) {
198 $criteriatypes = array(
199 BADGE_CRITERIA_TYPE_OVERALL,
200 BADGE_CRITERIA_TYPE_MANUAL,
201 BADGE_CRITERIA_TYPE_COURSESET,
202 BADGE_CRITERIA_TYPE_BADGE,
203 BADGE_CRITERIA_TYPE_PROFILE,
204 BADGE_CRITERIA_TYPE_COHORT,
208 return $criteriatypes;
212 * Save/update badge information in 'badge' table only.
213 * Cannot be used for updating awards and criteria settings.
215 * @return bool Returns true on success.
217 public function save() {
218 global $DB;
220 $fordb = new stdClass();
221 foreach (get_object_vars($this) as $k => $v) {
222 $fordb->{$k} = $v;
224 unset($fordb->criteria);
226 $fordb->timemodified = time();
227 if ($DB->update_record_raw('badge', $fordb)) {
228 // Trigger event, badge updated.
229 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
230 $event = \core\event\badge_updated::create($eventparams);
231 $event->trigger();
232 return true;
233 } else {
234 throw new moodle_exception('error:save', 'badges');
235 return false;
240 * Creates and saves a clone of badge with all its properties.
241 * Clone is not active by default and has 'Copy of' attached to its name.
243 * @return int ID of new badge.
245 public function make_clone() {
246 global $DB, $USER, $PAGE;
248 $fordb = new stdClass();
249 foreach (get_object_vars($this) as $k => $v) {
250 $fordb->{$k} = $v;
253 $fordb->name = get_string('copyof', 'badges', $this->name);
254 $fordb->status = BADGE_STATUS_INACTIVE;
255 $fordb->usercreated = $USER->id;
256 $fordb->usermodified = $USER->id;
257 $fordb->timecreated = time();
258 $fordb->timemodified = time();
259 unset($fordb->id);
261 if ($fordb->notification > 1) {
262 $fordb->nextcron = badges_calculate_message_schedule($fordb->notification);
265 $criteria = $fordb->criteria;
266 unset($fordb->criteria);
268 if ($new = $DB->insert_record('badge', $fordb, true)) {
269 $newbadge = new badge($new);
271 // Copy badge image.
272 $fs = get_file_storage();
273 if ($file = $fs->get_file($this->get_context()->id, 'badges', 'badgeimage', $this->id, '/', 'f1.png')) {
274 if ($imagefile = $file->copy_content_to_temp()) {
275 badges_process_badge_image($newbadge, $imagefile);
279 // Copy badge criteria.
280 foreach ($this->criteria as $crit) {
281 $crit->make_clone($new);
284 // Trigger event, badge duplicated.
285 $eventparams = array('objectid' => $new, 'context' => $PAGE->context);
286 $event = \core\event\badge_duplicated::create($eventparams);
287 $event->trigger();
289 return $new;
290 } else {
291 throw new moodle_exception('error:clone', 'badges');
292 return false;
297 * Checks if badges is active.
298 * Used in badge award.
300 * @return bool A status indicating badge is active
302 public function is_active() {
303 if (($this->status == BADGE_STATUS_ACTIVE) ||
304 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
305 return true;
307 return false;
311 * Use to get the name of badge status.
314 public function get_status_name() {
315 return get_string('badgestatus_' . $this->status, 'badges');
319 * Use to set badge status.
320 * Only active badges can be earned/awarded/issued.
322 * @param int $status Status from BADGE_STATUS constants
324 public function set_status($status = 0) {
325 $this->status = $status;
326 $this->save();
327 if ($status == BADGE_STATUS_ACTIVE) {
328 // Trigger event, badge enabled.
329 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
330 $event = \core\event\badge_enabled::create($eventparams);
331 $event->trigger();
332 } else if ($status == BADGE_STATUS_INACTIVE) {
333 // Trigger event, badge disabled.
334 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
335 $event = \core\event\badge_disabled::create($eventparams);
336 $event->trigger();
341 * Checks if badges is locked.
342 * Used in badge award and editing.
344 * @return bool A status indicating badge is locked
346 public function is_locked() {
347 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
348 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
349 return true;
351 return false;
355 * Checks if badge has been awarded to users.
356 * Used in badge editing.
358 * @return bool A status indicating badge has been awarded at least once
360 public function has_awards() {
361 global $DB;
362 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
363 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
364 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
366 return $awarded;
370 * Gets list of users who have earned an instance of this badge.
372 * @return array An array of objects with information about badge awards.
374 public function get_awards() {
375 global $DB;
377 $awards = $DB->get_records_sql(
378 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
379 FROM {badge_issued} b INNER JOIN {user} u
380 ON b.userid = u.id
381 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
383 return $awards;
387 * Indicates whether badge has already been issued to a user.
390 public function is_issued($userid) {
391 global $DB;
392 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
396 * Issue a badge to user.
398 * @param int $userid User who earned the badge
399 * @param bool $nobake Not baking actual badges (for testing purposes)
401 public function issue($userid, $nobake = false) {
402 global $DB, $CFG;
404 $now = time();
405 $issued = new stdClass();
406 $issued->badgeid = $this->id;
407 $issued->userid = $userid;
408 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
409 $issued->dateissued = $now;
411 if ($this->can_expire()) {
412 $issued->dateexpire = $this->calculate_expiry($now);
413 } else {
414 $issued->dateexpire = null;
417 // Take into account user badges privacy settings.
418 // If none set, badges default visibility is set to public.
419 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
421 $result = $DB->insert_record('badge_issued', $issued, true);
423 if ($result) {
424 // Trigger badge awarded event.
425 $eventdata = array (
426 'context' => $this->get_context(),
427 'objectid' => $this->id,
428 'relateduserid' => $userid,
429 'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
431 \core\event\badge_awarded::create($eventdata)->trigger();
433 // Lock the badge, so that its criteria could not be changed any more.
434 if ($this->status == BADGE_STATUS_ACTIVE) {
435 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
438 // Update details in criteria_met table.
439 $compl = $this->get_criteria_completions($userid);
440 foreach ($compl as $c) {
441 $obj = new stdClass();
442 $obj->id = $c->id;
443 $obj->issuedid = $result;
444 $DB->update_record('badge_criteria_met', $obj, true);
447 if (!$nobake) {
448 // Bake a badge image.
449 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
451 // Notify recipients and badge creators.
452 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
458 * Reviews all badge criteria and checks if badge can be instantly awarded.
460 * @return int Number of awards
462 public function review_all_criteria() {
463 global $DB, $CFG;
464 $awards = 0;
466 // Raise timelimit as this could take a while for big web sites.
467 core_php_time_limit::raise();
468 raise_memory_limit(MEMORY_HUGE);
470 foreach ($this->criteria as $crit) {
471 // Overall criterion is decided when other criteria are reviewed.
472 if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
473 continue;
476 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
477 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
478 if ($this->type == BADGE_TYPE_SITE) {
479 $sql = "SELECT DISTINCT u.id, bi.badgeid
480 FROM {user} u
481 {$extrajoin}
482 LEFT JOIN {badge_issued} bi
483 ON u.id = bi.userid AND bi.badgeid = :badgeid
484 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
485 $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
486 $toearn = $DB->get_fieldset_sql($sql, $params);
487 } else {
488 // For course level badges, get all users who already earned the badge in this course.
489 // Then find the ones who are enrolled in the course and don't have a badge yet.
490 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
491 $wheresql = '';
492 $earnedparams = array();
493 if (!empty($earned)) {
494 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
495 $wheresql = ' WHERE u.id ' . $earnedsql;
497 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
498 $sql = "SELECT DISTINCT u.id
499 FROM {user} u
500 {$extrajoin}
501 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
502 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
503 $toearn = $DB->get_fieldset_sql($sql, $params);
506 foreach ($toearn as $uid) {
507 $reviewoverall = false;
508 if ($crit->review($uid, true)) {
509 $crit->mark_complete($uid);
510 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
511 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
512 $this->issue($uid);
513 $awards++;
514 } else {
515 $reviewoverall = true;
517 } else {
518 // Will be reviewed some other time.
519 $reviewoverall = false;
521 // Review overall if it is required.
522 if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
523 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
524 $this->issue($uid);
525 $awards++;
530 return $awards;
534 * Gets an array of completed criteria from 'badge_criteria_met' table.
536 * @param int $userid Completions for a user
537 * @return array Records of criteria completions
539 public function get_criteria_completions($userid) {
540 global $DB;
541 $completions = array();
542 $sql = "SELECT bcm.id, bcm.critid
543 FROM {badge_criteria_met} bcm
544 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
545 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
546 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
548 return $completions;
552 * Checks if badges has award criteria set up.
554 * @return bool A status indicating badge has at least one criterion
556 public function has_criteria() {
557 if (count($this->criteria) > 0) {
558 return true;
560 return false;
564 * Returns badge award criteria
566 * @return array An array of badge criteria
568 public function get_criteria() {
569 global $DB;
570 $criteria = array();
572 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
573 foreach ($records as $record) {
574 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
578 return $criteria;
582 * Get aggregation method for badge criteria
584 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
585 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
587 public function get_aggregation_method($criteriatype = 0) {
588 global $DB;
589 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
590 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
592 if (!$aggregation) {
593 return BADGE_CRITERIA_AGGREGATION_ALL;
596 return $aggregation;
600 * Checks if badge has expiry period or date set up.
602 * @return bool A status indicating badge can expire
604 public function can_expire() {
605 if ($this->expireperiod || $this->expiredate) {
606 return true;
608 return false;
612 * Calculates badge expiry date based on either expirydate or expiryperiod.
614 * @param int $timestamp Time of badge issue
615 * @return int A timestamp
617 public function calculate_expiry($timestamp) {
618 $expiry = null;
620 if (isset($this->expiredate)) {
621 $expiry = $this->expiredate;
622 } else if (isset($this->expireperiod)) {
623 $expiry = $timestamp + $this->expireperiod;
626 return $expiry;
630 * Checks if badge has manual award criteria set.
632 * @return bool A status indicating badge can be awarded manually
634 public function has_manual_award_criteria() {
635 foreach ($this->criteria as $criterion) {
636 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
637 return true;
640 return false;
644 * Fully deletes the badge or marks it as archived.
646 * @param $archive bool Achive a badge without actual deleting of any data.
648 public function delete($archive = true) {
649 global $DB;
651 if ($archive) {
652 $this->status = BADGE_STATUS_ARCHIVED;
653 $this->save();
655 // Trigger event, badge archived.
656 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
657 $event = \core\event\badge_archived::create($eventparams);
658 $event->trigger();
659 return;
662 $fs = get_file_storage();
664 // Remove all issued badge image files and badge awards.
665 // Cannot bulk remove area files here because they are issued in user context.
666 $awards = $this->get_awards();
667 foreach ($awards as $award) {
668 $usercontext = context_user::instance($award->userid);
669 $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
671 $DB->delete_records('badge_issued', array('badgeid' => $this->id));
673 // Remove all badge criteria.
674 $criteria = $this->get_criteria();
675 foreach ($criteria as $criterion) {
676 $criterion->delete();
679 // Delete badge images.
680 $badgecontext = $this->get_context();
681 $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
683 // Finally, remove badge itself.
684 $DB->delete_records('badge', array('id' => $this->id));
686 // Trigger event, badge deleted.
687 $eventparams = array('objectid' => $this->id,
688 'context' => $this->get_context(),
689 'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
691 $event = \core\event\badge_deleted::create($eventparams);
692 $event->trigger();
697 * Sends notifications to users about awarded badges.
699 * @param badge $badge Badge that was issued
700 * @param int $userid Recipient ID
701 * @param string $issued Unique hash of an issued badge
702 * @param string $filepathhash File path hash of an issued badge for attachments
704 function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
705 global $CFG, $DB;
707 $admin = get_admin();
708 $userfrom = new stdClass();
709 $userfrom->id = $admin->id;
710 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
711 foreach (get_all_user_name_fields() as $addname) {
712 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
714 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
715 $userfrom->maildisplay = true;
717 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
718 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
720 $params = new stdClass();
721 $params->badgename = $badge->name;
722 $params->username = fullname($userto);
723 $params->badgelink = $issuedlink;
724 $message = badge_message_from_template($badge->message, $params);
725 $plaintext = html_to_text($message);
727 // Notify recipient.
728 $eventdata = new \core\message\message();
729 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
730 $eventdata->component = 'moodle';
731 $eventdata->name = 'badgerecipientnotice';
732 $eventdata->userfrom = $userfrom;
733 $eventdata->userto = $userto;
734 $eventdata->notification = 1;
735 $eventdata->subject = $badge->messagesubject;
736 $eventdata->fullmessage = $plaintext;
737 $eventdata->fullmessageformat = FORMAT_HTML;
738 $eventdata->fullmessagehtml = $message;
739 $eventdata->smallmessage = '';
741 // Attach badge image if possible.
742 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
743 $fs = get_file_storage();
744 $file = $fs->get_file_by_hash($filepathhash);
745 $eventdata->attachment = $file;
746 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
748 message_send($eventdata);
749 } else {
750 message_send($eventdata);
753 // Notify badge creator about the award if they receive notifications every time.
754 if ($badge->notification == 1) {
755 $userfrom = core_user::get_noreply_user();
756 $userfrom->maildisplay = true;
758 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
759 $a = new stdClass();
760 $a->user = fullname($userto);
761 $a->link = $issuedlink;
762 $creatormessage = get_string('creatorbody', 'badges', $a);
763 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
765 $eventdata = new \core\message\message();
766 $eventdata->courseid = $badge->courseid;
767 $eventdata->component = 'moodle';
768 $eventdata->name = 'badgecreatornotice';
769 $eventdata->userfrom = $userfrom;
770 $eventdata->userto = $creator;
771 $eventdata->notification = 1;
772 $eventdata->subject = $creatorsubject;
773 $eventdata->fullmessage = html_to_text($creatormessage);
774 $eventdata->fullmessageformat = FORMAT_HTML;
775 $eventdata->fullmessagehtml = $creatormessage;
776 $eventdata->smallmessage = '';
778 message_send($eventdata);
779 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
784 * Caclulates date for the next message digest to badge creators.
786 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
787 * @return int Timestamp for next cron
789 function badges_calculate_message_schedule($schedule) {
790 $nextcron = 0;
792 switch ($schedule) {
793 case BADGE_MESSAGE_DAILY:
794 $nextcron = time() + 60 * 60 * 24;
795 break;
796 case BADGE_MESSAGE_WEEKLY:
797 $nextcron = time() + 60 * 60 * 24 * 7;
798 break;
799 case BADGE_MESSAGE_MONTHLY:
800 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
801 break;
804 return $nextcron;
808 * Replaces variables in a message template and returns text ready to be emailed to a user.
810 * @param string $message Message body.
811 * @return string Message with replaced values
813 function badge_message_from_template($message, $params) {
814 $msg = $message;
815 foreach ($params as $key => $value) {
816 $msg = str_replace("%$key%", $value, $msg);
819 return $msg;
823 * Get all badges.
825 * @param int Type of badges to return
826 * @param int Course ID for course badges
827 * @param string $sort An SQL field to sort by
828 * @param string $dir The sort direction ASC|DESC
829 * @param int $page The page or records to return
830 * @param int $perpage The number of records to return per page
831 * @param int $user User specific search
832 * @return array $badge Array of records matching criteria
834 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
835 global $DB;
836 $records = array();
837 $params = array();
838 $where = "b.status != :deleted AND b.type = :type ";
839 $params['deleted'] = BADGE_STATUS_ARCHIVED;
841 $userfields = array('b.id, b.name, b.status');
842 $usersql = "";
843 if ($user != 0) {
844 $userfields[] = 'bi.dateissued';
845 $userfields[] = 'bi.uniquehash';
846 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
847 $params['userid'] = $user;
848 $where .= " AND (b.status = 1 OR b.status = 3) ";
850 $fields = implode(', ', $userfields);
852 if ($courseid != 0 ) {
853 $where .= "AND b.courseid = :courseid ";
854 $params['courseid'] = $courseid;
857 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
858 $params['type'] = $type;
860 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
861 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
863 $badges = array();
864 foreach ($records as $r) {
865 $badge = new badge($r->id);
866 $badges[$r->id] = $badge;
867 if ($user != 0) {
868 $badges[$r->id]->dateissued = $r->dateissued;
869 $badges[$r->id]->uniquehash = $r->uniquehash;
870 } else {
871 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
872 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
873 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
874 $badges[$r->id]->statstring = $badge->get_status_name();
877 return $badges;
881 * Get badges for a specific user.
883 * @param int $userid User ID
884 * @param int $courseid Badges earned by a user in a specific course
885 * @param int $page The page or records to return
886 * @param int $perpage The number of records to return per page
887 * @param string $search A simple string to search for
888 * @param bool $onlypublic Return only public badges
889 * @return array of badges ordered by decreasing date of issue
891 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
892 global $CFG, $DB;
894 $params = array(
895 'userid' => $userid
897 $sql = 'SELECT
898 bi.uniquehash,
899 bi.dateissued,
900 bi.dateexpire,
901 bi.id as issuedid,
902 bi.visible,
903 u.email,
905 FROM
906 {badge} b,
907 {badge_issued} bi,
908 {user} u
909 WHERE b.id = bi.badgeid
910 AND u.id = bi.userid
911 AND bi.userid = :userid';
913 if (!empty($search)) {
914 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
915 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
917 if ($onlypublic) {
918 $sql .= ' AND (bi.visible = 1) ';
921 if (empty($CFG->badges_allowcoursebadges)) {
922 $sql .= ' AND b.courseid IS NULL';
923 } else if ($courseid != 0) {
924 $sql .= ' AND (b.courseid = :courseid) ';
925 $params['courseid'] = $courseid;
927 $sql .= ' ORDER BY bi.dateissued DESC';
928 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
930 return $badges;
934 * Extends the course administration navigation with the Badges page
936 * @param navigation_node $coursenode
937 * @param object $course
939 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
940 global $CFG, $SITE;
942 $coursecontext = context_course::instance($course->id);
943 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
944 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
945 'moodle/badges:createbadge',
946 'moodle/badges:awardbadge',
947 'moodle/badges:configurecriteria',
948 'moodle/badges:configuremessages',
949 'moodle/badges:configuredetails',
950 'moodle/badges:deletebadge'), $coursecontext);
952 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
953 $coursenode->add(get_string('coursebadges', 'badges'), null,
954 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
955 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
957 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
959 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
960 navigation_node::TYPE_SETTING, null, 'coursebadges');
962 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
963 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
965 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
966 navigation_node::TYPE_SETTING, null, 'newbadge');
972 * Triggered when badge is manually awarded.
974 * @param object $data
975 * @return boolean
977 function badges_award_handle_manual_criteria_review(stdClass $data) {
978 $criteria = $data->crit;
979 $userid = $data->userid;
980 $badge = new badge($criteria->badgeid);
982 if (!$badge->is_active() || $badge->is_issued($userid)) {
983 return true;
986 if ($criteria->review($userid)) {
987 $criteria->mark_complete($userid);
989 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
990 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
991 $badge->issue($userid);
995 return true;
999 * Process badge image from form data
1001 * @param badge $badge Badge object
1002 * @param string $iconfile Original file
1004 function badges_process_badge_image(badge $badge, $iconfile) {
1005 global $CFG, $USER;
1006 require_once($CFG->libdir. '/gdlib.php');
1008 if (!empty($CFG->gdversion)) {
1009 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
1010 @unlink($iconfile);
1012 // Clean up file draft area after badge image has been saved.
1013 $context = context_user::instance($USER->id, MUST_EXIST);
1014 $fs = get_file_storage();
1015 $fs->delete_area_files($context->id, 'user', 'draft');
1020 * Print badge image.
1022 * @param badge $badge Badge object
1023 * @param stdClass $context
1024 * @param string $size
1026 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1027 $fsize = ($size == 'small') ? 'f2' : 'f1';
1029 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1030 // Appending a random parameter to image link to forse browser reload the image.
1031 $imageurl->param('refresh', rand(1, 10000));
1032 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
1034 return html_writer::empty_tag('img', $attributes);
1038 * Bake issued badge.
1040 * @param string $hash Unique hash of an issued badge.
1041 * @param int $badgeid ID of the original badge.
1042 * @param int $userid ID of badge recipient (optional).
1043 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1044 * @return string|url Returns either new file path hash or new file URL
1046 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1047 global $CFG, $USER;
1048 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
1050 $badge = new badge($badgeid);
1051 $badge_context = $badge->get_context();
1052 $userid = ($userid) ? $userid : $USER->id;
1053 $user_context = context_user::instance($userid);
1055 $fs = get_file_storage();
1056 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
1057 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f1.png')) {
1058 $contents = $file->get_content();
1060 $filehandler = new PNG_MetaDataHandler($contents);
1061 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1062 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1063 // Add assertion URL tExt chunk.
1064 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1065 $fileinfo = array(
1066 'contextid' => $user_context->id,
1067 'component' => 'badges',
1068 'filearea' => 'userbadge',
1069 'itemid' => $badge->id,
1070 'filepath' => '/',
1071 'filename' => $hash . '.png',
1074 // Create a file with added contents.
1075 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1076 if ($pathhash) {
1077 return $newfile->get_pathnamehash();
1080 } else {
1081 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1082 return;
1086 // If file exists and we just need its path hash, return it.
1087 if ($pathhash) {
1088 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1089 return $file->get_pathnamehash();
1092 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1093 return $fileurl;
1097 * Returns external backpack settings and badges from this backpack.
1099 * This function first checks if badges for the user are cached and
1100 * tries to retrieve them from the cache. Otherwise, badges are obtained
1101 * through curl request to the backpack.
1103 * @param int $userid Backpack user ID.
1104 * @param boolean $refresh Refresh badges collection in cache.
1105 * @return null|object Returns null is there is no backpack or object with backpack settings.
1107 function get_backpack_settings($userid, $refresh = false) {
1108 global $DB;
1109 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
1111 // Try to get badges from cache first.
1112 $badgescache = cache::make('core', 'externalbadges');
1113 $out = $badgescache->get($userid);
1114 if ($out !== false && !$refresh) {
1115 return $out;
1117 // Get badges through curl request to the backpack.
1118 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1119 if ($record) {
1120 $backpack = new OpenBadgesBackpackHandler($record);
1121 $out = new stdClass();
1122 $out->backpackurl = $backpack->get_url();
1124 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1125 $out->totalcollections = count($collections);
1126 $out->totalbadges = 0;
1127 $out->badges = array();
1128 foreach ($collections as $collection) {
1129 $badges = $backpack->get_badges($collection->collectionid);
1130 if (isset($badges->badges)) {
1131 $out->badges = array_merge($out->badges, $badges->badges);
1132 $out->totalbadges += count($badges->badges);
1133 } else {
1134 $out->badges = array_merge($out->badges, array());
1137 } else {
1138 $out->totalbadges = 0;
1139 $out->totalcollections = 0;
1142 $badgescache->set($userid, $out);
1143 return $out;
1146 return null;
1150 * Download all user badges in zip archive.
1152 * @param int $userid ID of badge owner.
1154 function badges_download($userid) {
1155 global $CFG, $DB;
1156 $context = context_user::instance($userid);
1157 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1159 // Get list of files to download.
1160 $fs = get_file_storage();
1161 $filelist = array();
1162 foreach ($records as $issued) {
1163 $badge = new badge($issued->badgeid);
1164 // Need to make image name user-readable and unique using filename safe characters.
1165 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1166 $name = str_replace(' ', '_', $name);
1167 $name = clean_param($name, PARAM_FILE);
1168 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1169 $filelist[$name . '.png'] = $file;
1173 // Zip files and sent them to a user.
1174 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1175 $zipper = new zip_packer();
1176 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1177 send_temp_file($tempzip, 'badges.zip');
1178 } else {
1179 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1180 die;
1185 * Checks if badges can be pushed to external backpack.
1187 * @return string Code of backpack accessibility status.
1189 function badges_check_backpack_accessibility() {
1190 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
1191 // For behat sites, do not poll the remote badge site.
1192 // Behat sites should not be available, but we should pretend as though they are.
1193 return 'available';
1196 global $CFG;
1197 include_once $CFG->libdir . '/filelib.php';
1199 // Using fake assertion url to check whether backpack can access the web site.
1200 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1202 // Curl request to backpack baker.
1203 $curl = new curl();
1204 $options = array(
1205 'FRESH_CONNECT' => true,
1206 'RETURNTRANSFER' => true,
1207 'HEADER' => 0,
1208 'CONNECTTIMEOUT' => 2,
1210 $location = BADGE_BACKPACKURL . '/baker';
1211 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1213 $data = json_decode($out);
1214 if (!empty($curl->error)) {
1215 return 'curl-request-timeout';
1216 } else {
1217 if (isset($data->code) && $data->code == 'http-unreachable') {
1218 return 'http-unreachable';
1219 } else {
1220 return 'available';
1224 return false;
1228 * Checks if user has external backpack connected.
1230 * @param int $userid ID of a user.
1231 * @return bool True|False whether backpack connection exists.
1233 function badges_user_has_backpack($userid) {
1234 global $DB;
1235 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1239 * Handles what happens to the course badges when a course is deleted.
1241 * @param int $courseid course ID.
1242 * @return void.
1244 function badges_handle_course_deletion($courseid) {
1245 global $CFG, $DB;
1246 include_once $CFG->libdir . '/filelib.php';
1248 $systemcontext = context_system::instance();
1249 $coursecontext = context_course::instance($courseid);
1250 $fs = get_file_storage();
1252 // Move badges images to the system context.
1253 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1255 // Get all course badges.
1256 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1257 foreach ($badges as $badge) {
1258 // Archive badges in this course.
1259 $toupdate = new stdClass();
1260 $toupdate->id = $badge->id;
1261 $toupdate->type = BADGE_TYPE_SITE;
1262 $toupdate->courseid = null;
1263 $toupdate->status = BADGE_STATUS_ARCHIVED;
1264 $DB->update_record('badge', $toupdate);
1269 * Loads JS files required for backpack support.
1271 * @uses $CFG, $PAGE
1272 * @return void
1274 function badges_setup_backpack_js() {
1275 global $CFG, $PAGE;
1276 if (!empty($CFG->badges_allowexternalbackpack)) {
1277 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
1278 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
1279 $PAGE->requires->js('/badges/backpack.js', true);