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