MDL-61364 core: fix cibot coding issues
[moodle.git] / lib / badgeslib.php
blobaa5efbb4a3b59c0e4c19cd3ebb05e3a86b4e876d
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,
207 return $criteriatypes;
211 * Save/update badge information in 'badge' table only.
212 * Cannot be used for updating awards and criteria settings.
214 * @return bool Returns true on success.
216 public function save() {
217 global $DB;
219 $fordb = new stdClass();
220 foreach (get_object_vars($this) as $k => $v) {
221 $fordb->{$k} = $v;
223 unset($fordb->criteria);
225 $fordb->timemodified = time();
226 if ($DB->update_record_raw('badge', $fordb)) {
227 // Trigger event, badge updated.
228 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
229 $event = \core\event\badge_updated::create($eventparams);
230 $event->trigger();
231 return true;
232 } else {
233 throw new moodle_exception('error:save', 'badges');
234 return false;
239 * Creates and saves a clone of badge with all its properties.
240 * Clone is not active by default and has 'Copy of' attached to its name.
242 * @return int ID of new badge.
244 public function make_clone() {
245 global $DB, $USER, $PAGE;
247 $fordb = new stdClass();
248 foreach (get_object_vars($this) as $k => $v) {
249 $fordb->{$k} = $v;
252 $fordb->name = get_string('copyof', 'badges', $this->name);
253 $fordb->status = BADGE_STATUS_INACTIVE;
254 $fordb->usercreated = $USER->id;
255 $fordb->usermodified = $USER->id;
256 $fordb->timecreated = time();
257 $fordb->timemodified = time();
258 unset($fordb->id);
260 if ($fordb->notification > 1) {
261 $fordb->nextcron = badges_calculate_message_schedule($fordb->notification);
264 $criteria = $fordb->criteria;
265 unset($fordb->criteria);
267 if ($new = $DB->insert_record('badge', $fordb, true)) {
268 $newbadge = new badge($new);
270 // Copy badge image.
271 $fs = get_file_storage();
272 if ($file = $fs->get_file($this->get_context()->id, 'badges', 'badgeimage', $this->id, '/', 'f1.png')) {
273 if ($imagefile = $file->copy_content_to_temp()) {
274 badges_process_badge_image($newbadge, $imagefile);
278 // Copy badge criteria.
279 foreach ($this->criteria as $crit) {
280 $crit->make_clone($new);
283 // Trigger event, badge duplicated.
284 $eventparams = array('objectid' => $new, 'context' => $PAGE->context);
285 $event = \core\event\badge_duplicated::create($eventparams);
286 $event->trigger();
288 return $new;
289 } else {
290 throw new moodle_exception('error:clone', 'badges');
291 return false;
296 * Checks if badges is active.
297 * Used in badge award.
299 * @return bool A status indicating badge is active
301 public function is_active() {
302 if (($this->status == BADGE_STATUS_ACTIVE) ||
303 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
304 return true;
306 return false;
310 * Use to get the name of badge status.
313 public function get_status_name() {
314 return get_string('badgestatus_' . $this->status, 'badges');
318 * Use to set badge status.
319 * Only active badges can be earned/awarded/issued.
321 * @param int $status Status from BADGE_STATUS constants
323 public function set_status($status = 0) {
324 $this->status = $status;
325 $this->save();
326 if ($status == BADGE_STATUS_ACTIVE) {
327 // Trigger event, badge enabled.
328 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
329 $event = \core\event\badge_enabled::create($eventparams);
330 $event->trigger();
331 } else if ($status == BADGE_STATUS_INACTIVE) {
332 // Trigger event, badge disabled.
333 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
334 $event = \core\event\badge_disabled::create($eventparams);
335 $event->trigger();
340 * Checks if badges is locked.
341 * Used in badge award and editing.
343 * @return bool A status indicating badge is locked
345 public function is_locked() {
346 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
347 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
348 return true;
350 return false;
354 * Checks if badge has been awarded to users.
355 * Used in badge editing.
357 * @return bool A status indicating badge has been awarded at least once
359 public function has_awards() {
360 global $DB;
361 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
362 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
363 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
365 return $awarded;
369 * Gets list of users who have earned an instance of this badge.
371 * @return array An array of objects with information about badge awards.
373 public function get_awards() {
374 global $DB;
376 $awards = $DB->get_records_sql(
377 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
378 FROM {badge_issued} b INNER JOIN {user} u
379 ON b.userid = u.id
380 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
382 return $awards;
386 * Indicates whether badge has already been issued to a user.
389 public function is_issued($userid) {
390 global $DB;
391 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
395 * Issue a badge to user.
397 * @param int $userid User who earned the badge
398 * @param bool $nobake Not baking actual badges (for testing purposes)
400 public function issue($userid, $nobake = false) {
401 global $DB, $CFG;
403 $now = time();
404 $issued = new stdClass();
405 $issued->badgeid = $this->id;
406 $issued->userid = $userid;
407 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
408 $issued->dateissued = $now;
410 if ($this->can_expire()) {
411 $issued->dateexpire = $this->calculate_expiry($now);
412 } else {
413 $issued->dateexpire = null;
416 // Take into account user badges privacy settings.
417 // If none set, badges default visibility is set to public.
418 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
420 $result = $DB->insert_record('badge_issued', $issued, true);
422 if ($result) {
423 // Trigger badge awarded event.
424 $eventdata = array (
425 'context' => $this->get_context(),
426 'objectid' => $this->id,
427 'relateduserid' => $userid,
428 'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
430 \core\event\badge_awarded::create($eventdata)->trigger();
432 // Lock the badge, so that its criteria could not be changed any more.
433 if ($this->status == BADGE_STATUS_ACTIVE) {
434 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
437 // Update details in criteria_met table.
438 $compl = $this->get_criteria_completions($userid);
439 foreach ($compl as $c) {
440 $obj = new stdClass();
441 $obj->id = $c->id;
442 $obj->issuedid = $result;
443 $DB->update_record('badge_criteria_met', $obj, true);
446 if (!$nobake) {
447 // Bake a badge image.
448 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
450 // Notify recipients and badge creators.
451 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
457 * Reviews all badge criteria and checks if badge can be instantly awarded.
459 * @return int Number of awards
461 public function review_all_criteria() {
462 global $DB, $CFG;
463 $awards = 0;
465 // Raise timelimit as this could take a while for big web sites.
466 core_php_time_limit::raise();
467 raise_memory_limit(MEMORY_HUGE);
469 foreach ($this->criteria as $crit) {
470 // Overall criterion is decided when other criteria are reviewed.
471 if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
472 continue;
475 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
476 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
477 if ($this->type == BADGE_TYPE_SITE) {
478 $sql = "SELECT DISTINCT u.id, bi.badgeid
479 FROM {user} u
480 {$extrajoin}
481 LEFT JOIN {badge_issued} bi
482 ON u.id = bi.userid AND bi.badgeid = :badgeid
483 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
484 $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
485 $toearn = $DB->get_fieldset_sql($sql, $params);
486 } else {
487 // For course level badges, get all users who already earned the badge in this course.
488 // Then find the ones who are enrolled in the course and don't have a badge yet.
489 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
490 $wheresql = '';
491 $earnedparams = array();
492 if (!empty($earned)) {
493 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
494 $wheresql = ' WHERE u.id ' . $earnedsql;
496 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
497 $sql = "SELECT DISTINCT u.id
498 FROM {user} u
499 {$extrajoin}
500 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
501 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
502 $toearn = $DB->get_fieldset_sql($sql, $params);
505 foreach ($toearn as $uid) {
506 $reviewoverall = false;
507 if ($crit->review($uid, true)) {
508 $crit->mark_complete($uid);
509 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
510 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
511 $this->issue($uid);
512 $awards++;
513 } else {
514 $reviewoverall = true;
516 } else {
517 // Will be reviewed some other time.
518 $reviewoverall = false;
520 // Review overall if it is required.
521 if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
522 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
523 $this->issue($uid);
524 $awards++;
529 return $awards;
533 * Gets an array of completed criteria from 'badge_criteria_met' table.
535 * @param int $userid Completions for a user
536 * @return array Records of criteria completions
538 public function get_criteria_completions($userid) {
539 global $DB;
540 $completions = array();
541 $sql = "SELECT bcm.id, bcm.critid
542 FROM {badge_criteria_met} bcm
543 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
544 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
545 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
547 return $completions;
551 * Checks if badges has award criteria set up.
553 * @return bool A status indicating badge has at least one criterion
555 public function has_criteria() {
556 if (count($this->criteria) > 0) {
557 return true;
559 return false;
563 * Returns badge award criteria
565 * @return array An array of badge criteria
567 public function get_criteria() {
568 global $DB;
569 $criteria = array();
571 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
572 foreach ($records as $record) {
573 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
577 return $criteria;
581 * Get aggregation method for badge criteria
583 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
584 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
586 public function get_aggregation_method($criteriatype = 0) {
587 global $DB;
588 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
589 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
591 if (!$aggregation) {
592 return BADGE_CRITERIA_AGGREGATION_ALL;
595 return $aggregation;
599 * Checks if badge has expiry period or date set up.
601 * @return bool A status indicating badge can expire
603 public function can_expire() {
604 if ($this->expireperiod || $this->expiredate) {
605 return true;
607 return false;
611 * Calculates badge expiry date based on either expirydate or expiryperiod.
613 * @param int $timestamp Time of badge issue
614 * @return int A timestamp
616 public function calculate_expiry($timestamp) {
617 $expiry = null;
619 if (isset($this->expiredate)) {
620 $expiry = $this->expiredate;
621 } else if (isset($this->expireperiod)) {
622 $expiry = $timestamp + $this->expireperiod;
625 return $expiry;
629 * Checks if badge has manual award criteria set.
631 * @return bool A status indicating badge can be awarded manually
633 public function has_manual_award_criteria() {
634 foreach ($this->criteria as $criterion) {
635 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
636 return true;
639 return false;
643 * Fully deletes the badge or marks it as archived.
645 * @param $archive bool Achive a badge without actual deleting of any data.
647 public function delete($archive = true) {
648 global $DB;
650 if ($archive) {
651 $this->status = BADGE_STATUS_ARCHIVED;
652 $this->save();
654 // Trigger event, badge archived.
655 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
656 $event = \core\event\badge_archived::create($eventparams);
657 $event->trigger();
658 return;
661 $fs = get_file_storage();
663 // Remove all issued badge image files and badge awards.
664 // Cannot bulk remove area files here because they are issued in user context.
665 $awards = $this->get_awards();
666 foreach ($awards as $award) {
667 $usercontext = context_user::instance($award->userid);
668 $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
670 $DB->delete_records('badge_issued', array('badgeid' => $this->id));
672 // Remove all badge criteria.
673 $criteria = $this->get_criteria();
674 foreach ($criteria as $criterion) {
675 $criterion->delete();
678 // Delete badge images.
679 $badgecontext = $this->get_context();
680 $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
682 // Finally, remove badge itself.
683 $DB->delete_records('badge', array('id' => $this->id));
685 // Trigger event, badge deleted.
686 $eventparams = array('objectid' => $this->id,
687 'context' => $this->get_context(),
688 'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
690 $event = \core\event\badge_deleted::create($eventparams);
691 $event->trigger();
696 * Sends notifications to users about awarded badges.
698 * @param badge $badge Badge that was issued
699 * @param int $userid Recipient ID
700 * @param string $issued Unique hash of an issued badge
701 * @param string $filepathhash File path hash of an issued badge for attachments
703 function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
704 global $CFG, $DB;
706 $admin = get_admin();
707 $userfrom = new stdClass();
708 $userfrom->id = $admin->id;
709 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
710 foreach (get_all_user_name_fields() as $addname) {
711 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
713 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
714 $userfrom->maildisplay = true;
716 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
717 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
719 $params = new stdClass();
720 $params->badgename = $badge->name;
721 $params->username = fullname($userto);
722 $params->badgelink = $issuedlink;
723 $message = badge_message_from_template($badge->message, $params);
724 $plaintext = html_to_text($message);
726 // Notify recipient.
727 $eventdata = new \core\message\message();
728 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
729 $eventdata->component = 'moodle';
730 $eventdata->name = 'badgerecipientnotice';
731 $eventdata->userfrom = $userfrom;
732 $eventdata->userto = $userto;
733 $eventdata->notification = 1;
734 $eventdata->subject = $badge->messagesubject;
735 $eventdata->fullmessage = $plaintext;
736 $eventdata->fullmessageformat = FORMAT_HTML;
737 $eventdata->fullmessagehtml = $message;
738 $eventdata->smallmessage = '';
740 // Attach badge image if possible.
741 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
742 $fs = get_file_storage();
743 $file = $fs->get_file_by_hash($filepathhash);
744 $eventdata->attachment = $file;
745 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
747 message_send($eventdata);
748 } else {
749 message_send($eventdata);
752 // Notify badge creator about the award if they receive notifications every time.
753 if ($badge->notification == 1) {
754 $userfrom = core_user::get_noreply_user();
755 $userfrom->maildisplay = true;
757 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
758 $a = new stdClass();
759 $a->user = fullname($userto);
760 $a->link = $issuedlink;
761 $creatormessage = get_string('creatorbody', 'badges', $a);
762 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
764 $eventdata = new \core\message\message();
765 $eventdata->courseid = $badge->courseid;
766 $eventdata->component = 'moodle';
767 $eventdata->name = 'badgecreatornotice';
768 $eventdata->userfrom = $userfrom;
769 $eventdata->userto = $creator;
770 $eventdata->notification = 1;
771 $eventdata->subject = $creatorsubject;
772 $eventdata->fullmessage = html_to_text($creatormessage);
773 $eventdata->fullmessageformat = FORMAT_HTML;
774 $eventdata->fullmessagehtml = $creatormessage;
775 $eventdata->smallmessage = '';
777 message_send($eventdata);
778 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
783 * Caclulates date for the next message digest to badge creators.
785 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
786 * @return int Timestamp for next cron
788 function badges_calculate_message_schedule($schedule) {
789 $nextcron = 0;
791 switch ($schedule) {
792 case BADGE_MESSAGE_DAILY:
793 $nextcron = time() + 60 * 60 * 24;
794 break;
795 case BADGE_MESSAGE_WEEKLY:
796 $nextcron = time() + 60 * 60 * 24 * 7;
797 break;
798 case BADGE_MESSAGE_MONTHLY:
799 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
800 break;
803 return $nextcron;
807 * Replaces variables in a message template and returns text ready to be emailed to a user.
809 * @param string $message Message body.
810 * @return string Message with replaced values
812 function badge_message_from_template($message, $params) {
813 $msg = $message;
814 foreach ($params as $key => $value) {
815 $msg = str_replace("%$key%", $value, $msg);
818 return $msg;
822 * Get all badges.
824 * @param int Type of badges to return
825 * @param int Course ID for course badges
826 * @param string $sort An SQL field to sort by
827 * @param string $dir The sort direction ASC|DESC
828 * @param int $page The page or records to return
829 * @param int $perpage The number of records to return per page
830 * @param int $user User specific search
831 * @return array $badge Array of records matching criteria
833 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
834 global $DB;
835 $records = array();
836 $params = array();
837 $where = "b.status != :deleted AND b.type = :type ";
838 $params['deleted'] = BADGE_STATUS_ARCHIVED;
840 $userfields = array('b.id, b.name, b.status');
841 $usersql = "";
842 if ($user != 0) {
843 $userfields[] = 'bi.dateissued';
844 $userfields[] = 'bi.uniquehash';
845 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
846 $params['userid'] = $user;
847 $where .= " AND (b.status = 1 OR b.status = 3) ";
849 $fields = implode(', ', $userfields);
851 if ($courseid != 0 ) {
852 $where .= "AND b.courseid = :courseid ";
853 $params['courseid'] = $courseid;
856 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
857 $params['type'] = $type;
859 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
860 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
862 $badges = array();
863 foreach ($records as $r) {
864 $badge = new badge($r->id);
865 $badges[$r->id] = $badge;
866 if ($user != 0) {
867 $badges[$r->id]->dateissued = $r->dateissued;
868 $badges[$r->id]->uniquehash = $r->uniquehash;
869 } else {
870 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
871 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
872 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
873 $badges[$r->id]->statstring = $badge->get_status_name();
876 return $badges;
880 * Get badges for a specific user.
882 * @param int $userid User ID
883 * @param int $courseid Badges earned by a user in a specific course
884 * @param int $page The page or records to return
885 * @param int $perpage The number of records to return per page
886 * @param string $search A simple string to search for
887 * @param bool $onlypublic Return only public badges
888 * @return array of badges ordered by decreasing date of issue
890 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
891 global $CFG, $DB;
893 $params = array(
894 'userid' => $userid
896 $sql = 'SELECT
897 bi.uniquehash,
898 bi.dateissued,
899 bi.dateexpire,
900 bi.id as issuedid,
901 bi.visible,
902 u.email,
904 FROM
905 {badge} b,
906 {badge_issued} bi,
907 {user} u
908 WHERE b.id = bi.badgeid
909 AND u.id = bi.userid
910 AND bi.userid = :userid';
912 if (!empty($search)) {
913 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
914 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
916 if ($onlypublic) {
917 $sql .= ' AND (bi.visible = 1) ';
920 if (empty($CFG->badges_allowcoursebadges)) {
921 $sql .= ' AND b.courseid IS NULL';
922 } else if ($courseid != 0) {
923 $sql .= ' AND (b.courseid = :courseid) ';
924 $params['courseid'] = $courseid;
926 $sql .= ' ORDER BY bi.dateissued DESC';
927 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
929 return $badges;
933 * Extends the course administration navigation with the Badges page
935 * @param navigation_node $coursenode
936 * @param object $course
938 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
939 global $CFG, $SITE;
941 $coursecontext = context_course::instance($course->id);
942 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
943 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
944 'moodle/badges:createbadge',
945 'moodle/badges:awardbadge',
946 'moodle/badges:configurecriteria',
947 'moodle/badges:configuremessages',
948 'moodle/badges:configuredetails',
949 'moodle/badges:deletebadge'), $coursecontext);
951 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
952 $coursenode->add(get_string('coursebadges', 'badges'), null,
953 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
954 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
956 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
958 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
959 navigation_node::TYPE_SETTING, null, 'coursebadges');
961 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
962 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
964 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
965 navigation_node::TYPE_SETTING, null, 'newbadge');
971 * Triggered when badge is manually awarded.
973 * @param object $data
974 * @return boolean
976 function badges_award_handle_manual_criteria_review(stdClass $data) {
977 $criteria = $data->crit;
978 $userid = $data->userid;
979 $badge = new badge($criteria->badgeid);
981 if (!$badge->is_active() || $badge->is_issued($userid)) {
982 return true;
985 if ($criteria->review($userid)) {
986 $criteria->mark_complete($userid);
988 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
989 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
990 $badge->issue($userid);
994 return true;
998 * Process badge image from form data
1000 * @param badge $badge Badge object
1001 * @param string $iconfile Original file
1003 function badges_process_badge_image(badge $badge, $iconfile) {
1004 global $CFG, $USER;
1005 require_once($CFG->libdir. '/gdlib.php');
1007 if (!empty($CFG->gdversion)) {
1008 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
1009 @unlink($iconfile);
1011 // Clean up file draft area after badge image has been saved.
1012 $context = context_user::instance($USER->id, MUST_EXIST);
1013 $fs = get_file_storage();
1014 $fs->delete_area_files($context->id, 'user', 'draft');
1019 * Print badge image.
1021 * @param badge $badge Badge object
1022 * @param stdClass $context
1023 * @param string $size
1025 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1026 $fsize = ($size == 'small') ? 'f2' : 'f1';
1028 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1029 // Appending a random parameter to image link to forse browser reload the image.
1030 $imageurl->param('refresh', rand(1, 10000));
1031 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
1033 return html_writer::empty_tag('img', $attributes);
1037 * Bake issued badge.
1039 * @param string $hash Unique hash of an issued badge.
1040 * @param int $badgeid ID of the original badge.
1041 * @param int $userid ID of badge recipient (optional).
1042 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1043 * @return string|url Returns either new file path hash or new file URL
1045 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1046 global $CFG, $USER;
1047 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
1049 $badge = new badge($badgeid);
1050 $badge_context = $badge->get_context();
1051 $userid = ($userid) ? $userid : $USER->id;
1052 $user_context = context_user::instance($userid);
1054 $fs = get_file_storage();
1055 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
1056 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f1.png')) {
1057 $contents = $file->get_content();
1059 $filehandler = new PNG_MetaDataHandler($contents);
1060 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1061 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1062 // Add assertion URL tExt chunk.
1063 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1064 $fileinfo = array(
1065 'contextid' => $user_context->id,
1066 'component' => 'badges',
1067 'filearea' => 'userbadge',
1068 'itemid' => $badge->id,
1069 'filepath' => '/',
1070 'filename' => $hash . '.png',
1073 // Create a file with added contents.
1074 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1075 if ($pathhash) {
1076 return $newfile->get_pathnamehash();
1079 } else {
1080 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1081 return;
1085 // If file exists and we just need its path hash, return it.
1086 if ($pathhash) {
1087 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1088 return $file->get_pathnamehash();
1091 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1092 return $fileurl;
1096 * Returns external backpack settings and badges from this backpack.
1098 * This function first checks if badges for the user are cached and
1099 * tries to retrieve them from the cache. Otherwise, badges are obtained
1100 * through curl request to the backpack.
1102 * @param int $userid Backpack user ID.
1103 * @param boolean $refresh Refresh badges collection in cache.
1104 * @return null|object Returns null is there is no backpack or object with backpack settings.
1106 function get_backpack_settings($userid, $refresh = false) {
1107 global $DB;
1108 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
1110 // Try to get badges from cache first.
1111 $badgescache = cache::make('core', 'externalbadges');
1112 $out = $badgescache->get($userid);
1113 if ($out !== false && !$refresh) {
1114 return $out;
1116 // Get badges through curl request to the backpack.
1117 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1118 if ($record) {
1119 $backpack = new OpenBadgesBackpackHandler($record);
1120 $out = new stdClass();
1121 $out->backpackurl = $backpack->get_url();
1123 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1124 $out->totalcollections = count($collections);
1125 $out->totalbadges = 0;
1126 $out->badges = array();
1127 foreach ($collections as $collection) {
1128 $badges = $backpack->get_badges($collection->collectionid);
1129 if (isset($badges->badges)) {
1130 $out->badges = array_merge($out->badges, $badges->badges);
1131 $out->totalbadges += count($badges->badges);
1132 } else {
1133 $out->badges = array_merge($out->badges, array());
1136 } else {
1137 $out->totalbadges = 0;
1138 $out->totalcollections = 0;
1141 $badgescache->set($userid, $out);
1142 return $out;
1145 return null;
1149 * Download all user badges in zip archive.
1151 * @param int $userid ID of badge owner.
1153 function badges_download($userid) {
1154 global $CFG, $DB;
1155 $context = context_user::instance($userid);
1156 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1158 // Get list of files to download.
1159 $fs = get_file_storage();
1160 $filelist = array();
1161 foreach ($records as $issued) {
1162 $badge = new badge($issued->badgeid);
1163 // Need to make image name user-readable and unique using filename safe characters.
1164 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1165 $name = str_replace(' ', '_', $name);
1166 $name = clean_param($name, PARAM_FILE);
1167 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1168 $filelist[$name . '.png'] = $file;
1172 // Zip files and sent them to a user.
1173 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1174 $zipper = new zip_packer();
1175 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1176 send_temp_file($tempzip, 'badges.zip');
1177 } else {
1178 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1179 die;
1184 * Checks if badges can be pushed to external backpack.
1186 * @return string Code of backpack accessibility status.
1188 function badges_check_backpack_accessibility() {
1189 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
1190 // For behat sites, do not poll the remote badge site.
1191 // Behat sites should not be available, but we should pretend as though they are.
1192 return 'available';
1195 global $CFG;
1196 include_once $CFG->libdir . '/filelib.php';
1198 // Using fake assertion url to check whether backpack can access the web site.
1199 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1201 // Curl request to backpack baker.
1202 $curl = new curl();
1203 $options = array(
1204 'FRESH_CONNECT' => true,
1205 'RETURNTRANSFER' => true,
1206 'HEADER' => 0,
1207 'CONNECTTIMEOUT' => 2,
1209 $location = BADGE_BACKPACKURL . '/baker';
1210 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1212 $data = json_decode($out);
1213 if (!empty($curl->error)) {
1214 return 'curl-request-timeout';
1215 } else {
1216 if (isset($data->code) && $data->code == 'http-unreachable') {
1217 return 'http-unreachable';
1218 } else {
1219 return 'available';
1223 return false;
1227 * Checks if user has external backpack connected.
1229 * @param int $userid ID of a user.
1230 * @return bool True|False whether backpack connection exists.
1232 function badges_user_has_backpack($userid) {
1233 global $DB;
1234 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1238 * Handles what happens to the course badges when a course is deleted.
1240 * @param int $courseid course ID.
1241 * @return void.
1243 function badges_handle_course_deletion($courseid) {
1244 global $CFG, $DB;
1245 include_once $CFG->libdir . '/filelib.php';
1247 $systemcontext = context_system::instance();
1248 $coursecontext = context_course::instance($courseid);
1249 $fs = get_file_storage();
1251 // Move badges images to the system context.
1252 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1254 // Get all course badges.
1255 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1256 foreach ($badges as $badge) {
1257 // Archive badges in this course.
1258 $toupdate = new stdClass();
1259 $toupdate->id = $badge->id;
1260 $toupdate->type = BADGE_TYPE_SITE;
1261 $toupdate->courseid = null;
1262 $toupdate->status = BADGE_STATUS_ARCHIVED;
1263 $DB->update_record('badge', $toupdate);
1268 * Loads JS files required for backpack support.
1270 * @uses $CFG, $PAGE
1271 * @return void
1273 function badges_setup_backpack_js() {
1274 global $CFG, $PAGE;
1275 if (!empty($CFG->badges_allowexternalbackpack)) {
1276 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
1277 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
1278 $PAGE->requires->js('/badges/backpack.js', true);