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