Merge branch 'MDL-56954-32' of git://github.com/lameze/moodle into MOODLE_32_STABLE
[moodle.git] / lib / badgeslib.php
blob8c42e62845cbcf4cec9484f4a55fd4dc4667ef96
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_ACTIVITY
196 } else if ($this->type == BADGE_TYPE_SITE) {
197 $criteriatypes = array(
198 BADGE_CRITERIA_TYPE_OVERALL,
199 BADGE_CRITERIA_TYPE_MANUAL,
200 BADGE_CRITERIA_TYPE_COURSESET,
201 BADGE_CRITERIA_TYPE_PROFILE,
205 return $criteriatypes;
209 * Save/update badge information in 'badge' table only.
210 * Cannot be used for updating awards and criteria settings.
212 * @return bool Returns true on success.
214 public function save() {
215 global $DB;
217 $fordb = new stdClass();
218 foreach (get_object_vars($this) as $k => $v) {
219 $fordb->{$k} = $v;
221 unset($fordb->criteria);
223 $fordb->timemodified = time();
224 if ($DB->update_record_raw('badge', $fordb)) {
225 // Trigger event, badge updated.
226 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
227 $event = \core\event\badge_updated::create($eventparams);
228 $event->trigger();
229 return true;
230 } else {
231 throw new moodle_exception('error:save', 'badges');
232 return false;
237 * Creates and saves a clone of badge with all its properties.
238 * Clone is not active by default and has 'Copy of' attached to its name.
240 * @return int ID of new badge.
242 public function make_clone() {
243 global $DB, $USER, $PAGE;
245 $fordb = new stdClass();
246 foreach (get_object_vars($this) as $k => $v) {
247 $fordb->{$k} = $v;
250 $fordb->name = get_string('copyof', 'badges', $this->name);
251 $fordb->status = BADGE_STATUS_INACTIVE;
252 $fordb->usercreated = $USER->id;
253 $fordb->usermodified = $USER->id;
254 $fordb->timecreated = time();
255 $fordb->timemodified = time();
256 unset($fordb->id);
258 if ($fordb->notification > 1) {
259 $fordb->nextcron = badges_calculate_message_schedule($fordb->notification);
262 $criteria = $fordb->criteria;
263 unset($fordb->criteria);
265 if ($new = $DB->insert_record('badge', $fordb, true)) {
266 $newbadge = new badge($new);
268 // Copy badge image.
269 $fs = get_file_storage();
270 if ($file = $fs->get_file($this->get_context()->id, 'badges', 'badgeimage', $this->id, '/', 'f1.png')) {
271 if ($imagefile = $file->copy_content_to_temp()) {
272 badges_process_badge_image($newbadge, $imagefile);
276 // Copy badge criteria.
277 foreach ($this->criteria as $crit) {
278 $crit->make_clone($new);
281 // Trigger event, badge duplicated.
282 $eventparams = array('objectid' => $new, 'context' => $PAGE->context);
283 $event = \core\event\badge_duplicated::create($eventparams);
284 $event->trigger();
286 return $new;
287 } else {
288 throw new moodle_exception('error:clone', 'badges');
289 return false;
294 * Checks if badges is active.
295 * Used in badge award.
297 * @return bool A status indicating badge is active
299 public function is_active() {
300 if (($this->status == BADGE_STATUS_ACTIVE) ||
301 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
302 return true;
304 return false;
308 * Use to get the name of badge status.
311 public function get_status_name() {
312 return get_string('badgestatus_' . $this->status, 'badges');
316 * Use to set badge status.
317 * Only active badges can be earned/awarded/issued.
319 * @param int $status Status from BADGE_STATUS constants
321 public function set_status($status = 0) {
322 $this->status = $status;
323 $this->save();
324 if ($status == BADGE_STATUS_ACTIVE) {
325 // Trigger event, badge enabled.
326 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
327 $event = \core\event\badge_enabled::create($eventparams);
328 $event->trigger();
329 } else if ($status == BADGE_STATUS_INACTIVE) {
330 // Trigger event, badge disabled.
331 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
332 $event = \core\event\badge_disabled::create($eventparams);
333 $event->trigger();
338 * Checks if badges is locked.
339 * Used in badge award and editing.
341 * @return bool A status indicating badge is locked
343 public function is_locked() {
344 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
345 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
346 return true;
348 return false;
352 * Checks if badge has been awarded to users.
353 * Used in badge editing.
355 * @return bool A status indicating badge has been awarded at least once
357 public function has_awards() {
358 global $DB;
359 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
360 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
361 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
363 return $awarded;
367 * Gets list of users who have earned an instance of this badge.
369 * @return array An array of objects with information about badge awards.
371 public function get_awards() {
372 global $DB;
374 $awards = $DB->get_records_sql(
375 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
376 FROM {badge_issued} b INNER JOIN {user} u
377 ON b.userid = u.id
378 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
380 return $awards;
384 * Indicates whether badge has already been issued to a user.
387 public function is_issued($userid) {
388 global $DB;
389 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
393 * Issue a badge to user.
395 * @param int $userid User who earned the badge
396 * @param bool $nobake Not baking actual badges (for testing purposes)
398 public function issue($userid, $nobake = false) {
399 global $DB, $CFG;
401 $now = time();
402 $issued = new stdClass();
403 $issued->badgeid = $this->id;
404 $issued->userid = $userid;
405 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
406 $issued->dateissued = $now;
408 if ($this->can_expire()) {
409 $issued->dateexpire = $this->calculate_expiry($now);
410 } else {
411 $issued->dateexpire = null;
414 // Take into account user badges privacy settings.
415 // If none set, badges default visibility is set to public.
416 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
418 $result = $DB->insert_record('badge_issued', $issued, true);
420 if ($result) {
421 // Trigger badge awarded event.
422 $eventdata = array (
423 'context' => $this->get_context(),
424 'objectid' => $this->id,
425 'relateduserid' => $userid,
426 'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
428 \core\event\badge_awarded::create($eventdata)->trigger();
430 // Lock the badge, so that its criteria could not be changed any more.
431 if ($this->status == BADGE_STATUS_ACTIVE) {
432 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
435 // Update details in criteria_met table.
436 $compl = $this->get_criteria_completions($userid);
437 foreach ($compl as $c) {
438 $obj = new stdClass();
439 $obj->id = $c->id;
440 $obj->issuedid = $result;
441 $DB->update_record('badge_criteria_met', $obj, true);
444 if (!$nobake) {
445 // Bake a badge image.
446 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
448 // Notify recipients and badge creators.
449 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
455 * Reviews all badge criteria and checks if badge can be instantly awarded.
457 * @return int Number of awards
459 public function review_all_criteria() {
460 global $DB, $CFG;
461 $awards = 0;
463 // Raise timelimit as this could take a while for big web sites.
464 core_php_time_limit::raise();
465 raise_memory_limit(MEMORY_HUGE);
467 foreach ($this->criteria as $crit) {
468 // Overall criterion is decided when other criteria are reviewed.
469 if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
470 continue;
473 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
474 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
475 if ($this->type == BADGE_TYPE_SITE) {
476 $sql = "SELECT DISTINCT u.id, bi.badgeid
477 FROM {user} u
478 {$extrajoin}
479 LEFT JOIN {badge_issued} bi
480 ON u.id = bi.userid AND bi.badgeid = :badgeid
481 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
482 $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
483 $toearn = $DB->get_fieldset_sql($sql, $params);
484 } else {
485 // For course level badges, get all users who already earned the badge in this course.
486 // Then find the ones who are enrolled in the course and don't have a badge yet.
487 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
488 $wheresql = '';
489 $earnedparams = array();
490 if (!empty($earned)) {
491 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
492 $wheresql = ' WHERE u.id ' . $earnedsql;
494 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
495 $sql = "SELECT DISTINCT u.id
496 FROM {user} u
497 {$extrajoin}
498 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
499 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
500 $toearn = $DB->get_fieldset_sql($sql, $params);
503 foreach ($toearn as $uid) {
504 $reviewoverall = false;
505 if ($crit->review($uid, true)) {
506 $crit->mark_complete($uid);
507 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
508 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
509 $this->issue($uid);
510 $awards++;
511 } else {
512 $reviewoverall = true;
514 } else {
515 // Will be reviewed some other time.
516 $reviewoverall = false;
518 // Review overall if it is required.
519 if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
520 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
521 $this->issue($uid);
522 $awards++;
527 return $awards;
531 * Gets an array of completed criteria from 'badge_criteria_met' table.
533 * @param int $userid Completions for a user
534 * @return array Records of criteria completions
536 public function get_criteria_completions($userid) {
537 global $DB;
538 $completions = array();
539 $sql = "SELECT bcm.id, bcm.critid
540 FROM {badge_criteria_met} bcm
541 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
542 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
543 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
545 return $completions;
549 * Checks if badges has award criteria set up.
551 * @return bool A status indicating badge has at least one criterion
553 public function has_criteria() {
554 if (count($this->criteria) > 0) {
555 return true;
557 return false;
561 * Returns badge award criteria
563 * @return array An array of badge criteria
565 public function get_criteria() {
566 global $DB;
567 $criteria = array();
569 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
570 foreach ($records as $record) {
571 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
575 return $criteria;
579 * Get aggregation method for badge criteria
581 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
582 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
584 public function get_aggregation_method($criteriatype = 0) {
585 global $DB;
586 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
587 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
589 if (!$aggregation) {
590 return BADGE_CRITERIA_AGGREGATION_ALL;
593 return $aggregation;
597 * Checks if badge has expiry period or date set up.
599 * @return bool A status indicating badge can expire
601 public function can_expire() {
602 if ($this->expireperiod || $this->expiredate) {
603 return true;
605 return false;
609 * Calculates badge expiry date based on either expirydate or expiryperiod.
611 * @param int $timestamp Time of badge issue
612 * @return int A timestamp
614 public function calculate_expiry($timestamp) {
615 $expiry = null;
617 if (isset($this->expiredate)) {
618 $expiry = $this->expiredate;
619 } else if (isset($this->expireperiod)) {
620 $expiry = $timestamp + $this->expireperiod;
623 return $expiry;
627 * Checks if badge has manual award criteria set.
629 * @return bool A status indicating badge can be awarded manually
631 public function has_manual_award_criteria() {
632 foreach ($this->criteria as $criterion) {
633 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
634 return true;
637 return false;
641 * Fully deletes the badge or marks it as archived.
643 * @param $archive bool Achive a badge without actual deleting of any data.
645 public function delete($archive = true) {
646 global $DB;
648 if ($archive) {
649 $this->status = BADGE_STATUS_ARCHIVED;
650 $this->save();
652 // Trigger event, badge archived.
653 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
654 $event = \core\event\badge_archived::create($eventparams);
655 $event->trigger();
656 return;
659 $fs = get_file_storage();
661 // Remove all issued badge image files and badge awards.
662 // Cannot bulk remove area files here because they are issued in user context.
663 $awards = $this->get_awards();
664 foreach ($awards as $award) {
665 $usercontext = context_user::instance($award->userid);
666 $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
668 $DB->delete_records('badge_issued', array('badgeid' => $this->id));
670 // Remove all badge criteria.
671 $criteria = $this->get_criteria();
672 foreach ($criteria as $criterion) {
673 $criterion->delete();
676 // Delete badge images.
677 $badgecontext = $this->get_context();
678 $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
680 // Finally, remove badge itself.
681 $DB->delete_records('badge', array('id' => $this->id));
683 // Trigger event, badge deleted.
684 $eventparams = array('objectid' => $this->id,
685 'context' => $this->get_context(),
686 'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
688 $event = \core\event\badge_deleted::create($eventparams);
689 $event->trigger();
694 * Sends notifications to users about awarded badges.
696 * @param badge $badge Badge that was issued
697 * @param int $userid Recipient ID
698 * @param string $issued Unique hash of an issued badge
699 * @param string $filepathhash File path hash of an issued badge for attachments
701 function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
702 global $CFG, $DB;
704 $admin = get_admin();
705 $userfrom = new stdClass();
706 $userfrom->id = $admin->id;
707 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
708 foreach (get_all_user_name_fields() as $addname) {
709 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
711 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
712 $userfrom->maildisplay = true;
714 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
715 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
717 $params = new stdClass();
718 $params->badgename = $badge->name;
719 $params->username = fullname($userto);
720 $params->badgelink = $issuedlink;
721 $message = badge_message_from_template($badge->message, $params);
722 $plaintext = html_to_text($message);
724 // Notify recipient.
725 $eventdata = new \core\message\message();
726 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
727 $eventdata->component = 'moodle';
728 $eventdata->name = 'badgerecipientnotice';
729 $eventdata->userfrom = $userfrom;
730 $eventdata->userto = $userto;
731 $eventdata->notification = 1;
732 $eventdata->subject = $badge->messagesubject;
733 $eventdata->fullmessage = $plaintext;
734 $eventdata->fullmessageformat = FORMAT_HTML;
735 $eventdata->fullmessagehtml = $message;
736 $eventdata->smallmessage = '';
738 // Attach badge image if possible.
739 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
740 $fs = get_file_storage();
741 $file = $fs->get_file_by_hash($filepathhash);
742 $eventdata->attachment = $file;
743 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
745 message_send($eventdata);
746 } else {
747 message_send($eventdata);
750 // Notify badge creator about the award if they receive notifications every time.
751 if ($badge->notification == 1) {
752 $userfrom = core_user::get_noreply_user();
753 $userfrom->maildisplay = true;
755 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
756 $a = new stdClass();
757 $a->user = fullname($userto);
758 $a->link = $issuedlink;
759 $creatormessage = get_string('creatorbody', 'badges', $a);
760 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
762 $eventdata = new \core\message\message();
763 $eventdata->courseid = $badge->courseid;
764 $eventdata->component = 'moodle';
765 $eventdata->name = 'badgecreatornotice';
766 $eventdata->userfrom = $userfrom;
767 $eventdata->userto = $creator;
768 $eventdata->notification = 1;
769 $eventdata->subject = $creatorsubject;
770 $eventdata->fullmessage = html_to_text($creatormessage);
771 $eventdata->fullmessageformat = FORMAT_HTML;
772 $eventdata->fullmessagehtml = $creatormessage;
773 $eventdata->smallmessage = '';
775 message_send($eventdata);
776 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
781 * Caclulates date for the next message digest to badge creators.
783 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
784 * @return int Timestamp for next cron
786 function badges_calculate_message_schedule($schedule) {
787 $nextcron = 0;
789 switch ($schedule) {
790 case BADGE_MESSAGE_DAILY:
791 $nextcron = time() + 60 * 60 * 24;
792 break;
793 case BADGE_MESSAGE_WEEKLY:
794 $nextcron = time() + 60 * 60 * 24 * 7;
795 break;
796 case BADGE_MESSAGE_MONTHLY:
797 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
798 break;
801 return $nextcron;
805 * Replaces variables in a message template and returns text ready to be emailed to a user.
807 * @param string $message Message body.
808 * @return string Message with replaced values
810 function badge_message_from_template($message, $params) {
811 $msg = $message;
812 foreach ($params as $key => $value) {
813 $msg = str_replace("%$key%", $value, $msg);
816 return $msg;
820 * Get all badges.
822 * @param int Type of badges to return
823 * @param int Course ID for course badges
824 * @param string $sort An SQL field to sort by
825 * @param string $dir The sort direction ASC|DESC
826 * @param int $page The page or records to return
827 * @param int $perpage The number of records to return per page
828 * @param int $user User specific search
829 * @return array $badge Array of records matching criteria
831 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
832 global $DB;
833 $records = array();
834 $params = array();
835 $where = "b.status != :deleted AND b.type = :type ";
836 $params['deleted'] = BADGE_STATUS_ARCHIVED;
838 $userfields = array('b.id, b.name, b.status');
839 $usersql = "";
840 if ($user != 0) {
841 $userfields[] = 'bi.dateissued';
842 $userfields[] = 'bi.uniquehash';
843 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
844 $params['userid'] = $user;
845 $where .= " AND (b.status = 1 OR b.status = 3) ";
847 $fields = implode(', ', $userfields);
849 if ($courseid != 0 ) {
850 $where .= "AND b.courseid = :courseid ";
851 $params['courseid'] = $courseid;
854 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
855 $params['type'] = $type;
857 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
858 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
860 $badges = array();
861 foreach ($records as $r) {
862 $badge = new badge($r->id);
863 $badges[$r->id] = $badge;
864 if ($user != 0) {
865 $badges[$r->id]->dateissued = $r->dateissued;
866 $badges[$r->id]->uniquehash = $r->uniquehash;
867 } else {
868 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
869 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
870 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
871 $badges[$r->id]->statstring = $badge->get_status_name();
874 return $badges;
878 * Get badges for a specific user.
880 * @param int $userid User ID
881 * @param int $courseid Badges earned by a user in a specific course
882 * @param int $page The page or records to return
883 * @param int $perpage The number of records to return per page
884 * @param string $search A simple string to search for
885 * @param bool $onlypublic Return only public badges
886 * @return array of badges ordered by decreasing date of issue
888 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
889 global $CFG, $DB;
891 $params = array(
892 'userid' => $userid
894 $sql = 'SELECT
895 bi.uniquehash,
896 bi.dateissued,
897 bi.dateexpire,
898 bi.id as issuedid,
899 bi.visible,
900 u.email,
902 FROM
903 {badge} b,
904 {badge_issued} bi,
905 {user} u
906 WHERE b.id = bi.badgeid
907 AND u.id = bi.userid
908 AND bi.userid = :userid';
910 if (!empty($search)) {
911 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
912 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
914 if ($onlypublic) {
915 $sql .= ' AND (bi.visible = 1) ';
918 if (empty($CFG->badges_allowcoursebadges)) {
919 $sql .= ' AND b.courseid IS NULL';
920 } else if ($courseid != 0) {
921 $sql .= ' AND (b.courseid = :courseid) ';
922 $params['courseid'] = $courseid;
924 $sql .= ' ORDER BY bi.dateissued DESC';
925 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
927 return $badges;
931 * Extends the course administration navigation with the Badges page
933 * @param navigation_node $coursenode
934 * @param object $course
936 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
937 global $CFG, $SITE;
939 $coursecontext = context_course::instance($course->id);
940 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
941 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
942 'moodle/badges:createbadge',
943 'moodle/badges:awardbadge',
944 'moodle/badges:configurecriteria',
945 'moodle/badges:configuremessages',
946 'moodle/badges:configuredetails',
947 'moodle/badges:deletebadge'), $coursecontext);
949 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
950 $coursenode->add(get_string('coursebadges', 'badges'), null,
951 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
952 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
954 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
956 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
957 navigation_node::TYPE_SETTING, null, 'coursebadges');
959 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
960 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
962 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
963 navigation_node::TYPE_SETTING, null, 'newbadge');
969 * Triggered when badge is manually awarded.
971 * @param object $data
972 * @return boolean
974 function badges_award_handle_manual_criteria_review(stdClass $data) {
975 $criteria = $data->crit;
976 $userid = $data->userid;
977 $badge = new badge($criteria->badgeid);
979 if (!$badge->is_active() || $badge->is_issued($userid)) {
980 return true;
983 if ($criteria->review($userid)) {
984 $criteria->mark_complete($userid);
986 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
987 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
988 $badge->issue($userid);
992 return true;
996 * Process badge image from form data
998 * @param badge $badge Badge object
999 * @param string $iconfile Original file
1001 function badges_process_badge_image(badge $badge, $iconfile) {
1002 global $CFG, $USER;
1003 require_once($CFG->libdir. '/gdlib.php');
1005 if (!empty($CFG->gdversion)) {
1006 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
1007 @unlink($iconfile);
1009 // Clean up file draft area after badge image has been saved.
1010 $context = context_user::instance($USER->id, MUST_EXIST);
1011 $fs = get_file_storage();
1012 $fs->delete_area_files($context->id, 'user', 'draft');
1017 * Print badge image.
1019 * @param badge $badge Badge object
1020 * @param stdClass $context
1021 * @param string $size
1023 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1024 $fsize = ($size == 'small') ? 'f2' : 'f1';
1026 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1027 // Appending a random parameter to image link to forse browser reload the image.
1028 $imageurl->param('refresh', rand(1, 10000));
1029 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
1031 return html_writer::empty_tag('img', $attributes);
1035 * Bake issued badge.
1037 * @param string $hash Unique hash of an issued badge.
1038 * @param int $badgeid ID of the original badge.
1039 * @param int $userid ID of badge recipient (optional).
1040 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1041 * @return string|url Returns either new file path hash or new file URL
1043 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1044 global $CFG, $USER;
1045 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
1047 $badge = new badge($badgeid);
1048 $badge_context = $badge->get_context();
1049 $userid = ($userid) ? $userid : $USER->id;
1050 $user_context = context_user::instance($userid);
1052 $fs = get_file_storage();
1053 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
1054 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f1.png')) {
1055 $contents = $file->get_content();
1057 $filehandler = new PNG_MetaDataHandler($contents);
1058 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1059 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1060 // Add assertion URL tExt chunk.
1061 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1062 $fileinfo = array(
1063 'contextid' => $user_context->id,
1064 'component' => 'badges',
1065 'filearea' => 'userbadge',
1066 'itemid' => $badge->id,
1067 'filepath' => '/',
1068 'filename' => $hash . '.png',
1071 // Create a file with added contents.
1072 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1073 if ($pathhash) {
1074 return $newfile->get_pathnamehash();
1077 } else {
1078 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1079 return;
1083 // If file exists and we just need its path hash, return it.
1084 if ($pathhash) {
1085 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1086 return $file->get_pathnamehash();
1089 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1090 return $fileurl;
1094 * Returns external backpack settings and badges from this backpack.
1096 * This function first checks if badges for the user are cached and
1097 * tries to retrieve them from the cache. Otherwise, badges are obtained
1098 * through curl request to the backpack.
1100 * @param int $userid Backpack user ID.
1101 * @param boolean $refresh Refresh badges collection in cache.
1102 * @return null|object Returns null is there is no backpack or object with backpack settings.
1104 function get_backpack_settings($userid, $refresh = false) {
1105 global $DB;
1106 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
1108 // Try to get badges from cache first.
1109 $badgescache = cache::make('core', 'externalbadges');
1110 $out = $badgescache->get($userid);
1111 if ($out !== false && !$refresh) {
1112 return $out;
1114 // Get badges through curl request to the backpack.
1115 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1116 if ($record) {
1117 $backpack = new OpenBadgesBackpackHandler($record);
1118 $out = new stdClass();
1119 $out->backpackurl = $backpack->get_url();
1121 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1122 $out->totalcollections = count($collections);
1123 $out->totalbadges = 0;
1124 $out->badges = array();
1125 foreach ($collections as $collection) {
1126 $badges = $backpack->get_badges($collection->collectionid);
1127 if (isset($badges->badges)) {
1128 $out->badges = array_merge($out->badges, $badges->badges);
1129 $out->totalbadges += count($badges->badges);
1130 } else {
1131 $out->badges = array_merge($out->badges, array());
1134 } else {
1135 $out->totalbadges = 0;
1136 $out->totalcollections = 0;
1139 $badgescache->set($userid, $out);
1140 return $out;
1143 return null;
1147 * Download all user badges in zip archive.
1149 * @param int $userid ID of badge owner.
1151 function badges_download($userid) {
1152 global $CFG, $DB;
1153 $context = context_user::instance($userid);
1154 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1156 // Get list of files to download.
1157 $fs = get_file_storage();
1158 $filelist = array();
1159 foreach ($records as $issued) {
1160 $badge = new badge($issued->badgeid);
1161 // Need to make image name user-readable and unique using filename safe characters.
1162 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1163 $name = str_replace(' ', '_', $name);
1164 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1165 $filelist[$name . '.png'] = $file;
1169 // Zip files and sent them to a user.
1170 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1171 $zipper = new zip_packer();
1172 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1173 send_temp_file($tempzip, 'badges.zip');
1174 } else {
1175 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1176 die;
1181 * Checks if badges can be pushed to external backpack.
1183 * @return string Code of backpack accessibility status.
1185 function badges_check_backpack_accessibility() {
1186 global $CFG;
1187 include_once $CFG->libdir . '/filelib.php';
1189 // Using fake assertion url to check whether backpack can access the web site.
1190 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1192 // Curl request to backpack baker.
1193 $curl = new curl();
1194 $options = array(
1195 'FRESH_CONNECT' => true,
1196 'RETURNTRANSFER' => true,
1197 'HEADER' => 0,
1198 'CONNECTTIMEOUT' => 2,
1200 $location = BADGE_BACKPACKURL . '/baker';
1201 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1203 $data = json_decode($out);
1204 if (!empty($curl->error)) {
1205 return 'curl-request-timeout';
1206 } else {
1207 if (isset($data->code) && $data->code == 'http-unreachable') {
1208 return 'http-unreachable';
1209 } else {
1210 return 'available';
1214 return false;
1218 * Checks if user has external backpack connected.
1220 * @param int $userid ID of a user.
1221 * @return bool True|False whether backpack connection exists.
1223 function badges_user_has_backpack($userid) {
1224 global $DB;
1225 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1229 * Handles what happens to the course badges when a course is deleted.
1231 * @param int $courseid course ID.
1232 * @return void.
1234 function badges_handle_course_deletion($courseid) {
1235 global $CFG, $DB;
1236 include_once $CFG->libdir . '/filelib.php';
1238 $systemcontext = context_system::instance();
1239 $coursecontext = context_course::instance($courseid);
1240 $fs = get_file_storage();
1242 // Move badges images to the system context.
1243 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1245 // Get all course badges.
1246 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1247 foreach ($badges as $badge) {
1248 // Archive badges in this course.
1249 $toupdate = new stdClass();
1250 $toupdate->id = $badge->id;
1251 $toupdate->type = BADGE_TYPE_SITE;
1252 $toupdate->courseid = null;
1253 $toupdate->status = BADGE_STATUS_ARCHIVED;
1254 $DB->update_record('badge', $toupdate);
1259 * Loads JS files required for backpack support.
1261 * @uses $CFG, $PAGE
1262 * @return void
1264 function badges_setup_backpack_js() {
1265 global $CFG, $PAGE;
1266 if (!empty($CFG->badges_allowexternalbackpack)) {
1267 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
1268 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
1269 $PAGE->requires->js('/badges/backpack.js', true);