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