MDL-67585 core_course: add content_item_service class
[moodle.git] / lib / badgeslib.php
blob940d567ca972e8a19c88d5e68463636a74738028
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('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) {
137 global $CFG, $DB;
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);
159 // Notify recipient.
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(),
175 'hash' => $issued,
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);
186 } else {
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);
196 $a = new stdClass();
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(),
217 'hash' => $issued,
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) {
232 $nextcron = 0;
234 switch ($schedule) {
235 case BADGE_MESSAGE_DAILY:
236 $tomorrow = new DateTime("1 day", core_date::get_server_timezone_object());
237 $nextcron = $tomorrow->getTimestamp();
238 break;
239 case BADGE_MESSAGE_WEEKLY:
240 $nextweek = new DateTime("1 week", core_date::get_server_timezone_object());
241 $nextcron = $nextweek->getTimestamp();
242 break;
243 case BADGE_MESSAGE_MONTHLY:
244 $nextmonth = new DateTime("1 month", core_date::get_server_timezone_object());
245 $nextcron = $nextmonth->getTimestamp();
246 break;
249 return $nextcron;
253 * Replaces variables in a message template and returns text ready to be emailed to a user.
255 * @param string $message Message body.
256 * @return string Message with replaced values
258 function badge_message_from_template($message, $params) {
259 $msg = $message;
260 foreach ($params as $key => $value) {
261 $msg = str_replace("%$key%", $value, $msg);
264 return $msg;
268 * Get all badges.
270 * @param int Type of badges to return
271 * @param int Course ID for course badges
272 * @param string $sort An SQL field to sort by
273 * @param string $dir The sort direction ASC|DESC
274 * @param int $page The page or records to return
275 * @param int $perpage The number of records to return per page
276 * @param int $user User specific search
277 * @return array $badge Array of records matching criteria
279 function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
280 global $DB;
281 $records = array();
282 $params = array();
283 $where = "b.status != :deleted AND b.type = :type ";
284 $params['deleted'] = BADGE_STATUS_ARCHIVED;
286 $userfields = array('b.id, b.name, b.status');
287 $usersql = "";
288 if ($user != 0) {
289 $userfields[] = 'bi.dateissued';
290 $userfields[] = 'bi.uniquehash';
291 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
292 $params['userid'] = $user;
293 $where .= " AND (b.status = 1 OR b.status = 3) ";
295 $fields = implode(', ', $userfields);
297 if ($courseid != 0 ) {
298 $where .= "AND b.courseid = :courseid ";
299 $params['courseid'] = $courseid;
302 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
303 $params['type'] = $type;
305 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
306 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
308 $badges = array();
309 foreach ($records as $r) {
310 $badge = new badge($r->id);
311 $badges[$r->id] = $badge;
312 if ($user != 0) {
313 $badges[$r->id]->dateissued = $r->dateissued;
314 $badges[$r->id]->uniquehash = $r->uniquehash;
315 } else {
316 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
317 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
318 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
319 $badges[$r->id]->statstring = $badge->get_status_name();
322 return $badges;
326 * Get badges for a specific user.
328 * @param int $userid User ID
329 * @param int $courseid Badges earned by a user in a specific course
330 * @param int $page The page or records to return
331 * @param int $perpage The number of records to return per page
332 * @param string $search A simple string to search for
333 * @param bool $onlypublic Return only public badges
334 * @return array of badges ordered by decreasing date of issue
336 function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
337 global $CFG, $DB;
339 $params = array(
340 'userid' => $userid
342 $sql = 'SELECT
343 bi.uniquehash,
344 bi.dateissued,
345 bi.dateexpire,
346 bi.id as issuedid,
347 bi.visible,
348 u.email,
350 FROM
351 {badge} b,
352 {badge_issued} bi,
353 {user} u
354 WHERE b.id = bi.badgeid
355 AND u.id = bi.userid
356 AND bi.userid = :userid';
358 if (!empty($search)) {
359 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
360 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
362 if ($onlypublic) {
363 $sql .= ' AND (bi.visible = 1) ';
366 if (empty($CFG->badges_allowcoursebadges)) {
367 $sql .= ' AND b.courseid IS NULL';
368 } else if ($courseid != 0) {
369 $sql .= ' AND (b.courseid = :courseid) ';
370 $params['courseid'] = $courseid;
372 $sql .= ' ORDER BY bi.dateissued DESC';
373 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
375 return $badges;
379 * Extends the course administration navigation with the Badges page
381 * @param navigation_node $coursenode
382 * @param object $course
384 function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
385 global $CFG, $SITE;
387 $coursecontext = context_course::instance($course->id);
388 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
389 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
390 'moodle/badges:createbadge',
391 'moodle/badges:awardbadge',
392 'moodle/badges:configurecriteria',
393 'moodle/badges:configuremessages',
394 'moodle/badges:configuredetails',
395 'moodle/badges:deletebadge'), $coursecontext);
397 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
398 $coursenode->add(get_string('coursebadges', 'badges'), null,
399 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
400 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
402 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
404 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
405 navigation_node::TYPE_SETTING, null, 'coursebadges');
407 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
408 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
410 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
411 navigation_node::TYPE_SETTING, null, 'newbadge');
417 * Triggered when badge is manually awarded.
419 * @param object $data
420 * @return boolean
422 function badges_award_handle_manual_criteria_review(stdClass $data) {
423 $criteria = $data->crit;
424 $userid = $data->userid;
425 $badge = new badge($criteria->badgeid);
427 if (!$badge->is_active() || $badge->is_issued($userid)) {
428 return true;
431 if ($criteria->review($userid)) {
432 $criteria->mark_complete($userid);
434 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
435 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
436 $badge->issue($userid);
440 return true;
444 * Process badge image from form data
446 * @param badge $badge Badge object
447 * @param string $iconfile Original file
449 function badges_process_badge_image(badge $badge, $iconfile) {
450 global $CFG, $USER;
451 require_once($CFG->libdir. '/gdlib.php');
453 if (!empty($CFG->gdversion)) {
454 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
455 @unlink($iconfile);
457 // Clean up file draft area after badge image has been saved.
458 $context = context_user::instance($USER->id, MUST_EXIST);
459 $fs = get_file_storage();
460 $fs->delete_area_files($context->id, 'user', 'draft');
465 * Print badge image.
467 * @param badge $badge Badge object
468 * @param stdClass $context
469 * @param string $size
471 function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
472 $fsize = ($size == 'small') ? 'f2' : 'f1';
474 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
475 // Appending a random parameter to image link to forse browser reload the image.
476 $imageurl->param('refresh', rand(1, 10000));
477 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
479 return html_writer::empty_tag('img', $attributes);
483 * Bake issued badge.
485 * @param string $hash Unique hash of an issued badge.
486 * @param int $badgeid ID of the original badge.
487 * @param int $userid ID of badge recipient (optional).
488 * @param boolean $pathhash Return file pathhash instead of image url (optional).
489 * @return string|url Returns either new file path hash or new file URL
491 function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
492 global $CFG, $USER;
493 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
495 $badge = new badge($badgeid);
496 $badge_context = $badge->get_context();
497 $userid = ($userid) ? $userid : $USER->id;
498 $user_context = context_user::instance($userid);
500 $fs = get_file_storage();
501 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
502 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
503 $contents = $file->get_content();
505 $filehandler = new PNG_MetaDataHandler($contents);
506 // For now, the site backpack OB version will be used as default.
507 $obversion = badges_open_badges_backpack_api();
508 $assertion = new core_badges_assertion($hash, $obversion);
509 $assertionjson = json_encode($assertion->get_badge_assertion());
510 if ($filehandler->check_chunks("iTXt", "openbadges")) {
511 // Add assertion URL iTXt chunk.
512 $newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
513 $fileinfo = array(
514 'contextid' => $user_context->id,
515 'component' => 'badges',
516 'filearea' => 'userbadge',
517 'itemid' => $badge->id,
518 'filepath' => '/',
519 'filename' => $hash . '.png',
522 // Create a file with added contents.
523 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
524 if ($pathhash) {
525 return $newfile->get_pathnamehash();
528 } else {
529 debugging('Error baking badge image!', DEBUG_DEVELOPER);
530 return;
534 // If file exists and we just need its path hash, return it.
535 if ($pathhash) {
536 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
537 return $file->get_pathnamehash();
540 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
541 return $fileurl;
545 * Returns external backpack settings and badges from this backpack.
547 * This function first checks if badges for the user are cached and
548 * tries to retrieve them from the cache. Otherwise, badges are obtained
549 * through curl request to the backpack.
551 * @param int $userid Backpack user ID.
552 * @param boolean $refresh Refresh badges collection in cache.
553 * @return null|object Returns null is there is no backpack or object with backpack settings.
555 function get_backpack_settings($userid, $refresh = false) {
556 global $DB;
558 // Try to get badges from cache first.
559 $badgescache = cache::make('core', 'externalbadges');
560 $out = $badgescache->get($userid);
561 if ($out !== false && !$refresh) {
562 return $out;
564 // Get badges through curl request to the backpack.
565 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
566 if ($record) {
567 $sitebackpack = badges_get_site_backpack($record->externalbackpackid);
568 $backpack = new \core_badges\backpack_api($sitebackpack, $record);
569 $out = new stdClass();
570 $out->backpackid = $sitebackpack->id;
572 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
573 $out->totalcollections = count($collections);
574 $out->totalbadges = 0;
575 $out->badges = array();
576 foreach ($collections as $collection) {
577 $badges = $backpack->get_badges($collection, true);
578 if (!empty($badges)) {
579 $out->badges = array_merge($out->badges, $badges);
580 $out->totalbadges += count($badges);
581 } else {
582 $out->badges = array_merge($out->badges, array());
585 } else {
586 $out->totalbadges = 0;
587 $out->totalcollections = 0;
590 $badgescache->set($userid, $out);
591 return $out;
594 return null;
598 * Download all user badges in zip archive.
600 * @param int $userid ID of badge owner.
602 function badges_download($userid) {
603 global $CFG, $DB;
604 $context = context_user::instance($userid);
605 $records = $DB->get_records('badge_issued', array('userid' => $userid));
607 // Get list of files to download.
608 $fs = get_file_storage();
609 $filelist = array();
610 foreach ($records as $issued) {
611 $badge = new badge($issued->badgeid);
612 // Need to make image name user-readable and unique using filename safe characters.
613 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
614 $name = str_replace(' ', '_', $name);
615 $name = clean_param($name, PARAM_FILE);
616 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
617 $filelist[$name . '.png'] = $file;
621 // Zip files and sent them to a user.
622 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
623 $zipper = new zip_packer();
624 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
625 send_temp_file($tempzip, 'badges.zip');
626 } else {
627 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
628 die;
633 * Checks if badges can be pushed to external backpack.
635 * @return string Code of backpack accessibility status.
637 function badges_check_backpack_accessibility() {
638 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
639 // For behat sites, do not poll the remote badge site.
640 // Behat sites should not be available, but we should pretend as though they are.
641 return 'available';
644 if (badges_open_badges_backpack_api() == OPEN_BADGES_V2) {
645 return 'available';
648 global $CFG;
649 include_once $CFG->libdir . '/filelib.php';
651 // Using fake assertion url to check whether backpack can access the web site.
652 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
654 // Curl request to backpack baker.
655 $curl = new curl();
656 $options = array(
657 'FRESH_CONNECT' => true,
658 'RETURNTRANSFER' => true,
659 'HEADER' => 0,
660 'CONNECTTIMEOUT' => 2,
662 // BADGE_BACKPACKURL and the "baker" API is deprecated and should never be used in future.
663 $location = BADGE_BACKPACKURL . '/baker';
664 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
666 $data = json_decode($out);
667 if (!empty($curl->error)) {
668 return 'curl-request-timeout';
669 } else {
670 if (isset($data->code) && $data->code == 'http-unreachable') {
671 return 'http-unreachable';
672 } else {
673 return 'available';
677 return false;
681 * Checks if user has external backpack connected.
683 * @param int $userid ID of a user.
684 * @return bool True|False whether backpack connection exists.
686 function badges_user_has_backpack($userid) {
687 global $DB;
688 return $DB->record_exists('badge_backpack', array('userid' => $userid));
692 * Handles what happens to the course badges when a course is deleted.
694 * @param int $courseid course ID.
695 * @return void.
697 function badges_handle_course_deletion($courseid) {
698 global $CFG, $DB;
699 include_once $CFG->libdir . '/filelib.php';
701 $systemcontext = context_system::instance();
702 $coursecontext = context_course::instance($courseid);
703 $fs = get_file_storage();
705 // Move badges images to the system context.
706 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
708 // Get all course badges.
709 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
710 foreach ($badges as $badge) {
711 // Archive badges in this course.
712 $toupdate = new stdClass();
713 $toupdate->id = $badge->id;
714 $toupdate->type = BADGE_TYPE_SITE;
715 $toupdate->courseid = null;
716 $toupdate->status = BADGE_STATUS_ARCHIVED;
717 $DB->update_record('badge', $toupdate);
722 * Loads JS files required for backpack support.
724 * @uses $CFG, $PAGE
725 * @return void
727 function badges_setup_backpack_js() {
728 global $CFG, $PAGE;
729 if (!empty($CFG->badges_allowexternalbackpack)) {
730 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
731 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
732 // The issuer.js API is deprecated and should not be used in future.
733 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
734 // The backpack.js file is deprecated and should not be used in future.
735 $PAGE->requires->js('/badges/backpack.js', true);
741 * No js files are required for backpack support.
742 * This only exists to directly support the custom V1 backpack api.
744 * @param boolean $checksite Call check site function.
745 * @return void
747 function badges_local_backpack_js($checksite = false) {
748 global $CFG, $PAGE;
749 if (!empty($CFG->badges_allowexternalbackpack)) {
750 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
751 $PAGE->requires->js('/badges/backpack.js', true);
752 if ($checksite) {
753 $PAGE->requires->js_init_call('check_site_access', null, false);
760 * Create the backpack with this data.
762 * @param stdClass $data The new backpack data.
763 * @return boolean
765 function badges_create_site_backpack($data) {
766 global $DB;
767 $context = context_system::instance();
768 require_capability('moodle/badges:manageglobalsettings', $context);
770 $count = $DB->count_records('badge_external_backpack');
772 $backpack = new stdClass();
773 $backpack->apiversion = $data->apiversion;
774 $backpack->backpackapiurl = $data->backpackapiurl;
775 $backpack->backpackweburl = $data->backpackweburl;
776 $backpack->sortorder = $count;
777 $DB->insert_record('badge_external_backpack', $backpack);
778 return true;
782 * Update the backpack with this id.
784 * @param integer $id The backpack to edit
785 * @param stdClass $data The new backpack data.
786 * @return boolean
788 function badges_update_site_backpack($id, $data) {
789 global $DB;
790 $context = context_system::instance();
791 require_capability('moodle/badges:manageglobalsettings', $context);
793 if ($backpack = badges_get_site_backpack($id)) {
794 $backpack = new stdClass();
795 $backpack->id = $id;
796 $backpack->apiversion = $data->apiversion;
797 $backpack->backpackweburl = $data->backpackweburl;
798 $backpack->backpackapiurl = $data->backpackapiurl;
799 $backpack->password = $data->password;
800 $DB->update_record('badge_external_backpack', $backpack);
801 return true;
803 return false;
807 * Is any backpack enabled that supports open badges V1?
808 * @return boolean
810 function badges_open_badges_backpack_api() {
811 global $CFG;
813 $backpack = badges_get_site_backpack($CFG->badges_site_backpack);
815 if (empty($backpack->apiversion)) {
816 return OPEN_BADGES_V2;
818 return $backpack->apiversion;
822 * Get a site backpacks by id or url.
824 * @param int $id The backpack id.
825 * @return array(stdClass)
827 function badges_get_site_backpack($id) {
828 global $DB;
830 return $DB->get_record('badge_external_backpack', ['id' => $id]);
834 * List the backpacks at site level.
836 * @return array(stdClass)
838 function badges_get_site_backpacks() {
839 global $DB, $CFG;
841 $all = $DB->get_records('badge_external_backpack');
843 foreach ($all as $key => $bp) {
844 if ($bp->id == $CFG->badges_site_backpack) {
845 $all[$key]->sitebackpack = true;
846 } else {
847 $all[$key]->sitebackpack = false;
850 return $all;
854 * List the supported badges api versions.
856 * @return array(version)
858 function badges_get_badge_api_versions() {
859 return [
860 OPEN_BADGES_V1 => get_string('openbadgesv1', 'badges'),
861 OPEN_BADGES_V2 => get_string('openbadgesv2', 'badges')
866 * Get the default issuer for a badge from this site.
868 * @return array
870 function badges_get_default_issuer() {
871 global $CFG, $SITE;
873 $issuer = array();
874 $issuerurl = new moodle_url('/badges/issuer.php');
875 $issuer['name'] = $CFG->badges_defaultissuername;
876 if (empty($issuer['name'])) {
877 $issuer['name'] = $SITE->fullname ? $SITE->fullname : $SITE->shortname;
879 $issuer['url'] = $issuerurl->out(false);
880 $issuer['email'] = $CFG->badges_defaultissuercontact;
881 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
882 $issuer['id'] = $issuerurl->out(false);
883 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
884 return $issuer;
888 * Disconnect from the user backpack by deleting the user preferences.
890 * @param integer $userid The user to diconnect.
891 * @return boolean
893 function badges_disconnect_user_backpack($userid) {
894 global $USER;
896 // We can only change backpack settings for our own real backpack.
897 if ($USER->id != $userid ||
898 \core\session\manager::is_loggedinas()) {
900 return false;
903 unset_user_preference('badges_email_verify_secret');
904 unset_user_preference('badges_email_verify_address');
905 unset_user_preference('badges_email_verify_backpackid');
906 unset_user_preference('badges_email_verify_password');
908 return true;
912 * Used to remember which objects we connected with a backpack before.
914 * @param integer $sitebackpackid The site backpack to connect to.
915 * @param string $type The type of this remote object.
916 * @param string $internalid The id for this object on the Moodle site.
917 * @return mixed The id or false if it doesn't exist.
919 function badges_external_get_mapping($sitebackpackid, $type, $internalid) {
920 global $DB;
921 // Return externalid if it exists.
922 $params = [
923 'sitebackpackid' => $sitebackpackid,
924 'type' => $type,
925 'internalid' => $internalid
928 $record = $DB->get_record('badge_external_identifier', $params, 'externalid', IGNORE_MISSING);
929 if ($record) {
930 return $record->externalid;
932 return false;
936 * Save the info about which objects we connected with a backpack before.
938 * @param integer $sitebackpackid The site backpack to connect to.
939 * @param string $type The type of this remote object.
940 * @param string $internalid The id for this object on the Moodle site.
941 * @param string $externalid The id of this object on the remote site.
942 * @return boolean
944 function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
945 global $DB;
947 $params = [
948 'sitebackpackid' => $sitebackpackid,
949 'type' => $type,
950 'internalid' => $internalid,
951 'externalid' => $externalid
954 return $DB->insert_record('badge_external_identifier', $params);
958 * Delete all external mapping information for a backpack.
960 * @param integer $sitebackpackid The site backpack to connect to.
961 * @return boolean
963 function badges_external_delete_mappings($sitebackpackid) {
964 global $DB;
966 $params = ['sitebackpackid' => $sitebackpackid];
968 return $DB->delete_records('badge_external_identifier', $params);
972 * Delete a specific external mapping information for a backpack.
974 * @param integer $sitebackpackid The site backpack to connect to.
975 * @param string $type The type of this remote object.
976 * @param string $internalid The id for this object on the Moodle site.
977 * @return boolean
979 function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
980 global $DB;
982 $params = [
983 'sitebackpackid' => $sitebackpackid,
984 'type' => $type,
985 'internalid' => $internalid
988 $DB->delete_record('badge_external_identifier', $params);
992 * Create and send a verification email to the email address supplied.
994 * Since we're not sending this email to a user, email_to_user can't be used
995 * but this function borrows largely the code from that process.
997 * @param string $email the email address to send the verification email to.
998 * @param int $backpackid the id of the backpack to connect to
999 * @param string $backpackpassword the user entered password to connect to this backpack
1000 * @return true if the email was sent successfully, false otherwise.
1002 function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1003 global $DB, $USER;
1005 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1006 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1007 // of verification emails to said address.
1008 $secret = random_string(15);
1009 set_user_preference('badges_email_verify_secret', $secret);
1010 set_user_preference('badges_email_verify_address', $email);
1011 set_user_preference('badges_email_verify_backpackid', $backpackid);
1012 set_user_preference('badges_email_verify_password', $backpackpassword);
1014 // To, from.
1015 $tempuser = $DB->get_record('user', array('id' => $USER->id), '*', MUST_EXIST);
1016 $tempuser->email = $email;
1017 $noreplyuser = core_user::get_noreply_user();
1019 // Generate the verification email body.
1020 $verificationurl = '/badges/backpackemailverify.php';
1021 $verificationurl = new moodle_url($verificationurl);
1022 $verificationpath = $verificationurl->out(false);
1024 $site = get_site();
1025 $args = new stdClass();
1026 $args->link = $verificationpath . '?data='. $secret;
1027 $args->sitename = $site->fullname;
1028 $args->admin = generate_email_signoff();
1030 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname);
1031 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1032 $messagehtml = text_to_html($messagetext, false, false, true);
1034 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1038 * Return all the enabled criteria types for this site.
1040 * @param boolean $enabled
1041 * @return array
1043 function badges_list_criteria($enabled = true) {
1044 global $CFG;
1046 $types = array(
1047 BADGE_CRITERIA_TYPE_OVERALL => 'overall',
1048 BADGE_CRITERIA_TYPE_ACTIVITY => 'activity',
1049 BADGE_CRITERIA_TYPE_MANUAL => 'manual',
1050 BADGE_CRITERIA_TYPE_SOCIAL => 'social',
1051 BADGE_CRITERIA_TYPE_COURSE => 'course',
1052 BADGE_CRITERIA_TYPE_COURSESET => 'courseset',
1053 BADGE_CRITERIA_TYPE_PROFILE => 'profile',
1054 BADGE_CRITERIA_TYPE_BADGE => 'badge',
1055 BADGE_CRITERIA_TYPE_COHORT => 'cohort',
1056 BADGE_CRITERIA_TYPE_COMPETENCY => 'competency',
1058 if ($enabled) {
1059 foreach ($types as $key => $type) {
1060 $class = 'award_criteria_' . $type;
1061 $file = $CFG->dirroot . '/badges/criteria/' . $class . '.php';
1062 if (file_exists($file)) {
1063 require_once($file);
1065 if (!$class::is_enabled()) {
1066 unset($types[$key]);
1071 return $types;
1075 * Check if any badge has records for competencies.
1077 * @param array $competencyids Array of competencies ids.
1078 * @return boolean Return true if competencies were found in any badge.
1080 function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1081 global $DB;
1083 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED);
1085 $sql = "SELECT DISTINCT bc.badgeid
1086 FROM {badge_criteria} bc
1087 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1088 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1089 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY;
1091 return $DB->record_exists_sql($sql, $params);
1095 * Creates single message for all notification and sends it out
1097 * @param object $badge A badge which is notified about.
1099 function badge_assemble_notification(stdClass $badge) {
1100 global $DB;
1102 $userfrom = core_user::get_noreply_user();
1103 $userfrom->maildisplay = true;
1105 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id))) {
1106 // Get badge creator.
1107 $creator = $DB->get_record('user', array('id' => $badge->creator), '*', MUST_EXIST);
1108 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1109 $creatormessage = '';
1111 // Put all messages in one digest.
1112 foreach ($msgs as $msg) {
1113 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash)), $badge->name);
1114 $recipient = $DB->get_record('user', array('id' => $msg->userid), '*', MUST_EXIST);
1116 $a = new stdClass();
1117 $a->user = fullname($recipient);
1118 $a->link = $issuedlink;
1119 $creatormessage .= get_string('creatorbody', 'badges', $a);
1120 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid, 'userid' => $msg->userid));
1123 // Create a message object.
1124 $eventdata = new \core\message\message();
1125 $eventdata->courseid = SITEID;
1126 $eventdata->component = 'moodle';
1127 $eventdata->name = 'badgecreatornotice';
1128 $eventdata->userfrom = $userfrom;
1129 $eventdata->userto = $creator;
1130 $eventdata->notification = 1;
1131 $eventdata->subject = $creatorsubject;
1132 $eventdata->fullmessage = format_text_email($creatormessage, FORMAT_HTML);
1133 $eventdata->fullmessageformat = FORMAT_PLAIN;
1134 $eventdata->fullmessagehtml = $creatormessage;
1135 $eventdata->smallmessage = $creatorsubject;
1137 message_send($eventdata);
1142 * Attempt to authenticate with the site backpack credentials and return an error
1143 * if the authentication fails. If external backpacks are not enabled, this will
1144 * not perform any test.
1146 * @return string
1148 function badges_verify_site_backpack() {
1149 global $OUTPUT, $CFG;
1151 if (empty($CFG->badges_allowexternalbackpack)) {
1152 return '';
1155 $backpack = badges_get_site_backpack($CFG->badges_site_backpack);
1157 if (empty($backpack->apiversion) || ($backpack->apiversion == OPEN_BADGES_V2)) {
1158 $backpackapi = new \core_badges\backpack_api($backpack);
1160 // Clear any cached access tokens in the session.
1161 $backpackapi->clear_system_user_session();
1163 // Now attempt a login with these credentials.
1164 $result = $backpackapi->authenticate();
1165 if (empty($result) || !empty($result->error)) {
1166 $warning = $backpackapi->get_authentication_error();
1168 $params = ['id' => $backpack->id, 'action' => 'edit'];
1169 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1171 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1172 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1173 return $OUTPUT->container($icon . $message, 'text-error');
1176 return '';