2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Contains classes, functions and constants used in badges.
22 * @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @author Yuliya Bozhko <yuliya.bozhko@totaralms.com>
27 defined('MOODLE_INTERNAL') ||
die();
29 /* Include required award criteria library. */
30 require_once($CFG->dirroot
. '/badges/criteria/award_criteria.php');
33 * Number of records per page.
35 define('BADGE_PERPAGE', 50);
38 * Badge award criteria aggregation method.
40 define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
43 * Badge award criteria aggregation method.
45 define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
48 * Inactive badge means that this badge cannot be earned and has not been awarded
49 * yet. Its award criteria can be changed.
51 define('BADGE_STATUS_INACTIVE', 0);
54 * Active badge means that this badge can we earned, but it has not been awarded
55 * yet. Can be deactivated for the purpose of changing its criteria.
57 define('BADGE_STATUS_ACTIVE', 1);
60 * Inactive badge can no longer be earned, but it has been awarded in the past and
61 * therefore its criteria cannot be changed.
63 define('BADGE_STATUS_INACTIVE_LOCKED', 2);
66 * Active badge means that it can be earned and has already been awarded to users.
67 * Its criteria cannot be changed any more.
69 define('BADGE_STATUS_ACTIVE_LOCKED', 3);
72 * Archived badge is considered deleted and can no longer be earned and is not
73 * displayed in the list of all badges.
75 define('BADGE_STATUS_ARCHIVED', 4);
78 * Badge type for site badges.
80 define('BADGE_TYPE_SITE', 1);
83 * Badge type for course badges.
85 define('BADGE_TYPE_COURSE', 2);
88 * Badge messaging schedule options.
90 define('BADGE_MESSAGE_NEVER', 0);
91 define('BADGE_MESSAGE_ALWAYS', 1);
92 define('BADGE_MESSAGE_DAILY', 2);
93 define('BADGE_MESSAGE_WEEKLY', 3);
94 define('BADGE_MESSAGE_MONTHLY', 4);
97 * URL of backpack. Custom ones can be added.
99 define('BADGE_BACKPACKAPIURL', 'https://backpack.openbadges.org');
100 define('BADGE_BACKPACKWEBURL', 'https://backpack.openbadges.org');
101 define('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
102 define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
105 * @deprecated since 3.7. Use the urls in the badge_external_backpack table instead.
107 define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
110 * Open Badges specifications.
112 define('OPEN_BADGES_V1', 1);
113 define('OPEN_BADGES_V2', 2);
116 * Only use for Open Badges 2.0 specification
118 define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
119 define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
120 define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
121 define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
122 define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
123 define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
125 // Global badge class has been moved to the component namespace.
126 class_alias('\core_badges\badge', 'badge');
129 * Sends notifications to users about awarded badges.
131 * @param badge $badge Badge that was issued
132 * @param int $userid Recipient ID
133 * @param string $issued Unique hash of an issued badge
134 * @param string $filepathhash File path hash of an issued badge for attachments
136 function badges_notify_badge_award(badge
$badge, $userid, $issued, $filepathhash) {
139 $admin = get_admin();
140 $userfrom = new stdClass();
141 $userfrom->id
= $admin->id
;
142 $userfrom->email
= !empty($CFG->badges_defaultissuercontact
) ?
$CFG->badges_defaultissuercontact
: $admin->email
;
143 foreach (get_all_user_name_fields() as $addname) {
144 $userfrom->$addname = !empty($CFG->badges_defaultissuername
) ?
'' : $admin->$addname;
146 $userfrom->firstname
= !empty($CFG->badges_defaultissuername
) ?
$CFG->badges_defaultissuername
: $admin->firstname
;
147 $userfrom->maildisplay
= true;
149 $issuedlink = html_writer
::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name
);
150 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
152 $params = new stdClass();
153 $params->badgename
= $badge->name
;
154 $params->username
= fullname($userto);
155 $params->badgelink
= $issuedlink;
156 $message = badge_message_from_template($badge->message
, $params);
157 $plaintext = html_to_text($message);
160 $eventdata = new \core\message\
message();
161 $eventdata->courseid
= is_null($badge->courseid
) ? SITEID
: $badge->courseid
; // Profile/site come with no courseid.
162 $eventdata->component
= 'moodle';
163 $eventdata->name
= 'badgerecipientnotice';
164 $eventdata->userfrom
= $userfrom;
165 $eventdata->userto
= $userto;
166 $eventdata->notification
= 1;
167 $eventdata->subject
= $badge->messagesubject
;
168 $eventdata->fullmessage
= $plaintext;
169 $eventdata->fullmessageformat
= FORMAT_HTML
;
170 $eventdata->fullmessagehtml
= $message;
171 $eventdata->smallmessage
= '';
172 $eventdata->customdata
= [
173 'notificationiconurl' => moodle_url
::make_pluginfile_url(
174 $badge->get_context()->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1')->out(),
178 // Attach badge image if possible.
179 if (!empty($CFG->allowattachments
) && $badge->attachment
&& is_string($filepathhash)) {
180 $fs = get_file_storage();
181 $file = $fs->get_file_by_hash($filepathhash);
182 $eventdata->attachment
= $file;
183 $eventdata->attachname
= str_replace(' ', '_', $badge->name
) . ".png";
185 message_send($eventdata);
187 message_send($eventdata);
190 // Notify badge creator about the award if they receive notifications every time.
191 if ($badge->notification
== 1) {
192 $userfrom = core_user
::get_noreply_user();
193 $userfrom->maildisplay
= true;
195 $creator = $DB->get_record('user', array('id' => $badge->usercreated
), '*', MUST_EXIST
);
197 $a->user
= fullname($userto);
198 $a->link
= $issuedlink;
199 $creatormessage = get_string('creatorbody', 'badges', $a);
200 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
202 $eventdata = new \core\message\
message();
203 $eventdata->courseid
= $badge->courseid
;
204 $eventdata->component
= 'moodle';
205 $eventdata->name
= 'badgecreatornotice';
206 $eventdata->userfrom
= $userfrom;
207 $eventdata->userto
= $creator;
208 $eventdata->notification
= 1;
209 $eventdata->subject
= $creatorsubject;
210 $eventdata->fullmessage
= html_to_text($creatormessage);
211 $eventdata->fullmessageformat
= FORMAT_HTML
;
212 $eventdata->fullmessagehtml
= $creatormessage;
213 $eventdata->smallmessage
= '';
214 $eventdata->customdata
= [
215 'notificationiconurl' => moodle_url
::make_pluginfile_url(
216 $badge->get_context()->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f1')->out(),
220 message_send($eventdata);
221 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id
, 'userid' => $userid));
226 * Caclulates date for the next message digest to badge creators.
228 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
229 * @return int Timestamp for next cron
231 function badges_calculate_message_schedule($schedule) {
235 case BADGE_MESSAGE_DAILY
:
236 $nextcron = time() +
60 * 60 * 24;
238 case BADGE_MESSAGE_WEEKLY
:
239 $nextcron = time() +
60 * 60 * 24 * 7;
241 case BADGE_MESSAGE_MONTHLY
:
242 $nextcron = time() +
60 * 60 * 24 * 7 * 30;
250 * Replaces variables in a message template and returns text ready to be emailed to a user.
252 * @param string $message Message body.
253 * @return string Message with replaced values
255 function badge_message_from_template($message, $params) {
257 foreach ($params as $key => $value) {
258 $msg = str_replace("%$key%", $value, $msg);
267 * @param int Type of badges to return
268 * @param int Course ID for course badges
269 * @param string $sort An SQL field to sort by
270 * @param string $dir The sort direction ASC|DESC
271 * @param int $page The page or records to return
272 * @param int $perpage The number of records to return per page
273 * @param int $user User specific search
274 * @return array $badge Array of records matching criteria
276 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE
, $user = 0) {
280 $where = "b.status != :deleted AND b.type = :type ";
281 $params['deleted'] = BADGE_STATUS_ARCHIVED
;
283 $userfields = array('b.id, b.name, b.status');
286 $userfields[] = 'bi.dateissued';
287 $userfields[] = 'bi.uniquehash';
288 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
289 $params['userid'] = $user;
290 $where .= " AND (b.status = 1 OR b.status = 3) ";
292 $fields = implode(', ', $userfields);
294 if ($courseid != 0 ) {
295 $where .= "AND b.courseid = :courseid ";
296 $params['courseid'] = $courseid;
299 $sorting = (($sort != '' && $dir != '') ?
'ORDER BY ' . $sort . ' ' . $dir : '');
300 $params['type'] = $type;
302 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
303 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
306 foreach ($records as $r) {
307 $badge = new badge($r->id
);
308 $badges[$r->id
] = $badge;
310 $badges[$r->id
]->dateissued
= $r->dateissued
;
311 $badges[$r->id
]->uniquehash
= $r->uniquehash
;
313 $badges[$r->id
]->awards
= $DB->count_records_sql('SELECT COUNT(b.userid)
314 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
315 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id
));
316 $badges[$r->id
]->statstring
= $badge->get_status_name();
323 * Get badges for a specific user.
325 * @param int $userid User ID
326 * @param int $courseid Badges earned by a user in a specific course
327 * @param int $page The page or records to return
328 * @param int $perpage The number of records to return per page
329 * @param string $search A simple string to search for
330 * @param bool $onlypublic Return only public badges
331 * @return array of badges ordered by decreasing date of issue
333 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
351 WHERE b.id = bi.badgeid
353 AND bi.userid = :userid';
355 if (!empty($search)) {
356 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
357 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
360 $sql .= ' AND (bi.visible = 1) ';
363 if (empty($CFG->badges_allowcoursebadges
)) {
364 $sql .= ' AND b.courseid IS NULL';
365 } else if ($courseid != 0) {
366 $sql .= ' AND (b.courseid = :courseid) ';
367 $params['courseid'] = $courseid;
369 $sql .= ' ORDER BY bi.dateissued DESC';
370 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
376 * Extends the course administration navigation with the Badges page
378 * @param navigation_node $coursenode
379 * @param object $course
381 function badges_add_course_navigation(navigation_node
$coursenode, stdClass
$course) {
384 $coursecontext = context_course
::instance($course->id
);
385 $isfrontpage = (!$coursecontext ||
$course->id
== $SITE->id
);
386 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
387 'moodle/badges:createbadge',
388 'moodle/badges:awardbadge',
389 'moodle/badges:configurecriteria',
390 'moodle/badges:configuremessages',
391 'moodle/badges:configuredetails',
392 'moodle/badges:deletebadge'), $coursecontext);
394 if (!empty($CFG->enablebadges
) && !empty($CFG->badges_allowcoursebadges
) && !$isfrontpage && $canmanage) {
395 $coursenode->add(get_string('coursebadges', 'badges'), null,
396 navigation_node
::TYPE_CONTAINER
, null, 'coursebadges',
397 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
399 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
401 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
402 navigation_node
::TYPE_SETTING
, null, 'coursebadges');
404 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
405 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE
, 'id' => $course->id
));
407 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
408 navigation_node
::TYPE_SETTING
, null, 'newbadge');
414 * Triggered when badge is manually awarded.
416 * @param object $data
419 function badges_award_handle_manual_criteria_review(stdClass
$data) {
420 $criteria = $data->crit
;
421 $userid = $data->userid
;
422 $badge = new badge($criteria->badgeid
);
424 if (!$badge->is_active() ||
$badge->is_issued($userid)) {
428 if ($criteria->review($userid)) {
429 $criteria->mark_complete($userid);
431 if ($badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->review($userid)) {
432 $badge->criteria
[BADGE_CRITERIA_TYPE_OVERALL
]->mark_complete($userid);
433 $badge->issue($userid);
441 * Process badge image from form data
443 * @param badge $badge Badge object
444 * @param string $iconfile Original file
446 function badges_process_badge_image(badge
$badge, $iconfile) {
448 require_once($CFG->libdir
. '/gdlib.php');
450 if (!empty($CFG->gdversion
)) {
451 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id
, $iconfile, true);
454 // Clean up file draft area after badge image has been saved.
455 $context = context_user
::instance($USER->id
, MUST_EXIST
);
456 $fs = get_file_storage();
457 $fs->delete_area_files($context->id
, 'user', 'draft');
464 * @param badge $badge Badge object
465 * @param stdClass $context
466 * @param string $size
468 function print_badge_image(badge
$badge, stdClass
$context, $size = 'small') {
469 $fsize = ($size == 'small') ?
'f2' : 'f1';
471 $imageurl = moodle_url
::make_pluginfile_url($context->id
, 'badges', 'badgeimage', $badge->id
, '/', $fsize, false);
472 // Appending a random parameter to image link to forse browser reload the image.
473 $imageurl->param('refresh', rand(1, 10000));
474 $attributes = array('src' => $imageurl, 'alt' => s($badge->name
), 'class' => 'activatebadge');
476 return html_writer
::empty_tag('img', $attributes);
482 * @param string $hash Unique hash of an issued badge.
483 * @param int $badgeid ID of the original badge.
484 * @param int $userid ID of badge recipient (optional).
485 * @param boolean $pathhash Return file pathhash instead of image url (optional).
486 * @return string|url Returns either new file path hash or new file URL
488 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
490 require_once(__DIR__
. '/../badges/lib/bakerlib.php');
492 $badge = new badge($badgeid);
493 $badge_context = $badge->get_context();
494 $userid = ($userid) ?
$userid : $USER->id
;
495 $user_context = context_user
::instance($userid);
497 $fs = get_file_storage();
498 if (!$fs->file_exists($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png')) {
499 if ($file = $fs->get_file($badge_context->id
, 'badges', 'badgeimage', $badge->id
, '/', 'f3.png')) {
500 $contents = $file->get_content();
502 $filehandler = new PNG_MetaDataHandler($contents);
503 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
504 if ($filehandler->check_chunks("tEXt", "openbadges")) {
505 // Add assertion URL tExt chunk.
506 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
508 'contextid' => $user_context->id
,
509 'component' => 'badges',
510 'filearea' => 'userbadge',
511 'itemid' => $badge->id
,
513 'filename' => $hash . '.png',
516 // Create a file with added contents.
517 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
519 return $newfile->get_pathnamehash();
523 debugging('Error baking badge image!', DEBUG_DEVELOPER
);
528 // If file exists and we just need its path hash, return it.
530 $file = $fs->get_file($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash . '.png');
531 return $file->get_pathnamehash();
534 $fileurl = moodle_url
::make_pluginfile_url($user_context->id
, 'badges', 'userbadge', $badge->id
, '/', $hash, true);
539 * Returns external backpack settings and badges from this backpack.
541 * This function first checks if badges for the user are cached and
542 * tries to retrieve them from the cache. Otherwise, badges are obtained
543 * through curl request to the backpack.
545 * @param int $userid Backpack user ID.
546 * @param boolean $refresh Refresh badges collection in cache.
547 * @return null|object Returns null is there is no backpack or object with backpack settings.
549 function get_backpack_settings($userid, $refresh = false) {
552 // Try to get badges from cache first.
553 $badgescache = cache
::make('core', 'externalbadges');
554 $out = $badgescache->get($userid);
555 if ($out !== false && !$refresh) {
558 // Get badges through curl request to the backpack.
559 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
561 $sitebackpack = badges_get_site_backpack($record->externalbackpackid
);
562 $backpack = new \core_badges\backpack_api
($sitebackpack, $record);
563 $out = new stdClass();
564 $out->backpackid
= $sitebackpack->id
;
566 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id
))) {
567 $out->totalcollections
= count($collections);
568 $out->totalbadges
= 0;
569 $out->badges
= array();
570 foreach ($collections as $collection) {
571 $badges = $backpack->get_badges($collection, true);
572 if (!empty($badges)) {
573 $out->badges
= array_merge($out->badges
, $badges);
574 $out->totalbadges +
= count($badges);
576 $out->badges
= array_merge($out->badges
, array());
580 $out->totalbadges
= 0;
581 $out->totalcollections
= 0;
584 $badgescache->set($userid, $out);
592 * Download all user badges in zip archive.
594 * @param int $userid ID of badge owner.
596 function badges_download($userid) {
598 $context = context_user
::instance($userid);
599 $records = $DB->get_records('badge_issued', array('userid' => $userid));
601 // Get list of files to download.
602 $fs = get_file_storage();
604 foreach ($records as $issued) {
605 $badge = new badge($issued->badgeid
);
606 // Need to make image name user-readable and unique using filename safe characters.
607 $name = $badge->name
. ' ' . userdate($issued->dateissued
, '%d %b %Y') . ' ' . hash('crc32', $badge->id
);
608 $name = str_replace(' ', '_', $name);
609 $name = clean_param($name, PARAM_FILE
);
610 if ($file = $fs->get_file($context->id
, 'badges', 'userbadge', $issued->badgeid
, '/', $issued->uniquehash
. '.png')) {
611 $filelist[$name . '.png'] = $file;
615 // Zip files and sent them to a user.
616 $tempzip = tempnam($CFG->tempdir
.'/', 'mybadges');
617 $zipper = new zip_packer();
618 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
619 send_temp_file($tempzip, 'badges.zip');
621 debugging("Problems with archiving the files.", DEBUG_DEVELOPER
);
627 * Checks if badges can be pushed to external backpack.
629 * @return string Code of backpack accessibility status.
631 function badges_check_backpack_accessibility() {
632 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING
) {
633 // For behat sites, do not poll the remote badge site.
634 // Behat sites should not be available, but we should pretend as though they are.
638 if (badges_open_badges_backpack_api() == OPEN_BADGES_V2
) {
643 include_once $CFG->libdir
. '/filelib.php';
645 // Using fake assertion url to check whether backpack can access the web site.
646 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
648 // Curl request to backpack baker.
651 'FRESH_CONNECT' => true,
652 'RETURNTRANSFER' => true,
654 'CONNECTTIMEOUT' => 2,
656 // BADGE_BACKPACKURL and the "baker" API is deprecated and should never be used in future.
657 $location = BADGE_BACKPACKURL
. '/baker';
658 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
660 $data = json_decode($out);
661 if (!empty($curl->error
)) {
662 return 'curl-request-timeout';
664 if (isset($data->code
) && $data->code
== 'http-unreachable') {
665 return 'http-unreachable';
675 * Checks if user has external backpack connected.
677 * @param int $userid ID of a user.
678 * @return bool True|False whether backpack connection exists.
680 function badges_user_has_backpack($userid) {
682 return $DB->record_exists('badge_backpack', array('userid' => $userid));
686 * Handles what happens to the course badges when a course is deleted.
688 * @param int $courseid course ID.
691 function badges_handle_course_deletion($courseid) {
693 include_once $CFG->libdir
. '/filelib.php';
695 $systemcontext = context_system
::instance();
696 $coursecontext = context_course
::instance($courseid);
697 $fs = get_file_storage();
699 // Move badges images to the system context.
700 $fs->move_area_files_to_new_context($coursecontext->id
, $systemcontext->id
, 'badges', 'badgeimage');
702 // Get all course badges.
703 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE
, 'courseid' => $courseid));
704 foreach ($badges as $badge) {
705 // Archive badges in this course.
706 $toupdate = new stdClass();
707 $toupdate->id
= $badge->id
;
708 $toupdate->type
= BADGE_TYPE_SITE
;
709 $toupdate->courseid
= null;
710 $toupdate->status
= BADGE_STATUS_ARCHIVED
;
711 $DB->update_record('badge', $toupdate);
716 * Loads JS files required for backpack support.
721 function badges_setup_backpack_js() {
723 if (!empty($CFG->badges_allowexternalbackpack
)) {
724 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1
) {
725 $PAGE->requires
->string_for_js('error:backpackproblem', 'badges');
726 // The issuer.js API is deprecated and should not be used in future.
727 $PAGE->requires
->js(new moodle_url(BADGE_BACKPACKURL
. '/issuer.js'), true);
728 // The backpack.js file is deprecated and should not be used in future.
729 $PAGE->requires
->js('/badges/backpack.js', true);
735 * No js files are required for backpack support.
736 * This only exists to directly support the custom V1 backpack api.
738 * @param boolean $checksite Call check site function.
741 function badges_local_backpack_js($checksite = false) {
743 if (!empty($CFG->badges_allowexternalbackpack
)) {
744 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1
) {
745 $PAGE->requires
->js('/badges/backpack.js', true);
747 $PAGE->requires
->js_init_call('check_site_access', null, false);
754 * Create the backpack with this data.
756 * @param stdClass $data The new backpack data.
759 function badges_create_site_backpack($data) {
761 $context = context_system
::instance();
762 require_capability('moodle/badges:manageglobalsettings', $context);
764 $count = $DB->count_records('badge_external_backpack');
766 $backpack = new stdClass();
767 $backpack->apiversion
= $data->apiversion
;
768 $backpack->backpackapiurl
= $data->backpackapiurl
;
769 $backpack->backpackweburl
= $data->backpackweburl
;
770 $backpack->sortorder
= $count;
771 $DB->insert_record('badge_external_backpack', $backpack);
776 * Update the backpack with this id.
778 * @param integer $id The backpack to edit
779 * @param stdClass $data The new backpack data.
782 function badges_update_site_backpack($id, $data) {
784 $context = context_system
::instance();
785 require_capability('moodle/badges:manageglobalsettings', $context);
787 if ($backpack = badges_get_site_backpack($id)) {
788 $backpack = new stdClass();
790 $backpack->apiversion
= $data->apiversion
;
791 $backpack->backpackweburl
= $data->backpackweburl
;
792 $backpack->backpackapiurl
= $data->backpackapiurl
;
793 $backpack->password
= $data->password
;
794 $DB->update_record('badge_external_backpack', $backpack);
801 * Is any backpack enabled that supports open badges V1?
804 function badges_open_badges_backpack_api() {
807 $backpack = badges_get_site_backpack($CFG->badges_site_backpack
);
809 if (empty($backpack->apiversion
)) {
810 return OPEN_BADGES_V2
;
812 return $backpack->apiversion
;
816 * Get a site backpacks by id or url.
818 * @param int $id The backpack id.
819 * @return array(stdClass)
821 function badges_get_site_backpack($id) {
824 return $DB->get_record('badge_external_backpack', ['id' => $id]);
828 * List the backpacks at site level.
830 * @return array(stdClass)
832 function badges_get_site_backpacks() {
835 $all = $DB->get_records('badge_external_backpack');
837 foreach ($all as $key => $bp) {
838 if ($bp->id
== $CFG->badges_site_backpack
) {
839 $all[$key]->sitebackpack
= true;
841 $all[$key]->sitebackpack
= false;
848 * List the supported badges api versions.
850 * @return array(version)
852 function badges_get_badge_api_versions() {
854 OPEN_BADGES_V1
=> get_string('openbadgesv1', 'badges'),
855 OPEN_BADGES_V2
=> get_string('openbadgesv2', 'badges')
860 * Called on install or upgrade to create default list of backpacks a user can connect to.
864 function badges_install_default_backpacks() {
867 $record = new stdClass();
868 $record->backpackweburl
= BADGE_BACKPACKWEBURL
;
869 $record->backpackapiurl
= BADGE_BACKPACKAPIURL
;
870 $record->apiversion
= OPEN_BADGES_V1
;
871 $record->sortorder
= 0;
872 $record->password
= '';
875 if (!($bp = $DB->get_record('badge_external_backpack', array('backpackapiurl' => $record->backpackapiurl
)))) {
876 $bpid = $DB->insert_record('badge_external_backpack', $record);
880 set_config('badges_site_backpack', $bpid);
882 // All existing backpacks default to V1.
883 $DB->set_field('badge_backpack', 'externalbackpackid', $bpid);
885 $record = new stdClass();
886 $record->backpackapiurl
= BADGRIO_BACKPACKAPIURL
;
887 $record->backpackweburl
= BADGRIO_BACKPACKWEBURL
;
888 $record->apiversion
= OPEN_BADGES_V2
;
889 $record->sortorder
= 1;
890 $record->password
= '';
892 if (!$DB->record_exists('badge_external_backpack', array('backpackapiurl' => $record->backpackapiurl
))) {
893 $DB->insert_record('badge_external_backpack', $record);
899 * Get the default issuer for a badge from this site.
903 function badges_get_default_issuer() {
907 $issuerurl = new moodle_url('/badges/issuer.php');
908 $issuer['name'] = $CFG->badges_defaultissuername
;
909 if (empty($issuer['name'])) {
910 $issuer['name'] = $SITE->fullname ?
$SITE->fullname
: $SITE->shortname
;
912 $issuer['url'] = $issuerurl->out(false);
913 $issuer['email'] = $CFG->badges_defaultissuercontact
;
914 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT
;
915 $issuer['id'] = $issuerurl->out(false);
916 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER
;
921 * Disconnect from the user backpack by deleting the user preferences.
923 * @param integer $userid The user to diconnect.
926 function badges_disconnect_user_backpack($userid) {
929 // We can only change backpack settings for our own real backpack.
930 if ($USER->id
!= $userid ||
931 \core\session\manager
::is_loggedinas()) {
936 unset_user_preference('badges_email_verify_secret');
937 unset_user_preference('badges_email_verify_address');
938 unset_user_preference('badges_email_verify_backpackid');
939 unset_user_preference('badges_email_verify_password');
945 * Used to remember which objects we connected with a backpack before.
947 * @param integer $sitebackpackid The site backpack to connect to.
948 * @param string $type The type of this remote object.
949 * @param string $internalid The id for this object on the Moodle site.
950 * @return mixed The id or false if it doesn't exist.
952 function badges_external_get_mapping($sitebackpackid, $type, $internalid) {
954 // Return externalid if it exists.
956 'sitebackpackid' => $sitebackpackid,
958 'internalid' => $internalid
961 $record = $DB->get_record('badge_external_identifier', $params, 'externalid', IGNORE_MISSING
);
963 return $record->externalid
;
969 * Save the info about which objects we connected with a backpack before.
971 * @param integer $sitebackpackid The site backpack to connect to.
972 * @param string $type The type of this remote object.
973 * @param string $internalid The id for this object on the Moodle site.
974 * @param string $externalid The id of this object on the remote site.
977 function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
981 'sitebackpackid' => $sitebackpackid,
983 'internalid' => $internalid,
984 'externalid' => $externalid
987 return $DB->insert_record('badge_external_identifier', $params);
991 * Delete all external mapping information for a backpack.
993 * @param integer $sitebackpackid The site backpack to connect to.
996 function badges_external_delete_mappings($sitebackpackid) {
999 $params = ['sitebackpackid' => $sitebackpackid];
1001 return $DB->delete_records('badge_external_identifier', $params);
1005 * Delete a specific external mapping information for a backpack.
1007 * @param integer $sitebackpackid The site backpack to connect to.
1008 * @param string $type The type of this remote object.
1009 * @param string $internalid The id for this object on the Moodle site.
1012 function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
1016 'sitebackpackid' => $sitebackpackid,
1018 'internalid' => $internalid
1021 $DB->delete_record('badge_external_identifier', $params);
1025 * Create and send a verification email to the email address supplied.
1027 * Since we're not sending this email to a user, email_to_user can't be used
1028 * but this function borrows largely the code from that process.
1030 * @param string $email the email address to send the verification email to.
1031 * @param int $backpackid the id of the backpack to connect to
1032 * @param string $backpackpassword the user entered password to connect to this backpack
1033 * @return true if the email was sent successfully, false otherwise.
1035 function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1038 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1039 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1040 // of verification emails to said address.
1041 $secret = random_string(15);
1042 set_user_preference('badges_email_verify_secret', $secret);
1043 set_user_preference('badges_email_verify_address', $email);
1044 set_user_preference('badges_email_verify_backpackid', $backpackid);
1045 set_user_preference('badges_email_verify_password', $backpackpassword);
1048 $tempuser = $DB->get_record('user', array('id' => $USER->id
), '*', MUST_EXIST
);
1049 $tempuser->email
= $email;
1050 $noreplyuser = core_user
::get_noreply_user();
1052 // Generate the verification email body.
1053 $verificationurl = '/badges/backpackemailverify.php';
1054 $verificationurl = new moodle_url($verificationurl);
1055 $verificationpath = $verificationurl->out(false);
1058 $args = new stdClass();
1059 $args->link
= $verificationpath . '?data='. $secret;
1060 $args->sitename
= $site->fullname
;
1061 $args->admin
= generate_email_signoff();
1063 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname
);
1064 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1065 $messagehtml = text_to_html($messagetext, false, false, true);
1067 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1071 * Return all the enabled criteria types for this site.
1073 * @param boolean $enabled
1076 function badges_list_criteria($enabled = true) {
1080 BADGE_CRITERIA_TYPE_OVERALL
=> 'overall',
1081 BADGE_CRITERIA_TYPE_ACTIVITY
=> 'activity',
1082 BADGE_CRITERIA_TYPE_MANUAL
=> 'manual',
1083 BADGE_CRITERIA_TYPE_SOCIAL
=> 'social',
1084 BADGE_CRITERIA_TYPE_COURSE
=> 'course',
1085 BADGE_CRITERIA_TYPE_COURSESET
=> 'courseset',
1086 BADGE_CRITERIA_TYPE_PROFILE
=> 'profile',
1087 BADGE_CRITERIA_TYPE_BADGE
=> 'badge',
1088 BADGE_CRITERIA_TYPE_COHORT
=> 'cohort',
1089 BADGE_CRITERIA_TYPE_COMPETENCY
=> 'competency',
1092 foreach ($types as $key => $type) {
1093 $class = 'award_criteria_' . $type;
1094 $file = $CFG->dirroot
. '/badges/criteria/' . $class . '.php';
1095 if (file_exists($file)) {
1096 require_once($file);
1098 if (!$class::is_enabled()) {
1099 unset($types[$key]);
1108 * Check if any badge has records for competencies.
1110 * @param array $competencyids Array of competencies ids.
1111 * @return boolean Return true if competencies were found in any badge.
1113 function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1116 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED
);
1118 $sql = "SELECT DISTINCT bc.badgeid
1119 FROM {badge_criteria} bc
1120 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1121 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1122 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY
;
1124 return $DB->record_exists_sql($sql, $params);
1128 * Creates single message for all notification and sends it out
1130 * @param object $badge A badge which is notified about.
1132 function badge_assemble_notification(stdClass
$badge) {
1135 $userfrom = core_user
::get_noreply_user();
1136 $userfrom->maildisplay
= true;
1138 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id
))) {
1139 // Get badge creator.
1140 $creator = $DB->get_record('user', array('id' => $badge->creator
), '*', MUST_EXIST
);
1141 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name
);
1142 $creatormessage = '';
1144 // Put all messages in one digest.
1145 foreach ($msgs as $msg) {
1146 $issuedlink = html_writer
::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash
)), $badge->name
);
1147 $recipient = $DB->get_record('user', array('id' => $msg->userid
), '*', MUST_EXIST
);
1149 $a = new stdClass();
1150 $a->user
= fullname($recipient);
1151 $a->link
= $issuedlink;
1152 $creatormessage .= get_string('creatorbody', 'badges', $a);
1153 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid
, 'userid' => $msg->userid
));
1156 // Create a message object.
1157 $eventdata = new \core\message\
message();
1158 $eventdata->courseid
= SITEID
;
1159 $eventdata->component
= 'moodle';
1160 $eventdata->name
= 'badgecreatornotice';
1161 $eventdata->userfrom
= $userfrom;
1162 $eventdata->userto
= $creator;
1163 $eventdata->notification
= 1;
1164 $eventdata->subject
= $creatorsubject;
1165 $eventdata->fullmessage
= format_text_email($creatormessage, FORMAT_HTML
);
1166 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1167 $eventdata->fullmessagehtml
= $creatormessage;
1168 $eventdata->smallmessage
= $creatorsubject;
1170 message_send($eventdata);
1175 * Attempt to authenticate with the site backpack credentials and return an error
1176 * if the authentication fails. If external backpacks are not enabled, this will
1177 * not perform any test.
1181 function badges_verify_site_backpack() {
1182 global $OUTPUT, $CFG;
1184 if (empty($CFG->badges_allowexternalbackpack
)) {
1188 $backpack = badges_get_site_backpack($CFG->badges_site_backpack
);
1190 if (empty($backpack->apiversion
) ||
($backpack->apiversion
== OPEN_BADGES_V2
)) {
1191 $backpackapi = new \core_badges\backpack_api
($backpack);
1193 // Clear any cached access tokens in the session.
1194 $backpackapi->clear_system_user_session();
1196 // Now attempt a login with these credentials.
1197 $result = $backpackapi->authenticate();
1198 if (empty($result) ||
!empty($result->error
)) {
1199 $warning = $backpackapi->get_authentication_error();
1201 $params = ['id' => $backpack->id
, 'action' => 'edit'];
1202 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1204 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1205 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1206 return $OUTPUT->container($icon . $message, 'text-error');