Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • /lib/ -> badgeslib.php (source)

    Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

       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  
      27  defined('MOODLE_INTERNAL') || die();
      28  
      29  /* Include required award criteria library. */
      30  require_once($CFG->dirroot . '/badges/criteria/award_criteria.php');
      31  
      32  /*
      33   * Number of records per page.
      34  */
      35  define('BADGE_PERPAGE', 50);
      36  
      37  /*
      38   * Badge award criteria aggregation method.
      39   */
      40  define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
      41  
      42  /*
      43   * Badge award criteria aggregation method.
      44   */
      45  define('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   */
      51  define('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   */
      57  define('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   */
      63  define('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   */
      69  define('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   */
      75  define('BADGE_STATUS_ARCHIVED', 4);
      76  
      77  /*
      78   * Badge type for site badges.
      79   */
      80  define('BADGE_TYPE_SITE', 1);
      81  
      82  /*
      83   * Badge type for course badges.
      84   */
      85  define('BADGE_TYPE_COURSE', 2);
      86  
      87  /*
      88   * Badge messaging schedule options.
      89   */
      90  define('BADGE_MESSAGE_NEVER', 0);
      91  define('BADGE_MESSAGE_ALWAYS', 1);
      92  define('BADGE_MESSAGE_DAILY', 2);
      93  define('BADGE_MESSAGE_WEEKLY', 3);
      94  define('BADGE_MESSAGE_MONTHLY', 4);
      95  
      96  /*
      97   * URL of backpack. Currently only the Open Badges backpack is supported.
      98   */
      99  define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
     100  
     101  /**
     102   * Class that represents badge.
     103   *
     104   */
     105  class 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;
     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;
     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;
     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;
     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
     358                      WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $this->id));
     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  
     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);
     397  
     398          $result = $DB->insert_record('badge_issued', $issued, true);
     399  
     400          if ($result) {
     401              // Lock the badge, so that its criteria could not be changed any more.
     402              if ($this->status == BADGE_STATUS_ACTIVE) {
     403                  $this->set_status(BADGE_STATUS_ACTIVE_LOCKED);
     404              }
     405  
     406              // Update details in criteria_met table.
     407              $compl = $this->get_criteria_completions($userid);
     408              foreach ($compl as $c) {
     409                  $obj = new stdClass();
     410                  $obj->id = $c->id;
     411                  $obj->issuedid = $result;
     412                  $DB->update_record('badge_criteria_met', $obj, true);
     413              }
     414  
     415              if (!$nobake) {
     416                  // Bake a badge image.
     417                  $pathhash = badges_bake($issued->uniquehash, $this->id, $userid, true);
     418  
     419                  // Notify recipients and badge creators.
     420                  badges_notify_badge_award($this, $userid, $issued->uniquehash, $pathhash);
     421              }
     422          }
     423      }
     424  
     425      /**
     426       * Reviews all badge criteria and checks if badge can be instantly awarded.
     427       *
     428       * @return int Number of awards
     429       */
     430      public function review_all_criteria() {
     431          global $DB, $CFG;
     432          $awards = 0;
     433  
     434          // Raise timelimit as this could take a while for big web sites.
     435          core_php_time_limit::raise();
     436          raise_memory_limit(MEMORY_HUGE);
     437  
     438          foreach ($this->criteria as $crit) {
     439              // Overall criterion is decided when other criteria are reviewed.
     440              if ($crit->criteriatype == BADGE_CRITERIA_TYPE_OVERALL) {
     441                  continue;
     442              }
     443  
     444              list($extrajoin, $extrawhere, $extraparams) = $crit->get_completed_criteria_sql();
     445              // For site level badges, get all active site users who can earn this badge and haven't got it yet.
     446              if ($this->type == BADGE_TYPE_SITE) {
     447                  $sql = "SELECT DISTINCT u.id, bi.badgeid
     448                          FROM {user} u
     449                          {$extrajoin}
     450                          LEFT JOIN {badge_issued} bi
     451                              ON u.id = bi.userid AND bi.badgeid = :badgeid
     452                          WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0 " . $extrawhere;
     453                  $params = array_merge(array('badgeid' => $this->id, 'guestid' => $CFG->siteguest), $extraparams);
     454                  $toearn = $DB->get_fieldset_sql($sql, $params);
     455              } else {
     456                  // For course level badges, get all users who already earned the badge in this course.
     457                  // Then find the ones who are enrolled in the course and don't have a badge yet.
     458                  $earned = $DB->get_fieldset_select('badge_issued', 'userid AS id', 'badgeid = :badgeid', array('badgeid' => $this->id));
     459                  $wheresql = '';
     460                  $earnedparams = array();
     461                  if (!empty($earned)) {
     462                      list($earnedsql, $earnedparams) = $DB->get_in_or_equal($earned, SQL_PARAMS_NAMED, 'u', false);
     463                      $wheresql = ' WHERE u.id ' . $earnedsql;
     464                  }
     465                  list($enrolledsql, $enrolledparams) = get_enrolled_sql($this->get_context(), 'moodle/badges:earnbadge', 0, true);
     466                  $sql = "SELECT DISTINCT u.id
     467                          FROM {user} u
     468                          {$extrajoin}
     469                          JOIN ({$enrolledsql}) je ON je.id = u.id " . $wheresql . $extrawhere;
     470                  $params = array_merge($enrolledparams, $earnedparams, $extraparams);
     471                  $toearn = $DB->get_fieldset_sql($sql, $params);
     472              }
     473  
     474              foreach ($toearn as $uid) {
     475                  $reviewoverall = false;
     476                  if ($crit->review($uid, true)) {
     477                      $crit->mark_complete($uid);
     478                      if ($this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->method == BADGE_CRITERIA_AGGREGATION_ANY) {
     479                          $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
     480                          $this->issue($uid);
     481                          $awards++;
     482                      } else {
     483                          $reviewoverall = true;
     484                      }
     485                  } else {
     486                      // Will be reviewed some other time.
     487                      $reviewoverall = false;
     488                  }
     489                  // Review overall if it is required.
     490                  if ($reviewoverall && $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($uid)) {
     491                      $this->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($uid);
     492                      $this->issue($uid);
     493                      $awards++;
     494                  }
     495              }
     496          }
     497  
     498          return $awards;
     499      }
     500  
     501      /**
     502       * Gets an array of completed criteria from 'badge_criteria_met' table.
     503       *
     504       * @param int $userid Completions for a user
     505       * @return array Records of criteria completions
     506       */
     507      public function get_criteria_completions($userid) {
     508          global $DB;
     509          $completions = array();
     510          $sql = "SELECT bcm.id, bcm.critid
     511                  FROM {badge_criteria_met} bcm
     512                      INNER JOIN {badge_criteria} bc ON bcm.critid = bc.id
     513                  WHERE bc.badgeid = :badgeid AND bcm.userid = :userid ";
     514          $completions = $DB->get_records_sql($sql, array('badgeid' => $this->id, 'userid' => $userid));
     515  
     516          return $completions;
     517      }
     518  
     519      /**
     520       * Checks if badges has award criteria set up.
     521       *
     522       * @return bool A status indicating badge has at least one criterion
     523       */
     524      public function has_criteria() {
     525          if (count($this->criteria) > 0) {
     526              return true;
     527          }
     528          return false;
     529      }
     530  
     531      /**
     532       * Returns badge award criteria
     533       *
     534       * @return array An array of badge criteria
     535       */
     536      public function get_criteria() {
     537          global $DB;
     538          $criteria = array();
     539  
     540          if ($records = (array)$DB->get_records('badge_criteria', array('badgeid' => $this->id))) {
     541              foreach ($records as $record) {
     542                  $criteria[$record->criteriatype] = award_criteria::build((array)$record);
     543              }
     544          }
     545  
     546          return $criteria;
     547      }
     548  
     549      /**
     550       * Get aggregation method for badge criteria
     551       *
     552       * @param int $criteriatype If none supplied, get overall aggregation method (optional)
     553       * @return int One of BADGE_CRITERIA_AGGREGATION_ALL or BADGE_CRITERIA_AGGREGATION_ANY
     554       */
     555      public function get_aggregation_method($criteriatype = 0) {
     556          global $DB;
     557          $params = array('badgeid' => $this->id, 'criteriatype' => $criteriatype);
     558          $aggregation = $DB->get_field('badge_criteria', 'method', $params, IGNORE_MULTIPLE);
     559  
     560          if (!$aggregation) {
     561              return BADGE_CRITERIA_AGGREGATION_ALL;
     562          }
     563  
     564          return $aggregation;
     565      }
     566  
     567      /**
     568       * Checks if badge has expiry period or date set up.
     569       *
     570       * @return bool A status indicating badge can expire
     571       */
     572      public function can_expire() {
     573          if ($this->expireperiod || $this->expiredate) {
     574              return true;
     575          }
     576          return false;
     577      }
     578  
     579      /**
     580       * Calculates badge expiry date based on either expirydate or expiryperiod.
     581       *
     582       * @param int $timestamp Time of badge issue
     583       * @return int A timestamp
     584       */
     585      public function calculate_expiry($timestamp) {
     586          $expiry = null;
     587  
     588          if (isset($this->expiredate)) {
     589              $expiry = $this->expiredate;
     590          } else if (isset($this->expireperiod)) {
     591              $expiry = $timestamp + $this->expireperiod;
     592          }
     593  
     594          return $expiry;
     595      }
     596  
     597      /**
     598       * Checks if badge has manual award criteria set.
     599       *
     600       * @return bool A status indicating badge can be awarded manually
     601       */
     602      public function has_manual_award_criteria() {
     603          foreach ($this->criteria as $criterion) {
     604              if ($criterion->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
     605                  return true;
     606              }
     607          }
     608          return false;
     609      }
     610  
     611      /**
     612       * Fully deletes the badge or marks it as archived.
     613       *
     614       * @param $archive bool Achive a badge without actual deleting of any data.
     615       */
     616      public function delete($archive = true) {
     617          global $DB;
     618  
     619          if ($archive) {
     620              $this->status = BADGE_STATUS_ARCHIVED;
     621              $this->save();
     622              return;
     623          }
     624  
     625          $fs = get_file_storage();
     626  
     627          // Remove all issued badge image files and badge awards.
     628          // Cannot bulk remove area files here because they are issued in user context.
     629          $awards = $this->get_awards();
     630          foreach ($awards as $award) {
     631              $usercontext = context_user::instance($award->userid);
     632              $fs->delete_area_files($usercontext->id, 'badges', 'userbadge', $this->id);
     633          }
     634          $DB->delete_records('badge_issued', array('badgeid' => $this->id));
     635  
     636          // Remove all badge criteria.
     637          $criteria = $this->get_criteria();
     638          foreach ($criteria as $criterion) {
     639              $criterion->delete();
     640          }
     641  
     642          // Delete badge images.
     643          $badgecontext = $this->get_context();
     644          $fs->delete_area_files($badgecontext->id, 'badges', 'badgeimage', $this->id);
     645  
     646          // Finally, remove badge itself.
     647          $DB->delete_records('badge', array('id' => $this->id));
     648      }
     649  }
     650  
     651  /**
     652   * Sends notifications to users about awarded badges.
     653   *
     654   * @param badge $badge Badge that was issued
     655   * @param int $userid Recipient ID
     656   * @param string $issued Unique hash of an issued badge
     657   * @param string $filepathhash File path hash of an issued badge for attachments
     658   */
     659  function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
     660      global $CFG, $DB;
     661  
     662      $admin = get_admin();
     663      $userfrom = new stdClass();
     664      $userfrom->id = $admin->id;
     665      $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
     666      foreach (get_all_user_name_fields() as $addname) {
     667          $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
     668      }
     669      $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
     670      $userfrom->maildisplay = true;
     671  
     672      $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
     673      $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
     674  
     675      $params = new stdClass();
     676      $params->badgename = $badge->name;
     677      $params->username = fullname($userto);
     678      $params->badgelink = $issuedlink;
     679      $message = badge_message_from_template($badge->message, $params);
     680      $plaintext = html_to_text($message);
     681  
     682      // Notify recipient.
     683      $eventdata = new stdClass();
     684      $eventdata->component         = 'moodle';
     685      $eventdata->name              = 'badgerecipientnotice';
     686      $eventdata->userfrom          = $userfrom;
     687      $eventdata->userto            = $userto;
     688      $eventdata->notification      = 1;
     689      $eventdata->subject           = $badge->messagesubject;
     690      $eventdata->fullmessage       = $plaintext;
     691      $eventdata->fullmessageformat = FORMAT_HTML;
     692      $eventdata->fullmessagehtml   = $message;
     693      $eventdata->smallmessage      = '';
     694  
     695      // Attach badge image if possible.
     696      if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
     697          $fs = get_file_storage();
     698          $file = $fs->get_file_by_hash($filepathhash);
     699          $eventdata->attachment = $file;
     700          $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
     701  
     702          message_send($eventdata);
     703      } else {
     704          message_send($eventdata);
     705      }
     706  
     707      // Notify badge creator about the award if they receive notifications every time.
     708      if ($badge->notification == 1) {
     709          $userfrom = core_user::get_noreply_user();
     710          $userfrom->maildisplay = true;
     711  
     712          $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
     713          $a = new stdClass();
     714          $a->user = fullname($userto);
     715          $a->link = $issuedlink;
     716          $creatormessage = get_string('creatorbody', 'badges', $a);
     717          $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
     718  
     719          $eventdata = new stdClass();
     720          $eventdata->component         = 'moodle';
     721          $eventdata->name              = 'badgecreatornotice';
     722          $eventdata->userfrom          = $userfrom;
     723          $eventdata->userto            = $creator;
     724          $eventdata->notification      = 1;
     725          $eventdata->subject           = $creatorsubject;
     726          $eventdata->fullmessage       = html_to_text($creatormessage);
     727          $eventdata->fullmessageformat = FORMAT_HTML;
     728          $eventdata->fullmessagehtml   = $creatormessage;
     729          $eventdata->smallmessage      = '';
     730  
     731          message_send($eventdata);
     732          $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
     733      }
     734  }
     735  
     736  /**
     737   * Caclulates date for the next message digest to badge creators.
     738   *
     739   * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
     740   * @return int Timestamp for next cron
     741   */
     742  function badges_calculate_message_schedule($schedule) {
     743      $nextcron = 0;
     744  
     745      switch ($schedule) {
     746          case BADGE_MESSAGE_DAILY:
     747              $nextcron = time() + 60 * 60 * 24;
     748              break;
     749          case BADGE_MESSAGE_WEEKLY:
     750              $nextcron = time() + 60 * 60 * 24 * 7;
     751              break;
     752          case BADGE_MESSAGE_MONTHLY:
     753              $nextcron = time() + 60 * 60 * 24 * 7 * 30;
     754              break;
     755      }
     756  
     757      return $nextcron;
     758  }
     759  
     760  /**
     761   * Replaces variables in a message template and returns text ready to be emailed to a user.
     762   *
     763   * @param string $message Message body.
     764   * @return string Message with replaced values
     765   */
     766  function badge_message_from_template($message, $params) {
     767      $msg = $message;
     768      foreach ($params as $key => $value) {
     769          $msg = str_replace("%$key%", $value, $msg);
     770      }
     771  
     772      return $msg;
     773  }
     774  
     775  /**
     776   * Get all badges.
     777   *
     778   * @param int Type of badges to return
     779   * @param int Course ID for course badges
     780   * @param string $sort An SQL field to sort by
     781   * @param string $dir The sort direction ASC|DESC
     782   * @param int $page The page or records to return
     783   * @param int $perpage The number of records to return per page
     784   * @param int $user User specific search
     785   * @return array $badge Array of records matching criteria
     786   */
     787  function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
     788      global $DB;
     789      $records = array();
     790      $params = array();
     791      $where = "b.status != :deleted AND b.type = :type ";
     792      $params['deleted'] = BADGE_STATUS_ARCHIVED;
     793  
     794      $userfields = array('b.id, b.name, b.status');
     795      $usersql = "";
     796      if ($user != 0) {
     797          $userfields[] = 'bi.dateissued';
     798          $userfields[] = 'bi.uniquehash';
     799          $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
     800          $params['userid'] = $user;
     801          $where .= " AND (b.status = 1 OR b.status = 3) ";
     802      }
     803      $fields = implode(', ', $userfields);
     804  
     805      if ($courseid != 0 ) {
     806          $where .= "AND b.courseid = :courseid ";
     807          $params['courseid'] = $courseid;
     808      }
     809  
     810      $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
     811      $params['type'] = $type;
     812  
     813      $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
     814      $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
     815  
     816      $badges = array();
     817      foreach ($records as $r) {
     818          $badge = new badge($r->id);
     819          $badges[$r->id] = $badge;
     820          if ($user != 0) {
     821              $badges[$r->id]->dateissued = $r->dateissued;
     822              $badges[$r->id]->uniquehash = $r->uniquehash;
     823          } else {
     824              $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
     825                                          FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
     826                                          WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
     827              $badges[$r->id]->statstring = $badge->get_status_name();
     828          }
     829      }
     830      return $badges;
     831  }
     832  
     833  /**
     834   * Get badges for a specific user.
     835   *
     836   * @param int $userid User ID
     837   * @param int $courseid Badges earned by a user in a specific course
     838   * @param int $page The page or records to return
     839   * @param int $perpage The number of records to return per page
     840   * @param string $search A simple string to search for
     841   * @param bool $onlypublic Return only public badges
     842   * @return array of badges ordered by decreasing date of issue
     843   */
     844  function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
     845      global $DB;
     846  
     847      $params = array(
     848          'userid' => $userid
     849      );
     850      $sql = 'SELECT
     851                  bi.uniquehash,
     852                  bi.dateissued,
     853                  bi.dateexpire,
     854                  bi.id as issuedid,
     855                  bi.visible,
     856                  u.email,
     857                  b.*
     858              FROM
     859                  {badge} b,
     860                  {badge_issued} bi,
     861                  {user} u
     862              WHERE b.id = bi.badgeid
     863                  AND u.id = bi.userid
     864                  AND bi.userid = :userid';
     865  
     866      if (!empty($search)) {
     867          $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
     868          $params['search'] = '%'.$DB->sql_like_escape($search).'%';
     869      }
     870      if ($onlypublic) {
     871          $sql .= ' AND (bi.visible = 1) ';
     872      }
     873  
     874      if ($courseid != 0) {
     875          $sql .= ' AND (b.courseid = :courseid) ';
     876          $params['courseid'] = $courseid;
     877      }
     878      $sql .= ' ORDER BY bi.dateissued DESC';
     879      $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
     880  
     881      return $badges;
     882  }
     883  
     884  /**
     885   * Extends the course administration navigation with the Badges page
     886   *
     887   * @param navigation_node $coursenode
     888   * @param object $course
     889   */
     890  function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
     891      global $CFG, $SITE;
     892  
     893      $coursecontext = context_course::instance($course->id);
     894      $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
     895      $canmanage = has_any_capability(array('moodle/badges:viewawarded',
     896                                            'moodle/badges:createbadge',
     897                                            'moodle/badges:awardbadge',
     898                                            'moodle/badges:configurecriteria',
     899                                            'moodle/badges:configuremessages',
     900                                            'moodle/badges:configuredetails',
     901                                            'moodle/badges:deletebadge'), $coursecontext);
     902  
     903      if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
     904          $coursenode->add(get_string('coursebadges', 'badges'), null,
     905                  navigation_node::TYPE_CONTAINER, null, 'coursebadges',
     906                  new pix_icon('i/badge', get_string('coursebadges', 'badges')));
     907  
     908          $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
     909  
     910          $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
     911              navigation_node::TYPE_SETTING, null, 'coursebadges');
     912  
     913          if (has_capability('moodle/badges:createbadge', $coursecontext)) {
     914              $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
     915  
     916              $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
     917                      navigation_node::TYPE_SETTING, null, 'newbadge');
     918          }
     919      }
     920  }
     921  
     922  /**
     923   * Triggered when badge is manually awarded.
     924   *
     925   * @param   object      $data
     926   * @return  boolean
     927   */
     928  function badges_award_handle_manual_criteria_review(stdClass $data) {
     929      $criteria = $data->crit;
     930      $userid = $data->userid;
     931      $badge = new badge($criteria->badgeid);
     932  
     933      if (!$badge->is_active() || $badge->is_issued($userid)) {
     934          return true;
     935      }
     936  
     937      if ($criteria->review($userid)) {
     938          $criteria->mark_complete($userid);
     939  
     940          if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
     941              $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
     942              $badge->issue($userid);
     943          }
     944      }
     945  
     946      return true;
     947  }
     948  
     949  /**
     950   * Process badge image from form data
     951   *
     952   * @param badge $badge Badge object
     953   * @param string $iconfile Original file
     954   */
     955  function badges_process_badge_image(badge $badge, $iconfile) {
     956      global $CFG, $USER;
     957      require_once($CFG->libdir. '/gdlib.php');
     958  
     959      if (!empty($CFG->gdversion)) {
     960          process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile);
     961          @unlink($iconfile);
     962  
     963          // Clean up file draft area after badge image has been saved.
     964          $context = context_user::instance($USER->id, MUST_EXIST);
     965          $fs = get_file_storage();
     966          $fs->delete_area_files($context->id, 'user', 'draft');
     967      }
     968  }
     969  
     970  /**
     971   * Print badge image.
     972   *
     973   * @param badge $badge Badge object
     974   * @param stdClass $context
     975   * @param string $size
     976   */
     977  function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
     978      $fsize = ($size == 'small') ? 'f2' : 'f1';
     979  
     980      $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
     981      // Appending a random parameter to image link to forse browser reload the image.
     982      $imageurl->param('refresh', rand(1, 10000));
     983      $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
     984  
     985      return html_writer::empty_tag('img', $attributes);
     986  }
     987  
     988  /**
     989   * Bake issued badge.
     990   *
     991   * @param string $hash Unique hash of an issued badge.
     992   * @param int $badgeid ID of the original badge.
     993   * @param int $userid ID of badge recipient (optional).
     994   * @param boolean $pathhash Return file pathhash instead of image url (optional).
     995   * @return string|url Returns either new file path hash or new file URL
     996   */
     997  function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
     998      global $CFG, $USER;
     999      require_once(dirname(dirname(__FILE__)) . '/badges/lib/bakerlib.php');
    1000  
    1001      $badge = new badge($badgeid);
    1002      $badge_context = $badge->get_context();
    1003      $userid = ($userid) ? $userid : $USER->id;
    1004      $user_context = context_user::instance($userid);
    1005  
    1006      $fs = get_file_storage();
    1007      if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
    1008          if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f1.png')) {
    1009              $contents = $file->get_content();
    1010  
    1011              $filehandler = new PNG_MetaDataHandler($contents);
    1012              $assertion = new moodle_url('/badges/assertion.php', array('b' => $hash));
    1013              if ($filehandler->check_chunks("tEXt", "openbadges")) {
    1014                  // Add assertion URL tExt chunk.
    1015                  $newcontents = $filehandler->add_chunks("tEXt", "openbadges", $assertion->out(false));
    1016                  $fileinfo = array(
    1017                          'contextid' => $user_context->id,
    1018                          'component' => 'badges',
    1019                          'filearea' => 'userbadge',
    1020                          'itemid' => $badge->id,
    1021                          'filepath' => '/',
    1022                          'filename' => $hash . '.png',
    1023                  );
    1024  
    1025                  // Create a file with added contents.
    1026                  $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
    1027                  if ($pathhash) {
    1028                      return $newfile->get_pathnamehash();
    1029                  }
    1030              }
    1031          } else {
    1032              debugging('Error baking badge image!', DEBUG_DEVELOPER);
    1033              return;
    1034          }
    1035      }
    1036  
    1037      // If file exists and we just need its path hash, return it.
    1038      if ($pathhash) {
    1039          $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
    1040          return $file->get_pathnamehash();
    1041      }
    1042  
    1043      $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
    1044      return $fileurl;
    1045  }
    1046  
    1047  /**
    1048   * Returns external backpack settings and badges from this backpack.
    1049   *
    1050   * This function first checks if badges for the user are cached and
    1051   * tries to retrieve them from the cache. Otherwise, badges are obtained
    1052   * through curl request to the backpack.
    1053   *
    1054   * @param int $userid Backpack user ID.
    1055   * @param boolean $refresh Refresh badges collection in cache.
    1056   * @return null|object Returns null is there is no backpack or object with backpack settings.
    1057   */
    1058  function get_backpack_settings($userid, $refresh = false) {
    1059      global $DB;
    1060      require_once(dirname(dirname(__FILE__)) . '/badges/lib/backpacklib.php');
    1061  
    1062      // Try to get badges from cache first.
    1063      $badgescache = cache::make('core', 'externalbadges');
    1064      $out = $badgescache->get($userid);
    1065      if ($out !== false && !$refresh) {
    1066          return $out;
    1067      }
    1068      // Get badges through curl request to the backpack.
    1069      $record = $DB->get_record('badge_backpack', array('userid' => $userid));
    1070      if ($record) {
    1071          $backpack = new OpenBadgesBackpackHandler($record);
    1072          $out = new stdClass();
    1073          $out->backpackurl = $backpack->get_url();
    1074  
    1075          if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
    1076              $out->totalcollections = count($collections);
    1077              $out->totalbadges = 0;
    1078              $out->badges = array();
    1079              foreach ($collections as $collection) {
    1080                  $badges = $backpack->get_badges($collection->collectionid);
    1081                  if (isset($badges->badges)) {
    1082                      $out->badges = array_merge($out->badges, $badges->badges);
    1083                      $out->totalbadges += count($out->badges);
    1084                  } else {
    1085                      $out->badges = array_merge($out->badges, array());
    1086                  }
    1087              }
    1088          } else {
    1089              $out->totalbadges = 0;
    1090              $out->totalcollections = 0;
    1091          }
    1092  
    1093          $badgescache->set($userid, $out);
    1094          return $out;
    1095      }
    1096  
    1097      return null;
    1098  }
    1099  
    1100  /**
    1101   * Download all user badges in zip archive.
    1102   *
    1103   * @param int $userid ID of badge owner.
    1104   */
    1105  function badges_download($userid) {
    1106      global $CFG, $DB;
    1107      $context = context_user::instance($userid);
    1108      $records = $DB->get_records('badge_issued', array('userid' => $userid));
    1109  
    1110      // Get list of files to download.
    1111      $fs = get_file_storage();
    1112      $filelist = array();
    1113      foreach ($records as $issued) {
    1114          $badge = new badge($issued->badgeid);
    1115          // Need to make image name user-readable and unique using filename safe characters.
    1116          $name =  $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
    1117          $name = str_replace(' ', '_', $name);
    1118          if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
    1119              $filelist[$name . '.png'] = $file;
    1120          }
    1121      }
    1122  
    1123      // Zip files and sent them to a user.
    1124      $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
    1125      $zipper = new zip_packer();
    1126      if ($zipper->archive_to_pathname($filelist, $tempzip)) {
    1127          send_temp_file($tempzip, 'badges.zip');
    1128      } else {
    1129          debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
    1130          die;
    1131      }
    1132  }
    1133  
    1134  /**
    1135   * Print badges on user profile page.
    1136   *
    1137   * @param int $userid User ID.
    1138   * @param int $courseid Course if we need to filter badges (optional).
    1139   */
    1140  function profile_display_badges($userid, $courseid = 0) {
    1141      global $CFG, $PAGE, $USER, $SITE;
    1142      require_once($CFG->dirroot . '/badges/renderer.php');
    1143  
    1144      $context = context_user::instance($userid);
    1145  
    1146      if ($USER->id == $userid || has_capability('moodle/badges:viewotherbadges', $context)) {
    1147          $records = badges_get_user_badges($userid, $courseid, null, null, null, true);
    1148          $renderer = new core_badges_renderer($PAGE, '');
    1149  
    1150          // Print local badges.
    1151          if ($records) {
    1152              $left = get_string('localbadgesp', 'badges', format_string($SITE->fullname));
    1153              $right = $renderer->print_badges_list($records, $userid, true);
    1154              echo html_writer::tag('dt', $left);
    1155              echo html_writer::tag('dd', $right);
    1156          }
    1157  
    1158          // Print external badges.
    1159          if ($courseid == 0 && !empty($CFG->badges_allowexternalbackpack)) {
    1160              $backpack = get_backpack_settings($userid);
    1161              if (isset($backpack->totalbadges) && $backpack->totalbadges !== 0) {
    1162                  $left = get_string('externalbadgesp', 'badges');
    1163                  $right = $renderer->print_badges_list($backpack->badges, $userid, true, true);
    1164                  echo html_writer::tag('dt', $left);
    1165                  echo html_writer::tag('dd', $right);
    1166              }
    1167          }
    1168      }
    1169  }
    1170  
    1171  /**
    1172   * Checks if badges can be pushed to external backpack.
    1173   *
    1174   * @return string Code of backpack accessibility status.
    1175   */
    1176  function badges_check_backpack_accessibility() {
    1177      global $CFG;
    1178      include_once $CFG->libdir . '/filelib.php';
    1179  
    1180      // Using fake assertion url to check whether backpack can access the web site.
    1181      $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
    1182  
    1183      // Curl request to backpack baker.
    1184      $curl = new curl();
    1185      $options = array(
    1186          'FRESH_CONNECT' => true,
    1187          'RETURNTRANSFER' => true,
    1188          'HEADER' => 0,
    1189          'CONNECTTIMEOUT' => 2,
    1190      );
    1191      $location = BADGE_BACKPACKURL . '/baker';
    1192      $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
    1193  
    1194      $data = json_decode($out);
    1195      if (!empty($curl->error)) {
    1196          return 'curl-request-timeout';
    1197      } else {
    1198          if (isset($data->code) && $data->code == 'http-unreachable') {
    1199              return 'http-unreachable';
    1200          } else {
    1201              return 'available';
    1202          }
    1203      }
    1204  
    1205      return false;
    1206  }
    1207  
    1208  /**
    1209   * Checks if user has external backpack connected.
    1210   *
    1211   * @param int $userid ID of a user.
    1212   * @return bool True|False whether backpack connection exists.
    1213   */
    1214  function badges_user_has_backpack($userid) {
    1215      global $DB;
    1216      return $DB->record_exists('badge_backpack', array('userid' => $userid));
    1217  }
    1218  
    1219  /**
    1220   * Handles what happens to the course badges when a course is deleted.
    1221   *
    1222   * @param int $courseid course ID.
    1223   * @return void.
    1224   */
    1225  function badges_handle_course_deletion($courseid) {
    1226      global $CFG, $DB;
    1227      include_once $CFG->libdir . '/filelib.php';
    1228  
    1229      $systemcontext = context_system::instance();
    1230      $coursecontext = context_course::instance($courseid);
    1231      $fs = get_file_storage();
    1232  
    1233      // Move badges images to the system context.
    1234      $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
    1235  
    1236      // Get all course badges.
    1237      $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
    1238      foreach ($badges as $badge) {
    1239          // Archive badges in this course.
    1240          $toupdate = new stdClass();
    1241          $toupdate->id = $badge->id;
    1242          $toupdate->type = BADGE_TYPE_SITE;
    1243          $toupdate->courseid = null;
    1244          $toupdate->status = BADGE_STATUS_ARCHIVED;
    1245          $DB->update_record('badge', $toupdate);
    1246      }
    1247  }
    1248  
    1249  /**
    1250   * Loads JS files required for backpack support.
    1251   *
    1252   * @uses   $CFG, $PAGE
    1253   * @return void
    1254   */
    1255  function badges_setup_backpack_js() {
    1256      global $CFG, $PAGE;
    1257      if (!empty($CFG->badges_allowexternalbackpack)) {
    1258          $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
    1259          $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
    1260          $PAGE->requires->js('/badges/backpack.js', true);
    1261      }
    1262  }
    

    Search This Site: