2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Contains classes, functions and constants used in 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 * Class that represents badge.
101 /** @var int Badge id */
104 /** Values from the table 'badge' */
108 public $timemodified;
110 public $usermodified;
114 public $issuercontact;
116 public $expireperiod;
120 public $messagesubject;
122 public $notification;
126 /** @var array Badge criteria */
127 public $criteria = array();
130 * Constructs with badge details.
132 * @param int $badgeid badge ID.
134 public function __construct($badgeid) {
136 $this->id
= $badgeid;
138 $data = $DB->get_record('badge', array('id' => $badgeid));
141 print_error('error:nosuchbadge', 'badges', $badgeid);
144 foreach ((array)$data as $field => $value) {
145 if (property_exists($this, $field)) {
146 $this->{$field} = $value;
150 $this->criteria
= self
::get_criteria();
154 * Use to get context instance of a badge.
155 * @return context instance.
157 public function get_context() {
158 if ($this->type
== BADGE_TYPE_SITE
) {
159 return context_system
::instance();
160 } else if ($this->type
== BADGE_TYPE_COURSE
) {
161 return context_course
::instance($this->courseid
);
163 debugging('Something is wrong...');
168 * Return array of aggregation methods
171 public static function get_aggregation_methods() {
173 BADGE_CRITERIA_AGGREGATION_ALL
=> get_string('all', 'badges'),
174 BADGE_CRITERIA_AGGREGATION_ANY
=> get_string('any', 'badges'),
179 * Return array of accepted criteria types for this badge
182 public function get_accepted_criteria() {
183 $criteriatypes = array();
185 if ($this->type
== BADGE_TYPE_COURSE
) {
186 $criteriatypes = array(
187 BADGE_CRITERIA_TYPE_OVERALL
,
188 BADGE_CRITERIA_TYPE_MANUAL
,
189 BADGE_CRITERIA_TYPE_COURSE
,
190 BADGE_CRITERIA_TYPE_ACTIVITY
192 } else if ($this->type
== BADGE_TYPE_SITE
) {
193 $criteriatypes = array(
194 BADGE_CRITERIA_TYPE_OVERALL
,
195 BADGE_CRITERIA_TYPE_MANUAL
,
196 BADGE_CRITERIA_TYPE_COURSESET
,
197 BADGE_CRITERIA_TYPE_PROFILE
,
201 return $criteriatypes;
205 * Save/update badge information in 'badge' table only.
206 * Cannot be used for updating awards and criteria settings.
208 * @return bool Returns true on success.
210 public function save() {
213 $fordb = new stdClass();
214 foreach (get_object_vars($this) as $k => $v) {
217 unset($fordb->criteria
);
219 $fordb->timemodified
= time();
220 if ($DB->update_record_raw('badge', $fordb)) {
223 throw new moodle_exception('error:save', 'badges');
229 * Creates and saves a clone of badge with all its properties.
230 * Clone is not active by default and has 'Copy of' attached to its name.
232 * @return int ID of new badge.
234 public function make_clone() {
237 $fordb = new stdClass();
238 foreach (get_object_vars($this) as $k => $v) {
242 $fordb->name
= get_string('copyof', 'badges', $this->name
);
243 $fordb->status
= BADGE_STATUS_INACTIVE
;
245 $fordb->usercreated
= $USER->id
;
246 $fordb->usermodified
= $USER->id
;
247 $fordb->timecreated
= time();
248 $fordb->timemodified
= time();
251 if ($fordb->notification
> 1) {
252 $fordb->nextcron
= badges_calculate_message_schedule($fordb->notification
);
255 $criteria = $fordb->criteria
;
256 unset($fordb->criteria
);
258 if ($new = $DB->insert_record('badge', $fordb, true)) {
259 $newbadge = new badge($new);
262 $fs = get_file_storage();
263 if ($file = $fs->get_file($this->get_context()->id
, 'badges', 'badgeimage', $this->id
, '/', 'f1.png')) {
264 if ($imagefile = $file->copy_content_to_temp()) {
265 badges_process_badge_image($newbadge, $imagefile);
269 // Copy badge criteria.
270 foreach ($this->criteria
as $crit) {
271 $crit->make_clone($new);
276 throw new moodle_exception('error:clone', 'badges');
282 * Checks if badges is active.
283 * Used in badge award.
285 * @return bool A status indicating badge is active
287 public function is_active() {
288 if (($this->status
== BADGE_STATUS_ACTIVE
) ||
289 ($this->status
== BADGE_STATUS_ACTIVE_LOCKED
)) {
296 * Use to get the name of badge status.
299 public function get_status_name() {
300 return get_string('badgestatus_' . $this->status
, 'badges');
304 * Use to set badge status.
305 * Only active badges can be earned/awarded/issued.
307 * @param int $status Status from BADGE_STATUS constants
309 public function set_status($status = 0) {
310 $this->status
= $status;
315 * Checks if badges is locked.
316 * Used in badge award and editing.
318 * @return bool A status indicating badge is locked
320 public function is_locked() {
321 if (($this->status
== BADGE_STATUS_ACTIVE_LOCKED
) ||
322 ($this->status
== BADGE_STATUS_INACTIVE_LOCKED
)) {
329 * Checks if badge has been awarded to users.
330 * Used in badge editing.
332 * @return bool A status indicating badge has been awarded at least once
334 public function has_awards() {
336 if ($DB->record_exists('badge_issued', array('badgeid' => $this->id
))) {
343 * Gets list of users who have earned an instance of this badge.
345 * @return array An array of objects with information about badge awards.
347 public function get_awards() {
350 $awards = $DB->get_records_sql(
351 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
352 FROM {badge_issued} b INNER JOIN {user} u
354 WHERE b.badgeid = :badgeid', array('badgeid' => $this->id
));
360 * Indicates whether badge has already been issued to a user.
363 public function is_issued($userid) {
365 return $DB->record_exists('badge_issued', array('badgeid' => $this->id
, 'userid' => $userid));
369 * Issue a badge to user.
371 * @param int $userid User who earned the badge
372 * @param bool $nobake Not baking actual badges (for testing purposes)
374 public function issue($userid, $nobake = false) {
378 $issued = new stdClass();
379 $issued->badgeid
= $this->id
;
380 $issued->userid
= $userid;
381 $issued->uniquehash
= sha1(rand() . $userid . $this->id
. $now);
382 $issued->dateissued
= $now;
384 if ($this->can_expire()) {
385 $issued->dateexpire
= $this->calculate_expiry($now);
387 $issued->dateexpire
= null;
390 // Take into account user badges privacy settings.
391 // If none set, badges default visibility is set to public.
392 $issued->visible
= get_user_preferences('badgeprivacysetting', 1, $userid);
394 $result = $DB->insert_record('badge_issued', $issued, true);
397 // Lock the badge, so that its criteria could not be changed any more.
398 if ($this->status
== BADGE_STATUS_ACTIVE
) {
399 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED
);
402 // Update details in criteria_met table.
403 $compl = $this->get_criteria_completions($userid);
404 foreach ($compl as $c) {
405 $obj = new stdClass();
407 $obj->issuedid
= $result;
408 $DB->update_record('badge_criteria_met', $obj, true);
412 // Bake a badge image.
413 $pathhash = badges_bake($issued->uniquehash
, $this->id
, $userid, true);
415 // Notify recipients and badge creators.
416 if (empty($CFG->noemailever
)) {
417 badges_notify_badge_award($this, $userid, $issued->uniquehash
, $pathhash);
424 * Reviews all badge criteria and checks if badge can be instantly awarded.
426 * @return int Number of awards
428 public function review_all_criteria() {
432 // Raise timelimit as this could take a while for big web sites.
434 raise_memory_limit(MEMORY_HUGE
);
436 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
437 if ($this->type
== BADGE_TYPE_SITE
) {
438 $sql = 'SELECT DISTINCT u.id, bi.badgeid
440 LEFT JOIN {badge_issued} bi
441 ON u.id = bi.userid AND bi.badgeid = :badgeid
442 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0';
443 $toearn = $DB->get_fieldset_sql($sql, array('badgeid' => $this->id
, 'guestid' => $CFG->siteguest
));
445 // For course level badges, get users who can earn this badge in the course.
446 // These are all enrolled users with capability moodle/badges:earnbadge.
447 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id
));
448 $users = get_enrolled_users($this->get_context(), 'moodle/badges:earnbadge', 0, 'u.id');
449 $toearn = array_diff(array_keys($users), $earned);
452 foreach ($toearn as $uid) {
454 foreach ($this->criteria
as $crit) {
455 if ($crit->criteriatype
!= BADGE_CRITERIA_TYPE_OVERALL
) {
456 if ($crit->review($uid)) {
457 $crit->mark_complete($uid);
458 if ($this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->method
== BADGE_CRITERIA_AGGREGATION_ANY
) {
459 $this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($uid);
468 if ($this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->method
== BADGE_CRITERIA_AGGREGATION_ANY
) {
476 // Review overall if it is required.
477 if ($toreview && $this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($uid)) {
478 $this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($uid);
488 * Gets an array of completed criteria from 'badge_criteria_met' table.
490 * @param int $userid Completions for a user
491 * @return array Records of criteria completions
493 public function get_criteria_completions($userid) {
495 $completions = array();
496 $sql = "SELECT bcm.id, bcm.critid
497 FROM {badge_criteria_met} bcm
498 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
499 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
500 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id
, 'userid' => $userid));
506 * Checks if badges has award criteria set up.
508 * @return bool A status indicating badge has at least one criterion
510 public function has_criteria() {
511 if (count($this->criteria
) > 0) {
518 * Returns badge award criteria
520 * @return array An array of badge criteria
522 public function get_criteria() {
526 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id
))) {
527 foreach ($records as $record) {
528 $criteria[$record->criteriatype
] = award_criteria
::build((array)$record);
536 * Get aggregation method for badge criteria
538 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
539 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
541 public function get_aggregation_method($criteriatype = 0) {
543 $params = array('badgeid' => $this->id
, 'criteriatype' => $criteriatype);
544 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE
);
547 return BADGE_CRITERIA_AGGREGATION_ALL
;
554 * Checks if badge has expiry period or date set up.
556 * @return bool A status indicating badge can expire
558 public function can_expire() {
559 if ($this->expireperiod ||
$this->expiredate
) {
566 * Calculates badge expiry date based on either expirydate or expiryperiod.
568 * @param int $timestamp Time of badge issue
569 * @return int A timestamp
571 public function calculate_expiry($timestamp) {
574 if (isset($this->expiredate
)) {
575 $expiry = $this->expiredate
;
576 } else if (isset($this->expireperiod
)) {
577 $expiry = $timestamp +
$this->expireperiod
;
584 * Checks if badge has manual award criteria set.
586 * @return bool A status indicating badge can be awarded manually
588 public function has_manual_award_criteria() {
589 foreach ($this->criteria
as $criterion) {
590 if ($criterion->criteriatype
== BADGE_CRITERIA_TYPE_MANUAL
) {
598 * Marks the badge as archived.
599 * For reporting and historical purposed we cannot completely delete badges.
600 * We will just change their status to BADGE_STATUS_ARCHIVED.
602 public function delete() {
603 $this->status
= BADGE_STATUS_ARCHIVED
;
609 * Sends notifications to users about awarded badges.
611 * @param badge $badge Badge that was issued
612 * @param int $userid Recipient ID
613 * @param string $issued Unique hash of an issued badge
614 * @param string $filepathhash File path hash of an issued badge for attachments
616 function badges_notify_badge_award(badge
$badge, $userid, $issued, $filepathhash) {
619 $admin = get_admin();
620 $userfrom = new stdClass();
621 $userfrom->id
= $admin->id
;
622 $userfrom->email
= !empty($CFG->badges_defaultissuercontact
) ?
$CFG->badges_defaultissuercontact
: $admin->email
;
623 $userfrom->firstname
= !empty($CFG->badges_defaultissuername
) ?
$CFG->badges_defaultissuername
: $admin->firstname
;
624 $userfrom->lastname
= !empty($CFG->badges_defaultissuername
) ?
'' : $admin->lastname
;
625 $userfrom->maildisplay
= true;
627 $issuedlink = html_writer
::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name
);
628 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
630 $params = new stdClass();
631 $params->badgename
= $badge->name
;
632 $params->username
= fullname($userto);
633 $params->badgelink
= $issuedlink;
634 $message = badge_message_from_template($badge->message
, $params);
635 $plaintext = format_text_email($message, FORMAT_HTML
);
637 if ($badge->attachment
&& $filepathhash) {
638 $fs = get_file_storage();
639 $file = $fs->get_file_by_hash($filepathhash);
640 $attachment = $file->copy_content_to_temp();
641 email_to_user($userto,
643 $badge->messagesubject
,
646 str_replace($CFG->dataroot
, '', $attachment),
647 str_replace(' ', '_', $badge->name
) . ".png"
649 @unlink
($attachment);
651 email_to_user($userto, $userfrom, $badge->messagesubject
, $plaintext, $message);
654 // Notify badge creator about the award if they receive notifications every time.
655 if ($badge->notification
== 1) {
656 $creator = $DB->get_record('user', array('id' => $badge->usercreated
), '*', MUST_EXIST
);
658 $a->user
= fullname($userto);
659 $a->link
= $issuedlink;
660 $creatormessage = get_string('creatorbody', 'badges', $a);
661 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
663 $eventdata = new stdClass();
664 $eventdata->component
= 'moodle';
665 $eventdata->name
= 'instantmessage';
666 $eventdata->userfrom
= $userfrom;
667 $eventdata->userto
= $creator;
668 $eventdata->notification
= 1;
669 $eventdata->subject
= $creatorsubject;
670 $eventdata->fullmessage
= $creatormessage;
671 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
672 $eventdata->fullmessagehtml
= format_text($creatormessage, FORMAT_HTML
);
673 $eventdata->smallmessage
= '';
675 message_send($eventdata);
676 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id
, 'userid' => $userid));
681 * Caclulates date for the next message digest to badge creators.
683 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
684 * @return int Timestamp for next cron
686 function badges_calculate_message_schedule($schedule) {
690 case BADGE_MESSAGE_DAILY
:
691 $nextcron = time() +
60 * 60 * 24;
693 case BADGE_MESSAGE_WEEKLY
:
694 $nextcron = time() +
60 * 60 * 24 * 7;
696 case BADGE_MESSAGE_MONTHLY
:
697 $nextcron = time() +
60 * 60 * 24 * 7 * 30;
705 * Replaces variables in a message template and returns text ready to be emailed to a user.
707 * @param string $message Message body.
708 * @return string Message with replaced values
710 function badge_message_from_template($message, $params) {
712 foreach ($params as $key => $value) {
713 $msg = str_replace("%$key%", $value, $msg);
722 * @param int Type of badges to return
723 * @param int Course ID for course badges
724 * @param string $sort An SQL field to sort by
725 * @param string $dir The sort direction ASC|DESC
726 * @param int $page The page or records to return
727 * @param int $perpage The number of records to return per page
728 * @param int $user User specific search
729 * @return array $badge Array of records matching criteria
731 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE
, $user = 0) {
735 $where = "b.status != :deleted AND b.type = :type ";
736 $params['deleted'] = BADGE_STATUS_ARCHIVED
;
738 $userfields = array('b.id, b.name, b.status');
741 $userfields[] = 'bi.dateissued';
742 $userfields[] = 'bi.uniquehash';
743 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
744 $params['userid'] = $user;
745 $where .= " AND (b.status = 1 OR b.status = 3) ";
747 $fields = implode(', ', $userfields);
749 if ($courseid != 0 ) {
750 $where .= "AND b.courseid = :courseid ";
751 $params['courseid'] = $courseid;
754 $sorting = (($sort != '' && $dir != '') ?
'ORDER BY ' . $sort . ' ' . $dir : '');
755 $params['type'] = $type;
757 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
758 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
761 foreach ($records as $r) {
762 $badge = new badge($r->id
);
763 $badges[$r->id
] = $badge;
765 $badges[$r->id
]->dateissued
= $r->dateissued
;
766 $badges[$r->id
]->uniquehash
= $r->uniquehash
;
768 $badges[$r->id
]->awards
= $DB->count_records('badge_issued', array('badgeid' => $badge->id
));
769 $badges[$r->id
]->statstring
= $badge->get_status_name();
776 * Get badges for a specific user.
778 * @param int $userid User ID
779 * @param int $courseid Badges earned by a user in a specific course
780 * @param int $page The page or records to return
781 * @param int $perpage The number of records to return per page
782 * @param string $search A simple string to search for
783 * @param bool $onlypublic Return only public badges
784 * @return array of badges ordered by decreasing date of issue
786 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
803 WHERE b.id = bi.badgeid
807 if (!empty($search)) {
808 $sql .= ' AND (' . $DB->sql_like('b.name', '?', false) . ') ';
809 $params[] = "%$search%";
812 $sql .= ' AND (bi.visible = 1) ';
815 if ($courseid != 0) {
816 $sql .= ' AND (b.courseid = ' . $courseid . ') ';
818 $sql .= ' ORDER BY bi.dateissued DESC';
819 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
825 * Get issued badge details for assertion URL
827 * @param string $hash
829 function badges_get_issued_badge_info($hash) {
834 $record = $DB->get_record_sql('
844 WHERE b.id = bi.badgeid
846 AND ' . $DB->sql_compare_text('bi.uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40),
847 array('hash' => $hash), IGNORE_MISSING
);
850 if ($record->type
== BADGE_TYPE_SITE
) {
851 $context = context_system
::instance();
853 $context = context_course
::instance($record->courseid
);
856 $url = new moodle_url('/badges/badge.php', array('hash' => $hash));
858 // Recipient's email is hashed: <algorithm>$<hash(email + salt)>.
859 $badgesalt = isset($CFG->badgesalt
) ?
$CFG->badgesalt
: '';
860 $a['recipient'] = 'sha256$' . hash('sha256', $record->email
. $badgesalt);
861 $a['salt'] = $badgesalt;
863 if ($record->dateexpire
) {
864 $a['expires'] = date('Y-m-d', $record->dateexpire
);
867 $a['issued_on'] = date('Y-m-d', $record->dateissued
);
868 $a['evidence'] = $url->out(); // Issued badge URL.
869 $a['badge'] = array();
870 $a['badge']['version'] = '0.5.0'; // Version of OBI specification, 0.5.0 - current beta.
871 $a['badge']['name'] = $record->name
;
872 $a['badge']['image'] = moodle_url
::make_pluginfile_url($context->id
, 'badges', 'badgeimage', $record->id
, '/', 'f1')->out();
873 $a['badge']['description'] = $record->description
;
874 $a['badge']['criteria'] = $url->out(); // Issued badge URL.
875 $a['badge']['issuer'] = array();
876 $a['badge']['issuer']['origin'] = $record->issuerurl
;
877 $a['badge']['issuer']['name'] = $record->issuername
;
878 $a['badge']['issuer']['contact'] = $record->issuercontact
;
885 * Extends the course administration navigation with the Badges page
887 * @param navigation_node $coursenode
888 * @param object $course
890 function badges_add_course_navigation(navigation_node
$coursenode, stdClass
$course) {
893 $coursecontext = context_course
::instance($course->id
);
894 $isfrontpage = (!$coursecontext ||
$course->id
== $SITE->id
);
896 if (!empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
) && !$isfrontpage) {
897 if (has_capability('moodle/badges:configuredetails', $coursecontext)) {
898 $coursenode->add(get_string('coursebadges', 'badges'), null,
899 navigation_node
::TYPE_CONTAINER
, null, 'coursebadges',
900 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
902 if (has_capability('moodle/badges:viewawarded', $coursecontext)) {
903 $url = new moodle_url($CFG->wwwroot
. '/badges/index.php',
904 array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
906 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
907 navigation_node
::TYPE_SETTING
, null, 'coursebadges');
910 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
911 $url = new moodle_url($CFG->wwwroot
. '/badges/newbadge.php',
912 array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
914 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
915 navigation_node
::TYPE_SETTING
, null, 'newbadge');
922 * Triggered when 'course_completed' event happens.
924 * @param object $eventdata
927 function badges_award_handle_course_criteria_review(stdClass
$eventdata) {
930 if (!empty($CFG->enablebadges
)) {
931 $userid = $eventdata->userid
;
932 $courseid = $eventdata->course
;
934 // Need to take into account that course can be a part of course_completion and courseset_completion criteria.
935 if ($rs = $DB->get_records('badge_criteria_param', array('name' => 'course_' . $courseid, 'value' => $courseid))) {
936 foreach ($rs as $r) {
937 $crit = $DB->get_record('badge_criteria', array('id' => $r->critid
), 'badgeid, criteriatype', MUST_EXIST
);
938 $badge = new badge($crit->badgeid
);
939 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
943 if ($badge->criteria
[$crit->criteriatype
]->review($userid)) {
944 $badge->criteria
[$crit->criteriatype
]->mark_complete($userid);
946 if ($badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($userid)) {
947 $badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($userid);
948 $badge->issue($userid);
959 * Triggered when 'activity_completed' event happens.
961 * @param object $eventdata
964 function badges_award_handle_activity_criteria_review(stdClass
$eventdata) {
967 if (!empty($CFG->enablebadges
)) {
968 $userid = $eventdata->userid
;
969 $mod = $eventdata->coursemoduleid
;
971 if ($eventdata->completionstate
== COMPLETION_COMPLETE
972 ||
$eventdata->completionstate
== COMPLETION_COMPLETE_PASS
973 ||
$eventdata->completionstate
== COMPLETION_COMPLETE_FAIL
) {
974 // Need to take into account that there can be more than one badge with the same activity in its criteria.
975 if ($rs = $DB->get_records('badge_criteria_param', array('name' => 'module_' . $mod, 'value' => $mod))) {
976 foreach ($rs as $r) {
977 $bid = $DB->get_field('badge_criteria', 'badgeid', array('id' => $r->critid
), MUST_EXIST
);
978 $badge = new badge($bid);
979 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
983 if ($badge->criteria
[BADGE_CRITERIA_TYPE_ACTIVITY
]->review($userid)) {
984 $badge->criteria
[BADGE_CRITERIA_TYPE_ACTIVITY
]->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);
1000 * Triggered when 'user_updated' event happens.
1002 * @param object $eventdata Holds all information about a user.
1005 function badges_award_handle_profile_criteria_review(stdClass
$eventdata) {
1008 if (!empty($CFG->enablebadges
)) {
1009 $userid = $eventdata->id
;
1011 if ($rs = $DB->get_records('badge_criteria', array('criteriatype' => BADGE_CRITERIA_TYPE_PROFILE
))) {
1012 foreach ($rs as $r) {
1013 $badge = new badge($r->badgeid
);
1014 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
1018 if ($badge->criteria
[BADGE_CRITERIA_TYPE_PROFILE
]->review($userid)) {
1019 $badge->criteria
[BADGE_CRITERIA_TYPE_PROFILE
]->mark_complete($userid);
1021 if ($badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($userid)) {
1022 $badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($userid);
1023 $badge->issue($userid);
1034 * Triggered when badge is manually awarded.
1036 * @param object $data
1039 function badges_award_handle_manual_criteria_review(stdClass
$data) {
1040 $criteria = $data->crit
;
1041 $userid = $data->userid
;
1042 $badge = new badge($criteria->badgeid
);
1044 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
1048 if ($criteria->review($userid)) {
1049 $criteria->mark_complete($userid);
1051 if ($badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($userid)) {
1052 $badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($userid);
1053 $badge->issue($userid);
1061 * Process badge image from form data
1063 * @param badge $badge Badge object
1064 * @param string $iconfile Original file
1066 function badges_process_badge_image(badge
$badge, $iconfile) {
1068 require_once($CFG->libdir
. '/gdlib.php');
1070 if (!empty($CFG->gdversion
)) {
1071 if ($fileid = (int)process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id
, $iconfile)) {
1072 $badge->image
= $fileid;
1077 // Clean up file draft area after badge image has been saved.
1078 $context = context_user
::instance($USER->id
, MUST_EXIST
);
1079 $fs = get_file_storage();
1080 $fs->delete_area_files($context->id
, 'user', 'draft');
1085 * Print badge image.
1087 * @param badge $badge Badge object
1088 * @param stdClass $context
1089 * @param string $size
1091 function print_badge_image(badge
$badge, stdClass
$context, $size = 'small') {
1092 $fsize = ($size == 'small') ?
'f2' : 'f1';
1094 $imageurl = moodle_url
::make_pluginfile_url($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $fsize, false);
1095 // Appending a random parameter to image link to forse browser reload the image.
1096 $attributes = array('src' => $imageurl . '?' . rand(1, 10000), 'alt' => s($badge->name
), 'class' => 'activatebadge');
1098 return html_writer
::empty_tag('img', $attributes);
1102 * Bake issued badge.
1104 * @param string $hash Unique hash of an issued badge.
1105 * @param int $badgeid ID of the original badge.
1106 * @param int $userid ID of badge recipient (optional).
1107 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1108 * @return string|url Returns either new file path hash or new file URL
1110 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1112 require_once(dirname(dirname(__FILE__
)) . '/badges/lib/bakerlib.php');
1114 $badge = new badge($badgeid);
1115 $badge_context = $badge->get_context();
1116 $userid = ($userid) ?
$userid : $USER->id
;
1117 $user_context = context_user
::instance($userid);
1119 $fs = get_file_storage();
1120 if (!$fs->file_exists($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png')) {
1121 if ($file = $fs->get_file($badge_context->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1.png')) {
1122 $contents = $file->get_content();
1124 $filehandler = new PNG_MetaDataHandler($contents);
1125 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1126 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1127 // Add assertion URL tExt chunk.
1128 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1130 'contextid' => $user_context->id
,
1131 'component' => 'badges',
1132 'filearea' => 'userbadge',
1133 'itemid' => $badge->id
,
1135 'filename' => $hash . '.png',
1138 // Create a file with added contents.
1139 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1141 return $newfile->get_pathnamehash();
1145 debugging('Error baking badge image!');
1149 $fileurl = moodle_url
::make_pluginfile_url($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash, true);
1154 * Returns external backpack settings and badges from this backpack.
1156 * @param int $userid Backpack user ID.
1157 * @return null|object Returns null is there is no backpack or object with backpack settings.
1159 function get_backpack_settings($userid) {
1161 require_once(dirname(dirname(__FILE__
)) . '/badges/lib/backpacklib.php');
1163 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1165 $backpack = new OpenBadgesBackpackHandler($record);
1166 $out = new stdClass();
1167 $out->backpackurl
= $backpack->get_url();
1169 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id
))) {
1170 $out->totalcollections
= count($collections);
1171 $out->totalbadges
= 0;
1172 $out->badges
= array();
1173 foreach ($collections as $collection) {
1174 $badges = $backpack->get_badges($collection->collectionid
);
1175 if (isset($badges->badges
)) {
1176 $out->badges
= array_merge($out->badges
, $badges->badges
);
1177 $out->totalbadges +
= count($out->badges
);
1179 $out->badges
= array_merge($out->badges
, array());
1183 $out->totalbadges
= 0;
1184 $out->totalcollections
= 0;
1194 * Download all user badges in zip archive.
1196 * @param int $userid ID of badge owner.
1198 function badges_download($userid) {
1200 $context = context_user
::instance($userid);
1201 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1203 // Get list of files to download.
1204 $fs = get_file_storage();
1205 $filelist = array();
1206 foreach ($records as $issued) {
1207 $badge = new badge($issued->badgeid
);
1208 // Need to make image name user-readable and unique using filename safe characters.
1209 $name = $badge->name
. ' ' . userdate($issued->dateissued
, '%d %b %Y') . ' ' . hash('crc32', $badge->id
);
1210 $name = str_replace(' ', '_', $name);
1211 if ($file = $fs->get_file($context->id
, 'badges', 'userbadge', $issued->badgeid
, '/', $issued->uniquehash
. '.png')) {
1212 $filelist[$name . '.png'] = $file;
1216 // Zip files and sent them to a user.
1217 $tempzip = tempnam($CFG->tempdir
.'/', 'mybadges');
1218 $zipper = new zip_packer();
1219 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1220 send_temp_file($tempzip, 'badges.zip');
1222 debugging("Problems with archiving the files.");
1227 * Print badges on user profile page.
1229 * @param int $userid User ID.
1230 * @param int $courseid Course if we need to filter badges (optional).
1232 function profile_display_badges($userid, $courseid = 0) {
1233 global $CFG, $PAGE, $USER, $SITE;
1234 require_once($CFG->dirroot
. '/badges/renderer.php');
1236 if ($USER->id
== $userid ||
has_capability('moodle/badges:viewotherbadges', context_user
::instance($USER->id
))) {
1237 $records = badges_get_user_badges($userid, $courseid, null, null, null, true);
1238 $renderer = new core_badges_renderer($PAGE, '');
1240 // Print local badges.
1242 $left = get_string('localbadgesp', 'badges', $SITE->fullname
);
1243 $right = $renderer->print_badges_list($records, $userid, true);
1244 echo html_writer
::tag('dt', $left);
1245 echo html_writer
::tag('dd', $right);
1248 // Print external badges.
1249 if ($courseid == 0 && !empty($CFG->badges_allowexternalbackpack
)) {
1250 $backpack = get_backpack_settings($userid);
1251 if (isset($backpack->totalbadges
) && $backpack->totalbadges
!== 0) {
1252 $left = get_string('externalbadgesp', 'badges');
1253 $right = $renderer->print_badges_list($backpack->badges
, $userid, true, true);
1254 echo html_writer
::tag('dt', $left);
1255 echo html_writer
::tag('dd', $right);
1262 * Checks if badges can be pushed to external backpack.
1264 * @return string Code of backpack accessibility status.
1266 function badges_check_backpack_accessibility() {
1268 include_once $CFG->libdir
. '/filelib.php';
1270 // Using fake assertion url to check whether backpack can access the web site.
1271 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1273 // Curl request to http://backpack.openbadges.org/baker.
1276 'FRESH_CONNECT' => true,
1277 'RETURNTRANSFER' => true,
1279 'CONNECTTIMEOUT_MS' => 2000,
1281 $location = 'http://backpack.openbadges.org/baker';
1282 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1284 $data = json_decode($out);
1285 if (!empty($curl->error
)) {
1286 return 'curl-request-timeout';
1288 if (isset($data->code
) && $data->code
== 'http-unreachable') {
1289 return 'http-unreachable';
1299 * Checks if user has external backpack connected.
1301 * @param int $userid ID of a user.
1302 * @return bool True|False whether backpack connection exists.
1304 function badges_user_has_backpack($userid) {
1306 return $DB->record_exists('badge_backpack', array('userid' => $userid));