MDL-58454 badges: Open Badges Specification Version 2.0 Changes
[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
YB
96/*
97 * URL of backpack. Currently only the Open Badges backpack is supported.
98 */
4d0ebdeb 99define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
343534a8 100
d363a5c2
TT
101/*
102 * Only use for Open Badges 2.0 specification
103 */
104define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
105define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
106define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
107define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
108define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
109define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
110
27806552
YB
111/**
112 * Class that represents badge.
113 *
114 */
115class badge {
116 /** @var int Badge id */
117 public $id;
118
119 /** Values from the table 'badge' */
120 public $name;
121 public $description;
122 public $timecreated;
123 public $timemodified;
124 public $usercreated;
125 public $usermodified;
27806552
YB
126 public $issuername;
127 public $issuerurl;
128 public $issuercontact;
129 public $expiredate;
130 public $expireperiod;
131 public $type;
132 public $courseid;
133 public $message;
134 public $messagesubject;
135 public $attachment;
136 public $notification;
137 public $status = 0;
138 public $nextcron;
139
d363a5c2
TT
140 /** @var string control version of badge */
141 public $version;
142
143 /** @var string language code */
144 public $language;
145
146 /** @var string name image author */
147 public $imageauthorname;
148
149 /** @var string email image author */
150 public $imageauthoremail;
151
152 /** @var string url image author */
153 public $imageauthorurl;
154
155 /** @var string image caption */
156 public $imagecaption;
157
27806552
YB
158 /** @var array Badge criteria */
159 public $criteria = array();
160
161 /**
162 * Constructs with badge details.
163 *
164 * @param int $badgeid badge ID.
165 */
166 public function __construct($badgeid) {
167 global $DB;
168 $this->id = $badgeid;
169
170 $data = $DB->get_record('badge', array('id' => $badgeid));
171
172 if (empty($data)) {
173 print_error('error:nosuchbadge', 'badges', $badgeid);
174 }
175
176 foreach ((array)$data as $field => $value) {
177 if (property_exists($this, $field)) {
178 $this->{$field} = $value;
179 }
180 }
181
182 $this->criteria = self::get_criteria();
183 }
184
185 /**
186 * Use to get context instance of a badge.
187 * @return context instance.
188 */
189 public function get_context() {
190 if ($this->type == BADGE_TYPE_SITE) {
191 return context_system::instance();
192 } else if ($this->type == BADGE_TYPE_COURSE) {
193 return context_course::instance($this->courseid);
194 } else {
195 debugging('Something is wrong...');
196 }
197 }
198
199 /**
200 * Return array of aggregation methods
201 * @return array
202 */
203 public static function get_aggregation_methods() {
204 return array(
205 BADGE_CRITERIA_AGGREGATION_ALL => get_string('all', 'badges'),
206 BADGE_CRITERIA_AGGREGATION_ANY => get_string('any', 'badges'),
207 );
208 }
209
210 /**
211 * Return array of accepted criteria types for this badge
212 * @return array
213 */
214 public function get_accepted_criteria() {
215 $criteriatypes = array();
216
217 if ($this->type == BADGE_TYPE_COURSE) {
218 $criteriatypes = array(
219 BADGE_CRITERIA_TYPE_OVERALL,
220 BADGE_CRITERIA_TYPE_MANUAL,
221 BADGE_CRITERIA_TYPE_COURSE,
a7370e0d 222 BADGE_CRITERIA_TYPE_BADGE,
27806552
YB
223 BADGE_CRITERIA_TYPE_ACTIVITY
224 );
225 } else if ($this->type == BADGE_TYPE_SITE) {
226 $criteriatypes = array(
227 BADGE_CRITERIA_TYPE_OVERALL,
228 BADGE_CRITERIA_TYPE_MANUAL,
229 BADGE_CRITERIA_TYPE_COURSESET,
a7370e0d 230 BADGE_CRITERIA_TYPE_BADGE,
27806552 231 BADGE_CRITERIA_TYPE_PROFILE,
abc07b53 232 BADGE_CRITERIA_TYPE_COHORT,
27806552
YB
233 );
234 }
235
236 return $criteriatypes;
237 }
238
239 /**
240 * Save/update badge information in 'badge' table only.
241 * Cannot be used for updating awards and criteria settings.
242 *
243 * @return bool Returns true on success.
244 */
245 public function save() {
246 global $DB;
247
248 $fordb = new stdClass();
249 foreach (get_object_vars($this) as $k => $v) {
250 $fordb->{$k} = $v;
251 }
252 unset($fordb->criteria);
253
254 $fordb->timemodified = time();
255 if ($DB->update_record_raw('badge', $fordb)) {
a0e13871
SB
256 // Trigger event, badge updated.
257 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
258 $event = \core\event\badge_updated::create($eventparams);
259 $event->trigger();
27806552
YB
260 return true;
261 } else {
262 throw new moodle_exception('error:save', 'badges');
263 return false;
264 }
265 }
266
267 /**
268 * Creates and saves a clone of badge with all its properties.
269 * Clone is not active by default and has 'Copy of' attached to its name.
270 *
271 * @return int ID of new badge.
272 */
273 public function make_clone() {
a0e13871 274 global $DB, $USER, $PAGE;
27806552
YB
275
276 $fordb = new stdClass();
277 foreach (get_object_vars($this) as $k => $v) {
278 $fordb->{$k} = $v;
279 }
280
281 $fordb->name = get_string('copyof', 'badges', $this->name);
282 $fordb->status = BADGE_STATUS_INACTIVE;
27806552
YB
283 $fordb->usercreated = $USER->id;
284 $fordb->usermodified = $USER->id;
285 $fordb->timecreated = time();
286 $fordb->timemodified = time();
287 unset($fordb->id);
288
289 if ($fordb->notification > 1) {
290 $fordb->nextcron = badges_calculate_message_schedule($fordb->notification);
291 }
292
293 $criteria = $fordb->criteria;
294 unset($fordb->criteria);
295
296 if ($new = $DB->insert_record('badge', $fordb, true)) {
297 $newbadge = new badge($new);
298
299 // Copy badge image.
300 $fs = get_file_storage();
301 if ($file = $fs->get_file($this->get_context()->id, 'badges', 'badgeimage', $this->id, '/', 'f1.png')) {
302 if ($imagefile = $file->copy_content_to_temp()) {
303 badges_process_badge_image($newbadge, $imagefile);
304 }
305 }
306
307 // Copy badge criteria.
308 foreach ($this->criteria as $crit) {
309 $crit->make_clone($new);
310 }
311
a0e13871
SB
312 // Trigger event, badge duplicated.
313 $eventparams = array('objectid' => $new, 'context' => $PAGE->context);
314 $event = \core\event\badge_duplicated::create($eventparams);
315 $event->trigger();
316
27806552
YB
317 return $new;
318 } else {
319 throw new moodle_exception('error:clone', 'badges');
320 return false;
321 }
322 }
323
324 /**
325 * Checks if badges is active.
326 * Used in badge award.
327 *
328 * @return bool A status indicating badge is active
329 */
330 public function is_active() {
331 if (($this->status == BADGE_STATUS_ACTIVE) ||
332 ($this->status == BADGE_STATUS_ACTIVE_LOCKED)) {
333 return true;
334 }
335 return false;
336 }
337
338 /**
339 * Use to get the name of badge status.
340 *
341 */
342 public function get_status_name() {
343 return get_string('badgestatus_' . $this->status, 'badges');
344 }
345
346 /**
347 * Use to set badge status.
348 * Only active badges can be earned/awarded/issued.
349 *
350 * @param int $status Status from BADGE_STATUS constants
351 */
352 public function set_status($status = 0) {
353 $this->status = $status;
354 $this->save();
a0e13871
SB
355 if ($status == BADGE_STATUS_ACTIVE) {
356 // Trigger event, badge enabled.
357 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
358 $event = \core\event\badge_enabled::create($eventparams);
359 $event->trigger();
360 } else if ($status == BADGE_STATUS_INACTIVE) {
361 // Trigger event, badge disabled.
362 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
363 $event = \core\event\badge_disabled::create($eventparams);
364 $event->trigger();
365 }
27806552
YB
366 }
367
368 /**
369 * Checks if badges is locked.
370 * Used in badge award and editing.
371 *
372 * @return bool A status indicating badge is locked
373 */
374 public function is_locked() {
375 if (($this->status == BADGE_STATUS_ACTIVE_LOCKED) ||
376 ($this->status == BADGE_STATUS_INACTIVE_LOCKED)) {
377 return true;
378 }
379 return false;
380 }
381
382 /**
383 * Checks if badge has been awarded to users.
384 * Used in badge editing.
385 *
386 * @return bool A status indicating badge has been awarded at least once
387 */
388 public function has_awards() {
389 global $DB;
e477ec0a
YB
390 $awarded = $DB->record_exists_sql('SELECT b.uniquehash
391 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
392 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
393
394 return $awarded;
27806552
YB
395 }
396
397 /**
398 * Gets list of users who have earned an instance of this badge.
399 *
400 * @return array An array of objects with information about badge awards.
401 */
402 public function get_awards() {
403 global $DB;
404
405 $awards = $DB->get_records_sql(
406 'SELECT b.userid, b.dateissued, b.uniquehash, u.firstname, u.lastname
407 FROM {badge_issued} b INNER JOIN {user} u
408 ON b.userid = u.id
7f964cfd 409 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
27806552
YB
410
411 return $awards;
412 }
413
414 /**
415 * Indicates whether badge has already been issued to a user.
416 *
417 */
418 public function is_issued($userid) {
419 global $DB;
420 return $DB->record_exists('badge_issued', array('badgeid' => $this->id, 'userid' => $userid));
421 }
422
423 /**
424 * Issue a badge to user.
425 *
426 * @param int $userid User who earned the badge
427 * @param bool $nobake Not baking actual badges (for testing purposes)
428 */
429 public function issue($userid, $nobake = false) {
430 global $DB, $CFG;
431
432 $now = time();
433 $issued = new stdClass();
434 $issued->badgeid = $this->id;
435 $issued->userid = $userid;
436 $issued->uniquehash = sha1(rand() . $userid . $this->id . $now);
437 $issued->dateissued = $now;
438
439 if ($this->can_expire()) {
440 $issued->dateexpire = $this->calculate_expiry($now);
441 } else {
442 $issued->dateexpire = null;
443 }
444
e2805314
YB
445 // Take into account user badges privacy settings.
446 // If none set, badges default visibility is set to public.
447 $issued->visible = get_user_preferences('badgeprivacysetting', 1, $userid);
27806552
YB
448
449 $result = $DB->insert_record('badge_issued', $issued, true);
450
451 if ($result) {
483cfd76 452 // Trigger badge awarded event.
4ae5ecbe
SL
453 $eventdata = array (
454 'context' => $this->get_context(),
455 'objectid' => $this->id,
456 'relateduserid' => $userid,
2ec274f5 457 'other' => array('dateexpire' => $issued->dateexpire, 'badgeissuedid' => $result)
4ae5ecbe
SL
458 );
459 \core\event\badge_awarded::create($eventdata)->trigger();
483cfd76 460
27806552
YB
461 // Lock the badge, so that its criteria could not be changed any more.
462 if ($this->status == BADGE_STATUS_ACTIVE) {
463 $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
464 }
465
466 // Update details in criteria_met table.
467 $compl = $this->get_criteria_completions($userid);
468 foreach ($compl as $c) {
469 $obj = new stdClass();
470 $obj->id = $c->id;
471 $obj->issuedid = $result;
472 $DB->update_record('badge_criteria_met', $obj, true);
473 }
474
475 if (!$nobake) {
476 // Bake a badge image.
477 $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
478
479 // Notify recipients and badge creators.
f007e899 480 badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
27806552
YB
481 }
482 }
483 }
484
485 /**
486 * Reviews all badge criteria and checks if badge can be instantly awarded.
487 *
488 * @return int Number of awards
489 */
490 public function review_all_criteria() {
491 global $DB, $CFG;
492 $awards = 0;
493
494 // Raise timelimit as this could take a while for big web sites.
3ef7279f 495 core_php_time_limit::raise();
27806552
YB
496 raise_memory_limit(MEMORY_HUGE);
497
c8d2f392
YB
498 foreach ($this->criteria as $crit) {
499 // Overall criterion is decided when other criteria are reviewed.
500 if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
501 continue;
502 }
503
504 list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
505 // For site level badges, get all active site users who can earn this badge and haven't got it yet.
506 if ($this->type == BADGE_TYPE_SITE) {
507 $sql = "SELECT DISTINCT u.id, bi.badgeid
27806552 508 FROM {user} u
c8d2f392 509 {$extrajoin}
27806552
YB
510 LEFT JOIN {badge_issued} bi
511 ON u.id = bi.userid AND bi.badgeid = :badgeid
c8d2f392
YB
512 WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
513 $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
514 $toearn = $DB->get_fieldset_sql($sql, $params);
515 } else {
516 // For course level badges, get all users who already earned the badge in this course.
517 // Then find the ones who are enrolled in the course and don't have a badge yet.
518 $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
519 $wheresql = '';
520 $earnedparams = array();
521 if (!empty($earned)) {
522 list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
523 $wheresql = ' WHERE u.id ' . $earnedsql;
524 }
525 list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
5f92c736 526 $sql = "SELECT DISTINCT u.id
c8d2f392
YB
527 FROM {user} u
528 {$extrajoin}
529 JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
530 $params = array_merge($enrolledparams, $earnedparams, $extraparams);
531 $toearn = $DB->get_fieldset_sql($sql, $params);
532 }
27806552 533
c8d2f392
YB
534 foreach ($toearn as $uid) {
535 $reviewoverall = false;
536 if ($crit->review($uid, true)) {
537 $crit->mark_complete($uid);
538 if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
539 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
540 $this->issue($uid);
541 $awards++;
27806552 542 } else {
c8d2f392 543 $reviewoverall = true;
27806552 544 }
c8d2f392
YB
545 } else {
546 // Will be reviewed some other time.
547 $reviewoverall = false;
548 }
549 // Review overall if it is required.
550 if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
551 $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
552 $this->issue($uid);
553 $awards++;
27806552 554 }
27806552
YB
555 }
556 }
557
558 return $awards;
559 }
560
561 /**
562 * Gets an array of completed criteria from 'badge_criteria_met' table.
563 *
564 * @param int $userid Completions for a user
565 * @return array Records of criteria completions
566 */
567 public function get_criteria_completions($userid) {
568 global $DB;
569 $completions = array();
570 $sql = "SELECT bcm.id, bcm.critid
571 FROM {badge_criteria_met} bcm
572 INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
573 WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
574 $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
575
576 return $completions;
577 }
578
579 /**
580 * Checks if badges has award criteria set up.
581 *
582 * @return bool A status indicating badge has at least one criterion
583 */
584 public function has_criteria() {
585 if (count($this->criteria) > 0) {
586 return true;
587 }
588 return false;
589 }
590
591 /**
592 * Returns badge award criteria
593 *
594 * @return array An array of badge criteria
595 */
596 public function get_criteria() {
597 global $DB;
598 $criteria = array();
599
600 if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
601 foreach ($records as $record) {
602 $criteria[$record->criteriatype] = award_criteria::build((array)$record);
603 }
604 }
605
606 return $criteria;
607 }
608
609 /**
610 * Get aggregation method for badge criteria
611 *
612 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
613 * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
614 */
615 public function get_aggregation_method($criteriatype = 0) {
616 global $DB;
617 $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
618 $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
619
620 if (!$aggregation) {
621 return BADGE_CRITERIA_AGGREGATION_ALL;
622 }
623
624 return $aggregation;
625 }
626
627 /**
628 * Checks if badge has expiry period or date set up.
629 *
630 * @return bool A status indicating badge can expire
631 */
632 public function can_expire() {
633 if ($this->expireperiod || $this->expiredate) {
634 return true;
635 }
636 return false;
637 }
638
639 /**
640 * Calculates badge expiry date based on either expirydate or expiryperiod.
641 *
642 * @param int $timestamp Time of badge issue
643 * @return int A timestamp
644 */
645 public function calculate_expiry($timestamp) {
646 $expiry = null;
647
648 if (isset($this->expiredate)) {
649 $expiry = $this->expiredate;
650 } else if (isset($this->expireperiod)) {
651 $expiry = $timestamp + $this->expireperiod;
652 }
653
654 return $expiry;
655 }
656
657 /**
658 * Checks if badge has manual award criteria set.
659 *
660 * @return bool A status indicating badge can be awarded manually
661 */
662 public function has_manual_award_criteria() {
663 foreach ($this->criteria as $criterion) {
664 if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
665 return true;
666 }
667 }
668 return false;
669 }
670
671 /**
455d13b7
YB
672 * Fully deletes the badge or marks it as archived.
673 *
674 * @param $archive bool Achive a badge without actual deleting of any data.
27806552 675 */
455d13b7
YB
676 public function delete($archive = true) {
677 global $DB;
678
679 if ($archive) {
680 $this->status = BADGE_STATUS_ARCHIVED;
681 $this->save();
a0e13871
SB
682
683 // Trigger event, badge archived.
684 $eventparams = array('objectid' => $this->id, 'context' => $this->get_context());
685 $event = \core\event\badge_archived::create($eventparams);
686 $event->trigger();
455d13b7
YB
687 return;
688 }
689
690 $fs = get_file_storage();
691
692 // Remove all issued badge image files and badge awards.
693 // Cannot bulk remove area files here because they are issued in user context.
694 $awards = $this->get_awards();
695 foreach ($awards as $award) {
696 $usercontext = context_user::instance($award->userid);
697 $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
698 }
699 $DB->delete_records('badge_issued', array('badgeid' => $this->id));
700
701 // Remove all badge criteria.
702 $criteria = $this->get_criteria();
703 foreach ($criteria as $criterion) {
704 $criterion->delete();
705 }
706
707 // Delete badge images.
708 $badgecontext = $this->get_context();
709 $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
710
711 // Finally, remove badge itself.
712 $DB->delete_records('badge', array('id' => $this->id));
a0e13871
SB
713
714 // Trigger event, badge deleted.
715 $eventparams = array('objectid' => $this->id,
716 'context' => $this->get_context(),
717 'other' => array('badgetype' => $this->type, 'courseid' => $this->courseid)
718 );
719 $event = \core\event\badge_deleted::create($eventparams);
720 $event->trigger();
27806552 721 }
d363a5c2
TT
722
723 /**
724 * Add multiple related badges.
725 *
726 * @param array $relatedids Id of badges.
727 */
728 public function add_related_badges($relatedids) {
729 global $DB;
730 $relatedbadges = array();
731 foreach ($relatedids as $relatedid) {
732 $relatedbadge = new stdClass();
733 $relatedbadge->badgeid = $this->id;
734 $relatedbadge->relatedbadgeid = $relatedid;
735 $relatedbadges[] = $relatedbadge;
736 }
737 $DB->insert_records('badge_related', $relatedbadges);
738 }
739
740 /**
741 * Delete an related badge.
742 *
743 * @param int $relatedid Id related badge.
744 * @return bool A status for delete an related badge.
745 */
746 public function delete_related_badge($relatedid) {
747 global $DB;
748 return $DB->delete_records('badge_related', array('badgeid' => $this->id, 'relatedbadgeid' => $relatedid));
749 }
750
751 /**
752 * Checks if badge has related badges.
753 *
754 * @return bool A status related badge.
755 */
756 public function has_related() {
757 global $DB;
758 return $DB->record_exists('badge_related', array('badgeid' => $this->id));
759 }
760
761 /**
762 * Get related badges of badge.
763 *
764 * @param bool $activeonly Do not get the inactive badges when is true.
765 * @return array Related badges information.
766 */
767 public function get_related_badges(bool $activeonly = false) {
768 global $DB;
769
770 $params = array('badgeid' => $this->id);
771 $query = "SELECT b.id, b.name, b.version, b.language, b.type
772 FROM {badge_related} br
773 JOIN {badge} b ON b.id = br.relatedbadgeid
774 WHERE br.badgeid = :badgeid";
775 if ($activeonly) {
776 $query .= " AND b.status <> :status";
777 $params['status'] = BADGE_STATUS_INACTIVE;
778 }
779 $relatedbadges = $DB->get_records_sql($query, $params);
780 return $relatedbadges;
781 }
782
783 /**
784 * Insert/update competency alignment information of badge.
785 *
786 * @param stdClass $alignment Data of a competency alignment.
787 * @param int $alignmentid ID competency alignment.
788 * @return bool|int A status/ID when insert or update data.
789 */
790 public function save_alignment($alignment, $alignmentid = 0) {
791 global $DB;
792
793 $record = $DB->record_exists('badge_competencies', array('id' => $alignmentid));
794 if ($record) {
795 $alignment->id = $alignmentid;
796 return $DB->update_record('badge_competencies', $alignment);
797 } else {
798 return $DB->insert_record('badge_competencies', $alignment, true);
799 }
800 }
801
802 /**
803 * Delete a competency alignment of badge.
804 *
805 * @param int $alignmentid ID competency alignment.
806 * @return bool A status for delete a competency alignment.
807 */
808 public function delete_alignment($alignmentid = 0) {
809 global $DB;
810 return $DB->delete_records('badge_competencies', array('id' => $alignmentid));
811 }
812
813 /**
814 * Get competencies of badge.
815 *
816 * @return array List content competencies.
817 */
818 public function get_alignment() {
819 global $DB;
820 return $DB->get_records('badge_competencies', array('badgeid' => $this->id));
821 }
822
823 /**
824 * Insert/update Endorsement information of badge.
825 *
826 * @param stdClass $endorsement Data of an endorsement.
827 * @return bool|int A status/ID when insert or update data.
828 */
829 public function save_endorsement($endorsement) {
830 global $DB;
831 $record = $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
832 if ($record) {
833 $endorsement->id = $record->id;
834 return $DB->update_record('badge_endorsement', $endorsement);
835 } else {
836 return $DB->insert_record('badge_endorsement', $endorsement, true);
837 }
838 }
839
840 /**
841 * Get endorsement of badge.
842 *
843 * @return array|stdClass Endorsement information.
844 */
845 public function get_endorsement() {
846 global $DB;
847 return $DB->get_record('badge_endorsement', array('badgeid' => $this->id));
848 }
849
850 /**
851 * Markdown language support for criteria.
852 *
853 * @return string $output Markdown content to output.
854 */
855 public function markdown_badge_criteria() {
856 $agg = $this->get_aggregation_methods();
857 if (empty($this->criteria)) {
858 return get_string('nocriteria', 'badges');
859 }
860 $overalldescr = '';
861 $overall = $this->criteria[BADGE_CRITERIA_TYPE_OVERALL];
862 if (!empty($overall->description)) {
863 $overalldescr = format_text($overall->description, $overall->descriptionformat,
864 array('context' => $this->get_context())) . '\n';
865 }
866 // Get the condition string.
867 if (count($this->criteria) == 2) {
868 $condition = get_string('criteria_descr', 'badges');
869 } else {
870 $condition = get_string('criteria_descr_' . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
871 core_text::strtoupper($agg[$this->get_aggregation_method()]));
872 }
873 unset($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
874 $items = array();
875 // If only one criterion left, make sure its description goe to the top.
876 if (count($this->criteria) == 1) {
877 $c = reset($this->criteria);
878 if (!empty($c->description)) {
879 $overalldescr = $c->description . '\n';
880 }
881 if (count($c->params) == 1) {
882 $items[] = ' * ' . get_string('criteria_descr_single_' . $c->criteriatype, 'badges') .
883 $c->get_details();
884 } else {
885 $items[] = '* ' . get_string('criteria_descr_' . $c->criteriatype, 'badges',
886 core_text::strtoupper($agg[$this->get_aggregation_method($c->criteriatype)])) .
887 $c->get_details();
888 }
889 } else {
890 foreach ($this->criteria as $type => $c) {
891 $criteriadescr = '';
892 if (!empty($c->description)) {
893 $criteriadescr = $c->description;
894 }
895 if (count($c->params) == 1) {
896 $items[] = ' * ' . get_string('criteria_descr_single_' . $type, 'badges') .
897 $c->get_details() . $criteriadescr;
898 } else {
899 $items[] = '* ' . get_string('criteria_descr_' . $type, 'badges',
900 core_text::strtoupper($agg[$this->get_aggregation_method($type)])) .
901 $c->get_details() . $criteriadescr;
902 }
903 }
904 }
905 return strip_tags($overalldescr . $condition . html_writer::alist($items, array(), 'ul'));
906 }
907
908 /**
909 * Define issuer information by format Open Badges specification version 2.
910 *
911 * @return array Issuer informations of the badge.
912 */
913 public function get_badge_issuer() {
914 $issuer = array();
915 $issuerurl = new moodle_url('/badges/badge_json.php', array('id' => $this->id, 'action' => 0));
916 $issuer['name'] = $this->issuername;
917 $issuer['url'] = $this->issuerurl;
918 $issuer['email'] = $this->issuercontact;
919 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
920 $issuer['id'] = $issuerurl->out(false);
921 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
922 return $issuer;
923 }
27806552
YB
924}
925
926/**
927 * Sends notifications to users about awarded badges.
928 *
929 * @param badge $badge Badge that was issued
930 * @param int $userid Recipient ID
931 * @param string $issued Unique hash of an issued badge
932 * @param string $filepathhash File path hash of an issued badge for attachments
933 */
934function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
935 global $CFG, $DB;
936
937 $admin = get_admin();
938 $userfrom = new stdClass();
939 $userfrom->id = $admin->id;
940 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
a327f25e
AG
941 foreach (get_all_user_name_fields() as $addname) {
942 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
943 }
27806552 944 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
27806552
YB
945 $userfrom->maildisplay = true;
946
947 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
948 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
949
950 $params = new stdClass();
951 $params->badgename = $badge->name;
952 $params->username = fullname($userto);
953 $params->badgelink = $issuedlink;
954 $message = badge_message_from_template($badge->message, $params);
1f258cd8 955 $plaintext = html_to_text($message);
27806552 956
f5d17c14 957 // Notify recipient.
cc350fd9 958 $eventdata = new \core\message\message();
f593e827 959 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
f5d17c14
YB
960 $eventdata->component = 'moodle';
961 $eventdata->name = 'badgerecipientnotice';
962 $eventdata->userfrom = $userfrom;
963 $eventdata->userto = $userto;
964 $eventdata->notification = 1;
965 $eventdata->subject = $badge->messagesubject;
966 $eventdata->fullmessage = $plaintext;
1f258cd8 967 $eventdata->fullmessageformat = FORMAT_HTML;
f5d17c14 968 $eventdata->fullmessagehtml = $message;
1f258cd8 969 $eventdata->smallmessage = '';
f5d17c14
YB
970
971 // Attach badge image if possible.
972 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
27806552
YB
973 $fs = get_file_storage();
974 $file = $fs->get_file_by_hash($filepathhash);
f5d17c14
YB
975 $eventdata->attachment = $file;
976 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
977
978 message_send($eventdata);
27806552 979 } else {
f5d17c14 980 message_send($eventdata);
27806552
YB
981 }
982
983 // Notify badge creator about the award if they receive notifications every time.
984 if ($badge->notification == 1) {
f5d17c14
YB
985 $userfrom = core_user::get_noreply_user();
986 $userfrom->maildisplay = true;
987
27806552
YB
988 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
989 $a = new stdClass();
990 $a->user = fullname($userto);
991 $a->link = $issuedlink;
992 $creatormessage = get_string('creatorbody', 'badges', $a);
993 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
994
cc350fd9
AD
995 $eventdata = new \core\message\message();
996 $eventdata->courseid = $badge->courseid;
27806552 997 $eventdata->component = 'moodle';
f5d17c14 998 $eventdata->name = 'badgecreatornotice';
27806552
YB
999 $eventdata->userfrom = $userfrom;
1000 $eventdata->userto = $creator;
1001 $eventdata->notification = 1;
1002 $eventdata->subject = $creatorsubject;
1f258cd8
YB
1003 $eventdata->fullmessage = html_to_text($creatormessage);
1004 $eventdata->fullmessageformat = FORMAT_HTML;
f5d17c14 1005 $eventdata->fullmessagehtml = $creatormessage;
1f258cd8 1006 $eventdata->smallmessage = '';
27806552
YB
1007
1008 message_send($eventdata);
1009 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
1010 }
1011}
1012
1013/**
1014 * Caclulates date for the next message digest to badge creators.
1015 *
1016 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
1017 * @return int Timestamp for next cron
1018 */
1019function badges_calculate_message_schedule($schedule) {
1020 $nextcron = 0;
1021
1022 switch ($schedule) {
1023 case BADGE_MESSAGE_DAILY:
1024 $nextcron = time() + 60 * 60 * 24;
1025 break;
1026 case BADGE_MESSAGE_WEEKLY:
1027 $nextcron = time() + 60 * 60 * 24 * 7;
1028 break;
1029 case BADGE_MESSAGE_MONTHLY:
1030 $nextcron = time() + 60 * 60 * 24 * 7 * 30;
1031 break;
1032 }
1033
1034 return $nextcron;
1035}
1036
1037/**
1038 * Replaces variables in a message template and returns text ready to be emailed to a user.
1039 *
1040 * @param string $message Message body.
1041 * @return string Message with replaced values
1042 */
1043function badge_message_from_template($message, $params) {
1044 $msg = $message;
1045 foreach ($params as $key => $value) {
1046 $msg = str_replace("%$key%", $value, $msg);
1047 }
1048
1049 return $msg;
1050}
1051
1052/**
1053 * Get all badges.
1054 *
1055 * @param int Type of badges to return
1056 * @param int Course ID for course badges
1057 * @param string $sort An SQL field to sort by
1058 * @param string $dir The sort direction ASC|DESC
1059 * @param int $page The page or records to return
1060 * @param int $perpage The number of records to return per page
1061 * @param int $user User specific search
1062 * @return array $badge Array of records matching criteria
1063 */
1064function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
1065 global $DB;
1066 $records = array();
1067 $params = array();
1068 $where = "b.status != :deleted AND b.type = :type ";
1069 $params['deleted'] = BADGE_STATUS_ARCHIVED;
1070
1071 $userfields = array('b.id, b.name, b.status');
1072 $usersql = "";
1073 if ($user != 0) {
1074 $userfields[] = 'bi.dateissued';
1075 $userfields[] = 'bi.uniquehash';
1076 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
1077 $params['userid'] = $user;
1078 $where .= " AND (b.status = 1 OR b.status = 3) ";
1079 }
1080 $fields = implode(', ', $userfields);
1081
1082 if ($courseid != 0 ) {
1083 $where .= "AND b.courseid = :courseid ";
1084 $params['courseid'] = $courseid;
1085 }
1086
1087 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
1088 $params['type'] = $type;
1089
1090 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
1091 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1092
1093 $badges = array();
1094 foreach ($records as $r) {
1095 $badge = new badge($r->id);
1096 $badges[$r->id] = $badge;
1097 if ($user != 0) {
1098 $badges[$r->id]->dateissued = $r->dateissued;
1099 $badges[$r->id]->uniquehash = $r->uniquehash;
1100 } else {
7f964cfd
YB
1101 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
1102 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
1103 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
27806552
YB
1104 $badges[$r->id]->statstring = $badge->get_status_name();
1105 }
1106 }
1107 return $badges;
1108}
1109
1110/**
1111 * Get badges for a specific user.
1112 *
1113 * @param int $userid User ID
1114 * @param int $courseid Badges earned by a user in a specific course
1115 * @param int $page The page or records to return
1116 * @param int $perpage The number of records to return per page
1117 * @param string $search A simple string to search for
1118 * @param bool $onlypublic Return only public badges
1119 * @return array of badges ordered by decreasing date of issue
1120 */
1121function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
b4846b88 1122 global $CFG, $DB;
27806552 1123
d237385e
SH
1124 $params = array(
1125 'userid' => $userid
1126 );
27806552
YB
1127 $sql = 'SELECT
1128 bi.uniquehash,
1129 bi.dateissued,
1130 bi.dateexpire,
1131 bi.id as issuedid,
1132 bi.visible,
1133 u.email,
1134 b.*
1135 FROM
1136 {badge} b,
1137 {badge_issued} bi,
1138 {user} u
1139 WHERE b.id = bi.badgeid
1140 AND u.id = bi.userid
d237385e 1141 AND bi.userid = :userid';
27806552
YB
1142
1143 if (!empty($search)) {
d237385e
SH
1144 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
1145 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
27806552
YB
1146 }
1147 if ($onlypublic) {
1148 $sql .= ' AND (bi.visible = 1) ';
1149 }
1150
b4846b88
AO
1151 if (empty($CFG->badges_allowcoursebadges)) {
1152 $sql .= ' AND b.courseid IS NULL';
1153 } else if ($courseid != 0) {
d237385e
SH
1154 $sql .= ' AND (b.courseid = :courseid) ';
1155 $params['courseid'] = $courseid;
27806552
YB
1156 }
1157 $sql .= ' ORDER BY bi.dateissued DESC';
1158 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
1159
1160 return $badges;
1161}
1162
27806552
YB
1163/**
1164 * Extends the course administration navigation with the Badges page
1165 *
1166 * @param navigation_node $coursenode
1167 * @param object $course
1168 */
1169function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
1170 global $CFG, $SITE;
1171
1172 $coursecontext = context_course::instance($course->id);
1173 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
a72c2cd6
YB
1174 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
1175 'moodle/badges:createbadge',
1176 'moodle/badges:awardbadge',
1177 'moodle/badges:configurecriteria',
1178 'moodle/badges:configuremessages',
1179 'moodle/badges:configuredetails',
1180 'moodle/badges:deletebadge'), $coursecontext);
27806552 1181
a72c2cd6
YB
1182 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
1183 $coursenode->add(get_string('coursebadges', 'badges'), null,
1184 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
1185 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
27806552 1186
a72c2cd6 1187 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
27806552 1188
a72c2cd6
YB
1189 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
1190 navigation_node::TYPE_SETTING, null, 'coursebadges');
19a9f2ea 1191
a72c2cd6
YB
1192 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
1193 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
19a9f2ea 1194
a72c2cd6
YB
1195 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
1196 navigation_node::TYPE_SETTING, null, 'newbadge');
27806552
YB
1197 }
1198 }
1199}
1200
27806552
YB
1201/**
1202 * Triggered when badge is manually awarded.
1203 *
1204 * @param object $data
1205 * @return boolean
1206 */
1207function badges_award_handle_manual_criteria_review(stdClass $data) {
1208 $criteria = $data->crit;
1209 $userid = $data->userid;
1210 $badge = new badge($criteria->badgeid);
1211
1212 if (!$badge->is_active() || $badge->is_issued($userid)) {
1213 return true;
1214 }
1215
1216 if ($criteria->review($userid)) {
1217 $criteria->mark_complete($userid);
1218
1219 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
1220 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
1221 $badge->issue($userid);
1222 }
1223 }
1224
1225 return true;
1226}
1227
1228/**
1229 * Process badge image from form data
1230 *
1231 * @param badge $badge Badge object
1232 * @param string $iconfile Original file
1233 */
1234function badges_process_badge_image(badge $badge, $iconfile) {
1235 global $CFG, $USER;
1236 require_once($CFG->libdir. '/gdlib.php');
1237
1238 if (!empty($CFG->gdversion)) {
cda2a827 1239 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
27806552
YB
1240 @unlink($iconfile);
1241
1242 // Clean up file draft area after badge image has been saved.
1243 $context = context_user::instance($USER->id, MUST_EXIST);
1244 $fs = get_file_storage();
1245 $fs->delete_area_files($context->id, 'user', 'draft');
1246 }
1247}
1248
1249/**
1250 * Print badge image.
1251 *
1252 * @param badge $badge Badge object
1253 * @param stdClass $context
1254 * @param string $size
1255 */
1256function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
1257 $fsize = ($size == 'small') ? 'f2' : 'f1';
1258
1259 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
1260 // Appending a random parameter to image link to forse browser reload the image.
b143259e
YB
1261 $imageurl->param('refresh', rand(1, 10000));
1262 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
27806552
YB
1263
1264 return html_writer::empty_tag('img', $attributes);
1265}
1266
1267/**
1268 * Bake issued badge.
1269 *
1270 * @param string $hash Unique hash of an issued badge.
1271 * @param int $badgeid ID of the original badge.
1272 * @param int $userid ID of badge recipient (optional).
1273 * @param boolean $pathhash Return file pathhash instead of image url (optional).
1274 * @return string|url Returns either new file path hash or new file URL
1275 */
1276function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
1277 global $CFG, $USER;
1fcf0ca8 1278 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
27806552
YB
1279
1280 $badge = new badge($badgeid);
1281 $badge_context = $badge->get_context();
1282 $userid = ($userid) ? $userid : $USER->id;
1283 $user_context = context_user::instance($userid);
1284
1285 $fs = get_file_storage();
1286 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
49b464f8 1287 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
27806552
YB
1288 $contents = $file->get_content();
1289
1290 $filehandler = new PNG_MetaDataHandler($contents);
1291 $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
1292 if ($filehandler->check_chunks("tEXt", "openbadges")) {
1293 // Add assertion URL tExt chunk.
1294 $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
1295 $fileinfo = array(
1296 'contextid' => $user_context->id,
1297 'component' => 'badges',
1298 'filearea' => 'userbadge',
1299 'itemid' => $badge->id,
1300 'filepath' => '/',
1301 'filename' => $hash . '.png',
1302 );
1303
1304 // Create a file with added contents.
1305 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
1306 if ($pathhash) {
1307 return $newfile->get_pathnamehash();
1308 }
1309 }
1310 } else {
be2b37cf
Y
1311 debugging('Error baking badge image!', DEBUG_DEVELOPER);
1312 return;
27806552
YB
1313 }
1314 }
1315
f5d17c14
YB
1316 // If file exists and we just need its path hash, return it.
1317 if ($pathhash) {
1318 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
1319 return $file->get_pathnamehash();
1320 }
1321
27806552
YB
1322 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
1323 return $fileurl;
1324}
1325
1326/**
e2805314 1327 * Returns external backpack settings and badges from this backpack.
27806552 1328 *
2d3c0fae
YB
1329 * This function first checks if badges for the user are cached and
1330 * tries to retrieve them from the cache. Otherwise, badges are obtained
1331 * through curl request to the backpack.
1332 *
27806552 1333 * @param int $userid Backpack user ID.
2d3c0fae 1334 * @param boolean $refresh Refresh badges collection in cache.
27806552
YB
1335 * @return null|object Returns null is there is no backpack or object with backpack settings.
1336 */
2d3c0fae 1337function get_backpack_settings($userid, $refresh = false) {
27806552 1338 global $DB;
1fcf0ca8 1339 require_once(__DIR__ . '/../badges/lib/backpacklib.php');
27806552 1340
2d3c0fae
YB
1341 // Try to get badges from cache first.
1342 $badgescache = cache::make('core', 'externalbadges');
1343 $out = $badgescache->get($userid);
1344 if ($out !== false && !$refresh) {
1345 return $out;
1346 }
1347 // Get badges through curl request to the backpack.
e2805314 1348 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
27806552
YB
1349 if ($record) {
1350 $backpack = new OpenBadgesBackpackHandler($record);
1351 $out = new stdClass();
1352 $out->backpackurl = $backpack->get_url();
e2805314
YB
1353
1354 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
1355 $out->totalcollections = count($collections);
1356 $out->totalbadges = 0;
1357 $out->badges = array();
1358 foreach ($collections as $collection) {
1359 $badges = $backpack->get_badges($collection->collectionid);
1360 if (isset($badges->badges)) {
1361 $out->badges = array_merge($out->badges, $badges->badges);
a763bb05 1362 $out->totalbadges += count($badges->badges);
e2805314
YB
1363 } else {
1364 $out->badges = array_merge($out->badges, array());
1365 }
1366 }
1367 } else {
1368 $out->totalbadges = 0;
1369 $out->totalcollections = 0;
1370 }
1371
2d3c0fae 1372 $badgescache->set($userid, $out);
27806552
YB
1373 return $out;
1374 }
1375
1376 return null;
1377}
1378
1379/**
1380 * Download all user badges in zip archive.
1381 *
1382 * @param int $userid ID of badge owner.
1383 */
1384function badges_download($userid) {
1385 global $CFG, $DB;
1386 $context = context_user::instance($userid);
1387 $records = $DB->get_records('badge_issued', array('userid' => $userid));
1388
1389 // Get list of files to download.
1390 $fs = get_file_storage();
1391 $filelist = array();
1392 foreach ($records as $issued) {
1393 $badge = new badge($issued->badgeid);
1394 // Need to make image name user-readable and unique using filename safe characters.
1395 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
1396 $name = str_replace(' ', '_', $name);
d77a6026 1397 $name = clean_param($name, PARAM_FILE);
27806552
YB
1398 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
1399 $filelist[$name . '.png'] = $file;
1400 }
1401 }
1402
1403 // Zip files and sent them to a user.
1404 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
1405 $zipper = new zip_packer();
1406 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
1407 send_temp_file($tempzip, 'badges.zip');
1408 } else {
62fef3cf
YB
1409 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
1410 die;
27806552
YB
1411 }
1412}
1413
27806552
YB
1414/**
1415 * Checks if badges can be pushed to external backpack.
1416 *
1417 * @return string Code of backpack accessibility status.
1418 */
1419function badges_check_backpack_accessibility() {
389aad6e
AN
1420 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
1421 // For behat sites, do not poll the remote badge site.
1422 // Behat sites should not be available, but we should pretend as though they are.
1423 return 'available';
1424 }
1425
27806552
YB
1426 global $CFG;
1427 include_once $CFG->libdir . '/filelib.php';
1428
1429 // Using fake assertion url to check whether backpack can access the web site.
1430 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
1431
343534a8 1432 // Curl request to backpack baker.
27806552
YB
1433 $curl = new curl();
1434 $options = array(
1435 'FRESH_CONNECT' => true,
1436 'RETURNTRANSFER' => true,
27806552 1437 'HEADER' => 0,
dd4a197e 1438 'CONNECTTIMEOUT' => 2,
27806552 1439 );
4d0ebdeb 1440 $location = BADGE_BACKPACKURL . '/baker';
27806552
YB
1441 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
1442
1443 $data = json_decode($out);
1444 if (!empty($curl->error)) {
1445 return 'curl-request-timeout';
1446 } else {
1447 if (isset($data->code) && $data->code == 'http-unreachable') {
1448 return 'http-unreachable';
1449 } else {
1450 return 'available';
1451 }
1452 }
1453
1454 return false;
1455}
e2805314
YB
1456
1457/**
1458 * Checks if user has external backpack connected.
1459 *
1460 * @param int $userid ID of a user.
1461 * @return bool True|False whether backpack connection exists.
1462 */
1463function badges_user_has_backpack($userid) {
1464 global $DB;
1465 return $DB->record_exists('badge_backpack', array('userid' => $userid));
1466}
7deff81f
YB
1467
1468/**
1469 * Handles what happens to the course badges when a course is deleted.
1470 *
1471 * @param int $courseid course ID.
1472 * @return void.
1473 */
1474function badges_handle_course_deletion($courseid) {
1475 global $CFG, $DB;
1476 include_once $CFG->libdir . '/filelib.php';
1477
1478 $systemcontext = context_system::instance();
1479 $coursecontext = context_course::instance($courseid);
1480 $fs = get_file_storage();
1481
1482 // Move badges images to the system context.
1483 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
1484
1485 // Get all course badges.
1486 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
1487 foreach ($badges as $badge) {
1488 // Archive badges in this course.
1489 $toupdate = new stdClass();
1490 $toupdate->id = $badge->id;
1491 $toupdate->type = BADGE_TYPE_SITE;
1492 $toupdate->courseid = null;
1493 $toupdate->status = BADGE_STATUS_ARCHIVED;
1494 $DB->update_record('badge', $toupdate);
1495 }
1496}
2c910861
YB
1497
1498/**
1499 * Loads JS files required for backpack support.
1500 *
1501 * @uses $CFG, $PAGE
1502 * @return void
1503 */
1504function badges_setup_backpack_js() {
1505 global $CFG, $PAGE;
1506 if (!empty($CFG->badges_allowexternalbackpack)) {
1507 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
4d0ebdeb 1508 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
2c910861
YB
1509 $PAGE->requires->js('/badges/backpack.js', true);
1510 }
1511}