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 * URL of backpack. Currently only the Open Badges backpack is supported.
99 define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
102 * Open Badges specifications.
104 define('OPEN_BADGES_V1', 1);
105 define('OPEN_BADGES_V2', 2);
108 * Only use for Open Badges 2.0 specification
110 define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
111 define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
112 define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
113 define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
114 define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
115 define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
118 * Class that represents badge.
122 /** @var int Badge id */
125 /** Values from the table 'badge' */
129 public $timemodified;
131 public $usermodified;
134 public $issuercontact;
136 public $expireperiod;
140 public $messagesubject;
142 public $notification;
146 /** @var string control version of badge */
149 /** @var string language code */
152 /** @var string name image author */
153 public $imageauthorname;
155 /** @var string email image author */
156 public $imageauthoremail;
158 /** @var string url image author */
159 public $imageauthorurl;
161 /** @var string image caption */
162 public $imagecaption;
164 /** @var array Badge criteria */
165 public $criteria = array();
168 * Constructs with badge details.
170 * @param int $badgeid badge ID.
172 public function __construct($badgeid) {
174 $this->id
= $badgeid;
176 $data = $DB->get_record('badge', array('id' => $badgeid));
179 print_error('error:nosuchbadge', 'badges', $badgeid);
182 foreach ((array)$data as $field => $value) {
183 if (property_exists($this, $field)) {
184 $this->{$field} = $value;
188 $this->criteria
= self
::get_criteria();
192 * Use to get context instance of a badge.
193 * @return context instance.
195 public function get_context() {
196 if ($this->type
== BADGE_TYPE_SITE
) {
197 return context_system
::instance();
198 } else if ($this->type
== BADGE_TYPE_COURSE
) {
199 return context_course
::instance($this->courseid
);
201 debugging('Something is wrong...');
206 * Return array of aggregation methods
209 public static function get_aggregation_methods() {
211 BADGE_CRITERIA_AGGREGATION_ALL
=> get_string('all', 'badges'),
212 BADGE_CRITERIA_AGGREGATION_ANY
=> get_string('any', 'badges'),
217 * Return array of accepted criteria types for this badge
220 public function get_accepted_criteria() {
221 $criteriatypes = array();
223 if ($this->type
== BADGE_TYPE_COURSE
) {
224 $criteriatypes = array(
225 BADGE_CRITERIA_TYPE_OVERALL
,
226 BADGE_CRITERIA_TYPE_MANUAL
,
227 BADGE_CRITERIA_TYPE_COURSE
,
228 BADGE_CRITERIA_TYPE_BADGE
,
229 BADGE_CRITERIA_TYPE_ACTIVITY
231 } else if ($this->type
== BADGE_TYPE_SITE
) {
232 $criteriatypes = array(
233 BADGE_CRITERIA_TYPE_OVERALL
,
234 BADGE_CRITERIA_TYPE_MANUAL
,
235 BADGE_CRITERIA_TYPE_COURSESET
,
236 BADGE_CRITERIA_TYPE_BADGE
,
237 BADGE_CRITERIA_TYPE_PROFILE
,
238 BADGE_CRITERIA_TYPE_COHORT
,
242 return $criteriatypes;
246 * Save/update badge information in 'badge' table only.
247 * Cannot be used for updating awards and criteria settings.
249 * @return bool Returns true on success.
251 public function save() {
254 $fordb = new stdClass();
255 foreach (get_object_vars($this) as $k => $v) {
258 unset($fordb->criteria
);
260 $fordb->timemodified
= time();
261 if ($DB->update_record_raw('badge', $fordb)) {
262 // Trigger event, badge updated.
263 $eventparams = array('objectid' => $this->id
, 'context' => $this->get_context());
264 $event = \core\event\badge_updated
::create($eventparams);
268 throw new moodle_exception('error:save', 'badges');
274 * Creates and saves a clone of badge with all its properties.
275 * Clone is not active by default and has 'Copy of' attached to its name.
277 * @return int ID of new badge.
279 public function make_clone() {
280 global $DB, $USER, $PAGE;
282 $fordb = new stdClass();
283 foreach (get_object_vars($this) as $k => $v) {
287 $fordb->name
= get_string('copyof', 'badges', $this->name
);
288 $fordb->status
= BADGE_STATUS_INACTIVE
;
289 $fordb->usercreated
= $USER->id
;
290 $fordb->usermodified
= $USER->id
;
291 $fordb->timecreated
= time();
292 $fordb->timemodified
= time();
295 if ($fordb->notification
> 1) {
296 $fordb->nextcron
= badges_calculate_message_schedule($fordb->notification
);
299 $criteria = $fordb->criteria
;
300 unset($fordb->criteria
);
302 if ($new = $DB->insert_record('badge', $fordb, true)) {
303 $newbadge = new badge($new);
306 $fs = get_file_storage();
307 if ($file = $fs->get_file($this->get_context()->id
, 'badges', 'badgeimage', $this->id
, '/', 'f1.png')) {
308 if ($imagefile = $file->copy_content_to_temp()) {
309 badges_process_badge_image($newbadge, $imagefile);
313 // Copy badge criteria.
314 foreach ($this->criteria
as $crit) {
315 $crit->make_clone($new);
318 // Trigger event, badge duplicated.
319 $eventparams = array('objectid' => $new, 'context' => $PAGE->context
);
320 $event = \core\event\badge_duplicated
::create($eventparams);
325 throw new moodle_exception('error:clone', 'badges');
331 * Checks if badges is active.
332 * Used in badge award.
334 * @return bool A status indicating badge is active
336 public function is_active() {
337 if (($this->status
== BADGE_STATUS_ACTIVE
) ||
338 ($this->status
== BADGE_STATUS_ACTIVE_LOCKED
)) {
345 * Use to get the name of badge status.
348 public function get_status_name() {
349 return get_string('badgestatus_' . $this->status
, 'badges');
353 * Use to set badge status.
354 * Only active badges can be earned/awarded/issued.
356 * @param int $status Status from BADGE_STATUS constants
358 public function set_status($status = 0) {
359 $this->status
= $status;
361 if ($status == BADGE_STATUS_ACTIVE
) {
362 // Trigger event, badge enabled.
363 $eventparams = array('objectid' => $this->id
, 'context' => $this->get_context());
364 $event = \core\event\badge_enabled
::create($eventparams);
366 } else if ($status == BADGE_STATUS_INACTIVE
) {
367 // Trigger event, badge disabled.
368 $eventparams = array('objectid' => $this->id
, 'context' => $this->get_context());
369 $event = \core\event\badge_disabled
::create($eventparams);
375 * Checks if badges is locked.
376 * Used in badge award and editing.
378 * @return bool A status indicating badge is locked
380 public function is_locked() {
381 if (($this->status
== BADGE_STATUS_ACTIVE_LOCKED
) ||
382 ($this->status
== BADGE_STATUS_INACTIVE_LOCKED
)) {
389 * Checks if badge has been awarded to users.
390 * Used in badge editing.
392 * @return bool A status indicating badge has been awarded at least once
394 public function has_awards() {
396 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
397 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
398 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id
));
404 * Gets list of users who have earned an instance of this badge.
406 * @return array An array of objects with information about badge awards.
408 public function get_awards() {
411 $awards = $DB->get_records_sql(
412 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
413 FROM {badge_issued} b INNER JOIN {user} u
415 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id
));
421 * Indicates whether badge has already been issued to a user.
424 public function is_issued($userid) {
426 return $DB->record_exists('badge_issued', array('badgeid' => $this->id
, 'userid' => $userid));
430 * Issue a badge to user.
432 * @param int $userid User who earned the badge
433 * @param bool $nobake Not baking actual badges (for testing purposes)
435 public function issue($userid, $nobake = false) {
439 $issued = new stdClass();
440 $issued->badgeid
= $this->id
;
441 $issued->userid
= $userid;
442 $issued->uniquehash
= sha1(rand() . $userid . $this->id
. $now);
443 $issued->dateissued
= $now;
445 if ($this->can_expire()) {
446 $issued->dateexpire
= $this->calculate_expiry($now);
448 $issued->dateexpire
= null;
451 // Take into account user badges privacy settings.
452 // If none set, badges default visibility is set to public.
453 $issued->visible
= get_user_preferences('badgeprivacysetting', 1, $userid);
455 $result = $DB->insert_record('badge_issued', $issued, true);
458 // Trigger badge awarded event.
460 'context' => $this->get_context(),
461 'objectid' => $this->id
,
462 'relateduserid' => $userid,
463 'other' => array('dateexpire' => $issued->dateexpire
, 'badgeissuedid' => $result)
465 \core\event\badge_awarded
::create($eventdata)->trigger();
467 // Lock the badge, so that its criteria could not be changed any more.
468 if ($this->status
== BADGE_STATUS_ACTIVE
) {
469 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED
);
472 // Update details in criteria_met table.
473 $compl = $this->get_criteria_completions($userid);
474 foreach ($compl as $c) {
475 $obj = new stdClass();
477 $obj->issuedid
= $result;
478 $DB->update_record('badge_criteria_met', $obj, true);
482 // Bake a badge image.
483 $pathhash = badges_bake($issued->uniquehash
, $this->id
, $userid, true);
485 // Notify recipients and badge creators.
486 badges_notify_badge_award($this, $userid, $issued->uniquehash
, $pathhash);
492 * Reviews all badge criteria and checks if badge can be instantly awarded.
494 * @return int Number of awards
496 public function review_all_criteria() {
500 // Raise timelimit as this could take a while for big web sites.
501 core_php_time_limit
::raise();
502 raise_memory_limit(MEMORY_HUGE
);
504 foreach ($this->criteria
as $crit) {
505 // Overall criterion is decided when other criteria are reviewed.
506 if ($crit->criteriatype
== BADGE_CRITERIA_TYPE_OVERALL
) {
510 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
511 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
512 if ($this->type
== BADGE_TYPE_SITE
) {
513 $sql = "SELECT DISTINCT u.id, bi.badgeid
516 LEFT JOIN {badge_issued} bi
517 ON u.id = bi.userid AND bi.badgeid = :badgeid
518 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
519 $params = array_merge(array('badgeid' => $this->id
, 'guestid' => $CFG->siteguest
), $extraparams);
520 $toearn = $DB->get_fieldset_sql($sql, $params);
522 // For course level badges, get all users who already earned the badge in this course.
523 // Then find the ones who are enrolled in the course and don't have a badge yet.
524 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id
));
526 $earnedparams = array();
527 if (!empty($earned)) {
528 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED
, 'u', false);
529 $wheresql = ' WHERE u.id ' . $earnedsql;
531 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
532 $sql = "SELECT DISTINCT u.id
535 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
536 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
537 $toearn = $DB->get_fieldset_sql($sql, $params);
540 foreach ($toearn as $uid) {
541 $reviewoverall = false;
542 if ($crit->review($uid, true)) {
543 $crit->mark_complete($uid);
544 if ($this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->method
== BADGE_CRITERIA_AGGREGATION_ANY
) {
545 $this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($uid);
549 $reviewoverall = true;
552 // Will be reviewed some other time.
553 $reviewoverall = false;
555 // Review overall if it is required.
556 if ($reviewoverall && $this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($uid)) {
557 $this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($uid);
568 * Gets an array of completed criteria from 'badge_criteria_met' table.
570 * @param int $userid Completions for a user
571 * @return array Records of criteria completions
573 public function get_criteria_completions($userid) {
575 $completions = array();
576 $sql = "SELECT bcm.id, bcm.critid
577 FROM {badge_criteria_met} bcm
578 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
579 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
580 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id
, 'userid' => $userid));
586 * Checks if badges has award criteria set up.
588 * @return bool A status indicating badge has at least one criterion
590 public function has_criteria() {
591 if (count($this->criteria
) > 0) {
598 * Returns badge award criteria
600 * @return array An array of badge criteria
602 public function get_criteria() {
606 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id
))) {
607 foreach ($records as $record) {
608 $criteria[$record->criteriatype
] = award_criteria
::build((array)$record);
616 * Get aggregation method for badge criteria
618 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
619 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
621 public function get_aggregation_method($criteriatype = 0) {
623 $params = array('badgeid' => $this->id
, 'criteriatype' => $criteriatype);
624 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE
);
627 return BADGE_CRITERIA_AGGREGATION_ALL
;
634 * Checks if badge has expiry period or date set up.
636 * @return bool A status indicating badge can expire
638 public function can_expire() {
639 if ($this->expireperiod ||
$this->expiredate
) {
646 * Calculates badge expiry date based on either expirydate or expiryperiod.
648 * @param int $timestamp Time of badge issue
649 * @return int A timestamp
651 public function calculate_expiry($timestamp) {
654 if (isset($this->expiredate
)) {
655 $expiry = $this->expiredate
;
656 } else if (isset($this->expireperiod
)) {
657 $expiry = $timestamp +
$this->expireperiod
;
664 * Checks if badge has manual award criteria set.
666 * @return bool A status indicating badge can be awarded manually
668 public function has_manual_award_criteria() {
669 foreach ($this->criteria
as $criterion) {
670 if ($criterion->criteriatype
== BADGE_CRITERIA_TYPE_MANUAL
) {
678 * Fully deletes the badge or marks it as archived.
680 * @param $archive bool Achive a badge without actual deleting of any data.
682 public function delete($archive = true) {
686 $this->status
= BADGE_STATUS_ARCHIVED
;
689 // Trigger event, badge archived.
690 $eventparams = array('objectid' => $this->id
, 'context' => $this->get_context());
691 $event = \core\event\badge_archived
::create($eventparams);
696 $fs = get_file_storage();
698 // Remove all issued badge image files and badge awards.
699 // Cannot bulk remove area files here because they are issued in user context.
700 $awards = $this->get_awards();
701 foreach ($awards as $award) {
702 $usercontext = context_user
::instance($award->userid
);
703 $fs->delete_area_files($usercontext->id
, 'badges', 'userbadge', $this->id
);
705 $DB->delete_records('badge_issued', array('badgeid' => $this->id
));
707 // Remove all badge criteria.
708 $criteria = $this->get_criteria();
709 foreach ($criteria as $criterion) {
710 $criterion->delete();
713 // Delete badge images.
714 $badgecontext = $this->get_context();
715 $fs->delete_area_files($badgecontext->id
, 'badges', 'badgeimage', $this->id
);
717 // Delete endorsements, competencies and related badges.
718 $DB->delete_records('badge_endorsement', array('badgeid' => $this->id
));
719 $relatedsql = 'badgeid = :badgeid OR relatedbadgeid = :relatedbadgeid';
720 $relatedparams = array(
721 'badgeid' => $this->id
,
722 'relatedbadgeid' => $this->id
724 $DB->delete_records_select('badge_related', $relatedsql, $relatedparams);
725 $DB->delete_records('badge_competencies', array('badgeid' => $this->id
));
727 // Finally, remove badge itself.
728 $DB->delete_records('badge', array('id' => $this->id
));
730 // Trigger event, badge deleted.
731 $eventparams = array('objectid' => $this->id
,
732 'context' => $this->get_context(),
733 'other' => array('badgetype' => $this->type
, 'courseid' => $this->courseid
)
735 $event = \core\event\badge_deleted
::create($eventparams);
740 * Add multiple related badges.
742 * @param array $relatedids Id of badges.
744 public function add_related_badges($relatedids) {
746 $relatedbadges = array();
747 foreach ($relatedids as $relatedid) {
748 $relatedbadge = new stdClass();
749 $relatedbadge->badgeid
= $this->id
;
750 $relatedbadge->relatedbadgeid
= $relatedid;
751 $relatedbadges[] = $relatedbadge;
753 $DB->insert_records('badge_related', $relatedbadges);
757 * Delete an related badge.
759 * @param int $relatedid Id related badge.
760 * @return bool A status for delete an related badge.
762 public function delete_related_badge($relatedid) {
764 return $DB->delete_records('badge_related', array('badgeid' => $this->id
, 'relatedbadgeid' => $relatedid));
768 * Checks if badge has related badges.
770 * @return bool A status related badge.
772 public function has_related() {
774 return $DB->record_exists('badge_related', array('badgeid' => $this->id
));
778 * Get related badges of badge.
780 * @param bool $activeonly Do not get the inactive badges when is true.
781 * @return array Related badges information.
783 public function get_related_badges(bool $activeonly = false) {
786 $params = array('badgeid' => $this->id
);
787 $query = "SELECT b.id, b.name, b.version, b.language, b.type
788 FROM {badge_related} br
789 JOIN {badge} b ON b.id = br.relatedbadgeid
790 WHERE br.badgeid = :badgeid";
792 $query .= " AND b.status <> :status";
793 $params['status'] = BADGE_STATUS_INACTIVE
;
795 $relatedbadges = $DB->get_records_sql($query, $params);
796 return $relatedbadges;
800 * Insert/update competency alignment information of badge.
802 * @param stdClass $alignment Data of a competency alignment.
803 * @param int $alignmentid ID competency alignment.
804 * @return bool|int A status/ID when insert or update data.
806 public function save_alignment($alignment, $alignmentid = 0) {
809 $record = $DB->record_exists('badge_competencies', array('id' => $alignmentid));
811 $alignment->id
= $alignmentid;
812 return $DB->update_record('badge_competencies', $alignment);
814 return $DB->insert_record('badge_competencies', $alignment, true);
819 * Delete a competency alignment of badge.
821 * @param int $alignmentid ID competency alignment.
822 * @return bool A status for delete a competency alignment.
824 public function delete_alignment($alignmentid) {
826 return $DB->delete_records('badge_competencies', array('badgeid' => $this->id
, 'id' => $alignmentid));
830 * Get competencies of badge.
832 * @return array List content competencies.
834 public function get_alignment() {
836 return $DB->get_records('badge_competencies', array('badgeid' => $this->id
));
840 * Insert/update Endorsement information of badge.
842 * @param stdClass $endorsement Data of an endorsement.
843 * @return bool|int A status/ID when insert or update data.
845 public function save_endorsement($endorsement) {
847 $record = $DB->get_record('badge_endorsement', array('badgeid' => $this->id
));
849 $endorsement->id
= $record->id
;
850 return $DB->update_record('badge_endorsement', $endorsement);
852 return $DB->insert_record('badge_endorsement', $endorsement, true);
857 * Get endorsement of badge.
859 * @return array|stdClass Endorsement information.
861 public function get_endorsement() {
863 return $DB->get_record('badge_endorsement', array('badgeid' => $this->id
));
867 * Markdown language support for criteria.
869 * @return string $output Markdown content to output.
871 public function markdown_badge_criteria() {
872 $agg = $this->get_aggregation_methods();
873 if (empty($this->criteria
)) {
874 return get_string('nocriteria', 'badges');
877 $overall = $this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
];
878 if (!empty($overall->description
)) {
879 $overalldescr = format_text($overall->description
, $overall->descriptionformat
,
880 array('context' => $this->get_context())) . '\n';
882 // Get the condition string.
883 if (count($this->criteria
) == 2) {
884 $condition = get_string('criteria_descr', 'badges');
886 $condition = get_string('criteria_descr_' . BADGE_CRITERIA_TYPE_OVERALL
, 'badges',
887 core_text
::strtoupper($agg[$this->get_aggregation_method()]));
889 unset($this->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]);
891 // If only one criterion left, make sure its description goe to the top.
892 if (count($this->criteria
) == 1) {
893 $c = reset($this->criteria
);
894 if (!empty($c->description
)) {
895 $overalldescr = $c->description
. '\n';
897 if (count($c->params
) == 1) {
898 $items[] = ' * ' . get_string('criteria_descr_single_' . $c->criteriatype
, 'badges') .
901 $items[] = '* ' . get_string('criteria_descr_' . $c->criteriatype
, 'badges',
902 core_text
::strtoupper($agg[$this->get_aggregation_method($c->criteriatype
)])) .
906 foreach ($this->criteria
as $type => $c) {
908 if (!empty($c->description
)) {
909 $criteriadescr = $c->description
;
911 if (count($c->params
) == 1) {
912 $items[] = ' * ' . get_string('criteria_descr_single_' . $type, 'badges') .
913 $c->get_details() . $criteriadescr;
915 $items[] = '* ' . get_string('criteria_descr_' . $type, 'badges',
916 core_text
::strtoupper($agg[$this->get_aggregation_method($type)])) .
917 $c->get_details() . $criteriadescr;
921 return strip_tags($overalldescr . $condition . html_writer
::alist($items, array(), 'ul'));
925 * Define issuer information by format Open Badges specification version 2.
927 * @return array Issuer informations of the badge.
929 public function get_badge_issuer() {
931 $issuerurl = new moodle_url('/badges/badge_json.php', array('id' => $this->id
, 'action' => 0));
932 $issuer['name'] = $this->issuername
;
933 $issuer['url'] = $this->issuerurl
;
934 $issuer['email'] = $this->issuercontact
;
935 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT
;
936 $issuer['id'] = $issuerurl->out(false);
937 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER
;
943 * Sends notifications to users about awarded badges.
945 * @param badge $badge Badge that was issued
946 * @param int $userid Recipient ID
947 * @param string $issued Unique hash of an issued badge
948 * @param string $filepathhash File path hash of an issued badge for attachments
950 function badges_notify_badge_award(badge
$badge, $userid, $issued, $filepathhash) {
953 $admin = get_admin();
954 $userfrom = new stdClass();
955 $userfrom->id
= $admin->id
;
956 $userfrom->email
= !empty($CFG->badges_defaultissuercontact
) ?
$CFG->badges_defaultissuercontact
: $admin->email
;
957 foreach (get_all_user_name_fields() as $addname) {
958 $userfrom->$addname = !empty($CFG->badges_defaultissuername
) ?
'' : $admin->$addname;
960 $userfrom->firstname
= !empty($CFG->badges_defaultissuername
) ?
$CFG->badges_defaultissuername
: $admin->firstname
;
961 $userfrom->maildisplay
= true;
963 $issuedlink = html_writer
::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name
);
964 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
966 $params = new stdClass();
967 $params->badgename
= $badge->name
;
968 $params->username
= fullname($userto);
969 $params->badgelink
= $issuedlink;
970 $message = badge_message_from_template($badge->message
, $params);
971 $plaintext = html_to_text($message);
974 $eventdata = new \core\message\
message();
975 $eventdata->courseid
= is_null($badge->courseid
) ? SITEID
: $badge->courseid
; // Profile/site come with no courseid.
976 $eventdata->component
= 'moodle';
977 $eventdata->name
= 'badgerecipientnotice';
978 $eventdata->userfrom
= $userfrom;
979 $eventdata->userto
= $userto;
980 $eventdata->notification
= 1;
981 $eventdata->subject
= $badge->messagesubject
;
982 $eventdata->fullmessage
= $plaintext;
983 $eventdata->fullmessageformat
= FORMAT_HTML
;
984 $eventdata->fullmessagehtml
= $message;
985 $eventdata->smallmessage
= '';
987 // Attach badge image if possible.
988 if (!empty($CFG->allowattachments
) && $badge->attachment
&& is_string($filepathhash)) {
989 $fs = get_file_storage();
990 $file = $fs->get_file_by_hash($filepathhash);
991 $eventdata->attachment
= $file;
992 $eventdata->attachname
= str_replace(' ', '_', $badge->name
) . ".png";
994 message_send($eventdata);
996 message_send($eventdata);
999 // Notify badge creator about the award if they receive notifications every time.
1000 if ($badge->notification
== 1) {
1001 $userfrom = core_user
::get_noreply_user();
1002 $userfrom->maildisplay
= true;
1004 $creator = $DB->get_record('user', array('id' => $badge->usercreated
), '*', MUST_EXIST
);
1005 $a = new stdClass();
1006 $a->user
= fullname($userto);
1007 $a->link
= $issuedlink;
1008 $creatormessage = get_string('creatorbody', 'badges', $a);
1009 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
1011 $eventdata = new \core\message\
message();
1012 $eventdata->courseid
= $badge->courseid
;
1013 $eventdata->component
= 'moodle';
1014 $eventdata->name
= 'badgecreatornotice';
1015 $eventdata->userfrom
= $userfrom;
1016 $eventdata->userto
= $creator;
1017 $eventdata->notification
= 1;
1018 $eventdata->subject
= $creatorsubject;
1019 $eventdata->fullmessage
= html_to_text($creatormessage);
1020 $eventdata->fullmessageformat
= FORMAT_HTML
;
1021 $eventdata->fullmessagehtml
= $creatormessage;
1022 $eventdata->smallmessage
= '';
1024 message_send($eventdata);
1025 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id
, 'userid' => $userid));
1030 * Caclulates date for the next message digest to badge creators.
1032 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
1033 * @return int Timestamp for next cron
1035 function badges_calculate_message_schedule($schedule) {
1038 switch ($schedule) {
1039 case BADGE_MESSAGE_DAILY
:
1040 $nextcron = time() +
60 * 60 * 24;
1042 case BADGE_MESSAGE_WEEKLY
:
1043 $nextcron = time() +
60 * 60 * 24 * 7;
1045 case BADGE_MESSAGE_MONTHLY
:
1046 $nextcron = time() +
60 * 60 * 24 * 7 * 30;
1054 * Replaces variables in a message template and returns text ready to be emailed to a user.
1056 * @param string $message Message body.
1057 * @return string Message with replaced values
1059 function badge_message_from_template($message, $params) {
1061 foreach ($params as $key => $value) {
1062 $msg = str_replace("%$key%", $value, $msg);
1071 * @param int Type of badges to return
1072 * @param int Course ID for course badges
1073 * @param string $sort An SQL field to sort by
1074 * @param string $dir The sort direction ASC|DESC
1075 * @param int $page The page or records to return
1076 * @param int $perpage The number of records to return per page
1077 * @param int $user User specific search
1078 * @return array $badge Array of records matching criteria
1080 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE
, $user = 0) {
1084 $where = "b.status != :deleted AND b.type = :type ";
1085 $params['deleted'] = BADGE_STATUS_ARCHIVED
;
1087 $userfields = array('b.id, b.name, b.status');
1090 $userfields[] = 'bi.dateissued';
1091 $userfields[] = 'bi.uniquehash';
1092 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
1093 $params['userid'] = $user;
1094 $where .= " AND (b.status = 1 OR b.status = 3) ";
1096 $fields = implode(', ', $userfields);
1098 if ($courseid != 0 ) {
1099 $where .= "AND b.courseid = :courseid ";
1100 $params['courseid'] = $courseid;
1103 $sorting = (($sort != '' && $dir != '') ?
'ORDER BY ' . $sort . ' ' . $dir : '');
1104 $params['type'] = $type;
1106 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
1107 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1110 foreach ($records as $r) {
1111 $badge = new badge($r->id
);
1112 $badges[$r->id
] = $badge;
1114 $badges[$r->id
]->dateissued
= $r->dateissued
;
1115 $badges[$r->id
]->uniquehash
= $r->uniquehash
;
1117 $badges[$r->id
]->awards
= $DB->count_records_sql('SELECT COUNT(b.userid)
1118 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
1119 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id
));
1120 $badges[$r->id
]->statstring
= $badge->get_status_name();
1127 * Get badges for a specific user.
1129 * @param int $userid User ID
1130 * @param int $courseid Badges earned by a user in a specific course
1131 * @param int $page The page or records to return
1132 * @param int $perpage The number of records to return per page
1133 * @param string $search A simple string to search for
1134 * @param bool $onlypublic Return only public badges
1135 * @return array of badges ordered by decreasing date of issue
1137 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
1155 WHERE b.id = bi.badgeid
1156 AND u.id = bi.userid
1157 AND bi.userid = :userid';
1159 if (!empty($search)) {
1160 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
1161 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
1164 $sql .= ' AND (bi.visible = 1) ';
1167 if (empty($CFG->badges_allowcoursebadges
)) {
1168 $sql .= ' AND b.courseid IS NULL';
1169 } else if ($courseid != 0) {
1170 $sql .= ' AND (b.courseid = :courseid) ';
1171 $params['courseid'] = $courseid;
1173 $sql .= ' ORDER BY bi.dateissued DESC';
1174 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1180 * Extends the course administration navigation with the Badges page
1182 * @param navigation_node $coursenode
1183 * @param object $course
1185 function badges_add_course_navigation(navigation_node
$coursenode, stdClass
$course) {
1188 $coursecontext = context_course
::instance($course->id
);
1189 $isfrontpage = (!$coursecontext ||
$course->id
== $SITE->id
);
1190 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
1191 'moodle/badges:createbadge',
1192 'moodle/badges:awardbadge',
1193 'moodle/badges:configurecriteria',
1194 'moodle/badges:configuremessages',
1195 'moodle/badges:configuredetails',
1196 'moodle/badges:deletebadge'), $coursecontext);
1198 if (!empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
) && !$isfrontpage && $canmanage) {
1199 $coursenode->add(get_string('coursebadges', 'badges'), null,
1200 navigation_node
::TYPE_CONTAINER
, null, 'coursebadges',
1201 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
1203 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
1205 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
1206 navigation_node
::TYPE_SETTING
, null, 'coursebadges');
1208 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
1209 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
1211 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
1212 navigation_node
::TYPE_SETTING
, null, 'newbadge');
1218 * Triggered when badge is manually awarded.
1220 * @param object $data
1223 function badges_award_handle_manual_criteria_review(stdClass
$data) {
1224 $criteria = $data->crit
;
1225 $userid = $data->userid
;
1226 $badge = new badge($criteria->badgeid
);
1228 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
1232 if ($criteria->review($userid)) {
1233 $criteria->mark_complete($userid);
1235 if ($badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($userid)) {
1236 $badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($userid);
1237 $badge->issue($userid);
1245 * Process badge image from form data
1247 * @param badge $badge Badge object
1248 * @param string $iconfile Original file
1250 function badges_process_badge_image(badge
$badge, $iconfile) {
1252 require_once($CFG->libdir
. '/gdlib.php');
1254 if (!empty($CFG->gdversion
)) {
1255 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id
, $iconfile, true);
1258 // Clean up file draft area after badge image has been saved.
1259 $context = context_user
::instance($USER->id
, MUST_EXIST
);
1260 $fs = get_file_storage();
1261 $fs->delete_area_files($context->id
, 'user', 'draft');
1266 * Print badge image.
1268 * @param badge $badge Badge object
1269 * @param stdClass $context
1270 * @param string $size
1272 function print_badge_image(badge
$badge, stdClass
$context, $size = 'small') {
1273 $fsize = ($size == 'small') ?
'f2' : 'f1';
1275 $imageurl = moodle_url
::make_pluginfile_url($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $fsize, false);
1276 // Appending a random parameter to image link to forse browser reload the image.
1277 $imageurl->param('refresh', rand(1, 10000));
1278 $attributes = array('src' => $imageurl, 'alt' => s($badge->name
), 'class' => 'activatebadge');
1280 return html_writer
::empty_tag('img', $attributes);
1284 * Bake issued badge.
1286 * @param string $hash Unique hash of an issued badge.
1287 * @param int $badgeid ID of the original badge.
1288 * @param int $userid ID of badge recipient (optional).
1289 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1290 * @return string|url Returns either new file path hash or new file URL
1292 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1294 require_once(__DIR__
. '/../badges/lib/bakerlib.php');
1296 $badge = new badge($badgeid);
1297 $badge_context = $badge->get_context();
1298 $userid = ($userid) ?
$userid : $USER->id
;
1299 $user_context = context_user
::instance($userid);
1301 $fs = get_file_storage();
1302 if (!$fs->file_exists($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png')) {
1303 if ($file = $fs->get_file($badge_context->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f3.png')) {
1304 $contents = $file->get_content();
1306 $filehandler = new PNG_MetaDataHandler($contents);
1307 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1308 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1309 // Add assertion URL tExt chunk.
1310 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1312 'contextid' => $user_context->id
,
1313 'component' => 'badges',
1314 'filearea' => 'userbadge',
1315 'itemid' => $badge->id
,
1317 'filename' => $hash . '.png',
1320 // Create a file with added contents.
1321 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1323 return $newfile->get_pathnamehash();
1327 debugging('Error baking badge image!', DEBUG_DEVELOPER
);
1332 // If file exists and we just need its path hash, return it.
1334 $file = $fs->get_file($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png');
1335 return $file->get_pathnamehash();
1338 $fileurl = moodle_url
::make_pluginfile_url($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash, true);
1343 * Returns external backpack settings and badges from this backpack.
1345 * This function first checks if badges for the user are cached and
1346 * tries to retrieve them from the cache. Otherwise, badges are obtained
1347 * through curl request to the backpack.
1349 * @param int $userid Backpack user ID.
1350 * @param boolean $refresh Refresh badges collection in cache.
1351 * @return null|object Returns null is there is no backpack or object with backpack settings.
1353 function get_backpack_settings($userid, $refresh = false) {
1355 require_once(__DIR__
. '/../badges/lib/backpacklib.php');
1357 // Try to get badges from cache first.
1358 $badgescache = cache
::make('core', 'externalbadges');
1359 $out = $badgescache->get($userid);
1360 if ($out !== false && !$refresh) {
1363 // Get badges through curl request to the backpack.
1364 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
1366 $backpack = new OpenBadgesBackpackHandler($record);
1367 $out = new stdClass();
1368 $out->backpackurl
= $backpack->get_url();
1370 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id
))) {
1371 $out->totalcollections
= count($collections);
1372 $out->totalbadges
= 0;
1373 $out->badges
= array();
1374 foreach ($collections as $collection) {
1375 $badges = $backpack->get_badges($collection->collectionid
);
1376 if (isset($badges->badges
)) {
1377 $out->badges
= array_merge($out->badges
, $badges->badges
);
1378 $out->totalbadges +
= count($badges->badges
);
1380 $out->badges
= array_merge($out->badges
, array());
1384 $out->totalbadges
= 0;
1385 $out->totalcollections
= 0;
1388 $badgescache->set($userid, $out);
1396 * Download all user badges in zip archive.
1398 * @param int $userid ID of badge owner.
1400 function badges_download($userid) {
1402 $context = context_user
::instance($userid);
1403 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1405 // Get list of files to download.
1406 $fs = get_file_storage();
1407 $filelist = array();
1408 foreach ($records as $issued) {
1409 $badge = new badge($issued->badgeid
);
1410 // Need to make image name user-readable and unique using filename safe characters.
1411 $name = $badge->name
. ' ' . userdate($issued->dateissued
, '%d %b %Y') . ' ' . hash('crc32', $badge->id
);
1412 $name = str_replace(' ', '_', $name);
1413 $name = clean_param($name, PARAM_FILE
);
1414 if ($file = $fs->get_file($context->id
, 'badges', 'userbadge', $issued->badgeid
, '/', $issued->uniquehash
. '.png')) {
1415 $filelist[$name . '.png'] = $file;
1419 // Zip files and sent them to a user.
1420 $tempzip = tempnam($CFG->tempdir
.'/', 'mybadges');
1421 $zipper = new zip_packer();
1422 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1423 send_temp_file($tempzip, 'badges.zip');
1425 debugging("Problems with archiving the files.", DEBUG_DEVELOPER
);
1431 * Checks if badges can be pushed to external backpack.
1433 * @return string Code of backpack accessibility status.
1435 function badges_check_backpack_accessibility() {
1436 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING
) {
1437 // For behat sites, do not poll the remote badge site.
1438 // Behat sites should not be available, but we should pretend as though they are.
1443 include_once $CFG->libdir
. '/filelib.php';
1445 // Using fake assertion url to check whether backpack can access the web site.
1446 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1448 // Curl request to backpack baker.
1451 'FRESH_CONNECT' => true,
1452 'RETURNTRANSFER' => true,
1454 'CONNECTTIMEOUT' => 2,
1456 $location = BADGE_BACKPACKURL
. '/baker';
1457 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1459 $data = json_decode($out);
1460 if (!empty($curl->error
)) {
1461 return 'curl-request-timeout';
1463 if (isset($data->code
) && $data->code
== 'http-unreachable') {
1464 return 'http-unreachable';
1474 * Checks if user has external backpack connected.
1476 * @param int $userid ID of a user.
1477 * @return bool True|False whether backpack connection exists.
1479 function badges_user_has_backpack($userid) {
1481 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1485 * Handles what happens to the course badges when a course is deleted.
1487 * @param int $courseid course ID.
1490 function badges_handle_course_deletion($courseid) {
1492 include_once $CFG->libdir
. '/filelib.php';
1494 $systemcontext = context_system
::instance();
1495 $coursecontext = context_course
::instance($courseid);
1496 $fs = get_file_storage();
1498 // Move badges images to the system context.
1499 $fs->move_area_files_to_new_context($coursecontext->id
, $systemcontext->id
, 'badges', 'badgeimage');
1501 // Get all course badges.
1502 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE
, 'courseid' => $courseid));
1503 foreach ($badges as $badge) {
1504 // Archive badges in this course.
1505 $toupdate = new stdClass();
1506 $toupdate->id
= $badge->id
;
1507 $toupdate->type
= BADGE_TYPE_SITE
;
1508 $toupdate->courseid
= null;
1509 $toupdate->status
= BADGE_STATUS_ARCHIVED
;
1510 $DB->update_record('badge', $toupdate);
1515 * Loads JS files required for backpack support.
1520 function badges_setup_backpack_js() {
1522 if (!empty($CFG->badges_allowexternalbackpack
)) {
1523 $PAGE->requires
->string_for_js('error:backpackproblem', 'badges');
1524 $PAGE->requires
->js(new moodle_url(BADGE_BACKPACKURL
. '/issuer.js'), true);
1525 $PAGE->requires
->js('/badges/backpack.js', true);