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