on-demand release 3.9dev+
[moodle.git] / lib / badgeslib.php
CommitLineData
27806552
YB
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.
13//
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/>.
16
17/**
18 * Contains classes, functions and constants used in badges.
19 *
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>
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29/* Include required award criteria library. */
30require_once($CFG->dirroot . '/badges/criteria/award_criteria.php');
31
32/*
33 * Number of records per page.
34*/
35define('BADGE_PERPAGE', 50);
36
37/*
38 * Badge award criteria aggregation method.
39 */
40define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
41
42/*
43 * Badge award criteria aggregation method.
44 */
45define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
46
47/*
48 * Inactive badge means that this badge cannot be earned and has not been awarded
49 * yet. Its award criteria can be changed.
50 */
51define('BADGE_STATUS_INACTIVE', 0);
52
53/*
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.
56 */
57define('BADGE_STATUS_ACTIVE', 1);
58
59/*
60 * Inactive badge can no longer be earned, but it has been awarded in the past and
61 * therefore its criteria cannot be changed.
62 */
63define('BADGE_STATUS_INACTIVE_LOCKED', 2);
64
65/*
66 * Active badge means that it can be earned and has already been awarded to users.
67 * Its criteria cannot be changed any more.
68 */
69define('BADGE_STATUS_ACTIVE_LOCKED', 3);
70
71/*
72 * Archived badge is considered deleted and can no longer be earned and is not
73 * displayed in the list of all badges.
74 */
75define('BADGE_STATUS_ARCHIVED', 4);
76
77/*
78 * Badge type for site badges.
79 */
80define('BADGE_TYPE_SITE', 1);
81
82/*
83 * Badge type for course badges.
84 */
85define('BADGE_TYPE_COURSE', 2);
86
87/*
88 * Badge messaging schedule options.
89 */
90define('BADGE_MESSAGE_NEVER', 0);
91define('BADGE_MESSAGE_ALWAYS', 1);
92define('BADGE_MESSAGE_DAILY', 2);
93define('BADGE_MESSAGE_WEEKLY', 3);
94define('BADGE_MESSAGE_MONTHLY', 4);
95
343534a8 96/*
aae219ac 97 * URL of backpack. Custom ones can be added.
343534a8 98 */
aae219ac
DW
99define('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
100define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
343534a8 101
7444ba74
DW
102/*
103 * @deprecated since 3.7. Use the urls in the badge_external_backpack table instead.
104 */
105define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
106
f958f5c1
SA
107/*
108 * @deprecated since 3.9 (MDL-66357).
109 */
110define('BADGE_BACKPACKAPIURL', 'https://backpack.openbadges.org');
111define('BADGE_BACKPACKWEBURL', 'https://backpack.openbadges.org');
112
5a1ea828
SA
113/*
114 * Open Badges specifications.
115 */
116define('OPEN_BADGES_V1', 1);
117define('OPEN_BADGES_V2', 2);
118
d363a5c2
TT
119/*
120 * Only use for Open Badges 2.0 specification
121 */
122define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
123define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
124define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
125define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
126define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
127define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
128
aae219ac
DW
129// Global badge class has been moved to the component namespace.
130class_alias('\core_badges\badge', 'badge');
27806552
YB
131
132/**
133 * Sends notifications to users about awarded badges.
134 *
135 * @param badge $badge Badge that was issued
136 * @param int $userid Recipient ID
137 * @param string $issued Unique hash of an issued badge
138 * @param string $filepathhash File path hash of an issued badge for attachments
139 */
140function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
141 global $CFG, $DB;
142
143 $admin = get_admin();
144 $userfrom = new stdClass();
145 $userfrom->id = $admin->id;
146 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
a327f25e
AG
147 foreach (get_all_user_name_fields() as $addname) {
148 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
149 }
27806552 150 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
27806552
YB
151 $userfrom->maildisplay = true;
152
153 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
154 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
155
156 $params = new stdClass();
157 $params->badgename = $badge->name;
158 $params->username = fullname($userto);
159 $params->badgelink = $issuedlink;
160 $message = badge_message_from_template($badge->message, $params);
1f258cd8 161 $plaintext = html_to_text($message);
27806552 162
f5d17c14 163 // Notify recipient.
cc350fd9 164 $eventdata = new \core\message\message();
f593e827 165 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
f5d17c14
YB
166 $eventdata->component = 'moodle';
167 $eventdata->name = 'badgerecipientnotice';
168 $eventdata->userfrom = $userfrom;
169 $eventdata->userto = $userto;
170 $eventdata->notification = 1;
171 $eventdata->subject = $badge->messagesubject;
172 $eventdata->fullmessage = $plaintext;
1f258cd8 173 $eventdata->fullmessageformat = FORMAT_HTML;
f5d17c14 174 $eventdata->fullmessagehtml = $message;
1f258cd8 175 $eventdata->smallmessage = '';
36fa0ec9
JL
176 $eventdata->customdata = [
177 'notificationiconurl' => moodle_url::make_pluginfile_url(
178 $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
179 'hash' => $issued,
180 ];
f5d17c14
YB
181
182 // Attach badge image if possible.
183 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
27806552
YB
184 $fs = get_file_storage();
185 $file = $fs->get_file_by_hash($filepathhash);
f5d17c14
YB
186 $eventdata->attachment = $file;
187 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
188
189 message_send($eventdata);
27806552 190 } else {
f5d17c14 191 message_send($eventdata);
27806552
YB
192 }
193
194 // Notify badge creator about the award if they receive notifications every time.
195 if ($badge->notification == 1) {
f5d17c14
YB
196 $userfrom = core_user::get_noreply_user();
197 $userfrom->maildisplay = true;
198
27806552
YB
199 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
200 $a = new stdClass();
201 $a->user = fullname($userto);
202 $a->link = $issuedlink;
203 $creatormessage = get_string('creatorbody', 'badges', $a);
204 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
205
cc350fd9
AD
206 $eventdata = new \core\message\message();
207 $eventdata->courseid = $badge->courseid;
27806552 208 $eventdata->component = 'moodle';
f5d17c14 209 $eventdata->name = 'badgecreatornotice';
27806552
YB
210 $eventdata->userfrom = $userfrom;
211 $eventdata->userto = $creator;
212 $eventdata->notification = 1;
213 $eventdata->subject = $creatorsubject;
1f258cd8
YB
214 $eventdata->fullmessage = html_to_text($creatormessage);
215 $eventdata->fullmessageformat = FORMAT_HTML;
f5d17c14 216 $eventdata->fullmessagehtml = $creatormessage;
1f258cd8 217 $eventdata->smallmessage = '';
36fa0ec9
JL
218 $eventdata->customdata = [
219 'notificationiconurl' => moodle_url::make_pluginfile_url(
220 $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
221 'hash' => $issued,
222 ];
27806552
YB
223
224 message_send($eventdata);
225 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
226 }
227}
228
229/**
230 * Caclulates date for the next message digest to badge creators.
231 *
232 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
233 * @return int Timestamp for next cron
234 */
235function badges_calculate_message_schedule($schedule) {
236 $nextcron = 0;
237
238 switch ($schedule) {
239 case BADGE_MESSAGE_DAILY:
b0213770
DW
240 $tomorrow = new DateTime("1 day", core_date::get_server_timezone_object());
241 $nextcron = $tomorrow->getTimestamp();
27806552
YB
242 break;
243 case BADGE_MESSAGE_WEEKLY:
b0213770
DW
244 $nextweek = new DateTime("1 week", core_date::get_server_timezone_object());
245 $nextcron = $nextweek->getTimestamp();
27806552
YB
246 break;
247 case BADGE_MESSAGE_MONTHLY:
b0213770
DW
248 $nextmonth = new DateTime("1 month", core_date::get_server_timezone_object());
249 $nextcron = $nextmonth->getTimestamp();
27806552
YB
250 break;
251 }
252
253 return $nextcron;
254}
255
256/**
257 * Replaces variables in a message template and returns text ready to be emailed to a user.
258 *
259 * @param string $message Message body.
260 * @return string Message with replaced values
261 */
262function badge_message_from_template($message, $params) {
263 $msg = $message;
264 foreach ($params as $key => $value) {
265 $msg = str_replace("%$key%", $value, $msg);
266 }
267
268 return $msg;
269}
270
271/**
272 * Get all badges.
273 *
274 * @param int Type of badges to return
275 * @param int Course ID for course badges
276 * @param string $sort An SQL field to sort by
277 * @param string $dir The sort direction ASC|DESC
278 * @param int $page The page or records to return
279 * @param int $perpage The number of records to return per page
280 * @param int $user User specific search
281 * @return array $badge Array of records matching criteria
282 */
283function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
284 global $DB;
285 $records = array();
286 $params = array();
287 $where = "b.status != :deleted AND b.type = :type ";
288 $params['deleted'] = BADGE_STATUS_ARCHIVED;
289
290 $userfields = array('b.id, b.name, b.status');
291 $usersql = "";
292 if ($user != 0) {
293 $userfields[] = 'bi.dateissued';
294 $userfields[] = 'bi.uniquehash';
295 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
296 $params['userid'] = $user;
297 $where .= " AND (b.status = 1 OR b.status = 3) ";
298 }
299 $fields = implode(', ', $userfields);
300
301 if ($courseid != 0 ) {
302 $where .= "AND b.courseid = :courseid ";
303 $params['courseid'] = $courseid;
304 }
305
306 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
307 $params['type'] = $type;
308
309 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
310 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
311
312 $badges = array();
313 foreach ($records as $r) {
314 $badge = new badge($r->id);
315 $badges[$r->id] = $badge;
316 if ($user != 0) {
317 $badges[$r->id]->dateissued = $r->dateissued;
318 $badges[$r->id]->uniquehash = $r->uniquehash;
319 } else {
7f964cfd
YB
320 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
321 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
322 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
27806552
YB
323 $badges[$r->id]->statstring = $badge->get_status_name();
324 }
325 }
326 return $badges;
327}
328
329/**
330 * Get badges for a specific user.
331 *
332 * @param int $userid User ID
333 * @param int $courseid Badges earned by a user in a specific course
334 * @param int $page The page or records to return
335 * @param int $perpage The number of records to return per page
336 * @param string $search A simple string to search for
337 * @param bool $onlypublic Return only public badges
338 * @return array of badges ordered by decreasing date of issue
339 */
340function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
b4846b88 341 global $CFG, $DB;
27806552 342
d237385e
SH
343 $params = array(
344 'userid' => $userid
345 );
27806552
YB
346 $sql = 'SELECT
347 bi.uniquehash,
348 bi.dateissued,
349 bi.dateexpire,
350 bi.id as issuedid,
351 bi.visible,
352 u.email,
353 b.*
354 FROM
355 {badge} b,
356 {badge_issued} bi,
357 {user} u
358 WHERE b.id = bi.badgeid
359 AND u.id = bi.userid
d237385e 360 AND bi.userid = :userid';
27806552
YB
361
362 if (!empty($search)) {
d237385e
SH
363 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
364 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
27806552
YB
365 }
366 if ($onlypublic) {
367 $sql .= ' AND (bi.visible = 1) ';
368 }
369
b4846b88
AO
370 if (empty($CFG->badges_allowcoursebadges)) {
371 $sql .= ' AND b.courseid IS NULL';
372 } else if ($courseid != 0) {
d237385e
SH
373 $sql .= ' AND (b.courseid = :courseid) ';
374 $params['courseid'] = $courseid;
27806552
YB
375 }
376 $sql .= ' ORDER BY bi.dateissued DESC';
377 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
378
379 return $badges;
380}
381
27806552
YB
382/**
383 * Extends the course administration navigation with the Badges page
384 *
385 * @param navigation_node $coursenode
386 * @param object $course
387 */
388function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
389 global $CFG, $SITE;
390
391 $coursecontext = context_course::instance($course->id);
392 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
a72c2cd6
YB
393 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
394 'moodle/badges:createbadge',
395 'moodle/badges:awardbadge',
396 'moodle/badges:configurecriteria',
397 'moodle/badges:configuremessages',
398 'moodle/badges:configuredetails',
399 'moodle/badges:deletebadge'), $coursecontext);
27806552 400
a72c2cd6
YB
401 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
402 $coursenode->add(get_string('coursebadges', 'badges'), null,
403 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
404 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
27806552 405
a72c2cd6 406 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
27806552 407
a72c2cd6
YB
408 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
409 navigation_node::TYPE_SETTING, null, 'coursebadges');
19a9f2ea 410
a72c2cd6
YB
411 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
412 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
19a9f2ea 413
a72c2cd6
YB
414 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
415 navigation_node::TYPE_SETTING, null, 'newbadge');
27806552
YB
416 }
417 }
418}
419
27806552
YB
420/**
421 * Triggered when badge is manually awarded.
422 *
423 * @param object $data
424 * @return boolean
425 */
426function badges_award_handle_manual_criteria_review(stdClass $data) {
427 $criteria = $data->crit;
428 $userid = $data->userid;
429 $badge = new badge($criteria->badgeid);
430
431 if (!$badge->is_active() || $badge->is_issued($userid)) {
432 return true;
433 }
434
435 if ($criteria->review($userid)) {
436 $criteria->mark_complete($userid);
437
438 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
439 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
440 $badge->issue($userid);
441 }
442 }
443
444 return true;
445}
446
447/**
448 * Process badge image from form data
449 *
450 * @param badge $badge Badge object
451 * @param string $iconfile Original file
452 */
453function badges_process_badge_image(badge $badge, $iconfile) {
454 global $CFG, $USER;
455 require_once($CFG->libdir. '/gdlib.php');
456
457 if (!empty($CFG->gdversion)) {
cda2a827 458 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
27806552
YB
459 @unlink($iconfile);
460
461 // Clean up file draft area after badge image has been saved.
462 $context = context_user::instance($USER->id, MUST_EXIST);
463 $fs = get_file_storage();
464 $fs->delete_area_files($context->id, 'user', 'draft');
465 }
466}
467
468/**
469 * Print badge image.
470 *
471 * @param badge $badge Badge object
472 * @param stdClass $context
473 * @param string $size
474 */
475function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
476 $fsize = ($size == 'small') ? 'f2' : 'f1';
477
478 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
479 // Appending a random parameter to image link to forse browser reload the image.
b143259e
YB
480 $imageurl->param('refresh', rand(1, 10000));
481 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
27806552
YB
482
483 return html_writer::empty_tag('img', $attributes);
484}
485
486/**
487 * Bake issued badge.
488 *
489 * @param string $hash Unique hash of an issued badge.
490 * @param int $badgeid ID of the original badge.
491 * @param int $userid ID of badge recipient (optional).
492 * @param boolean $pathhash Return file pathhash instead of image url (optional).
493 * @return string|url Returns either new file path hash or new file URL
494 */
495function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
496 global $CFG, $USER;
1fcf0ca8 497 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
27806552
YB
498
499 $badge = new badge($badgeid);
500 $badge_context = $badge->get_context();
501 $userid = ($userid) ? $userid : $USER->id;
502 $user_context = context_user::instance($userid);
503
504 $fs = get_file_storage();
505 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
49b464f8 506 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
27806552
YB
507 $contents = $file->get_content();
508
509 $filehandler = new PNG_MetaDataHandler($contents);
f8d9b1eb
SA
510 // For now, the site backpack OB version will be used as default.
511 $obversion = badges_open_badges_backpack_api();
512 $assertion = new core_badges_assertion($hash, $obversion);
513 $assertionjson = json_encode($assertion->get_badge_assertion());
514 if ($filehandler->check_chunks("iTXt", "openbadges")) {
515 // Add assertion URL iTXt chunk.
516 $newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
27806552
YB
517 $fileinfo = array(
518 'contextid' => $user_context->id,
519 'component' => 'badges',
520 'filearea' => 'userbadge',
521 'itemid' => $badge->id,
522 'filepath' => '/',
523 'filename' => $hash . '.png',
524 );
525
526 // Create a file with added contents.
527 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
528 if ($pathhash) {
529 return $newfile->get_pathnamehash();
530 }
531 }
532 } else {
be2b37cf
Y
533 debugging('Error baking badge image!', DEBUG_DEVELOPER);
534 return;
27806552
YB
535 }
536 }
537
f5d17c14
YB
538 // If file exists and we just need its path hash, return it.
539 if ($pathhash) {
540 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
541 return $file->get_pathnamehash();
542 }
543
27806552
YB
544 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
545 return $fileurl;
546}
547
548/**
e2805314 549 * Returns external backpack settings and badges from this backpack.
27806552 550 *
2d3c0fae
YB
551 * This function first checks if badges for the user are cached and
552 * tries to retrieve them from the cache. Otherwise, badges are obtained
553 * through curl request to the backpack.
554 *
27806552 555 * @param int $userid Backpack user ID.
2d3c0fae 556 * @param boolean $refresh Refresh badges collection in cache.
27806552
YB
557 * @return null|object Returns null is there is no backpack or object with backpack settings.
558 */
2d3c0fae 559function get_backpack_settings($userid, $refresh = false) {
27806552 560 global $DB;
27806552 561
2d3c0fae
YB
562 // Try to get badges from cache first.
563 $badgescache = cache::make('core', 'externalbadges');
564 $out = $badgescache->get($userid);
565 if ($out !== false && !$refresh) {
566 return $out;
567 }
568 // Get badges through curl request to the backpack.
e2805314 569 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
27806552 570 if ($record) {
7444ba74 571 $sitebackpack = badges_get_site_backpack($record->externalbackpackid);
aae219ac 572 $backpack = new \core_badges\backpack_api($sitebackpack, $record);
27806552 573 $out = new stdClass();
aae219ac 574 $out->backpackid = $sitebackpack->id;
e2805314
YB
575
576 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
577 $out->totalcollections = count($collections);
578 $out->totalbadges = 0;
579 $out->badges = array();
580 foreach ($collections as $collection) {
aae219ac
DW
581 $badges = $backpack->get_badges($collection, true);
582 if (!empty($badges)) {
583 $out->badges = array_merge($out->badges, $badges);
584 $out->totalbadges += count($badges);
e2805314
YB
585 } else {
586 $out->badges = array_merge($out->badges, array());
587 }
588 }
589 } else {
590 $out->totalbadges = 0;
591 $out->totalcollections = 0;
592 }
593
2d3c0fae 594 $badgescache->set($userid, $out);
27806552
YB
595 return $out;
596 }
597
598 return null;
599}
600
601/**
602 * Download all user badges in zip archive.
603 *
604 * @param int $userid ID of badge owner.
605 */
606function badges_download($userid) {
607 global $CFG, $DB;
608 $context = context_user::instance($userid);
609 $records = $DB->get_records('badge_issued', array('userid' => $userid));
610
611 // Get list of files to download.
612 $fs = get_file_storage();
613 $filelist = array();
614 foreach ($records as $issued) {
615 $badge = new badge($issued->badgeid);
616 // Need to make image name user-readable and unique using filename safe characters.
617 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
618 $name = str_replace(' ', '_', $name);
d77a6026 619 $name = clean_param($name, PARAM_FILE);
27806552
YB
620 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
621 $filelist[$name . '.png'] = $file;
622 }
623 }
624
625 // Zip files and sent them to a user.
626 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
627 $zipper = new zip_packer();
628 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
629 send_temp_file($tempzip, 'badges.zip');
630 } else {
62fef3cf
YB
631 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
632 die;
27806552
YB
633 }
634}
635
27806552
YB
636/**
637 * Checks if badges can be pushed to external backpack.
638 *
639 * @return string Code of backpack accessibility status.
640 */
641function badges_check_backpack_accessibility() {
389aad6e
AN
642 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
643 // For behat sites, do not poll the remote badge site.
644 // Behat sites should not be available, but we should pretend as though they are.
645 return 'available';
646 }
647
aae219ac
DW
648 if (badges_open_badges_backpack_api() == OPEN_BADGES_V2) {
649 return 'available';
650 }
651
27806552
YB
652 global $CFG;
653 include_once $CFG->libdir . '/filelib.php';
654
655 // Using fake assertion url to check whether backpack can access the web site.
656 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
657
343534a8 658 // Curl request to backpack baker.
27806552
YB
659 $curl = new curl();
660 $options = array(
661 'FRESH_CONNECT' => true,
662 'RETURNTRANSFER' => true,
27806552 663 'HEADER' => 0,
dd4a197e 664 'CONNECTTIMEOUT' => 2,
27806552 665 );
7444ba74 666 // BADGE_BACKPACKURL and the "baker" API is deprecated and should never be used in future.
4d0ebdeb 667 $location = BADGE_BACKPACKURL . '/baker';
27806552
YB
668 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
669
670 $data = json_decode($out);
671 if (!empty($curl->error)) {
672 return 'curl-request-timeout';
673 } else {
674 if (isset($data->code) && $data->code == 'http-unreachable') {
675 return 'http-unreachable';
676 } else {
677 return 'available';
678 }
679 }
680
681 return false;
682}
e2805314
YB
683
684/**
685 * Checks if user has external backpack connected.
686 *
687 * @param int $userid ID of a user.
688 * @return bool True|False whether backpack connection exists.
689 */
690function badges_user_has_backpack($userid) {
691 global $DB;
692 return $DB->record_exists('badge_backpack', array('userid' => $userid));
693}
7deff81f
YB
694
695/**
696 * Handles what happens to the course badges when a course is deleted.
697 *
698 * @param int $courseid course ID.
699 * @return void.
700 */
701function badges_handle_course_deletion($courseid) {
702 global $CFG, $DB;
703 include_once $CFG->libdir . '/filelib.php';
704
705 $systemcontext = context_system::instance();
706 $coursecontext = context_course::instance($courseid);
707 $fs = get_file_storage();
708
709 // Move badges images to the system context.
710 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
711
712 // Get all course badges.
713 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
714 foreach ($badges as $badge) {
715 // Archive badges in this course.
716 $toupdate = new stdClass();
717 $toupdate->id = $badge->id;
718 $toupdate->type = BADGE_TYPE_SITE;
719 $toupdate->courseid = null;
720 $toupdate->status = BADGE_STATUS_ARCHIVED;
721 $DB->update_record('badge', $toupdate);
722 }
723}
2c910861
YB
724
725/**
726 * Loads JS files required for backpack support.
727 *
728 * @uses $CFG, $PAGE
729 * @return void
730 */
731function badges_setup_backpack_js() {
732 global $CFG, $PAGE;
733 if (!empty($CFG->badges_allowexternalbackpack)) {
aae219ac
DW
734 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
735 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
7444ba74 736 // The issuer.js API is deprecated and should not be used in future.
aae219ac 737 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
7444ba74 738 // The backpack.js file is deprecated and should not be used in future.
aae219ac
DW
739 $PAGE->requires->js('/badges/backpack.js', true);
740 }
2c910861
YB
741 }
742}
43f1c8e2 743
aae219ac
DW
744/**
745 * No js files are required for backpack support.
746 * This only exists to directly support the custom V1 backpack api.
747 *
748 * @param boolean $checksite Call check site function.
749 * @return void
750 */
751function badges_local_backpack_js($checksite = false) {
752 global $CFG, $PAGE;
753 if (!empty($CFG->badges_allowexternalbackpack)) {
754 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
755 $PAGE->requires->js('/badges/backpack.js', true);
756 if ($checksite) {
757 $PAGE->requires->js_init_call('check_site_access', null, false);
758 }
759 }
760 }
761}
762
763/**
764 * Create the backpack with this data.
765 *
766 * @param stdClass $data The new backpack data.
767 * @return boolean
768 */
769function badges_create_site_backpack($data) {
770 global $DB;
771 $context = context_system::instance();
772 require_capability('moodle/badges:manageglobalsettings', $context);
773
774 $count = $DB->count_records('badge_external_backpack');
775
776 $backpack = new stdClass();
777 $backpack->apiversion = $data->apiversion;
778 $backpack->backpackapiurl = $data->backpackapiurl;
779 $backpack->backpackweburl = $data->backpackweburl;
780 $backpack->sortorder = $count;
781 $DB->insert_record('badge_external_backpack', $backpack);
782 return true;
783}
784
785/**
786 * Update the backpack with this id.
787 *
788 * @param integer $id The backpack to edit
789 * @param stdClass $data The new backpack data.
790 * @return boolean
791 */
792function badges_update_site_backpack($id, $data) {
793 global $DB;
794 $context = context_system::instance();
795 require_capability('moodle/badges:manageglobalsettings', $context);
796
797 if ($backpack = badges_get_site_backpack($id)) {
798 $backpack = new stdClass();
799 $backpack->id = $id;
800 $backpack->apiversion = $data->apiversion;
801 $backpack->backpackweburl = $data->backpackweburl;
802 $backpack->backpackapiurl = $data->backpackapiurl;
803 $backpack->password = $data->password;
804 $DB->update_record('badge_external_backpack', $backpack);
805 return true;
806 }
807 return false;
808}
809
810/**
811 * Is any backpack enabled that supports open badges V1?
812 * @return boolean
813 */
814function badges_open_badges_backpack_api() {
815 global $CFG;
816
817 $backpack = badges_get_site_backpack($CFG->badges_site_backpack);
818
819 if (empty($backpack->apiversion)) {
820 return OPEN_BADGES_V2;
821 }
822 return $backpack->apiversion;
823}
824
825/**
826 * Get a site backpacks by id or url.
827 *
828 * @param int $id The backpack id.
aae219ac
DW
829 * @return array(stdClass)
830 */
7444ba74 831function badges_get_site_backpack($id) {
aae219ac
DW
832 global $DB;
833
7444ba74 834 return $DB->get_record('badge_external_backpack', ['id' => $id]);
aae219ac
DW
835}
836
837/**
838 * List the backpacks at site level.
839 *
840 * @return array(stdClass)
841 */
842function badges_get_site_backpacks() {
843 global $DB, $CFG;
844
845 $all = $DB->get_records('badge_external_backpack');
846
847 foreach ($all as $key => $bp) {
848 if ($bp->id == $CFG->badges_site_backpack) {
849 $all[$key]->sitebackpack = true;
850 } else {
851 $all[$key]->sitebackpack = false;
852 }
853 }
854 return $all;
855}
856
857/**
858 * List the supported badges api versions.
859 *
860 * @return array(version)
861 */
862function badges_get_badge_api_versions() {
863 return [
864 OPEN_BADGES_V1 => get_string('openbadgesv1', 'badges'),
865 OPEN_BADGES_V2 => get_string('openbadgesv2', 'badges')
866 ];
867}
868
aae219ac
DW
869/**
870 * Get the default issuer for a badge from this site.
871 *
872 * @return array
873 */
874function badges_get_default_issuer() {
c659b1c5 875 global $CFG, $SITE;
aae219ac
DW
876
877 $issuer = array();
2f45b6f7 878 $issuerurl = new moodle_url('/');
aae219ac 879 $issuer['name'] = $CFG->badges_defaultissuername;
c659b1c5
DW
880 if (empty($issuer['name'])) {
881 $issuer['name'] = $SITE->fullname ? $SITE->fullname : $SITE->shortname;
882 }
7444ba74 883 $issuer['url'] = $issuerurl->out(false);
aae219ac
DW
884 $issuer['email'] = $CFG->badges_defaultissuercontact;
885 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
2f45b6f7
SA
886 $issuerid = new moodle_url('/badges/issuer_json.php');
887 $issuer['id'] = $issuerid->out(false);
aae219ac
DW
888 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
889 return $issuer;
890}
891
892/**
893 * Disconnect from the user backpack by deleting the user preferences.
894 *
895 * @param integer $userid The user to diconnect.
896 * @return boolean
897 */
898function badges_disconnect_user_backpack($userid) {
899 global $USER;
900
901 // We can only change backpack settings for our own real backpack.
902 if ($USER->id != $userid ||
903 \core\session\manager::is_loggedinas()) {
904
905 return false;
906 }
907
908 unset_user_preference('badges_email_verify_secret');
909 unset_user_preference('badges_email_verify_address');
910 unset_user_preference('badges_email_verify_backpackid');
911 unset_user_preference('badges_email_verify_password');
912
913 return true;
914}
915
916/**
917 * Used to remember which objects we connected with a backpack before.
918 *
919 * @param integer $sitebackpackid The site backpack to connect to.
920 * @param string $type The type of this remote object.
921 * @param string $internalid The id for this object on the Moodle site.
922 * @return mixed The id or false if it doesn't exist.
923 */
924function badges_external_get_mapping($sitebackpackid, $type, $internalid) {
925 global $DB;
926 // Return externalid if it exists.
927 $params = [
928 'sitebackpackid' => $sitebackpackid,
929 'type' => $type,
930 'internalid' => $internalid
931 ];
932
933 $record = $DB->get_record('badge_external_identifier', $params, 'externalid', IGNORE_MISSING);
934 if ($record) {
935 return $record->externalid;
936 }
937 return false;
938}
939
940/**
941 * Save the info about which objects we connected with a backpack before.
942 *
943 * @param integer $sitebackpackid The site backpack to connect to.
944 * @param string $type The type of this remote object.
945 * @param string $internalid The id for this object on the Moodle site.
946 * @param string $externalid The id of this object on the remote site.
947 * @return boolean
948 */
949function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
950 global $DB;
951
952 $params = [
953 'sitebackpackid' => $sitebackpackid,
954 'type' => $type,
955 'internalid' => $internalid,
956 'externalid' => $externalid
957 ];
958
959 return $DB->insert_record('badge_external_identifier', $params);
960}
961
962/**
963 * Delete all external mapping information for a backpack.
964 *
965 * @param integer $sitebackpackid The site backpack to connect to.
966 * @return boolean
967 */
968function badges_external_delete_mappings($sitebackpackid) {
969 global $DB;
970
971 $params = ['sitebackpackid' => $sitebackpackid];
972
973 return $DB->delete_records('badge_external_identifier', $params);
974}
975
976/**
977 * Delete a specific external mapping information for a backpack.
978 *
979 * @param integer $sitebackpackid The site backpack to connect to.
980 * @param string $type The type of this remote object.
981 * @param string $internalid The id for this object on the Moodle site.
982 * @return boolean
983 */
984function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
985 global $DB;
986
987 $params = [
988 'sitebackpackid' => $sitebackpackid,
989 'type' => $type,
990 'internalid' => $internalid
991 ];
992
993 $DB->delete_record('badge_external_identifier', $params);
994}
995
996/**
997 * Create and send a verification email to the email address supplied.
998 *
999 * Since we're not sending this email to a user, email_to_user can't be used
1000 * but this function borrows largely the code from that process.
1001 *
1002 * @param string $email the email address to send the verification email to.
1003 * @param int $backpackid the id of the backpack to connect to
1837b1d5 1004 * @param string $backpackpassword the user entered password to connect to this backpack
aae219ac
DW
1005 * @return true if the email was sent successfully, false otherwise.
1006 */
1007function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1008 global $DB, $USER;
1009
1010 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1011 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1012 // of verification emails to said address.
1013 $secret = random_string(15);
1014 set_user_preference('badges_email_verify_secret', $secret);
1015 set_user_preference('badges_email_verify_address', $email);
1016 set_user_preference('badges_email_verify_backpackid', $backpackid);
1017 set_user_preference('badges_email_verify_password', $backpackpassword);
1018
1019 // To, from.
1020 $tempuser = $DB->get_record('user', array('id' => $USER->id), '*', MUST_EXIST);
1021 $tempuser->email = $email;
1022 $noreplyuser = core_user::get_noreply_user();
1023
1024 // Generate the verification email body.
1025 $verificationurl = '/badges/backpackemailverify.php';
1026 $verificationurl = new moodle_url($verificationurl);
1027 $verificationpath = $verificationurl->out(false);
1028
1029 $site = get_site();
1030 $args = new stdClass();
1031 $args->link = $verificationpath . '?data='. $secret;
1032 $args->sitename = $site->fullname;
1033 $args->admin = generate_email_signoff();
1034
1035 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname);
1036 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1037 $messagehtml = text_to_html($messagetext, false, false, true);
1038
1039 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1040}
1041
43f1c8e2
DW
1042/**
1043 * Return all the enabled criteria types for this site.
1044 *
8aff6f6f 1045 * @param boolean $enabled
43f1c8e2
DW
1046 * @return array
1047 */
1048function badges_list_criteria($enabled = true) {
1049 global $CFG;
1050
1051 $types = array(
1052 BADGE_CRITERIA_TYPE_OVERALL => 'overall',
1053 BADGE_CRITERIA_TYPE_ACTIVITY => 'activity',
1054 BADGE_CRITERIA_TYPE_MANUAL => 'manual',
1055 BADGE_CRITERIA_TYPE_SOCIAL => 'social',
1056 BADGE_CRITERIA_TYPE_COURSE => 'course',
1057 BADGE_CRITERIA_TYPE_COURSESET => 'courseset',
1058 BADGE_CRITERIA_TYPE_PROFILE => 'profile',
1059 BADGE_CRITERIA_TYPE_BADGE => 'badge',
1060 BADGE_CRITERIA_TYPE_COHORT => 'cohort',
1061 BADGE_CRITERIA_TYPE_COMPETENCY => 'competency',
1062 );
1063 if ($enabled) {
1064 foreach ($types as $key => $type) {
1065 $class = 'award_criteria_' . $type;
1066 $file = $CFG->dirroot . '/badges/criteria/' . $class . '.php';
1067 if (file_exists($file)) {
1068 require_once($file);
1069
1070 if (!$class::is_enabled()) {
1071 unset($types[$key]);
1072 }
1073 }
1074 }
1075 }
1076 return $types;
1077}
f44557d0
DW
1078
1079/**
1080 * Check if any badge has records for competencies.
1081 *
1082 * @param array $competencyids Array of competencies ids.
1083 * @return boolean Return true if competencies were found in any badge.
1084 */
1085function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1086 global $DB;
1087
1088 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED);
1089
1090 $sql = "SELECT DISTINCT bc.badgeid
1091 FROM {badge_criteria} bc
1092 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1093 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1094 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY;
1095
1096 return $DB->record_exists_sql($sql, $params);
1097}
dabc69af 1098
7c36d669
SL
1099/**
1100 * Creates single message for all notification and sends it out
1101 *
1102 * @param object $badge A badge which is notified about.
1103 */
1104function badge_assemble_notification(stdClass $badge) {
1105 global $DB;
1106
1107 $userfrom = core_user::get_noreply_user();
1108 $userfrom->maildisplay = true;
1109
1110 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id))) {
1111 // Get badge creator.
1112 $creator = $DB->get_record('user', array('id' => $badge->creator), '*', MUST_EXIST);
1113 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1114 $creatormessage = '';
1115
1116 // Put all messages in one digest.
1117 foreach ($msgs as $msg) {
1118 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash)), $badge->name);
1119 $recipient = $DB->get_record('user', array('id' => $msg->userid), '*', MUST_EXIST);
1120
1121 $a = new stdClass();
1122 $a->user = fullname($recipient);
1123 $a->link = $issuedlink;
1124 $creatormessage .= get_string('creatorbody', 'badges', $a);
1125 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid, 'userid' => $msg->userid));
1126 }
1127
1128 // Create a message object.
1129 $eventdata = new \core\message\message();
1130 $eventdata->courseid = SITEID;
1131 $eventdata->component = 'moodle';
1132 $eventdata->name = 'badgecreatornotice';
1133 $eventdata->userfrom = $userfrom;
1134 $eventdata->userto = $creator;
1135 $eventdata->notification = 1;
1136 $eventdata->subject = $creatorsubject;
1137 $eventdata->fullmessage = format_text_email($creatormessage, FORMAT_HTML);
1138 $eventdata->fullmessageformat = FORMAT_PLAIN;
1139 $eventdata->fullmessagehtml = $creatormessage;
1140 $eventdata->smallmessage = $creatorsubject;
1141
1142 message_send($eventdata);
1143 }
1144}
d48a52dd
DW
1145
1146/**
1147 * Attempt to authenticate with the site backpack credentials and return an error
2fe34536
DW
1148 * if the authentication fails. If external backpacks are not enabled, this will
1149 * not perform any test.
d48a52dd
DW
1150 *
1151 * @return string
1152 */
1153function badges_verify_site_backpack() {
1154 global $OUTPUT, $CFG;
1155
1156 if (empty($CFG->badges_allowexternalbackpack)) {
1157 return '';
1158 }
1159
1160 $backpack = badges_get_site_backpack($CFG->badges_site_backpack);
1161
1162 if (empty($backpack->apiversion) || ($backpack->apiversion == OPEN_BADGES_V2)) {
1163 $backpackapi = new \core_badges\backpack_api($backpack);
1164
2fe34536
DW
1165 // Clear any cached access tokens in the session.
1166 $backpackapi->clear_system_user_session();
1167
1168 // Now attempt a login with these credentials.
d48a52dd 1169 $result = $backpackapi->authenticate();
084a42f9 1170 if (empty($result) || !empty($result->error)) {
d48a52dd
DW
1171 $warning = $backpackapi->get_authentication_error();
1172
1173 $params = ['id' => $backpack->id, 'action' => 'edit'];
1174 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1175
1176 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1177 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1178 return $OUTPUT->container($icon . $message, 'text-error');
1179 }
1180 }
1181 return '';
1182}