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
;
34 /* Include required badge class exporter */
35 use core_badges\external\badgeclass_exporter
;
38 * Number of records per page.
40 define('BADGE_PERPAGE', 50);
43 * Badge award criteria aggregation method.
45 define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
48 * Badge award criteria aggregation method.
50 define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
53 * Inactive badge means that this badge cannot be earned and has not been awarded
54 * yet. Its award criteria can be changed.
56 define('BADGE_STATUS_INACTIVE', 0);
59 * Active badge means that this badge can we earned, but it has not been awarded
60 * yet. Can be deactivated for the purpose of changing its criteria.
62 define('BADGE_STATUS_ACTIVE', 1);
65 * Inactive badge can no longer be earned, but it has been awarded in the past and
66 * therefore its criteria cannot be changed.
68 define('BADGE_STATUS_INACTIVE_LOCKED', 2);
71 * Active badge means that it can be earned and has already been awarded to users.
72 * Its criteria cannot be changed any more.
74 define('BADGE_STATUS_ACTIVE_LOCKED', 3);
77 * Archived badge is considered deleted and can no longer be earned and is not
78 * displayed in the list of all badges.
80 define('BADGE_STATUS_ARCHIVED', 4);
83 * Badge type for site badges.
85 define('BADGE_TYPE_SITE', 1);
88 * Badge type for course badges.
90 define('BADGE_TYPE_COURSE', 2);
93 * Badge messaging schedule options.
95 define('BADGE_MESSAGE_NEVER', 0);
96 define('BADGE_MESSAGE_ALWAYS', 1);
97 define('BADGE_MESSAGE_DAILY', 2);
98 define('BADGE_MESSAGE_WEEKLY', 3);
99 define('BADGE_MESSAGE_MONTHLY', 4);
102 * URL of backpack. Custom ones can be added.
104 define('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
105 define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
108 * @deprecated since Moodle 4.5.
109 * @todo Final deprecation in Moodle 6.0. See MDL-82332.
111 define('OPEN_BADGES_V1', 1);
114 * Open Badges specifications.
116 define('OPEN_BADGES_V2', 2);
117 define('OPEN_BADGES_V2P1', 2.1);
120 * Only use for Open Badges 2.0 specification
122 define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
123 define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
124 define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
125 define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
126 define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
127 define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
129 define('BACKPACK_MOVE_UP', -1);
130 define('BACKPACK_MOVE_DOWN', 1);
132 // Global badge class has been moved to the component namespace.
133 class_alias('\core_badges\badge', 'badge');
136 * Sends notifications to users about awarded badges.
138 * @param \core_badges\badge $badge Badge that was issued
139 * @param int $userid Recipient ID
140 * @param string $issued Unique hash of an issued badge
141 * @param string $filepathhash File path hash of an issued badge for attachments
143 function badges_notify_badge_award(badge
$badge, $userid, $issued, $filepathhash) {
146 $admin = get_admin();
147 $userfrom = new stdClass();
148 $userfrom->id
= $admin->id
;
149 $userfrom->email
= !empty($CFG->badges_defaultissuercontact
) ?
$CFG->badges_defaultissuercontact
: $admin->email
;
150 foreach (\core_user\fields
::get_name_fields() as $addname) {
151 $userfrom->$addname = !empty($CFG->badges_defaultissuername
) ?
'' : $admin->$addname;
153 $userfrom->firstname
= !empty($CFG->badges_defaultissuername
) ?
$CFG->badges_defaultissuername
: $admin->firstname
;
154 $userfrom->maildisplay
= true;
156 $badgeurl = new moodle_url('/badges/badge.php', ['hash' => $issued]);
157 $issuedlink = html_writer
::link($badgeurl, $badge->name
);
158 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
160 $params = new stdClass();
161 $params->badgename
= $badge->name
;
162 $params->username
= fullname($userto);
163 $params->badgelink
= $issuedlink;
164 $message = badge_message_from_template($badge->message
, $params);
165 $plaintext = html_to_text($message);
168 $eventdata = new \core\message\
message();
169 $eventdata->courseid
= is_null($badge->courseid
) ? SITEID
: $badge->courseid
; // Profile/site come with no courseid.
170 $eventdata->component
= 'moodle';
171 $eventdata->name
= 'badgerecipientnotice';
172 $eventdata->userfrom
= $userfrom;
173 $eventdata->userto
= $userto;
174 $eventdata->notification
= 1;
175 $eventdata->contexturl
= $badgeurl;
176 $eventdata->contexturlname
= $badge->name
;
177 $eventdata->subject
= $badge->messagesubject
;
178 $eventdata->fullmessage
= $plaintext;
179 $eventdata->fullmessageformat
= FORMAT_HTML
;
180 $eventdata->fullmessagehtml
= $message;
181 $eventdata->smallmessage
= '';
182 $eventdata->customdata
= [
183 'notificationiconurl' => moodle_url
::make_pluginfile_url(
184 $badge->get_context()->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1')->out(),
188 // Attach badge image if possible.
189 if (!empty($CFG->allowattachments
) && $badge->attachment
&& is_string($filepathhash)) {
190 $fs = get_file_storage();
191 $file = $fs->get_file_by_hash($filepathhash);
192 $eventdata->attachment
= $file;
193 $eventdata->attachname
= str_replace(' ', '_', $badge->name
) . ".png";
195 message_send($eventdata);
197 message_send($eventdata);
200 // Notify badge creator about the award if they receive notifications every time.
201 if ($badge->notification
== 1) {
202 $userfrom = core_user
::get_noreply_user();
203 $userfrom->maildisplay
= true;
205 $creator = $DB->get_record('user', array('id' => $badge->usercreated
), '*', MUST_EXIST
);
207 $a->user
= fullname($userto);
208 $a->link
= $issuedlink;
209 $creatormessage = get_string('creatorbody', 'badges', $a);
210 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
212 $eventdata = new \core\message\
message();
213 $eventdata->courseid
= $badge->courseid
;
214 $eventdata->component
= 'moodle';
215 $eventdata->name
= 'badgecreatornotice';
216 $eventdata->userfrom
= $userfrom;
217 $eventdata->userto
= $creator;
218 $eventdata->notification
= 1;
219 $eventdata->contexturl
= $badgeurl;
220 $eventdata->contexturlname
= $badge->name
;
221 $eventdata->subject
= $creatorsubject;
222 $eventdata->fullmessage
= html_to_text($creatormessage);
223 $eventdata->fullmessageformat
= FORMAT_HTML
;
224 $eventdata->fullmessagehtml
= $creatormessage;
225 $eventdata->smallmessage
= '';
226 $eventdata->customdata
= [
227 'notificationiconurl' => moodle_url
::make_pluginfile_url(
228 $badge->get_context()->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1')->out(),
232 message_send($eventdata);
233 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id
, 'userid' => $userid));
238 * Caclulates date for the next message digest to badge creators.
240 * @param int $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
241 * @return int Timestamp for next cron
243 function badges_calculate_message_schedule($schedule) {
247 case BADGE_MESSAGE_DAILY
:
248 $tomorrow = new DateTime("1 day", core_date
::get_server_timezone_object());
249 $nextcron = $tomorrow->getTimestamp();
251 case BADGE_MESSAGE_WEEKLY
:
252 $nextweek = new DateTime("1 week", core_date
::get_server_timezone_object());
253 $nextcron = $nextweek->getTimestamp();
255 case BADGE_MESSAGE_MONTHLY
:
256 $nextmonth = new DateTime("1 month", core_date
::get_server_timezone_object());
257 $nextcron = $nextmonth->getTimestamp();
265 * Replaces variables in a message template and returns text ready to be emailed to a user.
267 * @param string $message Message body.
268 * @return string Message with replaced values
270 function badge_message_from_template($message, $params) {
272 foreach ($params as $key => $value) {
273 $msg = str_replace("%$key%", $value, $msg);
282 * @param int Type of badges to return
283 * @param int Course ID for course badges
284 * @param string $sort An SQL field to sort by
285 * @param string $dir The sort direction ASC|DESC
286 * @param int $page The page or records to return
287 * @param int $perpage The number of records to return per page
288 * @param int $user User specific search
289 * @return array $badge Array of records matching criteria
291 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE
, $user = 0) {
295 $where = "b.status != :deleted AND b.type = :type ";
296 $params['deleted'] = BADGE_STATUS_ARCHIVED
;
298 $userfields = array('b.id, b.name, b.status');
301 $userfields[] = 'bi.dateissued';
302 $userfields[] = 'bi.uniquehash';
303 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
304 $params['userid'] = $user;
305 $where .= " AND (b.status = 1 OR b.status = 3) ";
307 $fields = implode(', ', $userfields);
309 if ($courseid != 0 ) {
310 $where .= "AND b.courseid = :courseid ";
311 $params['courseid'] = $courseid;
314 $sorting = (($sort != '' && $dir != '') ?
'ORDER BY ' . $sort . ' ' . $dir : '');
315 $params['type'] = $type;
317 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
318 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
321 foreach ($records as $r) {
322 $badge = new badge($r->id
);
323 $badges[$r->id
] = $badge;
325 $badges[$r->id
]->dateissued
= $r->dateissued
;
326 $badges[$r->id
]->uniquehash
= $r->uniquehash
;
328 $badges[$r->id
]->awards
= $DB->count_records_sql('SELECT COUNT(b.userid)
329 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
330 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id
));
331 $badges[$r->id
]->statstring
= $badge->get_status_name();
338 * Get badges for a specific user.
340 * @param int $userid User ID
341 * @param int $courseid Badges earned by a user in a specific course
342 * @param int $page The page or records to return
343 * @param int $perpage The number of records to return per page
344 * @param string $search A simple string to search for
345 * @param bool $onlypublic Return only public badges
346 * @return array of badges ordered by decreasing date of issue
348 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
366 WHERE b.id = bi.badgeid
368 AND bi.userid = :userid';
370 if (!empty($search)) {
371 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
372 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
375 $sql .= ' AND (bi.visible = 1) ';
378 if (empty($CFG->badges_allowcoursebadges
)) {
379 $sql .= ' AND b.courseid IS NULL';
380 } else if ($courseid != 0) {
381 $sql .= ' AND (b.courseid = :courseid) ';
382 $params['courseid'] = $courseid;
384 $sql .= ' ORDER BY bi.dateissued DESC';
385 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
393 * @param string $hash
394 * @return object|bool
396 function badges_get_badge_by_hash(string $hash): object|
bool {
411 WHERE b.id = bi.badgeid
413 AND ' . $DB->sql_compare_text('bi.uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40);
414 $badge = $DB->get_record_sql($sql, ['hash' => $hash], IGNORE_MISSING
);
419 * Update badge instance to external functions.
421 * @param stdClass $badge
422 * @param stdClass $user
425 function badges_prepare_badge_for_external(stdClass
$badge, stdClass
$user): object {
426 global $PAGE, $SITE, $USER;
427 if ($badge->type
== BADGE_TYPE_SITE
) {
428 $context = context_system
::instance();
430 $context = context_course
::instance($badge->courseid
);
432 $canconfiguredetails = has_capability('moodle/badges:configuredetails', $context);
433 // If the user is viewing another user's badge and doesn't have the right capability return only part of the data.
434 if ($USER->id
!= $user->id
&& !$canconfiguredetails) {
437 'name' => $badge->name
,
438 'type' => $badge->type
,
439 'description' => $badge->description
,
440 'issuername' => $badge->issuername
,
441 'issuerurl' => $badge->issuerurl
,
442 'issuercontact' => $badge->issuercontact
,
443 'uniquehash' => $badge->uniquehash
,
444 'dateissued' => $badge->dateissued
,
445 'dateexpire' => $badge->dateexpire
,
446 'version' => $badge->version
,
447 'language' => $badge->language
,
448 'imageauthorname' => $badge->imageauthorname
,
449 'imageauthoremail' => $badge->imageauthoremail
,
450 'imageauthorurl' => $badge->imageauthorurl
,
451 'imagecaption' => $badge->imagecaption
,
455 // Recipient (the badge was awarded to this person).
456 $badge->recipientid
= $user->id
;
457 if ($user->deleted
) {
458 $strdata = new stdClass();
459 $strdata->user
= fullname($user);
460 $strdata->site
= format_string($SITE->fullname
, true, ['context' => context_system
::instance()]);
461 $badge->recipientfullname
= get_string('error:userdeleted', 'badges', $strdata);
463 $badge->recipientfullname
= fullname($user);
466 // Create a badge instance to be able to get the endorsement and other info.
467 $badgeinstance = new badge($badge->id
);
468 $endorsement = $badgeinstance->get_endorsement();
469 $alignments = $badgeinstance->get_alignments();
470 $relatedbadges = $badgeinstance->get_related_badges();
472 if (!$canconfiguredetails) {
473 // Return only the properties visible by the user.
474 if (!empty($alignments)) {
475 foreach ($alignments as $alignment) {
476 unset($alignment->targetdescription
);
477 unset($alignment->targetframework
);
478 unset($alignment->targetcode
);
482 if (!empty($relatedbadges)) {
483 foreach ($relatedbadges as $relatedbadge) {
484 unset($relatedbadge->version
);
485 unset($relatedbadge->language
);
486 unset($relatedbadge->type
);
492 'context' => $context,
493 'endorsement' => $endorsement ?
$endorsement : null,
494 'alignment' => $alignments,
495 'relatedbadges' => $relatedbadges,
498 $exporter = new user_badge_exporter($badge, $related);
499 return $exporter->export($PAGE->get_renderer('core'));
503 * Prepare badgeclass for external functions.
504 * @param core_badges\output\badgeclass $badgeclass
507 function badges_prepare_badgeclass_for_external(core_badges\output\badgeclass
$badgeclass): stdClass
{
509 $context = $badgeclass->context
;
511 $badgeurl = new \
moodle_url('/badges/badgeclass.php', [
512 'id' => $badgeclass->badge
->id
,
514 $badgeurl = $badgeurl->out(false);
515 $file = \moodle_url
::make_webservice_pluginfile_url(
516 $badgeclass->context
->id
,
519 $badgeclass->badge
->id
,
523 $image = $file->out(false);
527 'name' => $badgeclass->badge
->name
,
528 'type' => OPEN_BADGES_V2_TYPE_BADGE
,
529 'description' => $badgeclass->badge
->description
,
530 'issuer' => $badgeclass->badge
->issuername
,
531 'hostedUrl' => $badgeclass->badge
->issuerurl
,
534 // Create a badge instance to be able to get the endorsement and other info.
535 $badgeinstance = new badge($badgeclass->badge
->id
);
536 $endorsement = $badgeinstance->get_endorsement();
537 $alignments = $badgeinstance->get_alignments();
538 $relatedbadges = $badgeinstance->get_related_badges();
540 $canconfiguredetails = has_capability('moodle/badges:configuredetails', $context);
542 if (!$canconfiguredetails) {
543 // Return only the properties visible by the user.
544 if (!empty($alignments)) {
545 foreach ($alignments as $alignment) {
546 unset($alignment->targetdescription
);
547 unset($alignment->targetframework
);
548 unset($alignment->targetcode
);
552 if (!empty($relatedbadges)) {
553 foreach ($relatedbadges as $relatedbadge) {
554 unset($relatedbadge->version
);
555 unset($relatedbadge->language
);
556 unset($relatedbadge->type
);
562 'context' => $context,
563 'endorsement' => $endorsement ?
$endorsement : null,
564 'relatedbadges' => $relatedbadges,
567 if (!empty($alignments)) {
568 $related['alignment'] = $alignments;
571 $exporter = new badgeclass_exporter($badge, $related);
572 return $exporter->export($PAGE->get_renderer('core', 'badges'));
576 * Extends the course administration navigation with the Badges page
578 * @param navigation_node $coursenode
579 * @param object $course
581 function badges_add_course_navigation(navigation_node
$coursenode, stdClass
$course) {
584 $coursecontext = context_course
::instance($course->id
);
585 $isfrontpage = (!$coursecontext ||
$course->id
== $SITE->id
);
586 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
587 'moodle/badges:createbadge',
588 'moodle/badges:awardbadge',
589 'moodle/badges:configurecriteria',
590 'moodle/badges:configuremessages',
591 'moodle/badges:configuredetails',
592 'moodle/badges:deletebadge'), $coursecontext);
594 if (!empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
) && !$isfrontpage && $canmanage) {
595 $coursenode->add(get_string('coursebadges', 'badges'), null,
596 navigation_node
::TYPE_CONTAINER
, null, 'coursebadges',
597 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
599 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
601 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
602 navigation_node
::TYPE_SETTING
, null, 'coursebadges');
604 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
605 $url = new moodle_url('/badges/edit.php', ['action' => 'new', 'courseid' => $course->id
]);
607 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
608 navigation_node
::TYPE_SETTING
, null, 'newbadge');
614 * Triggered when badge is manually awarded.
616 * @param object $data
619 function badges_award_handle_manual_criteria_review(stdClass
$data) {
620 $criteria = $data->crit
;
621 $userid = $data->userid
;
622 $badge = new badge($criteria->badgeid
);
624 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
628 if ($criteria->review($userid)) {
629 $criteria->mark_complete($userid);
631 if ($badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($userid)) {
632 $badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($userid);
633 $badge->issue($userid);
641 * Process badge image from form data
643 * @param badge $badge Badge object
644 * @param string $iconfile Original file
646 function badges_process_badge_image(badge
$badge, $iconfile) {
648 require_once($CFG->libdir
. '/gdlib.php');
650 if (!empty($CFG->gdversion
)) {
651 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id
, $iconfile, true);
654 // Clean up file draft area after badge image has been saved.
655 $context = context_user
::instance($USER->id
, MUST_EXIST
);
656 $fs = get_file_storage();
657 $fs->delete_area_files($context->id
, 'user', 'draft');
664 * @param badge $badge Badge object
665 * @param stdClass $context
666 * @param string $size
668 function print_badge_image(badge
$badge, stdClass
$context, $size = 'small') {
669 $fsize = ($size == 'small') ?
'f2' : 'f1';
671 $imageurl = moodle_url
::make_pluginfile_url($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $fsize, false);
672 // Appending a random parameter to image link to forse browser reload the image.
673 $imageurl->param('refresh', rand(1, 10000));
674 $attributes = array('src' => $imageurl, 'alt' => s($badge->name
), 'class' => 'activatebadge');
676 return html_writer
::empty_tag('img', $attributes);
682 * @param string $hash Unique hash of an issued badge.
683 * @param int $badgeid ID of the original badge.
684 * @param int $userid ID of badge recipient (optional).
685 * @param boolean $pathhash Return file pathhash instead of image url (optional).
686 * @return string|moodle_url|null Returns either new file path hash or new file URL
688 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
690 require_once(__DIR__
. '/../badges/lib/bakerlib.php');
692 $badge = new badge($badgeid);
693 $badge_context = $badge->get_context();
694 $userid = ($userid) ?
$userid : $USER->id
;
695 $user_context = context_user
::instance($userid);
697 $fs = get_file_storage();
698 if (!$fs->file_exists($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png')) {
699 if ($file = $fs->get_file($badge_context->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f3.png')) {
700 $contents = $file->get_content();
702 $filehandler = new PNG_MetaDataHandler($contents);
703 // For now, the site backpack OB version will be used as default.
704 $obversion = badges_open_badges_backpack_api();
705 $assertion = new core_badges_assertion($hash, $obversion);
706 $assertionjson = json_encode($assertion->get_badge_assertion());
707 if ($filehandler->check_chunks("iTXt", "openbadges")) {
708 // Add assertion URL iTXt chunk.
709 $newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
711 'contextid' => $user_context->id
,
712 'component' => 'badges',
713 'filearea' => 'userbadge',
714 'itemid' => $badge->id
,
716 'filename' => $hash . '.png',
719 // Create a file with added contents.
720 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
722 return $newfile->get_pathnamehash();
726 debugging('Error baking badge image!', DEBUG_DEVELOPER
);
731 // If file exists and we just need its path hash, return it.
733 $file = $fs->get_file($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png');
734 return $file->get_pathnamehash();
737 $fileurl = moodle_url
::make_pluginfile_url($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash, true);
742 * Returns external backpack settings and badges from this backpack.
744 * This function first checks if badges for the user are cached and
745 * tries to retrieve them from the cache. Otherwise, badges are obtained
746 * through curl request to the backpack.
748 * @param int $userid Backpack user ID.
749 * @param boolean $refresh Refresh badges collection in cache.
750 * @return null|object Returns null is there is no backpack or object with backpack settings.
752 function get_backpack_settings($userid, $refresh = false) {
755 // Try to get badges from cache first.
756 $badgescache = cache
::make('core', 'externalbadges');
757 $out = $badgescache->get($userid);
758 if ($out !== false && !$refresh) {
761 // Get badges through curl request to the backpack.
762 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
764 $sitebackpack = badges_get_site_backpack($record->externalbackpackid
);
765 $backpack = new \core_badges\backpack_api
($sitebackpack, $record);
766 $out = new stdClass();
767 $out->backpackid
= $sitebackpack->id
;
769 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id
))) {
770 $out->totalcollections
= count($collections);
771 $out->totalbadges
= 0;
772 $out->badges
= array();
773 foreach ($collections as $collection) {
774 $badges = $backpack->get_badges($collection, true);
775 if (!empty($badges)) {
776 $out->badges
= array_merge($out->badges
, $badges);
777 $out->totalbadges +
= count($badges);
779 $out->badges
= array_merge($out->badges
, array());
783 $out->totalbadges
= 0;
784 $out->totalcollections
= 0;
787 $badgescache->set($userid, $out);
795 * Download all user badges in zip archive.
797 * @param int $userid ID of badge owner.
799 function badges_download($userid) {
801 $context = context_user
::instance($userid);
802 $records = $DB->get_records('badge_issued', array('userid' => $userid));
804 // Get list of files to download.
805 $fs = get_file_storage();
807 foreach ($records as $issued) {
808 $badge = new badge($issued->badgeid
);
809 // Need to make image name user-readable and unique using filename safe characters.
810 $name = $badge->name
. ' ' . userdate($issued->dateissued
, '%d %b %Y') . ' ' . hash('crc32', $badge->id
);
811 $name = str_replace(' ', '_', $name);
812 $name = clean_param($name, PARAM_FILE
);
813 if ($file = $fs->get_file($context->id
, 'badges', 'userbadge', $issued->badgeid
, '/', $issued->uniquehash
. '.png')) {
814 $filelist[$name . '.png'] = $file;
818 // Zip files and sent them to a user.
819 $tempzip = tempnam($CFG->tempdir
.'/', 'mybadges');
820 $zipper = new zip_packer();
821 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
822 send_temp_file($tempzip, 'badges.zip');
824 debugging("Problems with archiving the files.", DEBUG_DEVELOPER
);
830 * Checks if user has external backpack connected.
832 * @param int $userid ID of a user.
833 * @return bool True|False whether backpack connection exists.
835 function badges_user_has_backpack($userid) {
837 return $DB->record_exists('badge_backpack', array('userid' => $userid));
841 * Handles what happens to the course badges when a course is deleted.
843 * @param int $courseid course ID.
846 function badges_handle_course_deletion($courseid) {
848 include_once $CFG->libdir
. '/filelib.php';
850 $systemcontext = context_system
::instance();
851 $coursecontext = context_course
::instance($courseid);
852 $fs = get_file_storage();
854 // Move badges images to the system context.
855 $fs->move_area_files_to_new_context($coursecontext->id
, $systemcontext->id
, 'badges', 'badgeimage');
857 // Get all course badges.
858 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE
, 'courseid' => $courseid));
859 foreach ($badges as $badge) {
860 // Archive badges in this course.
861 $toupdate = new stdClass();
862 $toupdate->id
= $badge->id
;
863 $toupdate->type
= BADGE_TYPE_SITE
;
864 $toupdate->courseid
= null;
865 $toupdate->status
= BADGE_STATUS_ARCHIVED
;
866 $DB->update_record('badge', $toupdate);
871 * Create the site backpack with this data.
873 * @param stdClass $data The new backpack data.
876 function badges_create_site_backpack($data) {
878 $context = context_system
::instance();
879 require_capability('moodle/badges:manageglobalsettings', $context);
881 $max = $DB->get_field_sql('SELECT MAX(sortorder) FROM {badge_external_backpack}');
882 $data->sortorder
= $max +
1;
884 return badges_save_external_backpack($data);
888 * Update the backpack with this id.
890 * @param integer $id The backpack to edit
891 * @param stdClass $data The new backpack data.
894 function badges_update_site_backpack($id, $data) {
896 $context = context_system
::instance();
897 require_capability('moodle/badges:manageglobalsettings', $context);
899 if ($backpack = badges_get_site_backpack($id)) {
901 return badges_save_external_backpack($data);
908 * Delete the backpack with this id.
910 * @param integer $id The backpack to delete.
913 function badges_delete_site_backpack($id) {
916 $context = context_system
::instance();
917 require_capability('moodle/badges:manageglobalsettings', $context);
919 // Only remove site backpack if it's not the default one.
920 $defaultbackpack = badges_get_site_primary_backpack();
921 if ($defaultbackpack->id
!= $id && $DB->record_exists('badge_external_backpack', ['id' => $id])) {
922 $transaction = $DB->start_delegated_transaction();
924 // Remove connections for users to this backpack.
925 $sql = "SELECT DISTINCT bb.id
926 FROM {badge_backpack} bb
927 WHERE bb.externalbackpackid = :backpackid";
928 $params = ['backpackid' => $id];
929 $userbackpacks = $DB->get_fieldset_sql($sql, $params);
930 if ($userbackpacks) {
931 // Delete user external collections references to this backpack.
932 list($insql, $params) = $DB->get_in_or_equal($userbackpacks);
933 $DB->delete_records_select('badge_external', "backpackid $insql", $params);
935 $DB->delete_records('badge_backpack', ['externalbackpackid' => $id]);
937 // Delete backpack entry.
938 $result = $DB->delete_records('badge_external_backpack', ['id' => $id]);
940 $transaction->allow_commit();
949 * Perform the actual create/update of external bakpacks. Any checks on the validity of the id will need to be
950 * performed before it reaches this function.
952 * @param stdClass $data The backpack data we are updating/inserting
953 * @return int Returns the id of the new/updated record
955 function badges_save_external_backpack(stdClass
$data) {
957 if ($data->apiversion
== OPEN_BADGES_V2P1
) {
958 // Check if there is an existing issuer for the given backpackapiurl.
959 foreach (core\oauth2\api
::get_all_issuers() as $tmpissuer) {
960 if ($data->backpackweburl
== $tmpissuer->get('baseurl')) {
961 $issuer = $tmpissuer;
966 // Create the issuer if it doesn't exist yet.
967 if (empty($issuer)) {
968 $issuer = new \core\oauth2\
issuer(0, (object) [
969 'name' => $data->backpackweburl
,
970 'baseurl' => $data->backpackweburl
,
971 // Note: This is required because the DB schema is broken and does not accept a null value when it should.
977 // This can't be run from PHPUNIT because testing platforms need real URLs.
978 // In the future, this request can be moved to the moodle-exttests repository.
980 // Create/update the endpoints for the issuer.
981 \core\oauth2\discovery\imsbadgeconnect
::create_endpoints($issuer);
982 $data->oauth2_issuerid
= $issuer->get('id');
984 $apibase = \core\oauth2\endpoint
::get_record([
985 'issuerid' => $data->oauth2_issuerid
,
988 $data->backpackapiurl
= $apibase->get('url');
991 $backpack = new stdClass();
993 $backpack->apiversion
= $data->apiversion
;
994 $backpack->backpackweburl
= $data->backpackweburl
;
995 $backpack->backpackapiurl
= $data->backpackapiurl
;
996 $backpack->oauth2_issuerid
= $data->oauth2_issuerid ??
'';
997 if (isset($data->sortorder
)) {
998 $backpack->sortorder
= $data->sortorder
;
1001 if (empty($data->id
)) {
1002 $backpack->id
= $DB->insert_record('badge_external_backpack', $backpack);
1004 $backpack->id
= $data->id
;
1005 $DB->update_record('badge_external_backpack', $backpack);
1007 $data->externalbackpackid
= $backpack->id
;
1010 badges_save_backpack_credentials($data);
1011 return $data->externalbackpackid
;
1015 * Create a backpack with the provided details. Stores the auth details of the backpack
1017 * @param stdClass $data Backpack specific data.
1018 * @return int The id of the external backpack that the credentials correspond to
1020 function badges_save_backpack_credentials(stdClass
$data) {
1023 if (isset($data->backpackemail
) && isset($data->password
)) {
1024 $backpack = new stdClass();
1026 $backpack->email
= $data->backpackemail
;
1027 $backpack->password
= !empty($data->password
) ?
$data->password
: '';
1028 $backpack->externalbackpackid
= $data->externalbackpackid
;
1029 $backpack->userid
= $data->userid ??
0;
1030 $backpack->backpackuid
= $data->backpackuid ??
0;
1031 $backpack->autosync
= $data->autosync ??
0;
1033 if (!empty($data->badgebackpack
)) {
1034 $backpack->id
= $data->badgebackpack
;
1035 } else if (!empty($data->id
)) {
1036 $backpack->id
= $data->id
;
1039 if (empty($backpack->id
)) {
1040 $backpack->id
= $DB->insert_record('badge_backpack', $backpack);
1042 $DB->update_record('badge_backpack', $backpack);
1045 return $backpack->externalbackpackid
;
1048 return $data->externalbackpackid ??
0;
1052 * Is any backpack enabled that supports open badges V1?
1053 * @param int|null $backpackid Check the version of the given id OR if null the sitewide backpack
1056 function badges_open_badges_backpack_api(?
int $backpackid = null) {
1058 $backpack = badges_get_site_primary_backpack();
1060 $backpack = badges_get_site_backpack($backpackid);
1063 if (empty($backpack->apiversion
)) {
1064 return OPEN_BADGES_V2
;
1066 return $backpack->apiversion
;
1070 * Get a site backpacks by id for a particular user or site (if userid is 0)
1072 * @param int $id The backpack id.
1073 * @param int $userid The owner of the backpack, 0 if it's a sitewide backpack else a user's site backpack
1076 function badges_get_site_backpack($id, int $userid = 0) {
1079 $sql = "SELECT beb.*, bb.id AS badgebackpack, bb.password, bb.email AS backpackemail
1080 FROM {badge_external_backpack} beb
1081 LEFT JOIN {badge_backpack} bb ON bb.externalbackpackid = beb.id AND bb.userid=:userid
1084 return $DB->get_record_sql($sql, ['id' => $id, 'userid' => $userid]);
1088 * Get the user backpack for the currently logged in user OR the provided user
1090 * @param int|null $userid The user whose backpack you're requesting for. If null, get the logged in user's backpack
1091 * @return mixed The user's backpack or none.
1092 * @throws dml_exception
1094 function badges_get_user_backpack(?
int $userid = 0) {
1099 $userid = $USER->id
;
1102 $sql = "SELECT beb.*, bb.id AS badgebackpack, bb.password, bb.email AS backpackemail
1103 FROM {badge_external_backpack} beb
1104 JOIN {badge_backpack} bb ON bb.externalbackpackid = beb.id AND bb.userid=:userid";
1106 return $DB->get_record_sql($sql, ['userid' => $userid]);
1110 * Get the primary backpack for the site
1114 function badges_get_site_primary_backpack() {
1118 FROM {badge_external_backpack}
1119 WHERE sortorder = (SELECT MIN(sortorder)
1120 FROM {badge_external_backpack} b2)';
1121 $firstbackpack = $DB->get_record_sql($sql, null, MUST_EXIST
);
1123 return badges_get_site_backpack($firstbackpack->id
);
1127 * List the backpacks at site level.
1129 * @return array(stdClass)
1131 function badges_get_site_backpacks() {
1134 $defaultbackpack = badges_get_site_primary_backpack();
1135 $all = $DB->get_records('badge_external_backpack', null, 'sortorder ASC');
1136 foreach ($all as $key => $bp) {
1137 if ($bp->id
== $defaultbackpack->id
) {
1138 $all[$key]->sitebackpack
= true;
1140 $all[$key]->sitebackpack
= false;
1148 * Moves the backpack in the list one position up or down.
1150 * @param int $backpackid The backpack identifier to be moved.
1151 * @param int $direction The direction (BACKPACK_MOVE_UP/BACKPACK_MOVE_DOWN) where to move the backpack.
1153 * @throws \moodle_exception if attempting to use invalid direction value.
1155 function badges_change_sortorder_backpacks(int $backpackid, int $direction): void
{
1158 if ($direction != BACKPACK_MOVE_UP
&& $direction != BACKPACK_MOVE_DOWN
) {
1159 throw new \
coding_exception(
1160 'Must use a valid backpack API move direction constant (BACKPACK_MOVE_UP or BACKPACK_MOVE_DOWN)');
1163 $backpacks = badges_get_site_backpacks();
1164 $backpacktoupdate = $backpacks[$backpackid];
1166 $currentsortorder = $backpacktoupdate->sortorder
;
1167 $targetsortorder = $currentsortorder +
$direction;
1168 if ($targetsortorder > 0 && $targetsortorder <= count($backpacks) ) {
1169 foreach ($backpacks as $backpack) {
1170 if ($backpack->sortorder
== $targetsortorder) {
1171 $backpack->sortorder
= $backpack->sortorder
- $direction;
1172 $DB->update_record('badge_external_backpack', $backpack);
1176 $backpacktoupdate->sortorder
= $targetsortorder;
1177 $DB->update_record('badge_external_backpack', $backpacktoupdate);
1182 * List the supported badges api versions.
1184 * @return array(version)
1186 function badges_get_badge_api_versions() {
1188 (string)OPEN_BADGES_V2
=> get_string('openbadgesv2', 'badges'),
1189 (string)OPEN_BADGES_V2P1
=> get_string('openbadgesv2p1', 'badges')
1194 * Get the default issuer for a badge from this site.
1198 function badges_get_default_issuer() {
1201 $sitebackpack = badges_get_site_primary_backpack();
1203 $issuerurl = new moodle_url('/');
1204 $issuer['name'] = $CFG->badges_defaultissuername
;
1205 if (empty($issuer['name'])) {
1206 $issuer['name'] = $SITE->fullname ?
$SITE->fullname
: $SITE->shortname
;
1208 $issuer['url'] = $issuerurl->out(false);
1209 $issuer['email'] = $sitebackpack->backpackemail ?
: $CFG->badges_defaultissuercontact
;
1210 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT
;
1211 $issuerid = new moodle_url('/badges/issuer_json.php');
1212 $issuer['id'] = $issuerid->out(false);
1213 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER
;
1218 * Disconnect from the user backpack by deleting the user preferences.
1220 * @param integer $userid The user to diconnect.
1223 function badges_disconnect_user_backpack($userid) {
1226 // We can only change backpack settings for our own real backpack.
1227 if ($USER->id
!= $userid ||
1228 \core\session\manager
::is_loggedinas()) {
1233 unset_user_preference('badges_email_verify_secret');
1234 unset_user_preference('badges_email_verify_address');
1235 unset_user_preference('badges_email_verify_backpackid');
1236 unset_user_preference('badges_email_verify_password');
1242 * Used to remember which objects we connected with a backpack before.
1244 * @param integer $sitebackpackid The site backpack to connect to.
1245 * @param string $type The type of this remote object.
1246 * @param string $internalid The id for this object on the Moodle site.
1247 * @param string $param The param we need to return. Defaults to the externalid.
1248 * @return mixed The id or false if it doesn't exist.
1250 function badges_external_get_mapping($sitebackpackid, $type, $internalid, $param = 'externalid') {
1252 // Return externalid if it exists.
1254 'sitebackpackid' => $sitebackpackid,
1256 'internalid' => $internalid
1259 $record = $DB->get_record('badge_external_identifier', $params, $param, IGNORE_MISSING
);
1261 return $record->$param;
1267 * Save the info about which objects we connected with a backpack before.
1269 * @param integer $sitebackpackid The site backpack to connect to.
1270 * @param string $type The type of this remote object.
1271 * @param string $internalid The id for this object on the Moodle site.
1272 * @param string $externalid The id of this object on the remote site.
1275 function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
1279 'sitebackpackid' => $sitebackpackid,
1281 'internalid' => $internalid,
1282 'externalid' => $externalid
1285 return $DB->insert_record('badge_external_identifier', $params);
1289 * Delete all external mapping information for a backpack.
1291 * @param integer $sitebackpackid The site backpack to connect to.
1294 function badges_external_delete_mappings($sitebackpackid) {
1297 $params = ['sitebackpackid' => $sitebackpackid];
1299 return $DB->delete_records('badge_external_identifier', $params);
1303 * Delete a specific external mapping information for a backpack.
1305 * @param integer $sitebackpackid The site backpack to connect to.
1306 * @param string $type The type of this remote object.
1307 * @param string $internalid The id for this object on the Moodle site.
1309 function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
1313 'sitebackpackid' => $sitebackpackid,
1315 'internalid' => $internalid
1318 $DB->delete_record('badge_external_identifier', $params);
1322 * Create and send a verification email to the email address supplied.
1324 * Since we're not sending this email to a user, email_to_user can't be used
1325 * but this function borrows largely the code from that process.
1327 * @param string $email the email address to send the verification email to.
1328 * @param int $backpackid the id of the backpack to connect to
1329 * @param string $backpackpassword the user entered password to connect to this backpack
1330 * @return true if the email was sent successfully, false otherwise.
1332 function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1335 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1336 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1337 // of verification emails to said address.
1338 $secret = random_string(15);
1339 set_user_preference('badges_email_verify_secret', $secret);
1340 set_user_preference('badges_email_verify_address', $email);
1341 set_user_preference('badges_email_verify_backpackid', $backpackid);
1342 set_user_preference('badges_email_verify_password', $backpackpassword);
1345 $tempuser = $DB->get_record('user', array('id' => $USER->id
), '*', MUST_EXIST
);
1346 $tempuser->email
= $email;
1347 $noreplyuser = core_user
::get_noreply_user();
1349 // Generate the verification email body.
1350 $verificationurl = '/badges/backpackemailverify.php';
1351 $verificationurl = new moodle_url($verificationurl);
1352 $verificationpath = $verificationurl->out(false);
1355 $link = $verificationpath . '?data='. $secret;
1356 // Hard-coded button styles, because CSS can't be used in emails.
1358 'background-color: #0f6cbf',
1362 'text-align: center',
1363 'text-decoration: none',
1364 'display: inline-block',
1369 'border-radius: 8px',
1371 $button = html_writer
::start_tag('center') .
1374 get_string('verifyemail', 'badges'),
1375 ['style' => implode(';', $buttonstyles)]) .
1376 html_writer
::end_tag('center');
1378 'link' => html_writer
::link($link, $link),
1379 'buttonlink' => html_writer
::link($link, $button),
1380 'sitename' => $site->fullname
,
1381 'admin' => generate_email_signoff(),
1382 'userfirstname' => $USER->firstname
,
1385 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname
);
1386 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1387 $messagehtml = text_to_html($messagetext, false, false, true);
1389 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1393 * Return all the enabled criteria types for this site.
1395 * @param boolean $enabled
1398 function badges_list_criteria($enabled = true) {
1402 BADGE_CRITERIA_TYPE_OVERALL
=> 'overall',
1403 BADGE_CRITERIA_TYPE_ACTIVITY
=> 'activity',
1404 BADGE_CRITERIA_TYPE_MANUAL
=> 'manual',
1405 BADGE_CRITERIA_TYPE_SOCIAL
=> 'social',
1406 BADGE_CRITERIA_TYPE_COURSE
=> 'course',
1407 BADGE_CRITERIA_TYPE_COURSESET
=> 'courseset',
1408 BADGE_CRITERIA_TYPE_PROFILE
=> 'profile',
1409 BADGE_CRITERIA_TYPE_BADGE
=> 'badge',
1410 BADGE_CRITERIA_TYPE_COHORT
=> 'cohort',
1411 BADGE_CRITERIA_TYPE_COMPETENCY
=> 'competency',
1414 foreach ($types as $key => $type) {
1415 $class = 'award_criteria_' . $type;
1416 $file = $CFG->dirroot
. '/badges/criteria/' . $class . '.php';
1417 if (file_exists($file)) {
1418 require_once($file);
1420 if (!$class::is_enabled()) {
1421 unset($types[$key]);
1430 * Check if any badge has records for competencies.
1432 * @param array $competencyids Array of competencies ids.
1433 * @return boolean Return true if competencies were found in any badge.
1435 function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1438 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED
);
1440 $sql = "SELECT DISTINCT bc.badgeid
1441 FROM {badge_criteria} bc
1442 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1443 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1444 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY
;
1446 return $DB->record_exists_sql($sql, $params);
1450 * Creates single message for all notification and sends it out
1452 * @param object $badge A badge which is notified about.
1454 function badge_assemble_notification(stdClass
$badge) {
1457 $userfrom = core_user
::get_noreply_user();
1458 $userfrom->maildisplay
= true;
1460 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id
))) {
1461 // Get badge creator.
1462 $creator = $DB->get_record('user', array('id' => $badge->creator
), '*', MUST_EXIST
);
1463 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
1464 $creatormessage = '';
1466 // Put all messages in one digest.
1467 foreach ($msgs as $msg) {
1468 $issuedlink = html_writer
::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash
)), $badge->name
);
1469 $recipient = $DB->get_record('user', array('id' => $msg->userid
), '*', MUST_EXIST
);
1471 $a = new stdClass();
1472 $a->user
= fullname($recipient);
1473 $a->link
= $issuedlink;
1474 $creatormessage .= get_string('creatorbody', 'badges', $a);
1475 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid
, 'userid' => $msg->userid
));
1478 // Create a message object.
1479 $eventdata = new \core\message\
message();
1480 $eventdata->courseid
= SITEID
;
1481 $eventdata->component
= 'moodle';
1482 $eventdata->name
= 'badgecreatornotice';
1483 $eventdata->userfrom
= $userfrom;
1484 $eventdata->userto
= $creator;
1485 $eventdata->notification
= 1;
1486 $eventdata->subject
= $creatorsubject;
1487 $eventdata->fullmessage
= format_text_email($creatormessage, FORMAT_HTML
);
1488 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1489 $eventdata->fullmessagehtml
= $creatormessage;
1490 $eventdata->smallmessage
= $creatorsubject;
1492 message_send($eventdata);
1497 * Attempt to authenticate with the site backpack credentials and return an error
1498 * if the authentication fails. If external backpacks are not enabled, this will
1499 * not perform any test.
1503 function badges_verify_site_backpack() {
1504 $defaultbackpack = badges_get_site_primary_backpack();
1505 return badges_verify_backpack($defaultbackpack->id
);
1509 * Attempt to authenticate with a backpack credentials and return an error
1510 * if the authentication fails.
1511 * If external backpacks are not enabled or the backpack version is different
1512 * from OBv2, this will not perform any test.
1514 * @param int $backpackid Backpack identifier to verify.
1515 * @return string The result of the verification process.
1517 function badges_verify_backpack(int $backpackid) {
1518 global $OUTPUT, $CFG;
1520 if (empty($CFG->badges_allowexternalbackpack
)) {
1524 $backpack = badges_get_site_backpack($backpackid);
1525 if (empty($backpack->apiversion
) ||
($backpack->apiversion
== OPEN_BADGES_V2
)) {
1526 $backpackapi = new \core_badges\backpack_api
($backpack);
1528 // Clear any cached access tokens in the session.
1529 $backpackapi->clear_system_user_session();
1531 // Now attempt a login with these credentials.
1532 $result = $backpackapi->authenticate();
1533 if (empty($result) ||
!empty($result->error
)) {
1534 $warning = $backpackapi->get_authentication_error();
1536 $params = ['id' => $backpack->id
, 'action' => 'edit'];
1537 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1539 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1540 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1541 return $OUTPUT->container($icon . $message, 'text-danger');
1549 * Generate a public badgr URL that conforms to OBv2. This is done because badgr responses do not currently conform to
1552 * WARNING: This is an extremely hacky way of implementing this and should be removed once the standards are conformed to.
1554 * @param stdClass $backpack The Badgr backpack we are pushing to
1555 * @param string $type The type of object we are dealing with either Issuer, Assertion OR Badge.
1556 * @param string $externalid The externalid as provided by the backpack
1557 * @return ?string The public URL to access Badgr objects
1559 function badges_generate_badgr_open_url($backpack, $type, $externalid) {
1560 if (badges_open_badges_backpack_api($backpack->id
) == OPEN_BADGES_V2
) {
1561 $entity = strtolower($type);
1562 if ($type == OPEN_BADGES_V2_TYPE_BADGE
) {
1565 $url = new moodle_url($backpack->backpackapiurl
);
1566 return "{$url->get_scheme()}://{$url->get_host()}/public/{$entity}s/$externalid";