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