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