Moodle release 2.6.4
[moodle.git] / lib / badgeslib.php
blob41b59c3ddf299ef6611e4fa08ea2b53596c64849
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);
96 /**
97 * Class that represents badge.
100 class badge {
101 /** @var int Badge id */
102 public $id;
104 /** Values from the table 'badge' */
105 public $name;
106 public $description;
107 public $timecreated;
108 public $timemodified;
109 public $usercreated;
110 public $usermodified;
111 public $issuername;
112 public $issuerurl;
113 public $issuercontact;
114 public $expiredate;
115 public $expireperiod;
116 public $type;
117 public $courseid;
118 public $message;
119 public $messagesubject;
120 public $attachment;
121 public $notification;
122 public $status = 0;
123 public $nextcron;
125 /** @var array Badge criteria */
126 public $criteria = array();
129 * Constructs with badge details.
131 * @param int $badgeid badge ID.
133 public function __construct($badgeid) {
134 global $DB;
135 $this->id = $badgeid;
137 $data = $DB->get_record('badge', array('id' => $badgeid));
139 if (empty($data)) {
140 print_error('error:nosuchbadge', 'badges', $badgeid);
143 foreach ((array)$data as $field => $value) {
144 if (property_exists($this, $field)) {
145 $this->{$field} = $value;
149 $this->criteria = self::get_criteria();
153 * Use to get context instance of a badge.
154 * @return context instance.
156 public function get_context() {
157 if ($this->type == BADGE_TYPE_SITE) {
158 return context_system::instance();
159 } else if ($this->type == BADGE_TYPE_COURSE) {
160 return context_course::instance($this->courseid);
161 } else {
162 debugging('Something is wrong...');
167 * Return array of aggregation methods
168 * @return array
170 public static function get_aggregation_methods() {
171 return array(
172 BADGE_CRITERIA_AGGREGATION_ALL => get_string('all', 'badges'),
173 BADGE_CRITERIA_AGGREGATION_ANY => get_string('any', 'badges'),
178 * Return array of accepted criteria types for this badge
179 * @return array
181 public function get_accepted_criteria() {
182 $criteriatypes = array();
184 if ($this->type == BADGE_TYPE_COURSE) {
185 $criteriatypes = array(
186 BADGE_CRITERIA_TYPE_OVERALL,
187 BADGE_CRITERIA_TYPE_MANUAL,
188 BADGE_CRITERIA_TYPE_COURSE,
189 BADGE_CRITERIA_TYPE_ACTIVITY
191 } else if ($this->type == BADGE_TYPE_SITE) {
192 $criteriatypes = array(
193 BADGE_CRITERIA_TYPE_OVERALL,
194 BADGE_CRITERIA_TYPE_MANUAL,
195 BADGE_CRITERIA_TYPE_COURSESET,
196 BADGE_CRITERIA_TYPE_PROFILE,
200 return $criteriatypes;
204 * Save/update badge information in 'badge' table only.
205 * Cannot be used for updating awards and criteria settings.
207 * @return bool Returns true on success.
209 public function save() {
210 global $DB;
212 $fordb = new stdClass();
213 foreach (get_object_vars($this) as $k => $v) {
214 $fordb->{$k} = $v;
216 unset($fordb->criteria);
218 $fordb->timemodified = time();
219 if ($DB->update_record_raw('badge', $fordb)) {
220 return true;
221 } else {
222 throw new moodle_exception('error:save', 'badges');
223 return false;
228 * Creates and saves a clone of badge with all its properties.
229 * Clone is not active by default and has 'Copy of' attached to its name.
231 * @return int ID of new badge.
233 public function make_clone() {
234 global $DB, $USER;
236 $fordb = new stdClass();
237 foreach (get_object_vars($this) as $k => $v) {
238 $fordb->{$k} = $v;
241 $fordb->name = get_string('copyof', 'badges', $this->name);
242 $fordb->status = BADGE_STATUS_INACTIVE;
243 $fordb->usercreated = $USER->id;
244 $fordb->usermodified = $USER->id;
245 $fordb->timecreated = time();
246 $fordb->timemodified = time();
247 unset($fordb->id);
249 if ($fordb->notification > 1) {
250 $fordb->nextcron = badges_calculate_message_schedule($fordb->notification);
253 $criteria = $fordb->criteria;
254 unset($fordb->criteria);
256 if ($new = $DB->insert_record('badge', $fordb, true)) {
257 $newbadge = new badge($new);
259 // Copy badge image.
260 $fs = get_file_storage();
261 if ($file = $fs->get_file($this->get_context()->id, 'badges', 'badgeimage', $this->id, '/', 'f1.png')) {
262 if ($imagefile = $file->copy_content_to_temp()) {
263 badges_process_badge_image($newbadge, $imagefile);
267 // Copy badge criteria.
268 foreach ($this->criteria as $crit) {
269 $crit->make_clone($new);
272 return $new;
273 } else {
274 throw new moodle_exception('error:clone', 'badges');
275 return false;
280 * Checks if badges is active.
281 * Used in badge award.
283 * @return bool A status indicating badge is active
285 public function is_active() {
286 if (($this->status == BADGE_STATUS_ACTIVE) ||
287 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
288 return true;
290 return false;
294 * Use to get the name of badge status.
297 public function get_status_name() {
298 return get_string('badgestatus_' . $this->status, 'badges');
302 * Use to set badge status.
303 * Only active badges can be earned/awarded/issued.
305 * @param int $status Status from BADGE_STATUS constants
307 public function set_status($status = 0) {
308 $this->status = $status;
309 $this->save();
313 * Checks if badges is locked.
314 * Used in badge award and editing.
316 * @return bool A status indicating badge is locked
318 public function is_locked() {
319 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
320 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
321 return true;
323 return false;
327 * Checks if badge has been awarded to users.
328 * Used in badge editing.
330 * @return bool A status indicating badge has been awarded at least once
332 public function has_awards() {
333 global $DB;
334 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
335 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
336 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
338 return $awarded;
342 * Gets list of users who have earned an instance of this badge.
344 * @return array An array of objects with information about badge awards.
346 public function get_awards() {
347 global $DB;
349 $awards = $DB->get_records_sql(
350 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
351 FROM {badge_issued} b INNER JOIN {user} u
352 ON b.userid = u.id
353 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
355 return $awards;
359 * Indicates whether badge has already been issued to a user.
362 public function is_issued($userid) {
363 global $DB;
364 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
368 * Issue a badge to user.
370 * @param int $userid User who earned the badge
371 * @param bool $nobake Not baking actual badges (for testing purposes)
373 public function issue($userid, $nobake = false) {
374 global $DB, $CFG;
376 $now = time();
377 $issued = new stdClass();
378 $issued->badgeid = $this->id;
379 $issued->userid = $userid;
380 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
381 $issued->dateissued = $now;
383 if ($this->can_expire()) {
384 $issued->dateexpire = $this->calculate_expiry($now);
385 } else {
386 $issued->dateexpire = null;
389 // Take into account user badges privacy settings.
390 // If none set, badges default visibility is set to public.
391 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
393 $result = $DB->insert_record('badge_issued', $issued, true);
395 if ($result) {
396 // Lock the badge, so that its criteria could not be changed any more.
397 if ($this->status == BADGE_STATUS_ACTIVE) {
398 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
401 // Update details in criteria_met table.
402 $compl = $this->get_criteria_completions($userid);
403 foreach ($compl as $c) {
404 $obj = new stdClass();
405 $obj->id = $c->id;
406 $obj->issuedid = $result;
407 $DB->update_record('badge_criteria_met', $obj, true);
410 if (!$nobake) {
411 // Bake a badge image.
412 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
414 // Notify recipients and badge creators.
415 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
421 * Reviews all badge criteria and checks if badge can be instantly awarded.
423 * @return int Number of awards
425 public function review_all_criteria() {
426 global $DB, $CFG;
427 $awards = 0;
429 // Raise timelimit as this could take a while for big web sites.
430 set_time_limit(0);
431 raise_memory_limit(MEMORY_HUGE);
433 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
434 if ($this->type == BADGE_TYPE_SITE) {
435 $sql = 'SELECT DISTINCT u.id, bi.badgeid
436 FROM {user} u
437 LEFT JOIN {badge_issued} bi
438 ON u.id = bi.userid AND bi.badgeid = :badgeid
439 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0';
440 $toearn = $DB->get_fieldset_sql($sql, array('badgeid' => $this->id, 'guestid' => $CFG->siteguest));
441 } else {
442 // For course level badges, get users who can earn this badge in the course.
443 // These are all enrolled users with capability moodle/badges:earnbadge.
444 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
445 $users = get_enrolled_users($this->get_context(), 'moodle/badges:earnbadge', 0, 'u.id');
446 $toearn = array_diff(array_keys($users), $earned);
449 foreach ($toearn as $uid) {
450 $toreview = false;
451 foreach ($this->criteria as $crit) {
452 if ($crit->criteriatype != BADGE_CRITERIA_TYPE_OVERALL) {
453 if ($crit->review($uid)) {
454 $crit->mark_complete($uid);
455 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
456 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
457 $this->issue($uid);
458 $awards++;
459 break;
460 } else {
461 $toreview = true;
462 continue;
464 } else {
465 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
466 continue;
467 } else {
468 break;
473 // Review overall if it is required.
474 if ($toreview && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
475 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
476 $this->issue($uid);
477 $awards++;
481 return $awards;
485 * Gets an array of completed criteria from 'badge_criteria_met' table.
487 * @param int $userid Completions for a user
488 * @return array Records of criteria completions
490 public function get_criteria_completions($userid) {
491 global $DB;
492 $completions = array();
493 $sql = "SELECT bcm.id, bcm.critid
494 FROM {badge_criteria_met} bcm
495 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
496 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
497 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
499 return $completions;
503 * Checks if badges has award criteria set up.
505 * @return bool A status indicating badge has at least one criterion
507 public function has_criteria() {
508 if (count($this->criteria) > 0) {
509 return true;
511 return false;
515 * Returns badge award criteria
517 * @return array An array of badge criteria
519 public function get_criteria() {
520 global $DB;
521 $criteria = array();
523 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
524 foreach ($records as $record) {
525 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
529 return $criteria;
533 * Get aggregation method for badge criteria
535 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
536 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
538 public function get_aggregation_method($criteriatype = 0) {
539 global $DB;
540 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
541 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
543 if (!$aggregation) {
544 return BADGE_CRITERIA_AGGREGATION_ALL;
547 return $aggregation;
551 * Checks if badge has expiry period or date set up.
553 * @return bool A status indicating badge can expire
555 public function can_expire() {
556 if ($this->expireperiod || $this->expiredate) {
557 return true;
559 return false;
563 * Calculates badge expiry date based on either expirydate or expiryperiod.
565 * @param int $timestamp Time of badge issue
566 * @return int A timestamp
568 public function calculate_expiry($timestamp) {
569 $expiry = null;
571 if (isset($this->expiredate)) {
572 $expiry = $this->expiredate;
573 } else if (isset($this->expireperiod)) {
574 $expiry = $timestamp + $this->expireperiod;
577 return $expiry;
581 * Checks if badge has manual award criteria set.
583 * @return bool A status indicating badge can be awarded manually
585 public function has_manual_award_criteria() {
586 foreach ($this->criteria as $criterion) {
587 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
588 return true;
591 return false;
595 * Marks the badge as archived.
596 * For reporting and historical purposed we cannot completely delete badges.
597 * We will just change their status to BADGE_STATUS_ARCHIVED.
599 public function delete() {
600 $this->status = BADGE_STATUS_ARCHIVED;
601 $this->save();
606 * Sends notifications to users about awarded badges.
608 * @param badge $badge Badge that was issued
609 * @param int $userid Recipient ID
610 * @param string $issued Unique hash of an issued badge
611 * @param string $filepathhash File path hash of an issued badge for attachments
613 function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
614 global $CFG, $DB;
616 $admin = get_admin();
617 $userfrom = new stdClass();
618 $userfrom->id = $admin->id;
619 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
620 foreach (get_all_user_name_fields() as $addname) {
621 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
623 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
624 $userfrom->maildisplay = true;
626 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
627 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
629 $params = new stdClass();
630 $params->badgename = $badge->name;
631 $params->username = fullname($userto);
632 $params->badgelink = $issuedlink;
633 $message = badge_message_from_template($badge->message, $params);
634 $plaintext = format_text_email($message, FORMAT_HTML);
636 // Notify recipient.
637 $eventdata = new stdClass();
638 $eventdata->component = 'moodle';
639 $eventdata->name = 'badgerecipientnotice';
640 $eventdata->userfrom = $userfrom;
641 $eventdata->userto = $userto;
642 $eventdata->notification = 1;
643 $eventdata->subject = $badge->messagesubject;
644 $eventdata->fullmessage = $plaintext;
645 $eventdata->fullmessageformat = FORMAT_PLAIN;
646 $eventdata->fullmessagehtml = $message;
647 $eventdata->smallmessage = $plaintext;
649 // Attach badge image if possible.
650 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
651 $fs = get_file_storage();
652 $file = $fs->get_file_by_hash($filepathhash);
653 $eventdata->attachment = $file;
654 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
656 message_send($eventdata);
657 } else {
658 message_send($eventdata);
661 // Notify badge creator about the award if they receive notifications every time.
662 if ($badge->notification == 1) {
663 $userfrom = core_user::get_noreply_user();
664 $userfrom->maildisplay = true;
666 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
667 $a = new stdClass();
668 $a->user = fullname($userto);
669 $a->link = $issuedlink;
670 $creatormessage = get_string('creatorbody', 'badges', $a);
671 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
673 $eventdata = new stdClass();
674 $eventdata->component = 'moodle';
675 $eventdata->name = 'badgecreatornotice';
676 $eventdata->userfrom = $userfrom;
677 $eventdata->userto = $creator;
678 $eventdata->notification = 1;
679 $eventdata->subject = $creatorsubject;
680 $eventdata->fullmessage = format_text_email($creatormessage, FORMAT_HTML);
681 $eventdata->fullmessageformat = FORMAT_PLAIN;
682 $eventdata->fullmessagehtml = $creatormessage;
683 $eventdata->smallmessage = $creatorsubject;
685 message_send($eventdata);
686 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
691 * Caclulates date for the next message digest to badge creators.
693 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
694 * @return int Timestamp for next cron
696 function badges_calculate_message_schedule($schedule) {
697 $nextcron = 0;
699 switch ($schedule) {
700 case BADGE_MESSAGE_DAILY:
701 $nextcron = time() + 60 * 60 * 24;
702 break;
703 case BADGE_MESSAGE_WEEKLY:
704 $nextcron = time() + 60 * 60 * 24 * 7;
705 break;
706 case BADGE_MESSAGE_MONTHLY:
707 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
708 break;
711 return $nextcron;
715 * Replaces variables in a message template and returns text ready to be emailed to a user.
717 * @param string $message Message body.
718 * @return string Message with replaced values
720 function badge_message_from_template($message, $params) {
721 $msg = $message;
722 foreach ($params as $key => $value) {
723 $msg = str_replace("%$key%", $value, $msg);
726 return $msg;
730 * Get all badges.
732 * @param int Type of badges to return
733 * @param int Course ID for course badges
734 * @param string $sort An SQL field to sort by
735 * @param string $dir The sort direction ASC|DESC
736 * @param int $page The page or records to return
737 * @param int $perpage The number of records to return per page
738 * @param int $user User specific search
739 * @return array $badge Array of records matching criteria
741 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
742 global $DB;
743 $records = array();
744 $params = array();
745 $where = "b.status != :deleted AND b.type = :type ";
746 $params['deleted'] = BADGE_STATUS_ARCHIVED;
748 $userfields = array('b.id, b.name, b.status');
749 $usersql = "";
750 if ($user != 0) {
751 $userfields[] = 'bi.dateissued';
752 $userfields[] = 'bi.uniquehash';
753 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
754 $params['userid'] = $user;
755 $where .= " AND (b.status = 1 OR b.status = 3) ";
757 $fields = implode(', ', $userfields);
759 if ($courseid != 0 ) {
760 $where .= "AND b.courseid = :courseid ";
761 $params['courseid'] = $courseid;
764 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
765 $params['type'] = $type;
767 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
768 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
770 $badges = array();
771 foreach ($records as $r) {
772 $badge = new badge($r->id);
773 $badges[$r->id] = $badge;
774 if ($user != 0) {
775 $badges[$r->id]->dateissued = $r->dateissued;
776 $badges[$r->id]->uniquehash = $r->uniquehash;
777 } else {
778 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
779 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
780 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
781 $badges[$r->id]->statstring = $badge->get_status_name();
784 return $badges;
788 * Get badges for a specific user.
790 * @param int $userid User ID
791 * @param int $courseid Badges earned by a user in a specific course
792 * @param int $page The page or records to return
793 * @param int $perpage The number of records to return per page
794 * @param string $search A simple string to search for
795 * @param bool $onlypublic Return only public badges
796 * @return array of badges ordered by decreasing date of issue
798 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
799 global $DB;
800 $badges = array();
802 $params[] = $userid;
803 $sql = 'SELECT
804 bi.uniquehash,
805 bi.dateissued,
806 bi.dateexpire,
807 bi.id as issuedid,
808 bi.visible,
809 u.email,
811 FROM
812 {badge} b,
813 {badge_issued} bi,
814 {user} u
815 WHERE b.id = bi.badgeid
816 AND u.id = bi.userid
817 AND bi.userid = ?';
819 if (!empty($search)) {
820 $sql .= ' AND (' . $DB->sql_like('b.name', '?', false) . ') ';
821 $params[] = "%$search%";
823 if ($onlypublic) {
824 $sql .= ' AND (bi.visible = 1) ';
827 if ($courseid != 0) {
828 $sql .= ' AND (b.courseid = ' . $courseid . ') ';
830 $sql .= ' ORDER BY bi.dateissued DESC';
831 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
833 return $badges;
837 * Extends the course administration navigation with the Badges page
839 * @param navigation_node $coursenode
840 * @param object $course
842 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
843 global $CFG, $SITE;
845 $coursecontext = context_course::instance($course->id);
846 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
847 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
848 'moodle/badges:createbadge',
849 'moodle/badges:awardbadge',
850 'moodle/badges:configurecriteria',
851 'moodle/badges:configuremessages',
852 'moodle/badges:configuredetails',
853 'moodle/badges:deletebadge'), $coursecontext);
855 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
856 $coursenode->add(get_string('coursebadges', 'badges'), null,
857 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
858 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
860 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
862 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
863 navigation_node::TYPE_SETTING, null, 'coursebadges');
865 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
866 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
868 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
869 navigation_node::TYPE_SETTING, null, 'newbadge');
875 * Triggered when badge is manually awarded.
877 * @param object $data
878 * @return boolean
880 function badges_award_handle_manual_criteria_review(stdClass $data) {
881 $criteria = $data->crit;
882 $userid = $data->userid;
883 $badge = new badge($criteria->badgeid);
885 if (!$badge->is_active() || $badge->is_issued($userid)) {
886 return true;
889 if ($criteria->review($userid)) {
890 $criteria->mark_complete($userid);
892 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
893 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
894 $badge->issue($userid);
898 return true;
902 * Process badge image from form data
904 * @param badge $badge Badge object
905 * @param string $iconfile Original file
907 function badges_process_badge_image(badge $badge, $iconfile) {
908 global $CFG, $USER;
909 require_once($CFG->libdir. '/gdlib.php');
911 if (!empty($CFG->gdversion)) {
912 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile);
913 @unlink($iconfile);
915 // Clean up file draft area after badge image has been saved.
916 $context = context_user::instance($USER->id, MUST_EXIST);
917 $fs = get_file_storage();
918 $fs->delete_area_files($context->id, 'user', 'draft');
923 * Print badge image.
925 * @param badge $badge Badge object
926 * @param stdClass $context
927 * @param string $size
929 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
930 $fsize = ($size == 'small') ? 'f2' : 'f1';
932 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
933 // Appending a random parameter to image link to forse browser reload the image.
934 $imageurl->param('refresh', rand(1, 10000));
935 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
937 return html_writer::empty_tag('img', $attributes);
941 * Bake issued badge.
943 * @param string $hash Unique hash of an issued badge.
944 * @param int $badgeid ID of the original badge.
945 * @param int $userid ID of badge recipient (optional).
946 * @param boolean $pathhash Return file pathhash instead of image url (optional).
947 * @return string|url Returns either new file path hash or new file URL
949 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
950 global $CFG, $USER;
951 require_once(dirname(dirname(__FILE__)) . '/badges/lib/bakerlib.php');
953 $badge = new badge($badgeid);
954 $badge_context = $badge->get_context();
955 $userid = ($userid) ? $userid : $USER->id;
956 $user_context = context_user::instance($userid);
958 $fs = get_file_storage();
959 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
960 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f1.png')) {
961 $contents = $file->get_content();
963 $filehandler = new PNG_MetaDataHandler($contents);
964 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
965 if ($filehandler->check_chunks("tEXt", "openbadges")) {
966 // Add assertion URL tExt chunk.
967 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
968 $fileinfo = array(
969 'contextid' => $user_context->id,
970 'component' => 'badges',
971 'filearea' => 'userbadge',
972 'itemid' => $badge->id,
973 'filepath' => '/',
974 'filename' => $hash . '.png',
977 // Create a file with added contents.
978 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
979 if ($pathhash) {
980 return $newfile->get_pathnamehash();
983 } else {
984 debugging('Error baking badge image!', DEBUG_DEVELOPER);
985 return;
989 // If file exists and we just need its path hash, return it.
990 if ($pathhash) {
991 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
992 return $file->get_pathnamehash();
995 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
996 return $fileurl;
1000 * Returns external backpack settings and badges from this backpack.
1002 * This function first checks if badges for the user are cached and
1003 * tries to retrieve them from the cache. Otherwise, badges are obtained
1004 * through curl request to the backpack.
1006 * @param int $userid Backpack user ID.
1007 * @param boolean $refresh Refresh badges collection in cache.
1008 * @return null|object Returns null is there is no backpack or object with backpack settings.
1010 function get_backpack_settings($userid, $refresh = false) {
1011 global $DB;
1012 require_once(dirname(dirname(__FILE__)) . '/badges/lib/backpacklib.php');
1014 // Try to get badges from cache first.
1015 $badgescache = cache::make('core', 'externalbadges');
1016 $out = $badgescache->get($userid);
1017 if ($out !== false && !$refresh) {
1018 return $out;
1020 // Get badges through curl request to the backpack.
1021 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1022 if ($record) {
1023 $backpack = new OpenBadgesBackpackHandler($record);
1024 $out = new stdClass();
1025 $out->backpackurl = $backpack->get_url();
1027 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1028 $out->totalcollections = count($collections);
1029 $out->totalbadges = 0;
1030 $out->badges = array();
1031 foreach ($collections as $collection) {
1032 $badges = $backpack->get_badges($collection->collectionid);
1033 if (isset($badges->badges)) {
1034 $out->badges = array_merge($out->badges, $badges->badges);
1035 $out->totalbadges += count($out->badges);
1036 } else {
1037 $out->badges = array_merge($out->badges, array());
1040 } else {
1041 $out->totalbadges = 0;
1042 $out->totalcollections = 0;
1045 $badgescache->set($userid, $out);
1046 return $out;
1049 return null;
1053 * Download all user badges in zip archive.
1055 * @param int $userid ID of badge owner.
1057 function badges_download($userid) {
1058 global $CFG, $DB;
1059 $context = context_user::instance($userid);
1060 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1062 // Get list of files to download.
1063 $fs = get_file_storage();
1064 $filelist = array();
1065 foreach ($records as $issued) {
1066 $badge = new badge($issued->badgeid);
1067 // Need to make image name user-readable and unique using filename safe characters.
1068 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1069 $name = str_replace(' ', '_', $name);
1070 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1071 $filelist[$name . '.png'] = $file;
1075 // Zip files and sent them to a user.
1076 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1077 $zipper = new zip_packer();
1078 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1079 send_temp_file($tempzip, 'badges.zip');
1080 } else {
1081 debugging("Problems with archiving the files.");
1086 * Print badges on user profile page.
1088 * @param int $userid User ID.
1089 * @param int $courseid Course if we need to filter badges (optional).
1091 function profile_display_badges($userid, $courseid = 0) {
1092 global $CFG, $PAGE, $USER, $SITE;
1093 require_once($CFG->dirroot . '/badges/renderer.php');
1095 // Determine context.
1096 if (isloggedin()) {
1097 $context = context_user::instance($USER->id);
1098 } else {
1099 $context = context_system::instance();
1102 if ($USER->id == $userid || has_capability('moodle/badges:viewotherbadges', $context)) {
1103 $records = badges_get_user_badges($userid, $courseid, null, null, null, true);
1104 $renderer = new core_badges_renderer($PAGE, '');
1106 // Print local badges.
1107 if ($records) {
1108 $left = get_string('localbadgesp', 'badges', format_string($SITE->fullname));
1109 $right = $renderer->print_badges_list($records, $userid, true);
1110 echo html_writer::tag('dt', $left);
1111 echo html_writer::tag('dd', $right);
1114 // Print external badges.
1115 if ($courseid == 0 && !empty($CFG->badges_allowexternalbackpack)) {
1116 $backpack = get_backpack_settings($userid);
1117 if (isset($backpack->totalbadges) && $backpack->totalbadges !== 0) {
1118 $left = get_string('externalbadgesp', 'badges');
1119 $right = $renderer->print_badges_list($backpack->badges, $userid, true, true);
1120 echo html_writer::tag('dt', $left);
1121 echo html_writer::tag('dd', $right);
1128 * Checks if badges can be pushed to external backpack.
1130 * @return string Code of backpack accessibility status.
1132 function badges_check_backpack_accessibility() {
1133 global $CFG;
1134 include_once $CFG->libdir . '/filelib.php';
1136 // Using fake assertion url to check whether backpack can access the web site.
1137 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1139 // Curl request to http://backpack.openbadges.org/baker.
1140 $curl = new curl();
1141 $options = array(
1142 'FRESH_CONNECT' => true,
1143 'RETURNTRANSFER' => true,
1144 'HEADER' => 0,
1145 'CONNECTTIMEOUT' => 2,
1147 $location = 'http://backpack.openbadges.org/baker';
1148 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1150 $data = json_decode($out);
1151 if (!empty($curl->error)) {
1152 return 'curl-request-timeout';
1153 } else {
1154 if (isset($data->code) && $data->code == 'http-unreachable') {
1155 return 'http-unreachable';
1156 } else {
1157 return 'available';
1161 return false;
1165 * Checks if user has external backpack connected.
1167 * @param int $userid ID of a user.
1168 * @return bool True|False whether backpack connection exists.
1170 function badges_user_has_backpack($userid) {
1171 global $DB;
1172 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1176 * Handles what happens to the course badges when a course is deleted.
1178 * @param int $courseid course ID.
1179 * @return void.
1181 function badges_handle_course_deletion($courseid) {
1182 global $CFG, $DB;
1183 include_once $CFG->libdir . '/filelib.php';
1185 $systemcontext = context_system::instance();
1186 $coursecontext = context_course::instance($courseid);
1187 $fs = get_file_storage();
1189 // Move badges images to the system context.
1190 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1192 // Get all course badges.
1193 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1194 foreach ($badges as $badge) {
1195 // Archive badges in this course.
1196 $toupdate = new stdClass();
1197 $toupdate->id = $badge->id;
1198 $toupdate->type = BADGE_TYPE_SITE;
1199 $toupdate->courseid = null;
1200 $toupdate->status = BADGE_STATUS_ARCHIVED;
1201 $DB->update_record('badge', $toupdate);
1206 * Loads JS files required for backpack support.
1208 * @uses $CFG, $PAGE
1209 * @return void
1211 function badges_setup_backpack_js() {
1212 global $CFG, $PAGE;
1213 if (!empty($CFG->badges_allowexternalbackpack)) {
1214 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
1215 $protocol = (strpos($CFG->wwwroot, 'https://') === 0) ? 'https://' : 'http://';
1216 $PAGE->requires->js(new moodle_url($protocol . 'backpack.openbadges.org/issuer.js'), true);
1217 $PAGE->requires->js('/badges/backpack.js', true);