Merge branch 'MDL-81713-main' of https://github.com/junpataleta/moodle
[moodle.git] / lib / badgeslib.php
blob357aad0d3638fdbb9f815cc7f216529d81c7f554
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Contains classes, functions and constants used in badges.
20 * @package core
21 * @subpackage badges
22 * @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @author Yuliya Bozhko <yuliya.bozhko@totaralms.com>
27 defined('MOODLE_INTERNAL') || die();
29 /* Include required award criteria library. */
30 require_once($CFG->dirroot . '/badges/criteria/award_criteria.php');
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) {
143 global $CFG, $DB;
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);
166 // Notify recipient.
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(),
184 'hash' => $issued,
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);
195 } else {
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);
205 $a = new stdClass();
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(),
228 'hash' => $issued,
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 int $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) {
243 $nextcron = 0;
245 switch ($schedule) {
246 case BADGE_MESSAGE_DAILY:
247 $tomorrow = new DateTime("1 day", core_date::get_server_timezone_object());
248 $nextcron = $tomorrow->getTimestamp();
249 break;
250 case BADGE_MESSAGE_WEEKLY:
251 $nextweek = new DateTime("1 week", core_date::get_server_timezone_object());
252 $nextcron = $nextweek->getTimestamp();
253 break;
254 case BADGE_MESSAGE_MONTHLY:
255 $nextmonth = new DateTime("1 month", core_date::get_server_timezone_object());
256 $nextcron = $nextmonth->getTimestamp();
257 break;
260 return $nextcron;
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) {
270 $msg = $message;
271 foreach ($params as $key => $value) {
272 $msg = str_replace("%$key%", $value, $msg);
275 return $msg;
279 * Get all badges.
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) {
291 global $DB;
292 $records = array();
293 $params = array();
294 $where = "b.status != :deleted AND b.type = :type ";
295 $params['deleted'] = BADGE_STATUS_ARCHIVED;
297 $userfields = array('b.id, b.name, b.status');
298 $usersql = "";
299 if ($user != 0) {
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);
319 $badges = array();
320 foreach ($records as $r) {
321 $badge = new badge($r->id);
322 $badges[$r->id] = $badge;
323 if ($user != 0) {
324 $badges[$r->id]->dateissued = $r->dateissued;
325 $badges[$r->id]->uniquehash = $r->uniquehash;
326 } else {
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();
333 return $badges;
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) {
348 global $CFG, $DB;
350 $params = array(
351 'userid' => $userid
353 $sql = 'SELECT
354 bi.uniquehash,
355 bi.dateissued,
356 bi.dateexpire,
357 bi.id as issuedid,
358 bi.visible,
359 u.email,
361 FROM
362 {badge} b,
363 {badge_issued} bi,
364 {user} u
365 WHERE b.id = bi.badgeid
366 AND u.id = bi.userid
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).'%';
373 if ($onlypublic) {
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);
386 return $badges;
390 * Get badge by hash.
392 * @param string $hash
393 * @return object|bool
395 function badges_get_badge_by_hash(string $hash): object|bool {
396 global $DB;
397 $sql = 'SELECT
398 bi.uniquehash,
399 bi.dateissued,
400 bi.userid,
401 bi.dateexpire,
402 bi.id as issuedid,
403 bi.visible,
404 u.email,
406 FROM
407 {badge} b,
408 {badge_issued} bi,
409 {user} u
410 WHERE b.id = bi.badgeid
411 AND u.id = bi.userid
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);
414 return $badge;
418 * Update badge instance to external functions.
420 * @param stdClass $badge
421 * @param stdClass $user
422 * @return object
424 function badges_prepare_badge_for_external(stdClass $badge, stdClass $user): object {
425 global $PAGE, $USER;
426 if ($badge->type == BADGE_TYPE_SITE) {
427 $context = context_system::instance();
428 } else {
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) {
434 $badge = (object) [
435 'id' => $badge->id,
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);
479 $related = [
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) {
497 global $CFG, $SITE;
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
532 * @return boolean
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)) {
540 return true;
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);
552 return true;
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) {
562 global $CFG, $USER;
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);
567 @unlink($iconfile);
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');
577 * Print badge image.
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);
595 * Bake issued badge.
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|moodle_url|null Returns either new file path hash or new file URL
603 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
604 global $CFG, $USER;
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);
625 $fileinfo = array(
626 'contextid' => $user_context->id,
627 'component' => 'badges',
628 'filearea' => 'userbadge',
629 'itemid' => $badge->id,
630 'filepath' => '/',
631 'filename' => $hash . '.png',
634 // Create a file with added contents.
635 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
636 if ($pathhash) {
637 return $newfile->get_pathnamehash();
640 } else {
641 debugging('Error baking badge image!', DEBUG_DEVELOPER);
642 return;
646 // If file exists and we just need its path hash, return it.
647 if ($pathhash) {
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);
653 return $fileurl;
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) {
668 global $DB;
670 // Try to get badges from cache first.
671 $badgescache = cache::make('core', 'externalbadges');
672 $out = $badgescache->get($userid);
673 if ($out !== false && !$refresh) {
674 return $out;
676 // Get badges through curl request to the backpack.
677 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
678 if ($record) {
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);
693 } else {
694 $out->badges = array_merge($out->badges, array());
697 } else {
698 $out->totalbadges = 0;
699 $out->totalcollections = 0;
702 $badgescache->set($userid, $out);
703 return $out;
706 return null;
710 * Download all user badges in zip archive.
712 * @param int $userid ID of badge owner.
714 function badges_download($userid) {
715 global $CFG, $DB;
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();
721 $filelist = array();
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');
738 } else {
739 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
740 die;
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) {
751 global $DB;
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.
759 * @return void.
761 function badges_handle_course_deletion($courseid) {
762 global $CFG, $DB;
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.
789 * @return boolean
791 function badges_create_site_backpack($data) {
792 global $DB;
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.
807 * @return boolean
809 function badges_update_site_backpack($id, $data) {
810 global $DB;
811 $context = context_system::instance();
812 require_capability('moodle/badges:manageglobalsettings', $context);
814 if ($backpack = badges_get_site_backpack($id)) {
815 $data->id = $id;
816 return badges_save_external_backpack($data);
818 return false;
823 * Delete the backpack with this id.
825 * @param integer $id The backpack to delete.
826 * @return boolean
828 function badges_delete_site_backpack($id) {
829 global $DB;
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();
857 return $result;
860 return false;
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) {
871 global $DB;
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;
877 break;
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.
887 'image' => '',
889 $issuer->save();
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.
894 if (!PHPUNIT_TEST) {
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,
901 'name' => 'apiBase',
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);
918 } else {
919 $backpack->id = $data->id;
920 $DB->update_record('badge_external_backpack', $backpack);
922 $data->externalbackpackid = $backpack->id;
924 unset($data->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) {
936 global $DB;
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);
956 } else {
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
969 * @return boolean
971 function badges_open_badges_backpack_api(?int $backpackid = null) {
972 if (!$backpackid) {
973 $backpack = badges_get_site_primary_backpack();
974 } else {
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
989 * @return stdClass
991 function badges_get_site_backpack($id, int $userid = 0) {
992 global $DB;
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
997 WHERE beb.id=:id";
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) {
1010 global $DB;
1012 if (!$userid) {
1013 global $USER;
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
1027 * @return stdClass
1029 function badges_get_site_primary_backpack() {
1030 global $DB;
1032 $sql = 'SELECT *
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() {
1047 global $DB;
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;
1054 } else {
1055 $all[$key]->sitebackpack = false;
1059 return $all;
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 {
1071 global $DB;
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);
1088 break;
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() {
1102 return [
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.
1112 * @return array
1114 function badges_get_default_issuer() {
1115 global $CFG, $SITE;
1117 $sitebackpack = badges_get_site_primary_backpack();
1118 $issuer = array();
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;
1130 return $issuer;
1134 * Disconnect from the user backpack by deleting the user preferences.
1136 * @param integer $userid The user to diconnect.
1137 * @return boolean
1139 function badges_disconnect_user_backpack($userid) {
1140 global $USER;
1142 // We can only change backpack settings for our own real backpack.
1143 if ($USER->id != $userid ||
1144 \core\session\manager::is_loggedinas()) {
1146 return false;
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');
1154 return true;
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') {
1167 global $DB;
1168 // Return externalid if it exists.
1169 $params = [
1170 'sitebackpackid' => $sitebackpackid,
1171 'type' => $type,
1172 'internalid' => $internalid
1175 $record = $DB->get_record('badge_external_identifier', $params, $param, IGNORE_MISSING);
1176 if ($record) {
1177 return $record->$param;
1179 return false;
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.
1189 * @return boolean
1191 function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
1192 global $DB;
1194 $params = [
1195 'sitebackpackid' => $sitebackpackid,
1196 'type' => $type,
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.
1208 * @return boolean
1210 function badges_external_delete_mappings($sitebackpackid) {
1211 global $DB;
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.
1225 function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
1226 global $DB;
1228 $params = [
1229 'sitebackpackid' => $sitebackpackid,
1230 'type' => $type,
1231 'internalid' => $internalid
1234 $DB->delete_record('badge_external_identifier', $params);
1238 * Create and send a verification email to the email address supplied.
1240 * Since we're not sending this email to a user, email_to_user can't be used
1241 * but this function borrows largely the code from that process.
1243 * @param string $email the email address to send the verification email to.
1244 * @param int $backpackid the id of the backpack to connect to
1245 * @param string $backpackpassword the user entered password to connect to this backpack
1246 * @return true if the email was sent successfully, false otherwise.
1248 function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1249 global $DB, $USER;
1251 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1252 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1253 // of verification emails to said address.
1254 $secret = random_string(15);
1255 set_user_preference('badges_email_verify_secret', $secret);
1256 set_user_preference('badges_email_verify_address', $email);
1257 set_user_preference('badges_email_verify_backpackid', $backpackid);
1258 set_user_preference('badges_email_verify_password', $backpackpassword);
1260 // To, from.
1261 $tempuser = $DB->get_record('user', array('id' => $USER->id), '*', MUST_EXIST);
1262 $tempuser->email = $email;
1263 $noreplyuser = core_user::get_noreply_user();
1265 // Generate the verification email body.
1266 $verificationurl = '/badges/backpackemailverify.php';
1267 $verificationurl = new moodle_url($verificationurl);
1268 $verificationpath = $verificationurl->out(false);
1270 $site = get_site();
1271 $link = $verificationpath . '?data='. $secret;
1272 // Hard-coded button styles, because CSS can't be used in emails.
1273 $buttonstyles = [
1274 'background-color: #0f6cbf',
1275 'border: none',
1276 'color: white',
1277 'padding: 12px',
1278 'text-align: center',
1279 'text-decoration: none',
1280 'display: inline-block',
1281 'font-size: 20px',
1282 'font-weight: 800',
1283 'margin: 4px 2px',
1284 'cursor: pointer',
1285 'border-radius: 8px',
1287 $button = html_writer::start_tag('center') .
1288 html_writer::tag(
1289 'button',
1290 get_string('verifyemail', 'badges'),
1291 ['style' => implode(';', $buttonstyles)]) .
1292 html_writer::end_tag('center');
1293 $args = [
1294 'link' => html_writer::link($link, $link),
1295 'buttonlink' => html_writer::link($link, $button),
1296 'sitename' => $site->fullname,
1297 'admin' => generate_email_signoff(),
1298 'userfirstname' => $USER->firstname,
1301 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname);
1302 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1303 $messagehtml = text_to_html($messagetext, false, false, true);
1305 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1309 * Return all the enabled criteria types for this site.
1311 * @param boolean $enabled
1312 * @return array
1314 function badges_list_criteria($enabled = true) {
1315 global $CFG;
1317 $types = array(
1318 BADGE_CRITERIA_TYPE_OVERALL => 'overall',
1319 BADGE_CRITERIA_TYPE_ACTIVITY => 'activity',
1320 BADGE_CRITERIA_TYPE_MANUAL => 'manual',
1321 BADGE_CRITERIA_TYPE_SOCIAL => 'social',
1322 BADGE_CRITERIA_TYPE_COURSE => 'course',
1323 BADGE_CRITERIA_TYPE_COURSESET => 'courseset',
1324 BADGE_CRITERIA_TYPE_PROFILE => 'profile',
1325 BADGE_CRITERIA_TYPE_BADGE => 'badge',
1326 BADGE_CRITERIA_TYPE_COHORT => 'cohort',
1327 BADGE_CRITERIA_TYPE_COMPETENCY => 'competency',
1329 if ($enabled) {
1330 foreach ($types as $key => $type) {
1331 $class = 'award_criteria_' . $type;
1332 $file = $CFG->dirroot . '/badges/criteria/' . $class . '.php';
1333 if (file_exists($file)) {
1334 require_once($file);
1336 if (!$class::is_enabled()) {
1337 unset($types[$key]);
1342 return $types;
1346 * Check if any badge has records for competencies.
1348 * @param array $competencyids Array of competencies ids.
1349 * @return boolean Return true if competencies were found in any badge.
1351 function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1352 global $DB;
1354 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED);
1356 $sql = "SELECT DISTINCT bc.badgeid
1357 FROM {badge_criteria} bc
1358 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1359 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1360 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY;
1362 return $DB->record_exists_sql($sql, $params);
1366 * Creates single message for all notification and sends it out
1368 * @param object $badge A badge which is notified about.
1370 function badge_assemble_notification(stdClass $badge) {
1371 global $DB;
1373 $userfrom = core_user::get_noreply_user();
1374 $userfrom->maildisplay = true;
1376 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id))) {
1377 // Get badge creator.
1378 $creator = $DB->get_record('user', array('id' => $badge->creator), '*', MUST_EXIST);
1379 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1380 $creatormessage = '';
1382 // Put all messages in one digest.
1383 foreach ($msgs as $msg) {
1384 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash)), $badge->name);
1385 $recipient = $DB->get_record('user', array('id' => $msg->userid), '*', MUST_EXIST);
1387 $a = new stdClass();
1388 $a->user = fullname($recipient);
1389 $a->link = $issuedlink;
1390 $creatormessage .= get_string('creatorbody', 'badges', $a);
1391 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid, 'userid' => $msg->userid));
1394 // Create a message object.
1395 $eventdata = new \core\message\message();
1396 $eventdata->courseid = SITEID;
1397 $eventdata->component = 'moodle';
1398 $eventdata->name = 'badgecreatornotice';
1399 $eventdata->userfrom = $userfrom;
1400 $eventdata->userto = $creator;
1401 $eventdata->notification = 1;
1402 $eventdata->subject = $creatorsubject;
1403 $eventdata->fullmessage = format_text_email($creatormessage, FORMAT_HTML);
1404 $eventdata->fullmessageformat = FORMAT_PLAIN;
1405 $eventdata->fullmessagehtml = $creatormessage;
1406 $eventdata->smallmessage = $creatorsubject;
1408 message_send($eventdata);
1413 * Attempt to authenticate with the site backpack credentials and return an error
1414 * if the authentication fails. If external backpacks are not enabled, this will
1415 * not perform any test.
1417 * @return string
1419 function badges_verify_site_backpack() {
1420 $defaultbackpack = badges_get_site_primary_backpack();
1421 return badges_verify_backpack($defaultbackpack->id);
1425 * Attempt to authenticate with a backpack credentials and return an error
1426 * if the authentication fails.
1427 * If external backpacks are not enabled or the backpack version is different
1428 * from OBv2, this will not perform any test.
1430 * @param int $backpackid Backpack identifier to verify.
1431 * @return string The result of the verification process.
1433 function badges_verify_backpack(int $backpackid) {
1434 global $OUTPUT, $CFG;
1436 if (empty($CFG->badges_allowexternalbackpack)) {
1437 return '';
1440 $backpack = badges_get_site_backpack($backpackid);
1441 if (empty($backpack->apiversion) || ($backpack->apiversion == OPEN_BADGES_V2)) {
1442 $backpackapi = new \core_badges\backpack_api($backpack);
1444 // Clear any cached access tokens in the session.
1445 $backpackapi->clear_system_user_session();
1447 // Now attempt a login with these credentials.
1448 $result = $backpackapi->authenticate();
1449 if (empty($result) || !empty($result->error)) {
1450 $warning = $backpackapi->get_authentication_error();
1452 $params = ['id' => $backpack->id, 'action' => 'edit'];
1453 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1455 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1456 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1457 return $OUTPUT->container($icon . $message, 'text-danger');
1461 return '';
1465 * Generate a public badgr URL that conforms to OBv2. This is done because badgr responses do not currently conform to
1466 * the spec.
1468 * WARNING: This is an extremely hacky way of implementing this and should be removed once the standards are conformed to.
1470 * @param stdClass $backpack The Badgr backpack we are pushing to
1471 * @param string $type The type of object we are dealing with either Issuer, Assertion OR Badge.
1472 * @param string $externalid The externalid as provided by the backpack
1473 * @return ?string The public URL to access Badgr objects
1475 function badges_generate_badgr_open_url($backpack, $type, $externalid) {
1476 if (badges_open_badges_backpack_api($backpack->id) == OPEN_BADGES_V2) {
1477 $entity = strtolower($type);
1478 if ($type == OPEN_BADGES_V2_TYPE_BADGE) {
1479 $entity = "badge";
1481 $url = new moodle_url($backpack->backpackapiurl);
1482 return "{$url->get_scheme()}://{$url->get_host()}/public/{$entity}s/$externalid";