2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Contains classes, functions and constants used in badges.
22 * @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @author Yuliya Bozhko <yuliya.bozhko@totaralms.com>
27 defined('MOODLE_INTERNAL') ||
die();
29 /* Include required award criteria library. */
30 require_once($CFG->dirroot
. '/badges/criteria/award_criteria.php');
32 /* Include required user badge exporter */
33 use core_badges\external\user_badge_exporter
;
36 * Number of records per page.
38 define('BADGE_PERPAGE', 50);
41 * Badge award criteria aggregation method.
43 define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
46 * Badge award criteria aggregation method.
48 define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
51 * Inactive badge means that this badge cannot be earned and has not been awarded
52 * yet. Its award criteria can be changed.
54 define('BADGE_STATUS_INACTIVE', 0);
57 * Active badge means that this badge can we earned, but it has not been awarded
58 * yet. Can be deactivated for the purpose of changing its criteria.
60 define('BADGE_STATUS_ACTIVE', 1);
63 * Inactive badge can no longer be earned, but it has been awarded in the past and
64 * therefore its criteria cannot be changed.
66 define('BADGE_STATUS_INACTIVE_LOCKED', 2);
69 * Active badge means that it can be earned and has already been awarded to users.
70 * Its criteria cannot be changed any more.
72 define('BADGE_STATUS_ACTIVE_LOCKED', 3);
75 * Archived badge is considered deleted and can no longer be earned and is not
76 * displayed in the list of all badges.
78 define('BADGE_STATUS_ARCHIVED', 4);
81 * Badge type for site badges.
83 define('BADGE_TYPE_SITE', 1);
86 * Badge type for course badges.
88 define('BADGE_TYPE_COURSE', 2);
91 * Badge messaging schedule options.
93 define('BADGE_MESSAGE_NEVER', 0);
94 define('BADGE_MESSAGE_ALWAYS', 1);
95 define('BADGE_MESSAGE_DAILY', 2);
96 define('BADGE_MESSAGE_WEEKLY', 3);
97 define('BADGE_MESSAGE_MONTHLY', 4);
100 * URL of backpack. Custom ones can be added.
102 define('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
103 define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
106 * @deprecated since 3.9 (MDL-66357).
108 define('BADGE_BACKPACKAPIURL', 'https://backpack.openbadges.org');
109 define('BADGE_BACKPACKWEBURL', 'https://backpack.openbadges.org');
112 * Open Badges specifications.
114 define('OPEN_BADGES_V1', 1);
115 define('OPEN_BADGES_V2', 2);
116 define('OPEN_BADGES_V2P1', 2.1);
119 * Only use for Open Badges 2.0 specification
121 define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
122 define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
123 define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
124 define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
125 define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
126 define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
128 define('BACKPACK_MOVE_UP', -1);
129 define('BACKPACK_MOVE_DOWN', 1);
131 // Global badge class has been moved to the component namespace.
132 class_alias('\core_badges\badge', 'badge');
135 * Sends notifications to users about awarded badges.
137 * @param \core_badges\badge $badge Badge that was issued
138 * @param int $userid Recipient ID
139 * @param string $issued Unique hash of an issued badge
140 * @param string $filepathhash File path hash of an issued badge for attachments
142 function badges_notify_badge_award(badge
$badge, $userid, $issued, $filepathhash) {
145 $admin = get_admin();
146 $userfrom = new stdClass();
147 $userfrom->id
= $admin->id
;
148 $userfrom->email
= !empty($CFG->badges_defaultissuercontact
) ?
$CFG->badges_defaultissuercontact
: $admin->email
;
149 foreach (\core_user\fields
::get_name_fields() as $addname) {
150 $userfrom->$addname = !empty($CFG->badges_defaultissuername
) ?
'' : $admin->$addname;
152 $userfrom->firstname
= !empty($CFG->badges_defaultissuername
) ?
$CFG->badges_defaultissuername
: $admin->firstname
;
153 $userfrom->maildisplay
= true;
155 $issuedlink = html_writer
::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name
);
156 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
158 $params = new stdClass();
159 $params->badgename
= $badge->name
;
160 $params->username
= fullname($userto);
161 $params->badgelink
= $issuedlink;
162 $message = badge_message_from_template($badge->message
, $params);
163 $plaintext = html_to_text($message);
166 $eventdata = new \core\message\
message();
167 $eventdata->courseid
= is_null($badge->courseid
) ? SITEID
: $badge->courseid
; // Profile/site come with no courseid.
168 $eventdata->component
= 'moodle';
169 $eventdata->name
= 'badgerecipientnotice';
170 $eventdata->userfrom
= $userfrom;
171 $eventdata->userto
= $userto;
172 $eventdata->notification
= 1;
173 $eventdata->subject
= $badge->messagesubject
;
174 $eventdata->fullmessage
= $plaintext;
175 $eventdata->fullmessageformat
= FORMAT_HTML
;
176 $eventdata->fullmessagehtml
= $message;
177 $eventdata->smallmessage
= '';
178 $eventdata->customdata
= [
179 'notificationiconurl' => moodle_url
::make_pluginfile_url(
180 $badge->get_context()->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1')->out(),
184 // Attach badge image if possible.
185 if (!empty($CFG->allowattachments
) && $badge->attachment
&& is_string($filepathhash)) {
186 $fs = get_file_storage();
187 $file = $fs->get_file_by_hash($filepathhash);
188 $eventdata->attachment
= $file;
189 $eventdata->attachname
= str_replace(' ', '_', $badge->name
) . ".png";
191 message_send($eventdata);
193 message_send($eventdata);
196 // Notify badge creator about the award if they receive notifications every time.
197 if ($badge->notification
== 1) {
198 $userfrom = core_user
::get_noreply_user();
199 $userfrom->maildisplay
= true;
201 $creator = $DB->get_record('user', array('id' => $badge->usercreated
), '*', MUST_EXIST
);
203 $a->user
= fullname($userto);
204 $a->link
= $issuedlink;
205 $creatormessage = get_string('creatorbody', 'badges', $a);
206 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
208 $eventdata = new \core\message\
message();
209 $eventdata->courseid
= $badge->courseid
;
210 $eventdata->component
= 'moodle';
211 $eventdata->name
= 'badgecreatornotice';
212 $eventdata->userfrom
= $userfrom;
213 $eventdata->userto
= $creator;
214 $eventdata->notification
= 1;
215 $eventdata->subject
= $creatorsubject;
216 $eventdata->fullmessage
= html_to_text($creatormessage);
217 $eventdata->fullmessageformat
= FORMAT_HTML
;
218 $eventdata->fullmessagehtml
= $creatormessage;
219 $eventdata->smallmessage
= '';
220 $eventdata->customdata
= [
221 'notificationiconurl' => moodle_url
::make_pluginfile_url(
222 $badge->get_context()->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1')->out(),
226 message_send($eventdata);
227 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id
, 'userid' => $userid));
232 * Caclulates date for the next message digest to badge creators.
234 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
235 * @return int Timestamp for next cron
237 function badges_calculate_message_schedule($schedule) {
241 case BADGE_MESSAGE_DAILY
:
242 $tomorrow = new DateTime("1 day", core_date
::get_server_timezone_object());
243 $nextcron = $tomorrow->getTimestamp();
245 case BADGE_MESSAGE_WEEKLY
:
246 $nextweek = new DateTime("1 week", core_date
::get_server_timezone_object());
247 $nextcron = $nextweek->getTimestamp();
249 case BADGE_MESSAGE_MONTHLY
:
250 $nextmonth = new DateTime("1 month", core_date
::get_server_timezone_object());
251 $nextcron = $nextmonth->getTimestamp();
259 * Replaces variables in a message template and returns text ready to be emailed to a user.
261 * @param string $message Message body.
262 * @return string Message with replaced values
264 function badge_message_from_template($message, $params) {
266 foreach ($params as $key => $value) {
267 $msg = str_replace("%$key%", $value, $msg);
276 * @param int Type of badges to return
277 * @param int Course ID for course badges
278 * @param string $sort An SQL field to sort by
279 * @param string $dir The sort direction ASC|DESC
280 * @param int $page The page or records to return
281 * @param int $perpage The number of records to return per page
282 * @param int $user User specific search
283 * @return array $badge Array of records matching criteria
285 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE
, $user = 0) {
289 $where = "b.status != :deleted AND b.type = :type ";
290 $params['deleted'] = BADGE_STATUS_ARCHIVED
;
292 $userfields = array('b.id, b.name, b.status');
295 $userfields[] = 'bi.dateissued';
296 $userfields[] = 'bi.uniquehash';
297 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
298 $params['userid'] = $user;
299 $where .= " AND (b.status = 1 OR b.status = 3) ";
301 $fields = implode(', ', $userfields);
303 if ($courseid != 0 ) {
304 $where .= "AND b.courseid = :courseid ";
305 $params['courseid'] = $courseid;
308 $sorting = (($sort != '' && $dir != '') ?
'ORDER BY ' . $sort . ' ' . $dir : '');
309 $params['type'] = $type;
311 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
312 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
315 foreach ($records as $r) {
316 $badge = new badge($r->id
);
317 $badges[$r->id
] = $badge;
319 $badges[$r->id
]->dateissued
= $r->dateissued
;
320 $badges[$r->id
]->uniquehash
= $r->uniquehash
;
322 $badges[$r->id
]->awards
= $DB->count_records_sql('SELECT COUNT(b.userid)
323 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
324 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id
));
325 $badges[$r->id
]->statstring
= $badge->get_status_name();
332 * Get badges for a specific user.
334 * @param int $userid User ID
335 * @param int $courseid Badges earned by a user in a specific course
336 * @param int $page The page or records to return
337 * @param int $perpage The number of records to return per page
338 * @param string $search A simple string to search for
339 * @param bool $onlypublic Return only public badges
340 * @return array of badges ordered by decreasing date of issue
342 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
360 WHERE b.id = bi.badgeid
362 AND bi.userid = :userid';
364 if (!empty($search)) {
365 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
366 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
369 $sql .= ' AND (bi.visible = 1) ';
372 if (empty($CFG->badges_allowcoursebadges
)) {
373 $sql .= ' AND b.courseid IS NULL';
374 } else if ($courseid != 0) {
375 $sql .= ' AND (b.courseid = :courseid) ';
376 $params['courseid'] = $courseid;
378 $sql .= ' ORDER BY bi.dateissued DESC';
379 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
387 * @param string $hash
388 * @return object|bool
390 function badges_get_badge_by_hash(string $hash): object|
bool {
405 WHERE b.id = bi.badgeid
407 AND ' . $DB->sql_compare_text('bi.uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40);
408 $badge = $DB->get_record_sql($sql, ['hash' => $hash], IGNORE_MISSING
);
413 * Update badge instance to external functions.
415 * @param stdClass $badge
416 * @param stdClass $user
419 function badges_prepare_badge_for_external(stdClass
$badge, stdClass
$user): object {
421 if ($badge->type
== BADGE_TYPE_SITE
) {
422 $context = context_system
::instance();
424 $context = context_course
::instance($badge->courseid
);
426 $canconfiguredetails = has_capability('moodle/badges:configuredetails', $context);
427 // If the user is viewing another user's badge and doesn't have the right capability return only part of the data.
428 if ($USER->id
!= $user->id
&& !$canconfiguredetails) {
431 'name' => $badge->name
,
432 'type' => $badge->type
,
433 'description' => $badge->description
,
434 'issuername' => $badge->issuername
,
435 'issuerurl' => $badge->issuerurl
,
436 'issuercontact' => $badge->issuercontact
,
437 'uniquehash' => $badge->uniquehash
,
438 'dateissued' => $badge->dateissued
,
439 'dateexpire' => $badge->dateexpire
,
440 'version' => $badge->version
,
441 'language' => $badge->language
,
442 'imageauthorname' => $badge->imageauthorname
,
443 'imageauthoremail' => $badge->imageauthoremail
,
444 'imageauthorurl' => $badge->imageauthorurl
,
445 'imagecaption' => $badge->imagecaption
,
449 // Create a badge instance to be able to get the endorsement and other info.
450 $badgeinstance = new badge($badge->id
);
451 $endorsement = $badgeinstance->get_endorsement();
452 $alignments = $badgeinstance->get_alignments();
453 $relatedbadges = $badgeinstance->get_related_badges();
455 if (!$canconfiguredetails) {
456 // Return only the properties visible by the user.
457 if (!empty($alignments)) {
458 foreach ($alignments as $alignment) {
459 unset($alignment->targetdescription
);
460 unset($alignment->targetframework
);
461 unset($alignment->targetcode
);
465 if (!empty($relatedbadges)) {
466 foreach ($relatedbadges as $relatedbadge) {
467 unset($relatedbadge->version
);
468 unset($relatedbadge->language
);
469 unset($relatedbadge->type
);
475 'context' => $context,
476 'endorsement' => $endorsement ?
$endorsement : null,
477 'alignment' => $alignments,
478 'relatedbadges' => $relatedbadges,
481 $exporter = new user_badge_exporter($badge, $related);
482 return $exporter->export($PAGE->get_renderer('core'));
486 * Extends the course administration navigation with the Badges page
488 * @param navigation_node $coursenode
489 * @param object $course
491 function badges_add_course_navigation(navigation_node
$coursenode, stdClass
$course) {
494 $coursecontext = context_course
::instance($course->id
);
495 $isfrontpage = (!$coursecontext ||
$course->id
== $SITE->id
);
496 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
497 'moodle/badges:createbadge',
498 'moodle/badges:awardbadge',
499 'moodle/badges:configurecriteria',
500 'moodle/badges:configuremessages',
501 'moodle/badges:configuredetails',
502 'moodle/badges:deletebadge'), $coursecontext);
504 if (!empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
) && !$isfrontpage && $canmanage) {
505 $coursenode->add(get_string('coursebadges', 'badges'), null,
506 navigation_node
::TYPE_CONTAINER
, null, 'coursebadges',
507 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
509 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
511 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
512 navigation_node
::TYPE_SETTING
, null, 'coursebadges');
514 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
515 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
517 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
518 navigation_node
::TYPE_SETTING
, null, 'newbadge');
524 * Triggered when badge is manually awarded.
526 * @param object $data
529 function badges_award_handle_manual_criteria_review(stdClass
$data) {
530 $criteria = $data->crit
;
531 $userid = $data->userid
;
532 $badge = new badge($criteria->badgeid
);
534 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
538 if ($criteria->review($userid)) {
539 $criteria->mark_complete($userid);
541 if ($badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($userid)) {
542 $badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($userid);
543 $badge->issue($userid);
551 * Process badge image from form data
553 * @param badge $badge Badge object
554 * @param string $iconfile Original file
556 function badges_process_badge_image(badge
$badge, $iconfile) {
558 require_once($CFG->libdir
. '/gdlib.php');
560 if (!empty($CFG->gdversion
)) {
561 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id
, $iconfile, true);
564 // Clean up file draft area after badge image has been saved.
565 $context = context_user
::instance($USER->id
, MUST_EXIST
);
566 $fs = get_file_storage();
567 $fs->delete_area_files($context->id
, 'user', 'draft');
574 * @param badge $badge Badge object
575 * @param stdClass $context
576 * @param string $size
578 function print_badge_image(badge
$badge, stdClass
$context, $size = 'small') {
579 $fsize = ($size == 'small') ?
'f2' : 'f1';
581 $imageurl = moodle_url
::make_pluginfile_url($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $fsize, false);
582 // Appending a random parameter to image link to forse browser reload the image.
583 $imageurl->param('refresh', rand(1, 10000));
584 $attributes = array('src' => $imageurl, 'alt' => s($badge->name
), 'class' => 'activatebadge');
586 return html_writer
::empty_tag('img', $attributes);
592 * @param string $hash Unique hash of an issued badge.
593 * @param int $badgeid ID of the original badge.
594 * @param int $userid ID of badge recipient (optional).
595 * @param boolean $pathhash Return file pathhash instead of image url (optional).
596 * @return string|url Returns either new file path hash or new file URL
598 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
600 require_once(__DIR__
. '/../badges/lib/bakerlib.php');
602 $badge = new badge($badgeid);
603 $badge_context = $badge->get_context();
604 $userid = ($userid) ?
$userid : $USER->id
;
605 $user_context = context_user
::instance($userid);
607 $fs = get_file_storage();
608 if (!$fs->file_exists($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png')) {
609 if ($file = $fs->get_file($badge_context->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f3.png')) {
610 $contents = $file->get_content();
612 $filehandler = new PNG_MetaDataHandler($contents);
613 // For now, the site backpack OB version will be used as default.
614 $obversion = badges_open_badges_backpack_api();
615 $assertion = new core_badges_assertion($hash, $obversion);
616 $assertionjson = json_encode($assertion->get_badge_assertion());
617 if ($filehandler->check_chunks("iTXt", "openbadges")) {
618 // Add assertion URL iTXt chunk.
619 $newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
621 'contextid' => $user_context->id
,
622 'component' => 'badges',
623 'filearea' => 'userbadge',
624 'itemid' => $badge->id
,
626 'filename' => $hash . '.png',
629 // Create a file with added contents.
630 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
632 return $newfile->get_pathnamehash();
636 debugging('Error baking badge image!', DEBUG_DEVELOPER
);
641 // If file exists and we just need its path hash, return it.
643 $file = $fs->get_file($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png');
644 return $file->get_pathnamehash();
647 $fileurl = moodle_url
::make_pluginfile_url($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash, true);
652 * Returns external backpack settings and badges from this backpack.
654 * This function first checks if badges for the user are cached and
655 * tries to retrieve them from the cache. Otherwise, badges are obtained
656 * through curl request to the backpack.
658 * @param int $userid Backpack user ID.
659 * @param boolean $refresh Refresh badges collection in cache.
660 * @return null|object Returns null is there is no backpack or object with backpack settings.
662 function get_backpack_settings($userid, $refresh = false) {
665 // Try to get badges from cache first.
666 $badgescache = cache
::make('core', 'externalbadges');
667 $out = $badgescache->get($userid);
668 if ($out !== false && !$refresh) {
671 // Get badges through curl request to the backpack.
672 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
674 $sitebackpack = badges_get_site_backpack($record->externalbackpackid
);
675 $backpack = new \core_badges\backpack_api
($sitebackpack, $record);
676 $out = new stdClass();
677 $out->backpackid
= $sitebackpack->id
;
679 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id
))) {
680 $out->totalcollections
= count($collections);
681 $out->totalbadges
= 0;
682 $out->badges
= array();
683 foreach ($collections as $collection) {
684 $badges = $backpack->get_badges($collection, true);
685 if (!empty($badges)) {
686 $out->badges
= array_merge($out->badges
, $badges);
687 $out->totalbadges +
= count($badges);
689 $out->badges
= array_merge($out->badges
, array());
693 $out->totalbadges
= 0;
694 $out->totalcollections
= 0;
697 $badgescache->set($userid, $out);
705 * Download all user badges in zip archive.
707 * @param int $userid ID of badge owner.
709 function badges_download($userid) {
711 $context = context_user
::instance($userid);
712 $records = $DB->get_records('badge_issued', array('userid' => $userid));
714 // Get list of files to download.
715 $fs = get_file_storage();
717 foreach ($records as $issued) {
718 $badge = new badge($issued->badgeid
);
719 // Need to make image name user-readable and unique using filename safe characters.
720 $name = $badge->name
. ' ' . userdate($issued->dateissued
, '%d %b %Y') . ' ' . hash('crc32', $badge->id
);
721 $name = str_replace(' ', '_', $name);
722 $name = clean_param($name, PARAM_FILE
);
723 if ($file = $fs->get_file($context->id
, 'badges', 'userbadge', $issued->badgeid
, '/', $issued->uniquehash
. '.png')) {
724 $filelist[$name . '.png'] = $file;
728 // Zip files and sent them to a user.
729 $tempzip = tempnam($CFG->tempdir
.'/', 'mybadges');
730 $zipper = new zip_packer();
731 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
732 send_temp_file($tempzip, 'badges.zip');
734 debugging("Problems with archiving the files.", DEBUG_DEVELOPER
);
740 * Checks if user has external backpack connected.
742 * @param int $userid ID of a user.
743 * @return bool True|False whether backpack connection exists.
745 function badges_user_has_backpack($userid) {
747 return $DB->record_exists('badge_backpack', array('userid' => $userid));
751 * Handles what happens to the course badges when a course is deleted.
753 * @param int $courseid course ID.
756 function badges_handle_course_deletion($courseid) {
758 include_once $CFG->libdir
. '/filelib.php';
760 $systemcontext = context_system
::instance();
761 $coursecontext = context_course
::instance($courseid);
762 $fs = get_file_storage();
764 // Move badges images to the system context.
765 $fs->move_area_files_to_new_context($coursecontext->id
, $systemcontext->id
, 'badges', 'badgeimage');
767 // Get all course badges.
768 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE
, 'courseid' => $courseid));
769 foreach ($badges as $badge) {
770 // Archive badges in this course.
771 $toupdate = new stdClass();
772 $toupdate->id
= $badge->id
;
773 $toupdate->type
= BADGE_TYPE_SITE
;
774 $toupdate->courseid
= null;
775 $toupdate->status
= BADGE_STATUS_ARCHIVED
;
776 $DB->update_record('badge', $toupdate);
781 * Create the site backpack with this data.
783 * @param stdClass $data The new backpack data.
786 function badges_create_site_backpack($data) {
788 $context = context_system
::instance();
789 require_capability('moodle/badges:manageglobalsettings', $context);
791 $max = $DB->get_field_sql('SELECT MAX(sortorder) FROM {badge_external_backpack}');
792 $data->sortorder
= $max +
1;
794 return badges_save_external_backpack($data);
798 * Update the backpack with this id.
800 * @param integer $id The backpack to edit
801 * @param stdClass $data The new backpack data.
804 function badges_update_site_backpack($id, $data) {
806 $context = context_system
::instance();
807 require_capability('moodle/badges:manageglobalsettings', $context);
809 if ($backpack = badges_get_site_backpack($id)) {
811 return badges_save_external_backpack($data);
818 * Delete the backpack with this id.
820 * @param integer $id The backpack to delete.
823 function badges_delete_site_backpack($id) {
826 $context = context_system
::instance();
827 require_capability('moodle/badges:manageglobalsettings', $context);
829 // Only remove site backpack if it's not the default one.
830 $defaultbackpack = badges_get_site_primary_backpack();
831 if ($defaultbackpack->id
!= $id && $DB->record_exists('badge_external_backpack', ['id' => $id])) {
832 $transaction = $DB->start_delegated_transaction();
834 // Remove connections for users to this backpack.
835 $sql = "SELECT DISTINCT bb.id
836 FROM {badge_backpack} bb
837 WHERE bb.externalbackpackid = :backpackid";
838 $params = ['backpackid' => $id];
839 $userbackpacks = $DB->get_fieldset_sql($sql, $params);
840 if ($userbackpacks) {
841 // Delete user external collections references to this backpack.
842 list($insql, $params) = $DB->get_in_or_equal($userbackpacks);
843 $DB->delete_records_select('badge_external', "backpackid $insql", $params);
845 $DB->delete_records('badge_backpack', ['externalbackpackid' => $id]);
847 // Delete backpack entry.
848 $result = $DB->delete_records('badge_external_backpack', ['id' => $id]);
850 $transaction->allow_commit();
859 * Perform the actual create/update of external bakpacks. Any checks on the validity of the id will need to be
860 * performed before it reaches this function.
862 * @param stdClass $data The backpack data we are updating/inserting
863 * @return int Returns the id of the new/updated record
865 function badges_save_external_backpack(stdClass
$data) {
867 if ($data->apiversion
== OPEN_BADGES_V2P1
) {
868 // Check if there is an existing issuer for the given backpackapiurl.
869 foreach (core\oauth2\api
::get_all_issuers() as $tmpissuer) {
870 if ($data->backpackweburl
== $tmpissuer->get('baseurl')) {
871 $issuer = $tmpissuer;
876 // Create the issuer if it doesn't exist yet.
877 if (empty($issuer)) {
878 $issuer = new \core\oauth2\
issuer(0, (object) [
879 'name' => $data->backpackweburl
,
880 'baseurl' => $data->backpackweburl
,
881 // Note: This is required because the DB schema is broken and does not accept a null value when it should.
887 // This can't be run from PHPUNIT because testing platforms need real URLs.
888 // In the future, this request can be moved to the moodle-exttests repository.
890 // Create/update the endpoints for the issuer.
891 \core\oauth2\discovery\imsbadgeconnect
::create_endpoints($issuer);
892 $data->oauth2_issuerid
= $issuer->get('id');
894 $apibase = \core\oauth2\endpoint
::get_record([
895 'issuerid' => $data->oauth2_issuerid
,
898 $data->backpackapiurl
= $apibase->get('url');
901 $backpack = new stdClass();
903 $backpack->apiversion
= $data->apiversion
;
904 $backpack->backpackweburl
= $data->backpackweburl
;
905 $backpack->backpackapiurl
= $data->backpackapiurl
;
906 $backpack->oauth2_issuerid
= $data->oauth2_issuerid ??
'';
907 if (isset($data->sortorder
)) {
908 $backpack->sortorder
= $data->sortorder
;
911 if (empty($data->id
)) {
912 $backpack->id
= $DB->insert_record('badge_external_backpack', $backpack);
914 $backpack->id
= $data->id
;
915 $DB->update_record('badge_external_backpack', $backpack);
917 $data->externalbackpackid
= $backpack->id
;
920 badges_save_backpack_credentials($data);
921 return $data->externalbackpackid
;
925 * Create a backpack with the provided details. Stores the auth details of the backpack
927 * @param stdClass $data Backpack specific data.
928 * @return int The id of the external backpack that the credentials correspond to
930 function badges_save_backpack_credentials(stdClass
$data) {
933 if (isset($data->backpackemail
) && isset($data->password
)) {
934 $backpack = new stdClass();
936 $backpack->email
= $data->backpackemail
;
937 $backpack->password
= !empty($data->password
) ?
$data->password
: '';
938 $backpack->externalbackpackid
= $data->externalbackpackid
;
939 $backpack->userid
= $data->userid ??
0;
940 $backpack->backpackuid
= $data->backpackuid ??
0;
941 $backpack->autosync
= $data->autosync ??
0;
943 if (!empty($data->badgebackpack
)) {
944 $backpack->id
= $data->badgebackpack
;
945 } else if (!empty($data->id
)) {
946 $backpack->id
= $data->id
;
949 if (empty($backpack->id
)) {
950 $backpack->id
= $DB->insert_record('badge_backpack', $backpack);
952 $DB->update_record('badge_backpack', $backpack);
955 return $backpack->externalbackpackid
;
958 return $data->externalbackpackid ??
0;
962 * Is any backpack enabled that supports open badges V1?
963 * @param int|null $backpackid Check the version of the given id OR if null the sitewide backpack
966 function badges_open_badges_backpack_api(?
int $backpackid = null) {
968 $backpack = badges_get_site_primary_backpack();
970 $backpack = badges_get_site_backpack($backpackid);
973 if (empty($backpack->apiversion
)) {
974 return OPEN_BADGES_V2
;
976 return $backpack->apiversion
;
980 * Get a site backpacks by id for a particular user or site (if userid is 0)
982 * @param int $id The backpack id.
983 * @param int $userid The owner of the backpack, 0 if it's a sitewide backpack else a user's site backpack
986 function badges_get_site_backpack($id, int $userid = 0) {
989 $sql = "SELECT beb.*, bb.id AS badgebackpack, bb.password, bb.email AS backpackemail
990 FROM {badge_external_backpack} beb
991 LEFT JOIN {badge_backpack} bb ON bb.externalbackpackid = beb.id AND bb.userid=:userid
994 return $DB->get_record_sql($sql, ['id' => $id, 'userid' => $userid]);
998 * Get the user backpack for the currently logged in user OR the provided user
1000 * @param int|null $userid The user whose backpack you're requesting for. If null, get the logged in user's backpack
1001 * @return mixed The user's backpack or none.
1002 * @throws dml_exception
1004 function badges_get_user_backpack(?
int $userid = 0) {
1009 $userid = $USER->id
;
1012 $sql = "SELECT beb.*, bb.id AS badgebackpack, bb.password, bb.email AS backpackemail
1013 FROM {badge_external_backpack} beb
1014 JOIN {badge_backpack} bb ON bb.externalbackpackid = beb.id AND bb.userid=:userid";
1016 return $DB->get_record_sql($sql, ['userid' => $userid]);
1020 * Get the primary backpack for the site
1024 function badges_get_site_primary_backpack() {
1028 FROM {badge_external_backpack}
1029 WHERE sortorder = (SELECT MIN(sortorder)
1030 FROM {badge_external_backpack} b2)';
1031 $firstbackpack = $DB->get_record_sql($sql, null, MUST_EXIST
);
1033 return badges_get_site_backpack($firstbackpack->id
);
1037 * List the backpacks at site level.
1039 * @return array(stdClass)
1041 function badges_get_site_backpacks() {
1044 $defaultbackpack = badges_get_site_primary_backpack();
1045 $all = $DB->get_records('badge_external_backpack', null, 'sortorder ASC');
1046 foreach ($all as $key => $bp) {
1047 if ($bp->id
== $defaultbackpack->id
) {
1048 $all[$key]->sitebackpack
= true;
1050 $all[$key]->sitebackpack
= false;
1058 * Moves the backpack in the list one position up or down.
1060 * @param int $backpackid The backpack identifier to be moved.
1061 * @param int $direction The direction (BACKPACK_MOVE_UP/BACKPACK_MOVE_DOWN) where to move the backpack.
1063 * @throws \moodle_exception if attempting to use invalid direction value.
1065 function badges_change_sortorder_backpacks(int $backpackid, int $direction): void
{
1068 if ($direction != BACKPACK_MOVE_UP
&& $direction != BACKPACK_MOVE_DOWN
) {
1069 throw new \
coding_exception(
1070 'Must use a valid backpack API move direction constant (BACKPACK_MOVE_UP or BACKPACK_MOVE_DOWN)');
1073 $backpacks = badges_get_site_backpacks();
1074 $backpacktoupdate = $backpacks[$backpackid];
1076 $currentsortorder = $backpacktoupdate->sortorder
;
1077 $targetsortorder = $currentsortorder +
$direction;
1078 if ($targetsortorder > 0 && $targetsortorder <= count($backpacks) ) {
1079 foreach ($backpacks as $backpack) {
1080 if ($backpack->sortorder
== $targetsortorder) {
1081 $backpack->sortorder
= $backpack->sortorder
- $direction;
1082 $DB->update_record('badge_external_backpack', $backpack);
1086 $backpacktoupdate->sortorder
= $targetsortorder;
1087 $DB->update_record('badge_external_backpack', $backpacktoupdate);
1092 * List the supported badges api versions.
1094 * @return array(version)
1096 function badges_get_badge_api_versions() {
1098 (string)OPEN_BADGES_V1
=> get_string('openbadgesv1', 'badges'),
1099 (string)OPEN_BADGES_V2
=> get_string('openbadgesv2', 'badges'),
1100 (string)OPEN_BADGES_V2P1
=> get_string('openbadgesv2p1', 'badges')
1105 * Get the default issuer for a badge from this site.
1109 function badges_get_default_issuer() {
1112 $sitebackpack = badges_get_site_primary_backpack();
1114 $issuerurl = new moodle_url('/');
1115 $issuer['name'] = $CFG->badges_defaultissuername
;
1116 if (empty($issuer['name'])) {
1117 $issuer['name'] = $SITE->fullname ?
$SITE->fullname
: $SITE->shortname
;
1119 $issuer['url'] = $issuerurl->out(false);
1120 $issuer['email'] = $sitebackpack->backpackemail ?
: $CFG->badges_defaultissuercontact
;
1121 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT
;
1122 $issuerid = new moodle_url('/badges/issuer_json.php');
1123 $issuer['id'] = $issuerid->out(false);
1124 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER
;
1129 * Disconnect from the user backpack by deleting the user preferences.
1131 * @param integer $userid The user to diconnect.
1134 function badges_disconnect_user_backpack($userid) {
1137 // We can only change backpack settings for our own real backpack.
1138 if ($USER->id
!= $userid ||
1139 \core\session\manager
::is_loggedinas()) {
1144 unset_user_preference('badges_email_verify_secret');
1145 unset_user_preference('badges_email_verify_address');
1146 unset_user_preference('badges_email_verify_backpackid');
1147 unset_user_preference('badges_email_verify_password');
1153 * Used to remember which objects we connected with a backpack before.
1155 * @param integer $sitebackpackid The site backpack to connect to.
1156 * @param string $type The type of this remote object.
1157 * @param string $internalid The id for this object on the Moodle site.
1158 * @param string $param The param we need to return. Defaults to the externalid.
1159 * @return mixed The id or false if it doesn't exist.
1161 function badges_external_get_mapping($sitebackpackid, $type, $internalid, $param = 'externalid') {
1163 // Return externalid if it exists.
1165 'sitebackpackid' => $sitebackpackid,
1167 'internalid' => $internalid
1170 $record = $DB->get_record('badge_external_identifier', $params, $param, IGNORE_MISSING
);
1172 return $record->$param;
1178 * Save the info about which objects we connected with a backpack before.
1180 * @param integer $sitebackpackid The site backpack to connect to.
1181 * @param string $type The type of this remote object.
1182 * @param string $internalid The id for this object on the Moodle site.
1183 * @param string $externalid The id of this object on the remote site.
1186 function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
1190 'sitebackpackid' => $sitebackpackid,
1192 'internalid' => $internalid,
1193 'externalid' => $externalid
1196 return $DB->insert_record('badge_external_identifier', $params);
1200 * Delete all external mapping information for a backpack.
1202 * @param integer $sitebackpackid The site backpack to connect to.
1205 function badges_external_delete_mappings($sitebackpackid) {
1208 $params = ['sitebackpackid' => $sitebackpackid];
1210 return $DB->delete_records('badge_external_identifier', $params);
1214 * Delete a specific external mapping information for a backpack.
1216 * @param integer $sitebackpackid The site backpack to connect to.
1217 * @param string $type The type of this remote object.
1218 * @param string $internalid The id for this object on the Moodle site.
1221 function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
1225 'sitebackpackid' => $sitebackpackid,
1227 'internalid' => $internalid
1230 $DB->delete_record('badge_external_identifier', $params);
1234 * Create and send a verification email to the email address supplied.
1236 * Since we're not sending this email to a user, email_to_user can't be used
1237 * but this function borrows largely the code from that process.
1239 * @param string $email the email address to send the verification email to.
1240 * @param int $backpackid the id of the backpack to connect to
1241 * @param string $backpackpassword the user entered password to connect to this backpack
1242 * @return true if the email was sent successfully, false otherwise.
1244 function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1247 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1248 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1249 // of verification emails to said address.
1250 $secret = random_string(15);
1251 set_user_preference('badges_email_verify_secret', $secret);
1252 set_user_preference('badges_email_verify_address', $email);
1253 set_user_preference('badges_email_verify_backpackid', $backpackid);
1254 set_user_preference('badges_email_verify_password', $backpackpassword);
1257 $tempuser = $DB->get_record('user', array('id' => $USER->id
), '*', MUST_EXIST
);
1258 $tempuser->email
= $email;
1259 $noreplyuser = core_user
::get_noreply_user();
1261 // Generate the verification email body.
1262 $verificationurl = '/badges/backpackemailverify.php';
1263 $verificationurl = new moodle_url($verificationurl);
1264 $verificationpath = $verificationurl->out(false);
1267 $link = $verificationpath . '?data='. $secret;
1268 // Hard-coded button styles, because CSS can't be used in emails.
1270 'background-color: #0f6cbf',
1274 'text-align: center',
1275 'text-decoration: none',
1276 'display: inline-block',
1281 'border-radius: 8px',
1283 $button = html_writer
::start_tag('center') .
1286 get_string('verifyemail', 'badges'),
1287 ['style' => implode(';', $buttonstyles)]) .
1288 html_writer
::end_tag('center');
1290 'link' => html_writer
::link($link, $link),
1291 'buttonlink' => html_writer
::link($link, $button),
1292 'sitename' => $site->fullname
,
1293 'admin' => generate_email_signoff(),
1294 'userfirstname' => $USER->firstname
,
1297 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname
);
1298 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1299 $messagehtml = text_to_html($messagetext, false, false, true);
1301 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1305 * Return all the enabled criteria types for this site.
1307 * @param boolean $enabled
1310 function badges_list_criteria($enabled = true) {
1314 BADGE_CRITERIA_TYPE_OVERALL
=> 'overall',
1315 BADGE_CRITERIA_TYPE_ACTIVITY
=> 'activity',
1316 BADGE_CRITERIA_TYPE_MANUAL
=> 'manual',
1317 BADGE_CRITERIA_TYPE_SOCIAL
=> 'social',
1318 BADGE_CRITERIA_TYPE_COURSE
=> 'course',
1319 BADGE_CRITERIA_TYPE_COURSESET
=> 'courseset',
1320 BADGE_CRITERIA_TYPE_PROFILE
=> 'profile',
1321 BADGE_CRITERIA_TYPE_BADGE
=> 'badge',
1322 BADGE_CRITERIA_TYPE_COHORT
=> 'cohort',
1323 BADGE_CRITERIA_TYPE_COMPETENCY
=> 'competency',
1326 foreach ($types as $key => $type) {
1327 $class = 'award_criteria_' . $type;
1328 $file = $CFG->dirroot
. '/badges/criteria/' . $class . '.php';
1329 if (file_exists($file)) {
1330 require_once($file);
1332 if (!$class::is_enabled()) {
1333 unset($types[$key]);
1342 * Check if any badge has records for competencies.
1344 * @param array $competencyids Array of competencies ids.
1345 * @return boolean Return true if competencies were found in any badge.
1347 function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1350 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED
);
1352 $sql = "SELECT DISTINCT bc.badgeid
1353 FROM {badge_criteria} bc
1354 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1355 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1356 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY
;
1358 return $DB->record_exists_sql($sql, $params);
1362 * Creates single message for all notification and sends it out
1364 * @param object $badge A badge which is notified about.
1366 function badge_assemble_notification(stdClass
$badge) {
1369 $userfrom = core_user
::get_noreply_user();
1370 $userfrom->maildisplay
= true;
1372 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id
))) {
1373 // Get badge creator.
1374 $creator = $DB->get_record('user', array('id' => $badge->creator
), '*', MUST_EXIST
);
1375 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
1376 $creatormessage = '';
1378 // Put all messages in one digest.
1379 foreach ($msgs as $msg) {
1380 $issuedlink = html_writer
::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash
)), $badge->name
);
1381 $recipient = $DB->get_record('user', array('id' => $msg->userid
), '*', MUST_EXIST
);
1383 $a = new stdClass();
1384 $a->user
= fullname($recipient);
1385 $a->link
= $issuedlink;
1386 $creatormessage .= get_string('creatorbody', 'badges', $a);
1387 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid
, 'userid' => $msg->userid
));
1390 // Create a message object.
1391 $eventdata = new \core\message\
message();
1392 $eventdata->courseid
= SITEID
;
1393 $eventdata->component
= 'moodle';
1394 $eventdata->name
= 'badgecreatornotice';
1395 $eventdata->userfrom
= $userfrom;
1396 $eventdata->userto
= $creator;
1397 $eventdata->notification
= 1;
1398 $eventdata->subject
= $creatorsubject;
1399 $eventdata->fullmessage
= format_text_email($creatormessage, FORMAT_HTML
);
1400 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1401 $eventdata->fullmessagehtml
= $creatormessage;
1402 $eventdata->smallmessage
= $creatorsubject;
1404 message_send($eventdata);
1409 * Attempt to authenticate with the site backpack credentials and return an error
1410 * if the authentication fails. If external backpacks are not enabled, this will
1411 * not perform any test.
1415 function badges_verify_site_backpack() {
1416 $defaultbackpack = badges_get_site_primary_backpack();
1417 return badges_verify_backpack($defaultbackpack->id
);
1421 * Attempt to authenticate with a backpack credentials and return an error
1422 * if the authentication fails.
1423 * If external backpacks are not enabled or the backpack version is different
1424 * from OBv2, this will not perform any test.
1426 * @param int $backpackid Backpack identifier to verify.
1427 * @return string The result of the verification process.
1429 function badges_verify_backpack(int $backpackid) {
1430 global $OUTPUT, $CFG;
1432 if (empty($CFG->badges_allowexternalbackpack
)) {
1436 $backpack = badges_get_site_backpack($backpackid);
1437 if (empty($backpack->apiversion
) ||
($backpack->apiversion
== OPEN_BADGES_V2
)) {
1438 $backpackapi = new \core_badges\backpack_api
($backpack);
1440 // Clear any cached access tokens in the session.
1441 $backpackapi->clear_system_user_session();
1443 // Now attempt a login with these credentials.
1444 $result = $backpackapi->authenticate();
1445 if (empty($result) ||
!empty($result->error
)) {
1446 $warning = $backpackapi->get_authentication_error();
1448 $params = ['id' => $backpack->id
, 'action' => 'edit'];
1449 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1451 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1452 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1453 return $OUTPUT->container($icon . $message, 'text-danger');
1461 * Generate a public badgr URL that conforms to OBv2. This is done because badgr responses do not currently conform to
1464 * WARNING: This is an extremely hacky way of implementing this and should be removed once the standards are conformed to.
1466 * @param stdClass $backpack The Badgr backpack we are pushing to
1467 * @param string $type The type of object we are dealing with either Issuer, Assertion OR Badge.
1468 * @param string $externalid The externalid as provided by the backpack
1469 * @return string The public URL to access Badgr objects
1471 function badges_generate_badgr_open_url($backpack, $type, $externalid) {
1472 if (badges_open_badges_backpack_api($backpack->id
) == OPEN_BADGES_V2
) {
1473 $entity = strtolower($type);
1474 if ($type == OPEN_BADGES_V2_TYPE_BADGE
) {
1477 $url = new moodle_url($backpack->backpackapiurl
);
1478 return "{$url->get_scheme()}://{$url->get_host()}/public/{$entity}s/$externalid";