Merge branch 'MDL-45849-selfenrol' of https://github.com/Peterburnett/moodle
[moodle.git] / lib / badgeslib.php
blob352a086f0c5a03335a3dcecc59323f871954d959
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Contains classes, functions and constants used in badges.
20 * @package core
21 * @subpackage badges
22 * @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @author Yuliya Bozhko <yuliya.bozhko@totaralms.com>
27 defined('MOODLE_INTERNAL') || die();
29 /* Include required award criteria library. */
30 require_once($CFG->dirroot . '/badges/criteria/award_criteria.php');
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('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
100 define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
103 * @deprecated since 3.7. Use the urls in the badge_external_backpack table instead.
105 define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
108 * @deprecated since 3.9 (MDL-66357).
110 define('BADGE_BACKPACKAPIURL', 'https://backpack.openbadges.org');
111 define('BADGE_BACKPACKWEBURL', 'https://backpack.openbadges.org');
114 * Open Badges specifications.
116 define('OPEN_BADGES_V1', 1);
117 define('OPEN_BADGES_V2', 2);
118 define('OPEN_BADGES_V2P1', 2.1);
121 * Only use for Open Badges 2.0 specification
123 define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
124 define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
125 define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
126 define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
127 define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
128 define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
130 // Global badge class has been moved to the component namespace.
131 class_alias('\core_badges\badge', 'badge');
134 * Sends notifications to users about awarded badges.
136 * @param badge $badge Badge that was issued
137 * @param int $userid Recipient ID
138 * @param string $issued Unique hash of an issued badge
139 * @param string $filepathhash File path hash of an issued badge for attachments
141 function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
142 global $CFG, $DB;
144 $admin = get_admin();
145 $userfrom = new stdClass();
146 $userfrom->id = $admin->id;
147 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
148 foreach (get_all_user_name_fields() as $addname) {
149 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
151 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
152 $userfrom->maildisplay = true;
154 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
155 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
157 $params = new stdClass();
158 $params->badgename = $badge->name;
159 $params->username = fullname($userto);
160 $params->badgelink = $issuedlink;
161 $message = badge_message_from_template($badge->message, $params);
162 $plaintext = html_to_text($message);
164 // Notify recipient.
165 $eventdata = new \core\message\message();
166 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
167 $eventdata->component = 'moodle';
168 $eventdata->name = 'badgerecipientnotice';
169 $eventdata->userfrom = $userfrom;
170 $eventdata->userto = $userto;
171 $eventdata->notification = 1;
172 $eventdata->subject = $badge->messagesubject;
173 $eventdata->fullmessage = $plaintext;
174 $eventdata->fullmessageformat = FORMAT_HTML;
175 $eventdata->fullmessagehtml = $message;
176 $eventdata->smallmessage = '';
177 $eventdata->customdata = [
178 'notificationiconurl' => moodle_url::make_pluginfile_url(
179 $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
180 'hash' => $issued,
183 // Attach badge image if possible.
184 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
185 $fs = get_file_storage();
186 $file = $fs->get_file_by_hash($filepathhash);
187 $eventdata->attachment = $file;
188 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
190 message_send($eventdata);
191 } else {
192 message_send($eventdata);
195 // Notify badge creator about the award if they receive notifications every time.
196 if ($badge->notification == 1) {
197 $userfrom = core_user::get_noreply_user();
198 $userfrom->maildisplay = true;
200 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
201 $a = new stdClass();
202 $a->user = fullname($userto);
203 $a->link = $issuedlink;
204 $creatormessage = get_string('creatorbody', 'badges', $a);
205 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
207 $eventdata = new \core\message\message();
208 $eventdata->courseid = $badge->courseid;
209 $eventdata->component = 'moodle';
210 $eventdata->name = 'badgecreatornotice';
211 $eventdata->userfrom = $userfrom;
212 $eventdata->userto = $creator;
213 $eventdata->notification = 1;
214 $eventdata->subject = $creatorsubject;
215 $eventdata->fullmessage = html_to_text($creatormessage);
216 $eventdata->fullmessageformat = FORMAT_HTML;
217 $eventdata->fullmessagehtml = $creatormessage;
218 $eventdata->smallmessage = '';
219 $eventdata->customdata = [
220 'notificationiconurl' => moodle_url::make_pluginfile_url(
221 $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
222 'hash' => $issued,
225 message_send($eventdata);
226 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
231 * Caclulates date for the next message digest to badge creators.
233 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
234 * @return int Timestamp for next cron
236 function badges_calculate_message_schedule($schedule) {
237 $nextcron = 0;
239 switch ($schedule) {
240 case BADGE_MESSAGE_DAILY:
241 $tomorrow = new DateTime("1 day", core_date::get_server_timezone_object());
242 $nextcron = $tomorrow->getTimestamp();
243 break;
244 case BADGE_MESSAGE_WEEKLY:
245 $nextweek = new DateTime("1 week", core_date::get_server_timezone_object());
246 $nextcron = $nextweek->getTimestamp();
247 break;
248 case BADGE_MESSAGE_MONTHLY:
249 $nextmonth = new DateTime("1 month", core_date::get_server_timezone_object());
250 $nextcron = $nextmonth->getTimestamp();
251 break;
254 return $nextcron;
258 * Replaces variables in a message template and returns text ready to be emailed to a user.
260 * @param string $message Message body.
261 * @return string Message with replaced values
263 function badge_message_from_template($message, $params) {
264 $msg = $message;
265 foreach ($params as $key => $value) {
266 $msg = str_replace("%$key%", $value, $msg);
269 return $msg;
273 * Get all badges.
275 * @param int Type of badges to return
276 * @param int Course ID for course badges
277 * @param string $sort An SQL field to sort by
278 * @param string $dir The sort direction ASC|DESC
279 * @param int $page The page or records to return
280 * @param int $perpage The number of records to return per page
281 * @param int $user User specific search
282 * @return array $badge Array of records matching criteria
284 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
285 global $DB;
286 $records = array();
287 $params = array();
288 $where = "b.status != :deleted AND b.type = :type ";
289 $params['deleted'] = BADGE_STATUS_ARCHIVED;
291 $userfields = array('b.id, b.name, b.status');
292 $usersql = "";
293 if ($user != 0) {
294 $userfields[] = 'bi.dateissued';
295 $userfields[] = 'bi.uniquehash';
296 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
297 $params['userid'] = $user;
298 $where .= " AND (b.status = 1 OR b.status = 3) ";
300 $fields = implode(', ', $userfields);
302 if ($courseid != 0 ) {
303 $where .= "AND b.courseid = :courseid ";
304 $params['courseid'] = $courseid;
307 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
308 $params['type'] = $type;
310 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
311 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
313 $badges = array();
314 foreach ($records as $r) {
315 $badge = new badge($r->id);
316 $badges[$r->id] = $badge;
317 if ($user != 0) {
318 $badges[$r->id]->dateissued = $r->dateissued;
319 $badges[$r->id]->uniquehash = $r->uniquehash;
320 } else {
321 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
322 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
323 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
324 $badges[$r->id]->statstring = $badge->get_status_name();
327 return $badges;
331 * Get badges for a specific user.
333 * @param int $userid User ID
334 * @param int $courseid Badges earned by a user in a specific course
335 * @param int $page The page or records to return
336 * @param int $perpage The number of records to return per page
337 * @param string $search A simple string to search for
338 * @param bool $onlypublic Return only public badges
339 * @return array of badges ordered by decreasing date of issue
341 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
342 global $CFG, $DB;
344 $params = array(
345 'userid' => $userid
347 $sql = 'SELECT
348 bi.uniquehash,
349 bi.dateissued,
350 bi.dateexpire,
351 bi.id as issuedid,
352 bi.visible,
353 u.email,
355 FROM
356 {badge} b,
357 {badge_issued} bi,
358 {user} u
359 WHERE b.id = bi.badgeid
360 AND u.id = bi.userid
361 AND bi.userid = :userid';
363 if (!empty($search)) {
364 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
365 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
367 if ($onlypublic) {
368 $sql .= ' AND (bi.visible = 1) ';
371 if (empty($CFG->badges_allowcoursebadges)) {
372 $sql .= ' AND b.courseid IS NULL';
373 } else if ($courseid != 0) {
374 $sql .= ' AND (b.courseid = :courseid) ';
375 $params['courseid'] = $courseid;
377 $sql .= ' ORDER BY bi.dateissued DESC';
378 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
380 return $badges;
384 * Extends the course administration navigation with the Badges page
386 * @param navigation_node $coursenode
387 * @param object $course
389 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
390 global $CFG, $SITE;
392 $coursecontext = context_course::instance($course->id);
393 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
394 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
395 'moodle/badges:createbadge',
396 'moodle/badges:awardbadge',
397 'moodle/badges:configurecriteria',
398 'moodle/badges:configuremessages',
399 'moodle/badges:configuredetails',
400 'moodle/badges:deletebadge'), $coursecontext);
402 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
403 $coursenode->add(get_string('coursebadges', 'badges'), null,
404 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
405 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
407 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
409 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
410 navigation_node::TYPE_SETTING, null, 'coursebadges');
412 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
413 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
415 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
416 navigation_node::TYPE_SETTING, null, 'newbadge');
422 * Triggered when badge is manually awarded.
424 * @param object $data
425 * @return boolean
427 function badges_award_handle_manual_criteria_review(stdClass $data) {
428 $criteria = $data->crit;
429 $userid = $data->userid;
430 $badge = new badge($criteria->badgeid);
432 if (!$badge->is_active() || $badge->is_issued($userid)) {
433 return true;
436 if ($criteria->review($userid)) {
437 $criteria->mark_complete($userid);
439 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
440 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
441 $badge->issue($userid);
445 return true;
449 * Process badge image from form data
451 * @param badge $badge Badge object
452 * @param string $iconfile Original file
454 function badges_process_badge_image(badge $badge, $iconfile) {
455 global $CFG, $USER;
456 require_once($CFG->libdir. '/gdlib.php');
458 if (!empty($CFG->gdversion)) {
459 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
460 @unlink($iconfile);
462 // Clean up file draft area after badge image has been saved.
463 $context = context_user::instance($USER->id, MUST_EXIST);
464 $fs = get_file_storage();
465 $fs->delete_area_files($context->id, 'user', 'draft');
470 * Print badge image.
472 * @param badge $badge Badge object
473 * @param stdClass $context
474 * @param string $size
476 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
477 $fsize = ($size == 'small') ? 'f2' : 'f1';
479 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
480 // Appending a random parameter to image link to forse browser reload the image.
481 $imageurl->param('refresh', rand(1, 10000));
482 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
484 return html_writer::empty_tag('img', $attributes);
488 * Bake issued badge.
490 * @param string $hash Unique hash of an issued badge.
491 * @param int $badgeid ID of the original badge.
492 * @param int $userid ID of badge recipient (optional).
493 * @param boolean $pathhash Return file pathhash instead of image url (optional).
494 * @return string|url Returns either new file path hash or new file URL
496 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
497 global $CFG, $USER;
498 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
500 $badge = new badge($badgeid);
501 $badge_context = $badge->get_context();
502 $userid = ($userid) ? $userid : $USER->id;
503 $user_context = context_user::instance($userid);
505 $fs = get_file_storage();
506 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
507 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
508 $contents = $file->get_content();
510 $filehandler = new PNG_MetaDataHandler($contents);
511 // For now, the site backpack OB version will be used as default.
512 $obversion = badges_open_badges_backpack_api();
513 $assertion = new core_badges_assertion($hash, $obversion);
514 $assertionjson = json_encode($assertion->get_badge_assertion());
515 if ($filehandler->check_chunks("iTXt", "openbadges")) {
516 // Add assertion URL iTXt chunk.
517 $newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
518 $fileinfo = array(
519 'contextid' => $user_context->id,
520 'component' => 'badges',
521 'filearea' => 'userbadge',
522 'itemid' => $badge->id,
523 'filepath' => '/',
524 'filename' => $hash . '.png',
527 // Create a file with added contents.
528 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
529 if ($pathhash) {
530 return $newfile->get_pathnamehash();
533 } else {
534 debugging('Error baking badge image!', DEBUG_DEVELOPER);
535 return;
539 // If file exists and we just need its path hash, return it.
540 if ($pathhash) {
541 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
542 return $file->get_pathnamehash();
545 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
546 return $fileurl;
550 * Returns external backpack settings and badges from this backpack.
552 * This function first checks if badges for the user are cached and
553 * tries to retrieve them from the cache. Otherwise, badges are obtained
554 * through curl request to the backpack.
556 * @param int $userid Backpack user ID.
557 * @param boolean $refresh Refresh badges collection in cache.
558 * @return null|object Returns null is there is no backpack or object with backpack settings.
560 function get_backpack_settings($userid, $refresh = false) {
561 global $DB;
563 // Try to get badges from cache first.
564 $badgescache = cache::make('core', 'externalbadges');
565 $out = $badgescache->get($userid);
566 if ($out !== false && !$refresh) {
567 return $out;
569 // Get badges through curl request to the backpack.
570 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
571 if ($record) {
572 $sitebackpack = badges_get_site_backpack($record->externalbackpackid);
573 $backpack = new \core_badges\backpack_api($sitebackpack, $record);
574 $out = new stdClass();
575 $out->backpackid = $sitebackpack->id;
577 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
578 $out->totalcollections = count($collections);
579 $out->totalbadges = 0;
580 $out->badges = array();
581 foreach ($collections as $collection) {
582 $badges = $backpack->get_badges($collection, true);
583 if (!empty($badges)) {
584 $out->badges = array_merge($out->badges, $badges);
585 $out->totalbadges += count($badges);
586 } else {
587 $out->badges = array_merge($out->badges, array());
590 } else {
591 $out->totalbadges = 0;
592 $out->totalcollections = 0;
595 $badgescache->set($userid, $out);
596 return $out;
599 return null;
603 * Download all user badges in zip archive.
605 * @param int $userid ID of badge owner.
607 function badges_download($userid) {
608 global $CFG, $DB;
609 $context = context_user::instance($userid);
610 $records = $DB->get_records('badge_issued', array('userid' => $userid));
612 // Get list of files to download.
613 $fs = get_file_storage();
614 $filelist = array();
615 foreach ($records as $issued) {
616 $badge = new badge($issued->badgeid);
617 // Need to make image name user-readable and unique using filename safe characters.
618 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
619 $name = str_replace(' ', '_', $name);
620 $name = clean_param($name, PARAM_FILE);
621 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
622 $filelist[$name . '.png'] = $file;
626 // Zip files and sent them to a user.
627 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
628 $zipper = new zip_packer();
629 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
630 send_temp_file($tempzip, 'badges.zip');
631 } else {
632 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
633 die;
638 * Checks if badges can be pushed to external backpack.
640 * @return string Code of backpack accessibility status.
642 function badges_check_backpack_accessibility() {
643 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
644 // For behat sites, do not poll the remote badge site.
645 // Behat sites should not be available, but we should pretend as though they are.
646 return 'available';
649 if (badges_open_badges_backpack_api() == OPEN_BADGES_V2) {
650 return 'available';
653 global $CFG;
654 include_once $CFG->libdir . '/filelib.php';
656 // Using fake assertion url to check whether backpack can access the web site.
657 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
659 // Curl request to backpack baker.
660 $curl = new curl();
661 $options = array(
662 'FRESH_CONNECT' => true,
663 'RETURNTRANSFER' => true,
664 'HEADER' => 0,
665 'CONNECTTIMEOUT' => 2,
667 // BADGE_BACKPACKURL and the "baker" API is deprecated and should never be used in future.
668 $location = BADGE_BACKPACKURL . '/baker';
669 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
671 $data = json_decode($out);
672 if (!empty($curl->error)) {
673 return 'curl-request-timeout';
674 } else {
675 if (isset($data->code) && $data->code == 'http-unreachable') {
676 return 'http-unreachable';
677 } else {
678 return 'available';
682 return false;
686 * Checks if user has external backpack connected.
688 * @param int $userid ID of a user.
689 * @return bool True|False whether backpack connection exists.
691 function badges_user_has_backpack($userid) {
692 global $DB;
693 return $DB->record_exists('badge_backpack', array('userid' => $userid));
697 * Handles what happens to the course badges when a course is deleted.
699 * @param int $courseid course ID.
700 * @return void.
702 function badges_handle_course_deletion($courseid) {
703 global $CFG, $DB;
704 include_once $CFG->libdir . '/filelib.php';
706 $systemcontext = context_system::instance();
707 $coursecontext = context_course::instance($courseid);
708 $fs = get_file_storage();
710 // Move badges images to the system context.
711 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
713 // Get all course badges.
714 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
715 foreach ($badges as $badge) {
716 // Archive badges in this course.
717 $toupdate = new stdClass();
718 $toupdate->id = $badge->id;
719 $toupdate->type = BADGE_TYPE_SITE;
720 $toupdate->courseid = null;
721 $toupdate->status = BADGE_STATUS_ARCHIVED;
722 $DB->update_record('badge', $toupdate);
727 * Loads JS files required for backpack support.
729 * @uses $CFG, $PAGE
730 * @return void
732 function badges_setup_backpack_js() {
733 global $CFG, $PAGE;
734 if (!empty($CFG->badges_allowexternalbackpack)) {
735 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
736 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
737 // The issuer.js API is deprecated and should not be used in future.
738 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
739 // The backpack.js file is deprecated and should not be used in future.
740 $PAGE->requires->js('/badges/backpack.js', true);
746 * No js files are required for backpack support.
747 * This only exists to directly support the custom V1 backpack api.
749 * @param boolean $checksite Call check site function.
750 * @return void
752 function badges_local_backpack_js($checksite = false) {
753 global $CFG, $PAGE;
754 if (!empty($CFG->badges_allowexternalbackpack)) {
755 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
756 $PAGE->requires->js('/badges/backpack.js', true);
757 if ($checksite) {
758 $PAGE->requires->js_init_call('check_site_access', null, false);
765 * Create the backpack with this data.
767 * @param stdClass $data The new backpack data.
768 * @return boolean
770 function badges_create_site_backpack($data) {
771 global $DB;
772 $context = context_system::instance();
773 require_capability('moodle/badges:manageglobalsettings', $context);
775 $count = $DB->count_records('badge_external_backpack');
777 $backpack = new stdClass();
778 $backpack->apiversion = $data->apiversion;
779 $backpack->backpackapiurl = $data->backpackapiurl;
780 $backpack->backpackweburl = $data->backpackweburl;
781 $backpack->sortorder = $count;
782 $DB->insert_record('badge_external_backpack', $backpack);
783 return true;
787 * Update the backpack with this id.
789 * @param integer $id The backpack to edit
790 * @param stdClass $data The new backpack data.
791 * @return boolean
793 function badges_update_site_backpack($id, $data) {
794 global $DB;
795 $context = context_system::instance();
796 require_capability('moodle/badges:manageglobalsettings', $context);
798 if ($backpack = badges_get_site_backpack($id)) {
799 $backpack = new stdClass();
800 $backpack->id = $id;
801 $backpack->apiversion = $data->apiversion;
802 $backpack->backpackweburl = $data->backpackweburl;
803 $backpack->backpackapiurl = $data->backpackapiurl;
804 $backpack->password = !empty($data->password) ? $data->password : '';
805 $backpack->oauth2_issuerid = !empty($data->oauth2_issuerid) ? $data->oauth2_issuerid : '';
806 $DB->update_record('badge_external_backpack', $backpack);
807 return true;
809 return false;
814 * Delete the backpack with this id.
816 * @param integer $id The backpack to delete.
817 * @return boolean
819 function badges_delete_site_backpack($id) {
820 global $DB, $CFG;
822 $context = context_system::instance();
823 require_capability('moodle/badges:manageglobalsettings', $context);
825 // Only remove site backpack if it's not the default one.
826 if ($CFG->badges_site_backpack != $id && $DB->record_exists('badge_external_backpack', ['id' => $id])) {
827 $transaction = $DB->start_delegated_transaction();
829 // Remove connections for users to this backpack.
830 $sql = "SELECT DISTINCT bb.id
831 FROM {badge_backpack} bb
832 WHERE bb.externalbackpackid = :backpackid";
833 $params = ['backpackid' => $id];
834 $userbackpacks = $DB->get_fieldset_sql($sql, $params);
835 if ($userbackpacks) {
836 // Delete user external collections references to this backpack.
837 list($insql, $params) = $DB->get_in_or_equal($userbackpacks);
838 $DB->delete_records_select('badge_external', "backpackid $insql", $params);
840 $DB->delete_records('badge_backpack', ['externalbackpackid' => $id]);
842 // Delete backpack entry.
843 $result = $DB->delete_records('badge_external_backpack', ['id' => $id]);
845 $transaction->allow_commit();
847 return $result;
850 return false;
854 * Is any backpack enabled that supports open badges V1?
855 * @return boolean
857 function badges_open_badges_backpack_api() {
858 global $CFG;
860 $backpack = badges_get_site_backpack($CFG->badges_site_backpack);
861 if (empty($backpack->apiversion)) {
862 return OPEN_BADGES_V2;
864 return $backpack->apiversion;
868 * Get a site backpacks by id or url.
870 * @param int $id The backpack id.
871 * @return array(stdClass)
873 function badges_get_site_backpack($id) {
874 global $DB;
876 return $DB->get_record('badge_external_backpack', ['id' => $id]);
880 * List the backpacks at site level.
882 * @return array(stdClass)
884 function badges_get_site_backpacks() {
885 global $DB, $CFG;
887 $all = $DB->get_records('badge_external_backpack');
889 foreach ($all as $key => $bp) {
890 if ($bp->id == $CFG->badges_site_backpack) {
891 $all[$key]->sitebackpack = true;
892 } else {
893 $all[$key]->sitebackpack = false;
896 return $all;
900 * List the supported badges api versions.
902 * @return array(version)
904 function badges_get_badge_api_versions() {
905 return [
906 (string)OPEN_BADGES_V1 => get_string('openbadgesv1', 'badges'),
907 (string)OPEN_BADGES_V2 => get_string('openbadgesv2', 'badges'),
908 (string)OPEN_BADGES_V2P1 => get_string('openbadgesv2p1', 'badges')
913 * Get the default issuer for a badge from this site.
915 * @return array
917 function badges_get_default_issuer() {
918 global $CFG, $SITE;
920 $issuer = array();
921 $issuerurl = new moodle_url('/');
922 $issuer['name'] = $CFG->badges_defaultissuername;
923 if (empty($issuer['name'])) {
924 $issuer['name'] = $SITE->fullname ? $SITE->fullname : $SITE->shortname;
926 $issuer['url'] = $issuerurl->out(false);
927 $issuer['email'] = $CFG->badges_defaultissuercontact;
928 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
929 $issuerid = new moodle_url('/badges/issuer_json.php');
930 $issuer['id'] = $issuerid->out(false);
931 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
932 return $issuer;
936 * Disconnect from the user backpack by deleting the user preferences.
938 * @param integer $userid The user to diconnect.
939 * @return boolean
941 function badges_disconnect_user_backpack($userid) {
942 global $USER;
944 // We can only change backpack settings for our own real backpack.
945 if ($USER->id != $userid ||
946 \core\session\manager::is_loggedinas()) {
948 return false;
951 unset_user_preference('badges_email_verify_secret');
952 unset_user_preference('badges_email_verify_address');
953 unset_user_preference('badges_email_verify_backpackid');
954 unset_user_preference('badges_email_verify_password');
956 return true;
960 * Used to remember which objects we connected with a backpack before.
962 * @param integer $sitebackpackid The site backpack to connect to.
963 * @param string $type The type of this remote object.
964 * @param string $internalid The id for this object on the Moodle site.
965 * @return mixed The id or false if it doesn't exist.
967 function badges_external_get_mapping($sitebackpackid, $type, $internalid) {
968 global $DB;
969 // Return externalid if it exists.
970 $params = [
971 'sitebackpackid' => $sitebackpackid,
972 'type' => $type,
973 'internalid' => $internalid
976 $record = $DB->get_record('badge_external_identifier', $params, 'externalid', IGNORE_MISSING);
977 if ($record) {
978 return $record->externalid;
980 return false;
984 * Save the info about which objects we connected with a backpack before.
986 * @param integer $sitebackpackid The site backpack to connect to.
987 * @param string $type The type of this remote object.
988 * @param string $internalid The id for this object on the Moodle site.
989 * @param string $externalid The id of this object on the remote site.
990 * @return boolean
992 function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
993 global $DB;
995 $params = [
996 'sitebackpackid' => $sitebackpackid,
997 'type' => $type,
998 'internalid' => $internalid,
999 'externalid' => $externalid
1002 return $DB->insert_record('badge_external_identifier', $params);
1006 * Delete all external mapping information for a backpack.
1008 * @param integer $sitebackpackid The site backpack to connect to.
1009 * @return boolean
1011 function badges_external_delete_mappings($sitebackpackid) {
1012 global $DB;
1014 $params = ['sitebackpackid' => $sitebackpackid];
1016 return $DB->delete_records('badge_external_identifier', $params);
1020 * Delete a specific external mapping information for a backpack.
1022 * @param integer $sitebackpackid The site backpack to connect to.
1023 * @param string $type The type of this remote object.
1024 * @param string $internalid The id for this object on the Moodle site.
1025 * @return boolean
1027 function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
1028 global $DB;
1030 $params = [
1031 'sitebackpackid' => $sitebackpackid,
1032 'type' => $type,
1033 'internalid' => $internalid
1036 $DB->delete_record('badge_external_identifier', $params);
1040 * Create and send a verification email to the email address supplied.
1042 * Since we're not sending this email to a user, email_to_user can't be used
1043 * but this function borrows largely the code from that process.
1045 * @param string $email the email address to send the verification email to.
1046 * @param int $backpackid the id of the backpack to connect to
1047 * @param string $backpackpassword the user entered password to connect to this backpack
1048 * @return true if the email was sent successfully, false otherwise.
1050 function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1051 global $DB, $USER;
1053 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1054 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1055 // of verification emails to said address.
1056 $secret = random_string(15);
1057 set_user_preference('badges_email_verify_secret', $secret);
1058 set_user_preference('badges_email_verify_address', $email);
1059 set_user_preference('badges_email_verify_backpackid', $backpackid);
1060 set_user_preference('badges_email_verify_password', $backpackpassword);
1062 // To, from.
1063 $tempuser = $DB->get_record('user', array('id' => $USER->id), '*', MUST_EXIST);
1064 $tempuser->email = $email;
1065 $noreplyuser = core_user::get_noreply_user();
1067 // Generate the verification email body.
1068 $verificationurl = '/badges/backpackemailverify.php';
1069 $verificationurl = new moodle_url($verificationurl);
1070 $verificationpath = $verificationurl->out(false);
1072 $site = get_site();
1073 $args = new stdClass();
1074 $args->link = $verificationpath . '?data='. $secret;
1075 $args->sitename = $site->fullname;
1076 $args->admin = generate_email_signoff();
1078 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname);
1079 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1080 $messagehtml = text_to_html($messagetext, false, false, true);
1082 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1086 * Return all the enabled criteria types for this site.
1088 * @param boolean $enabled
1089 * @return array
1091 function badges_list_criteria($enabled = true) {
1092 global $CFG;
1094 $types = array(
1095 BADGE_CRITERIA_TYPE_OVERALL => 'overall',
1096 BADGE_CRITERIA_TYPE_ACTIVITY => 'activity',
1097 BADGE_CRITERIA_TYPE_MANUAL => 'manual',
1098 BADGE_CRITERIA_TYPE_SOCIAL => 'social',
1099 BADGE_CRITERIA_TYPE_COURSE => 'course',
1100 BADGE_CRITERIA_TYPE_COURSESET => 'courseset',
1101 BADGE_CRITERIA_TYPE_PROFILE => 'profile',
1102 BADGE_CRITERIA_TYPE_BADGE => 'badge',
1103 BADGE_CRITERIA_TYPE_COHORT => 'cohort',
1104 BADGE_CRITERIA_TYPE_COMPETENCY => 'competency',
1106 if ($enabled) {
1107 foreach ($types as $key => $type) {
1108 $class = 'award_criteria_' . $type;
1109 $file = $CFG->dirroot . '/badges/criteria/' . $class . '.php';
1110 if (file_exists($file)) {
1111 require_once($file);
1113 if (!$class::is_enabled()) {
1114 unset($types[$key]);
1119 return $types;
1123 * Check if any badge has records for competencies.
1125 * @param array $competencyids Array of competencies ids.
1126 * @return boolean Return true if competencies were found in any badge.
1128 function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1129 global $DB;
1131 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED);
1133 $sql = "SELECT DISTINCT bc.badgeid
1134 FROM {badge_criteria} bc
1135 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1136 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1137 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY;
1139 return $DB->record_exists_sql($sql, $params);
1143 * Creates single message for all notification and sends it out
1145 * @param object $badge A badge which is notified about.
1147 function badge_assemble_notification(stdClass $badge) {
1148 global $DB;
1150 $userfrom = core_user::get_noreply_user();
1151 $userfrom->maildisplay = true;
1153 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id))) {
1154 // Get badge creator.
1155 $creator = $DB->get_record('user', array('id' => $badge->creator), '*', MUST_EXIST);
1156 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1157 $creatormessage = '';
1159 // Put all messages in one digest.
1160 foreach ($msgs as $msg) {
1161 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash)), $badge->name);
1162 $recipient = $DB->get_record('user', array('id' => $msg->userid), '*', MUST_EXIST);
1164 $a = new stdClass();
1165 $a->user = fullname($recipient);
1166 $a->link = $issuedlink;
1167 $creatormessage .= get_string('creatorbody', 'badges', $a);
1168 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid, 'userid' => $msg->userid));
1171 // Create a message object.
1172 $eventdata = new \core\message\message();
1173 $eventdata->courseid = SITEID;
1174 $eventdata->component = 'moodle';
1175 $eventdata->name = 'badgecreatornotice';
1176 $eventdata->userfrom = $userfrom;
1177 $eventdata->userto = $creator;
1178 $eventdata->notification = 1;
1179 $eventdata->subject = $creatorsubject;
1180 $eventdata->fullmessage = format_text_email($creatormessage, FORMAT_HTML);
1181 $eventdata->fullmessageformat = FORMAT_PLAIN;
1182 $eventdata->fullmessagehtml = $creatormessage;
1183 $eventdata->smallmessage = $creatorsubject;
1185 message_send($eventdata);
1190 * Attempt to authenticate with the site backpack credentials and return an error
1191 * if the authentication fails. If external backpacks are not enabled, this will
1192 * not perform any test.
1194 * @return string
1196 function badges_verify_site_backpack() {
1197 global $CFG;
1199 return badges_verify_backpack($CFG->badges_site_backpack);
1203 * Attempt to authenticate with a backpack credentials and return an error
1204 * if the authentication fails.
1205 * If external backpacks are not enabled or the backpack version is different
1206 * from OBv2, this will not perform any test.
1208 * @param int $backpackid Backpack identifier to verify.
1209 * @return string The result of the verification process.
1211 function badges_verify_backpack(int $backpackid) {
1212 global $OUTPUT, $CFG;
1214 if (empty($CFG->badges_allowexternalbackpack)) {
1215 return '';
1218 $backpack = badges_get_site_backpack($backpackid);
1219 if (empty($backpack->apiversion) || ($backpack->apiversion == OPEN_BADGES_V2)) {
1220 $backpackapi = new \core_badges\backpack_api($backpack);
1222 // Clear any cached access tokens in the session.
1223 $backpackapi->clear_system_user_session();
1225 // Now attempt a login with these credentials.
1226 $result = $backpackapi->authenticate();
1227 if (empty($result) || !empty($result->error)) {
1228 $warning = $backpackapi->get_authentication_error();
1230 $params = ['id' => $backpack->id, 'action' => 'edit'];
1231 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1233 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1234 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1235 return $OUTPUT->container($icon . $message, 'text-error');
1239 return '';
1243 * Get OAuth2 services for the external backpack.
1245 * @return array
1246 * @throws coding_exception
1248 function badges_get_oauth2_service_options() {
1249 global $DB;
1251 $issuers = core\oauth2\api::get_all_issuers();
1252 $options = ['' => 'None'];
1253 foreach ($issuers as $issuer) {
1254 $options[$issuer->get('id')] = $issuer->get('name');
1257 return $options;