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