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