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');
32 /* Include required user badge exporter */
33 use core_badges\external\user_badge_exporter
;
36 * Number of records per page.
38 define('BADGE_PERPAGE', 50);
41 * Badge award criteria aggregation method.
43 define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
46 * Badge award criteria aggregation method.
48 define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
51 * Inactive badge means that this badge cannot be earned and has not been awarded
52 * yet. Its award criteria can be changed.
54 define('BADGE_STATUS_INACTIVE', 0);
57 * Active badge means that this badge can we earned, but it has not been awarded
58 * yet. Can be deactivated for the purpose of changing its criteria.
60 define('BADGE_STATUS_ACTIVE', 1);
63 * Inactive badge can no longer be earned, but it has been awarded in the past and
64 * therefore its criteria cannot be changed.
66 define('BADGE_STATUS_INACTIVE_LOCKED', 2);
69 * Active badge means that it can be earned and has already been awarded to users.
70 * Its criteria cannot be changed any more.
72 define('BADGE_STATUS_ACTIVE_LOCKED', 3);
75 * Archived badge is considered deleted and can no longer be earned and is not
76 * displayed in the list of all badges.
78 define('BADGE_STATUS_ARCHIVED', 4);
81 * Badge type for site badges.
83 define('BADGE_TYPE_SITE', 1);
86 * Badge type for course badges.
88 define('BADGE_TYPE_COURSE', 2);
91 * Badge messaging schedule options.
93 define('BADGE_MESSAGE_NEVER', 0);
94 define('BADGE_MESSAGE_ALWAYS', 1);
95 define('BADGE_MESSAGE_DAILY', 2);
96 define('BADGE_MESSAGE_WEEKLY', 3);
97 define('BADGE_MESSAGE_MONTHLY', 4);
100 * URL of backpack. Custom ones can be added.
102 define('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
103 define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
106 * @deprecated since 3.9 (MDL-66357).
108 define('BADGE_BACKPACKAPIURL', 'https://backpack.openbadges.org');
109 define('BADGE_BACKPACKWEBURL', 'https://backpack.openbadges.org');
112 * Open Badges specifications.
114 define('OPEN_BADGES_V1', 1);
115 define('OPEN_BADGES_V2', 2);
116 define('OPEN_BADGES_V2P1', 2.1);
119 * Only use for Open Badges 2.0 specification
121 define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
122 define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
123 define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
124 define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
125 define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
126 define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
128 define('BACKPACK_MOVE_UP', -1);
129 define('BACKPACK_MOVE_DOWN', 1);
131 // Global badge class has been moved to the component namespace.
132 class_alias('\core_badges\badge', 'badge');
135 * Sends notifications to users about awarded badges.
137 * @param \core_badges\badge $badge Badge that was issued
138 * @param int $userid Recipient ID
139 * @param string $issued Unique hash of an issued badge
140 * @param string $filepathhash File path hash of an issued badge for attachments
142 function badges_notify_badge_award(badge
$badge, $userid, $issued, $filepathhash) {
145 $admin = get_admin();
146 $userfrom = new stdClass();
147 $userfrom->id
= $admin->id
;
148 $userfrom->email
= !empty($CFG->badges_defaultissuercontact
) ?
$CFG->badges_defaultissuercontact
: $admin->email
;
149 foreach (\core_user\fields
::get_name_fields() as $addname) {
150 $userfrom->$addname = !empty($CFG->badges_defaultissuername
) ?
'' : $admin->$addname;
152 $userfrom->firstname
= !empty($CFG->badges_defaultissuername
) ?
$CFG->badges_defaultissuername
: $admin->firstname
;
153 $userfrom->maildisplay
= true;
155 $badgeurl = new moodle_url('/badges/badge.php', ['hash' => $issued]);
156 $issuedlink = html_writer
::link($badgeurl, $badge->name
);
157 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
159 $params = new stdClass();
160 $params->badgename
= $badge->name
;
161 $params->username
= fullname($userto);
162 $params->badgelink
= $issuedlink;
163 $message = badge_message_from_template($badge->message
, $params);
164 $plaintext = html_to_text($message);
167 $eventdata = new \core\message\
message();
168 $eventdata->courseid
= is_null($badge->courseid
) ? SITEID
: $badge->courseid
; // Profile/site come with no courseid.
169 $eventdata->component
= 'moodle';
170 $eventdata->name
= 'badgerecipientnotice';
171 $eventdata->userfrom
= $userfrom;
172 $eventdata->userto
= $userto;
173 $eventdata->notification
= 1;
174 $eventdata->contexturl
= $badgeurl;
175 $eventdata->contexturlname
= $badge->name
;
176 $eventdata->subject
= $badge->messagesubject
;
177 $eventdata->fullmessage
= $plaintext;
178 $eventdata->fullmessageformat
= FORMAT_HTML
;
179 $eventdata->fullmessagehtml
= $message;
180 $eventdata->smallmessage
= '';
181 $eventdata->customdata
= [
182 'notificationiconurl' => moodle_url
::make_pluginfile_url(
183 $badge->get_context()->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1')->out(),
187 // Attach badge image if possible.
188 if (!empty($CFG->allowattachments
) && $badge->attachment
&& is_string($filepathhash)) {
189 $fs = get_file_storage();
190 $file = $fs->get_file_by_hash($filepathhash);
191 $eventdata->attachment
= $file;
192 $eventdata->attachname
= str_replace(' ', '_', $badge->name
) . ".png";
194 message_send($eventdata);
196 message_send($eventdata);
199 // Notify badge creator about the award if they receive notifications every time.
200 if ($badge->notification
== 1) {
201 $userfrom = core_user
::get_noreply_user();
202 $userfrom->maildisplay
= true;
204 $creator = $DB->get_record('user', array('id' => $badge->usercreated
), '*', MUST_EXIST
);
206 $a->user
= fullname($userto);
207 $a->link
= $issuedlink;
208 $creatormessage = get_string('creatorbody', 'badges', $a);
209 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
211 $eventdata = new \core\message\
message();
212 $eventdata->courseid
= $badge->courseid
;
213 $eventdata->component
= 'moodle';
214 $eventdata->name
= 'badgecreatornotice';
215 $eventdata->userfrom
= $userfrom;
216 $eventdata->userto
= $creator;
217 $eventdata->notification
= 1;
218 $eventdata->contexturl
= $badgeurl;
219 $eventdata->contexturlname
= $badge->name
;
220 $eventdata->subject
= $creatorsubject;
221 $eventdata->fullmessage
= html_to_text($creatormessage);
222 $eventdata->fullmessageformat
= FORMAT_HTML
;
223 $eventdata->fullmessagehtml
= $creatormessage;
224 $eventdata->smallmessage
= '';
225 $eventdata->customdata
= [
226 'notificationiconurl' => moodle_url
::make_pluginfile_url(
227 $badge->get_context()->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1')->out(),
231 message_send($eventdata);
232 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id
, 'userid' => $userid));
237 * Caclulates date for the next message digest to badge creators.
239 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
240 * @return int Timestamp for next cron
242 function badges_calculate_message_schedule($schedule) {
246 case BADGE_MESSAGE_DAILY
:
247 $tomorrow = new DateTime("1 day", core_date
::get_server_timezone_object());
248 $nextcron = $tomorrow->getTimestamp();
250 case BADGE_MESSAGE_WEEKLY
:
251 $nextweek = new DateTime("1 week", core_date
::get_server_timezone_object());
252 $nextcron = $nextweek->getTimestamp();
254 case BADGE_MESSAGE_MONTHLY
:
255 $nextmonth = new DateTime("1 month", core_date
::get_server_timezone_object());
256 $nextcron = $nextmonth->getTimestamp();
264 * Replaces variables in a message template and returns text ready to be emailed to a user.
266 * @param string $message Message body.
267 * @return string Message with replaced values
269 function badge_message_from_template($message, $params) {
271 foreach ($params as $key => $value) {
272 $msg = str_replace("%$key%", $value, $msg);
281 * @param int Type of badges to return
282 * @param int Course ID for course badges
283 * @param string $sort An SQL field to sort by
284 * @param string $dir The sort direction ASC|DESC
285 * @param int $page The page or records to return
286 * @param int $perpage The number of records to return per page
287 * @param int $user User specific search
288 * @return array $badge Array of records matching criteria
290 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE
, $user = 0) {
294 $where = "b.status != :deleted AND b.type = :type ";
295 $params['deleted'] = BADGE_STATUS_ARCHIVED
;
297 $userfields = array('b.id, b.name, b.status');
300 $userfields[] = 'bi.dateissued';
301 $userfields[] = 'bi.uniquehash';
302 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
303 $params['userid'] = $user;
304 $where .= " AND (b.status = 1 OR b.status = 3) ";
306 $fields = implode(', ', $userfields);
308 if ($courseid != 0 ) {
309 $where .= "AND b.courseid = :courseid ";
310 $params['courseid'] = $courseid;
313 $sorting = (($sort != '' && $dir != '') ?
'ORDER BY ' . $sort . ' ' . $dir : '');
314 $params['type'] = $type;
316 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
317 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
320 foreach ($records as $r) {
321 $badge = new badge($r->id
);
322 $badges[$r->id
] = $badge;
324 $badges[$r->id
]->dateissued
= $r->dateissued
;
325 $badges[$r->id
]->uniquehash
= $r->uniquehash
;
327 $badges[$r->id
]->awards
= $DB->count_records_sql('SELECT COUNT(b.userid)
328 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
329 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id
));
330 $badges[$r->id
]->statstring
= $badge->get_status_name();
337 * Get badges for a specific user.
339 * @param int $userid User ID
340 * @param int $courseid Badges earned by a user in a specific course
341 * @param int $page The page or records to return
342 * @param int $perpage The number of records to return per page
343 * @param string $search A simple string to search for
344 * @param bool $onlypublic Return only public badges
345 * @return array of badges ordered by decreasing date of issue
347 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
365 WHERE b.id = bi.badgeid
367 AND bi.userid = :userid';
369 if (!empty($search)) {
370 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
371 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
374 $sql .= ' AND (bi.visible = 1) ';
377 if (empty($CFG->badges_allowcoursebadges
)) {
378 $sql .= ' AND b.courseid IS NULL';
379 } else if ($courseid != 0) {
380 $sql .= ' AND (b.courseid = :courseid) ';
381 $params['courseid'] = $courseid;
383 $sql .= ' ORDER BY bi.dateissued DESC';
384 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
392 * @param string $hash
393 * @return object|bool
395 function badges_get_badge_by_hash(string $hash): object|
bool {
410 WHERE b.id = bi.badgeid
412 AND ' . $DB->sql_compare_text('bi.uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40);
413 $badge = $DB->get_record_sql($sql, ['hash' => $hash], IGNORE_MISSING
);
418 * Update badge instance to external functions.
420 * @param stdClass $badge
421 * @param stdClass $user
424 function badges_prepare_badge_for_external(stdClass
$badge, stdClass
$user): object {
426 if ($badge->type
== BADGE_TYPE_SITE
) {
427 $context = context_system
::instance();
429 $context = context_course
::instance($badge->courseid
);
431 $canconfiguredetails = has_capability('moodle/badges:configuredetails', $context);
432 // If the user is viewing another user's badge and doesn't have the right capability return only part of the data.
433 if ($USER->id
!= $user->id
&& !$canconfiguredetails) {
436 'name' => $badge->name
,
437 'type' => $badge->type
,
438 'description' => $badge->description
,
439 'issuername' => $badge->issuername
,
440 'issuerurl' => $badge->issuerurl
,
441 'issuercontact' => $badge->issuercontact
,
442 'uniquehash' => $badge->uniquehash
,
443 'dateissued' => $badge->dateissued
,
444 'dateexpire' => $badge->dateexpire
,
445 'version' => $badge->version
,
446 'language' => $badge->language
,
447 'imageauthorname' => $badge->imageauthorname
,
448 'imageauthoremail' => $badge->imageauthoremail
,
449 'imageauthorurl' => $badge->imageauthorurl
,
450 'imagecaption' => $badge->imagecaption
,
454 // Create a badge instance to be able to get the endorsement and other info.
455 $badgeinstance = new badge($badge->id
);
456 $endorsement = $badgeinstance->get_endorsement();
457 $alignments = $badgeinstance->get_alignments();
458 $relatedbadges = $badgeinstance->get_related_badges();
460 if (!$canconfiguredetails) {
461 // Return only the properties visible by the user.
462 if (!empty($alignments)) {
463 foreach ($alignments as $alignment) {
464 unset($alignment->targetdescription
);
465 unset($alignment->targetframework
);
466 unset($alignment->targetcode
);
470 if (!empty($relatedbadges)) {
471 foreach ($relatedbadges as $relatedbadge) {
472 unset($relatedbadge->version
);
473 unset($relatedbadge->language
);
474 unset($relatedbadge->type
);
480 'context' => $context,
481 'endorsement' => $endorsement ?
$endorsement : null,
482 'alignment' => $alignments,
483 'relatedbadges' => $relatedbadges,
486 $exporter = new user_badge_exporter($badge, $related);
487 return $exporter->export($PAGE->get_renderer('core'));
491 * Extends the course administration navigation with the Badges page
493 * @param navigation_node $coursenode
494 * @param object $course
496 function badges_add_course_navigation(navigation_node
$coursenode, stdClass
$course) {
499 $coursecontext = context_course
::instance($course->id
);
500 $isfrontpage = (!$coursecontext ||
$course->id
== $SITE->id
);
501 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
502 'moodle/badges:createbadge',
503 'moodle/badges:awardbadge',
504 'moodle/badges:configurecriteria',
505 'moodle/badges:configuremessages',
506 'moodle/badges:configuredetails',
507 'moodle/badges:deletebadge'), $coursecontext);
509 if (!empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
) && !$isfrontpage && $canmanage) {
510 $coursenode->add(get_string('coursebadges', 'badges'), null,
511 navigation_node
::TYPE_CONTAINER
, null, 'coursebadges',
512 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
514 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
516 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
517 navigation_node
::TYPE_SETTING
, null, 'coursebadges');
519 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
520 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
522 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
523 navigation_node
::TYPE_SETTING
, null, 'newbadge');
529 * Triggered when badge is manually awarded.
531 * @param object $data
534 function badges_award_handle_manual_criteria_review(stdClass
$data) {
535 $criteria = $data->crit
;
536 $userid = $data->userid
;
537 $badge = new badge($criteria->badgeid
);
539 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
543 if ($criteria->review($userid)) {
544 $criteria->mark_complete($userid);
546 if ($badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($userid)) {
547 $badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($userid);
548 $badge->issue($userid);
556 * Process badge image from form data
558 * @param badge $badge Badge object
559 * @param string $iconfile Original file
561 function badges_process_badge_image(badge
$badge, $iconfile) {
563 require_once($CFG->libdir
. '/gdlib.php');
565 if (!empty($CFG->gdversion
)) {
566 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id
, $iconfile, true);
569 // Clean up file draft area after badge image has been saved.
570 $context = context_user
::instance($USER->id
, MUST_EXIST
);
571 $fs = get_file_storage();
572 $fs->delete_area_files($context->id
, 'user', 'draft');
579 * @param badge $badge Badge object
580 * @param stdClass $context
581 * @param string $size
583 function print_badge_image(badge
$badge, stdClass
$context, $size = 'small') {
584 $fsize = ($size == 'small') ?
'f2' : 'f1';
586 $imageurl = moodle_url
::make_pluginfile_url($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $fsize, false);
587 // Appending a random parameter to image link to forse browser reload the image.
588 $imageurl->param('refresh', rand(1, 10000));
589 $attributes = array('src' => $imageurl, 'alt' => s($badge->name
), 'class' => 'activatebadge');
591 return html_writer
::empty_tag('img', $attributes);
597 * @param string $hash Unique hash of an issued badge.
598 * @param int $badgeid ID of the original badge.
599 * @param int $userid ID of badge recipient (optional).
600 * @param boolean $pathhash Return file pathhash instead of image url (optional).
601 * @return string|url Returns either new file path hash or new file URL
603 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
605 require_once(__DIR__
. '/../badges/lib/bakerlib.php');
607 $badge = new badge($badgeid);
608 $badge_context = $badge->get_context();
609 $userid = ($userid) ?
$userid : $USER->id
;
610 $user_context = context_user
::instance($userid);
612 $fs = get_file_storage();
613 if (!$fs->file_exists($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png')) {
614 if ($file = $fs->get_file($badge_context->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f3.png')) {
615 $contents = $file->get_content();
617 $filehandler = new PNG_MetaDataHandler($contents);
618 // For now, the site backpack OB version will be used as default.
619 $obversion = badges_open_badges_backpack_api();
620 $assertion = new core_badges_assertion($hash, $obversion);
621 $assertionjson = json_encode($assertion->get_badge_assertion());
622 if ($filehandler->check_chunks("iTXt", "openbadges")) {
623 // Add assertion URL iTXt chunk.
624 $newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
626 'contextid' => $user_context->id
,
627 'component' => 'badges',
628 'filearea' => 'userbadge',
629 'itemid' => $badge->id
,
631 'filename' => $hash . '.png',
634 // Create a file with added contents.
635 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
637 return $newfile->get_pathnamehash();
641 debugging('Error baking badge image!', DEBUG_DEVELOPER
);
646 // If file exists and we just need its path hash, return it.
648 $file = $fs->get_file($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png');
649 return $file->get_pathnamehash();
652 $fileurl = moodle_url
::make_pluginfile_url($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash, true);
657 * Returns external backpack settings and badges from this backpack.
659 * This function first checks if badges for the user are cached and
660 * tries to retrieve them from the cache. Otherwise, badges are obtained
661 * through curl request to the backpack.
663 * @param int $userid Backpack user ID.
664 * @param boolean $refresh Refresh badges collection in cache.
665 * @return null|object Returns null is there is no backpack or object with backpack settings.
667 function get_backpack_settings($userid, $refresh = false) {
670 // Try to get badges from cache first.
671 $badgescache = cache
::make('core', 'externalbadges');
672 $out = $badgescache->get($userid);
673 if ($out !== false && !$refresh) {
676 // Get badges through curl request to the backpack.
677 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
679 $sitebackpack = badges_get_site_backpack($record->externalbackpackid
);
680 $backpack = new \core_badges\backpack_api
($sitebackpack, $record);
681 $out = new stdClass();
682 $out->backpackid
= $sitebackpack->id
;
684 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id
))) {
685 $out->totalcollections
= count($collections);
686 $out->totalbadges
= 0;
687 $out->badges
= array();
688 foreach ($collections as $collection) {
689 $badges = $backpack->get_badges($collection, true);
690 if (!empty($badges)) {
691 $out->badges
= array_merge($out->badges
, $badges);
692 $out->totalbadges +
= count($badges);
694 $out->badges
= array_merge($out->badges
, array());
698 $out->totalbadges
= 0;
699 $out->totalcollections
= 0;
702 $badgescache->set($userid, $out);
710 * Download all user badges in zip archive.
712 * @param int $userid ID of badge owner.
714 function badges_download($userid) {
716 $context = context_user
::instance($userid);
717 $records = $DB->get_records('badge_issued', array('userid' => $userid));
719 // Get list of files to download.
720 $fs = get_file_storage();
722 foreach ($records as $issued) {
723 $badge = new badge($issued->badgeid
);
724 // Need to make image name user-readable and unique using filename safe characters.
725 $name = $badge->name
. ' ' . userdate($issued->dateissued
, '%d %b %Y') . ' ' . hash('crc32', $badge->id
);
726 $name = str_replace(' ', '_', $name);
727 $name = clean_param($name, PARAM_FILE
);
728 if ($file = $fs->get_file($context->id
, 'badges', 'userbadge', $issued->badgeid
, '/', $issued->uniquehash
. '.png')) {
729 $filelist[$name . '.png'] = $file;
733 // Zip files and sent them to a user.
734 $tempzip = tempnam($CFG->tempdir
.'/', 'mybadges');
735 $zipper = new zip_packer();
736 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
737 send_temp_file($tempzip, 'badges.zip');
739 debugging("Problems with archiving the files.", DEBUG_DEVELOPER
);
745 * Checks if user has external backpack connected.
747 * @param int $userid ID of a user.
748 * @return bool True|False whether backpack connection exists.
750 function badges_user_has_backpack($userid) {
752 return $DB->record_exists('badge_backpack', array('userid' => $userid));
756 * Handles what happens to the course badges when a course is deleted.
758 * @param int $courseid course ID.
761 function badges_handle_course_deletion($courseid) {
763 include_once $CFG->libdir
. '/filelib.php';
765 $systemcontext = context_system
::instance();
766 $coursecontext = context_course
::instance($courseid);
767 $fs = get_file_storage();
769 // Move badges images to the system context.
770 $fs->move_area_files_to_new_context($coursecontext->id
, $systemcontext->id
, 'badges', 'badgeimage');
772 // Get all course badges.
773 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE
, 'courseid' => $courseid));
774 foreach ($badges as $badge) {
775 // Archive badges in this course.
776 $toupdate = new stdClass();
777 $toupdate->id
= $badge->id
;
778 $toupdate->type
= BADGE_TYPE_SITE
;
779 $toupdate->courseid
= null;
780 $toupdate->status
= BADGE_STATUS_ARCHIVED
;
781 $DB->update_record('badge', $toupdate);
786 * Create the site backpack with this data.
788 * @param stdClass $data The new backpack data.
791 function badges_create_site_backpack($data) {
793 $context = context_system
::instance();
794 require_capability('moodle/badges:manageglobalsettings', $context);
796 $max = $DB->get_field_sql('SELECT MAX(sortorder) FROM {badge_external_backpack}');
797 $data->sortorder
= $max +
1;
799 return badges_save_external_backpack($data);
803 * Update the backpack with this id.
805 * @param integer $id The backpack to edit
806 * @param stdClass $data The new backpack data.
809 function badges_update_site_backpack($id, $data) {
811 $context = context_system
::instance();
812 require_capability('moodle/badges:manageglobalsettings', $context);
814 if ($backpack = badges_get_site_backpack($id)) {
816 return badges_save_external_backpack($data);
823 * Delete the backpack with this id.
825 * @param integer $id The backpack to delete.
828 function badges_delete_site_backpack($id) {
831 $context = context_system
::instance();
832 require_capability('moodle/badges:manageglobalsettings', $context);
834 // Only remove site backpack if it's not the default one.
835 $defaultbackpack = badges_get_site_primary_backpack();
836 if ($defaultbackpack->id
!= $id && $DB->record_exists('badge_external_backpack', ['id' => $id])) {
837 $transaction = $DB->start_delegated_transaction();
839 // Remove connections for users to this backpack.
840 $sql = "SELECT DISTINCT bb.id
841 FROM {badge_backpack} bb
842 WHERE bb.externalbackpackid = :backpackid";
843 $params = ['backpackid' => $id];
844 $userbackpacks = $DB->get_fieldset_sql($sql, $params);
845 if ($userbackpacks) {
846 // Delete user external collections references to this backpack.
847 list($insql, $params) = $DB->get_in_or_equal($userbackpacks);
848 $DB->delete_records_select('badge_external', "backpackid $insql", $params);
850 $DB->delete_records('badge_backpack', ['externalbackpackid' => $id]);
852 // Delete backpack entry.
853 $result = $DB->delete_records('badge_external_backpack', ['id' => $id]);
855 $transaction->allow_commit();
864 * Perform the actual create/update of external bakpacks. Any checks on the validity of the id will need to be
865 * performed before it reaches this function.
867 * @param stdClass $data The backpack data we are updating/inserting
868 * @return int Returns the id of the new/updated record
870 function badges_save_external_backpack(stdClass
$data) {
872 if ($data->apiversion
== OPEN_BADGES_V2P1
) {
873 // Check if there is an existing issuer for the given backpackapiurl.
874 foreach (core\oauth2\api
::get_all_issuers() as $tmpissuer) {
875 if ($data->backpackweburl
== $tmpissuer->get('baseurl')) {
876 $issuer = $tmpissuer;
881 // Create the issuer if it doesn't exist yet.
882 if (empty($issuer)) {
883 $issuer = new \core\oauth2\
issuer(0, (object) [
884 'name' => $data->backpackweburl
,
885 'baseurl' => $data->backpackweburl
,
886 // Note: This is required because the DB schema is broken and does not accept a null value when it should.
892 // This can't be run from PHPUNIT because testing platforms need real URLs.
893 // In the future, this request can be moved to the moodle-exttests repository.
895 // Create/update the endpoints for the issuer.
896 \core\oauth2\discovery\imsbadgeconnect
::create_endpoints($issuer);
897 $data->oauth2_issuerid
= $issuer->get('id');
899 $apibase = \core\oauth2\endpoint
::get_record([
900 'issuerid' => $data->oauth2_issuerid
,
903 $data->backpackapiurl
= $apibase->get('url');
906 $backpack = new stdClass();
908 $backpack->apiversion
= $data->apiversion
;
909 $backpack->backpackweburl
= $data->backpackweburl
;
910 $backpack->backpackapiurl
= $data->backpackapiurl
;
911 $backpack->oauth2_issuerid
= $data->oauth2_issuerid ??
'';
912 if (isset($data->sortorder
)) {
913 $backpack->sortorder
= $data->sortorder
;
916 if (empty($data->id
)) {
917 $backpack->id
= $DB->insert_record('badge_external_backpack', $backpack);
919 $backpack->id
= $data->id
;
920 $DB->update_record('badge_external_backpack', $backpack);
922 $data->externalbackpackid
= $backpack->id
;
925 badges_save_backpack_credentials($data);
926 return $data->externalbackpackid
;
930 * Create a backpack with the provided details. Stores the auth details of the backpack
932 * @param stdClass $data Backpack specific data.
933 * @return int The id of the external backpack that the credentials correspond to
935 function badges_save_backpack_credentials(stdClass
$data) {
938 if (isset($data->backpackemail
) && isset($data->password
)) {
939 $backpack = new stdClass();
941 $backpack->email
= $data->backpackemail
;
942 $backpack->password
= !empty($data->password
) ?
$data->password
: '';
943 $backpack->externalbackpackid
= $data->externalbackpackid
;
944 $backpack->userid
= $data->userid ??
0;
945 $backpack->backpackuid
= $data->backpackuid ??
0;
946 $backpack->autosync
= $data->autosync ??
0;
948 if (!empty($data->badgebackpack
)) {
949 $backpack->id
= $data->badgebackpack
;
950 } else if (!empty($data->id
)) {
951 $backpack->id
= $data->id
;
954 if (empty($backpack->id
)) {
955 $backpack->id
= $DB->insert_record('badge_backpack', $backpack);
957 $DB->update_record('badge_backpack', $backpack);
960 return $backpack->externalbackpackid
;
963 return $data->externalbackpackid ??
0;
967 * Is any backpack enabled that supports open badges V1?
968 * @param int|null $backpackid Check the version of the given id OR if null the sitewide backpack
971 function badges_open_badges_backpack_api(?
int $backpackid = null) {
973 $backpack = badges_get_site_primary_backpack();
975 $backpack = badges_get_site_backpack($backpackid);
978 if (empty($backpack->apiversion
)) {
979 return OPEN_BADGES_V2
;
981 return $backpack->apiversion
;
985 * Get a site backpacks by id for a particular user or site (if userid is 0)
987 * @param int $id The backpack id.
988 * @param int $userid The owner of the backpack, 0 if it's a sitewide backpack else a user's site backpack
991 function badges_get_site_backpack($id, int $userid = 0) {
994 $sql = "SELECT beb.*, bb.id AS badgebackpack, bb.password, bb.email AS backpackemail
995 FROM {badge_external_backpack} beb
996 LEFT JOIN {badge_backpack} bb ON bb.externalbackpackid = beb.id AND bb.userid=:userid
999 return $DB->get_record_sql($sql, ['id' => $id, 'userid' => $userid]);
1003 * Get the user backpack for the currently logged in user OR the provided user
1005 * @param int|null $userid The user whose backpack you're requesting for. If null, get the logged in user's backpack
1006 * @return mixed The user's backpack or none.
1007 * @throws dml_exception
1009 function badges_get_user_backpack(?
int $userid = 0) {
1014 $userid = $USER->id
;
1017 $sql = "SELECT beb.*, bb.id AS badgebackpack, bb.password, bb.email AS backpackemail
1018 FROM {badge_external_backpack} beb
1019 JOIN {badge_backpack} bb ON bb.externalbackpackid = beb.id AND bb.userid=:userid";
1021 return $DB->get_record_sql($sql, ['userid' => $userid]);
1025 * Get the primary backpack for the site
1029 function badges_get_site_primary_backpack() {
1033 FROM {badge_external_backpack}
1034 WHERE sortorder = (SELECT MIN(sortorder)
1035 FROM {badge_external_backpack} b2)';
1036 $firstbackpack = $DB->get_record_sql($sql, null, MUST_EXIST
);
1038 return badges_get_site_backpack($firstbackpack->id
);
1042 * List the backpacks at site level.
1044 * @return array(stdClass)
1046 function badges_get_site_backpacks() {
1049 $defaultbackpack = badges_get_site_primary_backpack();
1050 $all = $DB->get_records('badge_external_backpack', null, 'sortorder ASC');
1051 foreach ($all as $key => $bp) {
1052 if ($bp->id
== $defaultbackpack->id
) {
1053 $all[$key]->sitebackpack
= true;
1055 $all[$key]->sitebackpack
= false;
1063 * Moves the backpack in the list one position up or down.
1065 * @param int $backpackid The backpack identifier to be moved.
1066 * @param int $direction The direction (BACKPACK_MOVE_UP/BACKPACK_MOVE_DOWN) where to move the backpack.
1068 * @throws \moodle_exception if attempting to use invalid direction value.
1070 function badges_change_sortorder_backpacks(int $backpackid, int $direction): void
{
1073 if ($direction != BACKPACK_MOVE_UP
&& $direction != BACKPACK_MOVE_DOWN
) {
1074 throw new \
coding_exception(
1075 'Must use a valid backpack API move direction constant (BACKPACK_MOVE_UP or BACKPACK_MOVE_DOWN)');
1078 $backpacks = badges_get_site_backpacks();
1079 $backpacktoupdate = $backpacks[$backpackid];
1081 $currentsortorder = $backpacktoupdate->sortorder
;
1082 $targetsortorder = $currentsortorder +
$direction;
1083 if ($targetsortorder > 0 && $targetsortorder <= count($backpacks) ) {
1084 foreach ($backpacks as $backpack) {
1085 if ($backpack->sortorder
== $targetsortorder) {
1086 $backpack->sortorder
= $backpack->sortorder
- $direction;
1087 $DB->update_record('badge_external_backpack', $backpack);
1091 $backpacktoupdate->sortorder
= $targetsortorder;
1092 $DB->update_record('badge_external_backpack', $backpacktoupdate);
1097 * List the supported badges api versions.
1099 * @return array(version)
1101 function badges_get_badge_api_versions() {
1103 (string)OPEN_BADGES_V1
=> get_string('openbadgesv1', 'badges'),
1104 (string)OPEN_BADGES_V2
=> get_string('openbadgesv2', 'badges'),
1105 (string)OPEN_BADGES_V2P1
=> get_string('openbadgesv2p1', 'badges')
1110 * Get the default issuer for a badge from this site.
1114 function badges_get_default_issuer() {
1117 $sitebackpack = badges_get_site_primary_backpack();
1119 $issuerurl = new moodle_url('/');
1120 $issuer['name'] = $CFG->badges_defaultissuername
;
1121 if (empty($issuer['name'])) {
1122 $issuer['name'] = $SITE->fullname ?
$SITE->fullname
: $SITE->shortname
;
1124 $issuer['url'] = $issuerurl->out(false);
1125 $issuer['email'] = $sitebackpack->backpackemail ?
: $CFG->badges_defaultissuercontact
;
1126 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT
;
1127 $issuerid = new moodle_url('/badges/issuer_json.php');
1128 $issuer['id'] = $issuerid->out(false);
1129 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER
;
1134 * Disconnect from the user backpack by deleting the user preferences.
1136 * @param integer $userid The user to diconnect.
1139 function badges_disconnect_user_backpack($userid) {
1142 // We can only change backpack settings for our own real backpack.
1143 if ($USER->id
!= $userid ||
1144 \core\session\manager
::is_loggedinas()) {
1149 unset_user_preference('badges_email_verify_secret');
1150 unset_user_preference('badges_email_verify_address');
1151 unset_user_preference('badges_email_verify_backpackid');
1152 unset_user_preference('badges_email_verify_password');
1158 * Used to remember which objects we connected with a backpack before.
1160 * @param integer $sitebackpackid The site backpack to connect to.
1161 * @param string $type The type of this remote object.
1162 * @param string $internalid The id for this object on the Moodle site.
1163 * @param string $param The param we need to return. Defaults to the externalid.
1164 * @return mixed The id or false if it doesn't exist.
1166 function badges_external_get_mapping($sitebackpackid, $type, $internalid, $param = 'externalid') {
1168 // Return externalid if it exists.
1170 'sitebackpackid' => $sitebackpackid,
1172 'internalid' => $internalid
1175 $record = $DB->get_record('badge_external_identifier', $params, $param, IGNORE_MISSING
);
1177 return $record->$param;
1183 * Save the info about which objects we connected with a backpack before.
1185 * @param integer $sitebackpackid The site backpack to connect to.
1186 * @param string $type The type of this remote object.
1187 * @param string $internalid The id for this object on the Moodle site.
1188 * @param string $externalid The id of this object on the remote site.
1191 function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
1195 'sitebackpackid' => $sitebackpackid,
1197 'internalid' => $internalid,
1198 'externalid' => $externalid
1201 return $DB->insert_record('badge_external_identifier', $params);
1205 * Delete all external mapping information for a backpack.
1207 * @param integer $sitebackpackid The site backpack to connect to.
1210 function badges_external_delete_mappings($sitebackpackid) {
1213 $params = ['sitebackpackid' => $sitebackpackid];
1215 return $DB->delete_records('badge_external_identifier', $params);
1219 * Delete a specific external mapping information for a backpack.
1221 * @param integer $sitebackpackid The site backpack to connect to.
1222 * @param string $type The type of this remote object.
1223 * @param string $internalid The id for this object on the Moodle site.
1226 function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
1230 'sitebackpackid' => $sitebackpackid,
1232 'internalid' => $internalid
1235 $DB->delete_record('badge_external_identifier', $params);
1239 * Create and send a verification email to the email address supplied.
1241 * Since we're not sending this email to a user, email_to_user can't be used
1242 * but this function borrows largely the code from that process.
1244 * @param string $email the email address to send the verification email to.
1245 * @param int $backpackid the id of the backpack to connect to
1246 * @param string $backpackpassword the user entered password to connect to this backpack
1247 * @return true if the email was sent successfully, false otherwise.
1249 function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1252 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1253 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1254 // of verification emails to said address.
1255 $secret = random_string(15);
1256 set_user_preference('badges_email_verify_secret', $secret);
1257 set_user_preference('badges_email_verify_address', $email);
1258 set_user_preference('badges_email_verify_backpackid', $backpackid);
1259 set_user_preference('badges_email_verify_password', $backpackpassword);
1262 $tempuser = $DB->get_record('user', array('id' => $USER->id
), '*', MUST_EXIST
);
1263 $tempuser->email
= $email;
1264 $noreplyuser = core_user
::get_noreply_user();
1266 // Generate the verification email body.
1267 $verificationurl = '/badges/backpackemailverify.php';
1268 $verificationurl = new moodle_url($verificationurl);
1269 $verificationpath = $verificationurl->out(false);
1272 $link = $verificationpath . '?data='. $secret;
1273 // Hard-coded button styles, because CSS can't be used in emails.
1275 'background-color: #0f6cbf',
1279 'text-align: center',
1280 'text-decoration: none',
1281 'display: inline-block',
1286 'border-radius: 8px',
1288 $button = html_writer
::start_tag('center') .
1291 get_string('verifyemail', 'badges'),
1292 ['style' => implode(';', $buttonstyles)]) .
1293 html_writer
::end_tag('center');
1295 'link' => html_writer
::link($link, $link),
1296 'buttonlink' => html_writer
::link($link, $button),
1297 'sitename' => $site->fullname
,
1298 'admin' => generate_email_signoff(),
1299 'userfirstname' => $USER->firstname
,
1302 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname
);
1303 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1304 $messagehtml = text_to_html($messagetext, false, false, true);
1306 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1310 * Return all the enabled criteria types for this site.
1312 * @param boolean $enabled
1315 function badges_list_criteria($enabled = true) {
1319 BADGE_CRITERIA_TYPE_OVERALL
=> 'overall',
1320 BADGE_CRITERIA_TYPE_ACTIVITY
=> 'activity',
1321 BADGE_CRITERIA_TYPE_MANUAL
=> 'manual',
1322 BADGE_CRITERIA_TYPE_SOCIAL
=> 'social',
1323 BADGE_CRITERIA_TYPE_COURSE
=> 'course',
1324 BADGE_CRITERIA_TYPE_COURSESET
=> 'courseset',
1325 BADGE_CRITERIA_TYPE_PROFILE
=> 'profile',
1326 BADGE_CRITERIA_TYPE_BADGE
=> 'badge',
1327 BADGE_CRITERIA_TYPE_COHORT
=> 'cohort',
1328 BADGE_CRITERIA_TYPE_COMPETENCY
=> 'competency',
1331 foreach ($types as $key => $type) {
1332 $class = 'award_criteria_' . $type;
1333 $file = $CFG->dirroot
. '/badges/criteria/' . $class . '.php';
1334 if (file_exists($file)) {
1335 require_once($file);
1337 if (!$class::is_enabled()) {
1338 unset($types[$key]);
1347 * Check if any badge has records for competencies.
1349 * @param array $competencyids Array of competencies ids.
1350 * @return boolean Return true if competencies were found in any badge.
1352 function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1355 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED
);
1357 $sql = "SELECT DISTINCT bc.badgeid
1358 FROM {badge_criteria} bc
1359 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1360 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1361 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY
;
1363 return $DB->record_exists_sql($sql, $params);
1367 * Creates single message for all notification and sends it out
1369 * @param object $badge A badge which is notified about.
1371 function badge_assemble_notification(stdClass
$badge) {
1374 $userfrom = core_user
::get_noreply_user();
1375 $userfrom->maildisplay
= true;
1377 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id
))) {
1378 // Get badge creator.
1379 $creator = $DB->get_record('user', array('id' => $badge->creator
), '*', MUST_EXIST
);
1380 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
1381 $creatormessage = '';
1383 // Put all messages in one digest.
1384 foreach ($msgs as $msg) {
1385 $issuedlink = html_writer
::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash
)), $badge->name
);
1386 $recipient = $DB->get_record('user', array('id' => $msg->userid
), '*', MUST_EXIST
);
1388 $a = new stdClass();
1389 $a->user
= fullname($recipient);
1390 $a->link
= $issuedlink;
1391 $creatormessage .= get_string('creatorbody', 'badges', $a);
1392 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid
, 'userid' => $msg->userid
));
1395 // Create a message object.
1396 $eventdata = new \core\message\
message();
1397 $eventdata->courseid
= SITEID
;
1398 $eventdata->component
= 'moodle';
1399 $eventdata->name
= 'badgecreatornotice';
1400 $eventdata->userfrom
= $userfrom;
1401 $eventdata->userto
= $creator;
1402 $eventdata->notification
= 1;
1403 $eventdata->subject
= $creatorsubject;
1404 $eventdata->fullmessage
= format_text_email($creatormessage, FORMAT_HTML
);
1405 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1406 $eventdata->fullmessagehtml
= $creatormessage;
1407 $eventdata->smallmessage
= $creatorsubject;
1409 message_send($eventdata);
1414 * Attempt to authenticate with the site backpack credentials and return an error
1415 * if the authentication fails. If external backpacks are not enabled, this will
1416 * not perform any test.
1420 function badges_verify_site_backpack() {
1421 $defaultbackpack = badges_get_site_primary_backpack();
1422 return badges_verify_backpack($defaultbackpack->id
);
1426 * Attempt to authenticate with a backpack credentials and return an error
1427 * if the authentication fails.
1428 * If external backpacks are not enabled or the backpack version is different
1429 * from OBv2, this will not perform any test.
1431 * @param int $backpackid Backpack identifier to verify.
1432 * @return string The result of the verification process.
1434 function badges_verify_backpack(int $backpackid) {
1435 global $OUTPUT, $CFG;
1437 if (empty($CFG->badges_allowexternalbackpack
)) {
1441 $backpack = badges_get_site_backpack($backpackid);
1442 if (empty($backpack->apiversion
) ||
($backpack->apiversion
== OPEN_BADGES_V2
)) {
1443 $backpackapi = new \core_badges\backpack_api
($backpack);
1445 // Clear any cached access tokens in the session.
1446 $backpackapi->clear_system_user_session();
1448 // Now attempt a login with these credentials.
1449 $result = $backpackapi->authenticate();
1450 if (empty($result) ||
!empty($result->error
)) {
1451 $warning = $backpackapi->get_authentication_error();
1453 $params = ['id' => $backpack->id
, 'action' => 'edit'];
1454 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1456 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1457 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1458 return $OUTPUT->container($icon . $message, 'text-danger');
1466 * Generate a public badgr URL that conforms to OBv2. This is done because badgr responses do not currently conform to
1469 * WARNING: This is an extremely hacky way of implementing this and should be removed once the standards are conformed to.
1471 * @param stdClass $backpack The Badgr backpack we are pushing to
1472 * @param string $type The type of object we are dealing with either Issuer, Assertion OR Badge.
1473 * @param string $externalid The externalid as provided by the backpack
1474 * @return string The public URL to access Badgr objects
1476 function badges_generate_badgr_open_url($backpack, $type, $externalid) {
1477 if (badges_open_badges_backpack_api($backpack->id
) == OPEN_BADGES_V2
) {
1478 $entity = strtolower($type);
1479 if ($type == OPEN_BADGES_V2_TYPE_BADGE
) {
1482 $url = new moodle_url($backpack->backpackapiurl
);
1483 return "{$url->get_scheme()}://{$url->get_host()}/public/{$entity}s/$externalid";