Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/lib/ -> badgeslib.php (source)

Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 and 403] [Versions 39 and 310]

   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. Custom ones can be added.
  98   */
  99  define('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
 100  define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
 101  
 102  /*
 103   * @deprecated since 3.7. Use the urls in the badge_external_backpack table instead.
 104   */
 105  define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
 106  
 107  /*
 108   * @deprecated since 3.9 (MDL-66357).
 109   */
 110  define('BADGE_BACKPACKAPIURL', 'https://backpack.openbadges.org');
 111  define('BADGE_BACKPACKWEBURL', 'https://backpack.openbadges.org');
 112  
 113  /*
 114   * Open Badges specifications.
 115   */
 116  define('OPEN_BADGES_V1', 1);
 117  define('OPEN_BADGES_V2', 2);
 118  define('OPEN_BADGES_V2P1', 2.1);
 119  
 120  /*
 121   * Only use for Open Badges 2.0 specification
 122   */
 123  define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
 124  define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
 125  define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
 126  define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
 127  define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
 128  define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
 129  
 130  // Global badge class has been moved to the component namespace.
 131  class_alias('\core_badges\badge', 'badge');
 132  
 133  /**
 134   * Sends notifications to users about awarded badges.
 135   *
 136   * @param badge $badge Badge that was issued
 137   * @param int $userid Recipient ID
 138   * @param string $issued Unique hash of an issued badge
 139   * @param string $filepathhash File path hash of an issued badge for attachments
 140   */
 141  function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
 142      global $CFG, $DB;
 143  
 144      $admin = get_admin();
 145      $userfrom = new stdClass();
 146      $userfrom->id = $admin->id;
 147      $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
 148      foreach (get_all_user_name_fields() as $addname) {
 149          $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
 150      }
 151      $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
 152      $userfrom->maildisplay = true;
 153  
 154      $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
 155      $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
 156  
 157      $params = new stdClass();
 158      $params->badgename = $badge->name;
 159      $params->username = fullname($userto);
 160      $params->badgelink = $issuedlink;
 161      $message = badge_message_from_template($badge->message, $params);
 162      $plaintext = html_to_text($message);
 163  
 164      // Notify recipient.
 165      $eventdata = new \core\message\message();
 166      $eventdata->courseid          = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
 167      $eventdata->component         = 'moodle';
 168      $eventdata->name              = 'badgerecipientnotice';
 169      $eventdata->userfrom          = $userfrom;
 170      $eventdata->userto            = $userto;
 171      $eventdata->notification      = 1;
 172      $eventdata->subject           = $badge->messagesubject;
 173      $eventdata->fullmessage       = $plaintext;
 174      $eventdata->fullmessageformat = FORMAT_HTML;
 175      $eventdata->fullmessagehtml   = $message;
 176      $eventdata->smallmessage      = '';
 177      $eventdata->customdata        = [
 178          'notificationiconurl' => moodle_url::make_pluginfile_url(
 179              $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
 180          'hash' => $issued,
 181      ];
 182  
 183      // Attach badge image if possible.
 184      if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
 185          $fs = get_file_storage();
 186          $file = $fs->get_file_by_hash($filepathhash);
 187          $eventdata->attachment = $file;
 188          $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
 189  
 190          message_send($eventdata);
 191      } else {
 192          message_send($eventdata);
 193      }
 194  
 195      // Notify badge creator about the award if they receive notifications every time.
 196      if ($badge->notification == 1) {
 197          $userfrom = core_user::get_noreply_user();
 198          $userfrom->maildisplay = true;
 199  
 200          $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
 201          $a = new stdClass();
 202          $a->user = fullname($userto);
 203          $a->link = $issuedlink;
 204          $creatormessage = get_string('creatorbody', 'badges', $a);
 205          $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
 206  
 207          $eventdata = new \core\message\message();
 208          $eventdata->courseid          = $badge->courseid;
 209          $eventdata->component         = 'moodle';
 210          $eventdata->name              = 'badgecreatornotice';
 211          $eventdata->userfrom          = $userfrom;
 212          $eventdata->userto            = $creator;
 213          $eventdata->notification      = 1;
 214          $eventdata->subject           = $creatorsubject;
 215          $eventdata->fullmessage       = html_to_text($creatormessage);
 216          $eventdata->fullmessageformat = FORMAT_HTML;
 217          $eventdata->fullmessagehtml   = $creatormessage;
 218          $eventdata->smallmessage      = '';
 219          $eventdata->customdata        = [
 220              'notificationiconurl' => moodle_url::make_pluginfile_url(
 221                  $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
 222              'hash' => $issued,
 223          ];
 224  
 225          message_send($eventdata);
 226          $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
 227      }
 228  }
 229  
 230  /**
 231   * Caclulates date for the next message digest to badge creators.
 232   *
 233   * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
 234   * @return int Timestamp for next cron
 235   */
 236  function badges_calculate_message_schedule($schedule) {
 237      $nextcron = 0;
 238  
 239      switch ($schedule) {
 240          case BADGE_MESSAGE_DAILY:
 241              $tomorrow = new DateTime("1 day", core_date::get_server_timezone_object());
 242              $nextcron = $tomorrow->getTimestamp();
 243              break;
 244          case BADGE_MESSAGE_WEEKLY:
 245              $nextweek = new DateTime("1 week", core_date::get_server_timezone_object());
 246              $nextcron = $nextweek->getTimestamp();
 247              break;
 248          case BADGE_MESSAGE_MONTHLY:
 249              $nextmonth = new DateTime("1 month", core_date::get_server_timezone_object());
 250              $nextcron = $nextmonth->getTimestamp();
 251              break;
 252      }
 253  
 254      return $nextcron;
 255  }
 256  
 257  /**
 258   * Replaces variables in a message template and returns text ready to be emailed to a user.
 259   *
 260   * @param string $message Message body.
 261   * @return string Message with replaced values
 262   */
 263  function badge_message_from_template($message, $params) {
 264      $msg = $message;
 265      foreach ($params as $key => $value) {
 266          $msg = str_replace("%$key%", $value, $msg);
 267      }
 268  
 269      return $msg;
 270  }
 271  
 272  /**
 273   * Get all badges.
 274   *
 275   * @param int Type of badges to return
 276   * @param int Course ID for course badges
 277   * @param string $sort An SQL field to sort by
 278   * @param string $dir The sort direction ASC|DESC
 279   * @param int $page The page or records to return
 280   * @param int $perpage The number of records to return per page
 281   * @param int $user User specific search
 282   * @return array $badge Array of records matching criteria
 283   */
 284  function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
 285      global $DB;
 286      $records = array();
 287      $params = array();
 288      $where = "b.status != :deleted AND b.type = :type ";
 289      $params['deleted'] = BADGE_STATUS_ARCHIVED;
 290  
 291      $userfields = array('b.id, b.name, b.status');
 292      $usersql = "";
 293      if ($user != 0) {
 294          $userfields[] = 'bi.dateissued';
 295          $userfields[] = 'bi.uniquehash';
 296          $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
 297          $params['userid'] = $user;
 298          $where .= " AND (b.status = 1 OR b.status = 3) ";
 299      }
 300      $fields = implode(', ', $userfields);
 301  
 302      if ($courseid != 0 ) {
 303          $where .= "AND b.courseid = :courseid ";
 304          $params['courseid'] = $courseid;
 305      }
 306  
 307      $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
 308      $params['type'] = $type;
 309  
 310      $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
 311      $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
 312  
 313      $badges = array();
 314      foreach ($records as $r) {
 315          $badge = new badge($r->id);
 316          $badges[$r->id] = $badge;
 317          if ($user != 0) {
 318              $badges[$r->id]->dateissued = $r->dateissued;
 319              $badges[$r->id]->uniquehash = $r->uniquehash;
 320          } else {
 321              $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
 322                                          FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
 323                                          WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
 324              $badges[$r->id]->statstring = $badge->get_status_name();
 325          }
 326      }
 327      return $badges;
 328  }
 329  
 330  /**
 331   * Get badges for a specific user.
 332   *
 333   * @param int $userid User ID
 334   * @param int $courseid Badges earned by a user in a specific course
 335   * @param int $page The page or records to return
 336   * @param int $perpage The number of records to return per page
 337   * @param string $search A simple string to search for
 338   * @param bool $onlypublic Return only public badges
 339   * @return array of badges ordered by decreasing date of issue
 340   */
 341  function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
 342      global $CFG, $DB;
 343  
 344      $params = array(
 345          'userid' => $userid
 346      );
 347      $sql = 'SELECT
 348                  bi.uniquehash,
 349                  bi.dateissued,
 350                  bi.dateexpire,
 351                  bi.id as issuedid,
 352                  bi.visible,
 353                  u.email,
 354                  b.*
 355              FROM
 356                  {badge} b,
 357                  {badge_issued} bi,
 358                  {user} u
 359              WHERE b.id = bi.badgeid
 360                  AND u.id = bi.userid
 361                  AND bi.userid = :userid';
 362  
 363      if (!empty($search)) {
 364          $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
 365          $params['search'] = '%'.$DB->sql_like_escape($search).'%';
 366      }
 367      if ($onlypublic) {
 368          $sql .= ' AND (bi.visible = 1) ';
 369      }
 370  
 371      if (empty($CFG->badges_allowcoursebadges)) {
 372          $sql .= ' AND b.courseid IS NULL';
 373      } else if ($courseid != 0) {
 374          $sql .= ' AND (b.courseid = :courseid) ';
 375          $params['courseid'] = $courseid;
 376      }
 377      $sql .= ' ORDER BY bi.dateissued DESC';
 378      $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
 379  
 380      return $badges;
 381  }
 382  
 383  /**
 384   * Extends the course administration navigation with the Badges page
 385   *
 386   * @param navigation_node $coursenode
 387   * @param object $course
 388   */
 389  function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
 390      global $CFG, $SITE;
 391  
 392      $coursecontext = context_course::instance($course->id);
 393      $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
 394      $canmanage = has_any_capability(array('moodle/badges:viewawarded',
 395                                            'moodle/badges:createbadge',
 396                                            'moodle/badges:awardbadge',
 397                                            'moodle/badges:configurecriteria',
 398                                            'moodle/badges:configuremessages',
 399                                            'moodle/badges:configuredetails',
 400                                            'moodle/badges:deletebadge'), $coursecontext);
 401  
 402      if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
 403          $coursenode->add(get_string('coursebadges', 'badges'), null,
 404                  navigation_node::TYPE_CONTAINER, null, 'coursebadges',
 405                  new pix_icon('i/badge', get_string('coursebadges', 'badges')));
 406  
 407          $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
 408  
 409          $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
 410              navigation_node::TYPE_SETTING, null, 'coursebadges');
 411  
 412          if (has_capability('moodle/badges:createbadge', $coursecontext)) {
 413              $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
 414  
 415              $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
 416                      navigation_node::TYPE_SETTING, null, 'newbadge');
 417          }
 418      }
 419  }
 420  
 421  /**
 422   * Triggered when badge is manually awarded.
 423   *
 424   * @param   object      $data
 425   * @return  boolean
 426   */
 427  function badges_award_handle_manual_criteria_review(stdClass $data) {
 428      $criteria = $data->crit;
 429      $userid = $data->userid;
 430      $badge = new badge($criteria->badgeid);
 431  
 432      if (!$badge->is_active() || $badge->is_issued($userid)) {
 433          return true;
 434      }
 435  
 436      if ($criteria->review($userid)) {
 437          $criteria->mark_complete($userid);
 438  
 439          if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
 440              $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
 441              $badge->issue($userid);
 442          }
 443      }
 444  
 445      return true;
 446  }
 447  
 448  /**
 449   * Process badge image from form data
 450   *
 451   * @param badge $badge Badge object
 452   * @param string $iconfile Original file
 453   */
 454  function badges_process_badge_image(badge $badge, $iconfile) {
 455      global $CFG, $USER;
 456      require_once($CFG->libdir. '/gdlib.php');
 457  
 458      if (!empty($CFG->gdversion)) {
 459          process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
 460          @unlink($iconfile);
 461  
 462          // Clean up file draft area after badge image has been saved.
 463          $context = context_user::instance($USER->id, MUST_EXIST);
 464          $fs = get_file_storage();
 465          $fs->delete_area_files($context->id, 'user', 'draft');
 466      }
 467  }
 468  
 469  /**
 470   * Print badge image.
 471   *
 472   * @param badge $badge Badge object
 473   * @param stdClass $context
 474   * @param string $size
 475   */
 476  function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
 477      $fsize = ($size == 'small') ? 'f2' : 'f1';
 478  
 479      $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
 480      // Appending a random parameter to image link to forse browser reload the image.
 481      $imageurl->param('refresh', rand(1, 10000));
 482      $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
 483  
 484      return html_writer::empty_tag('img', $attributes);
 485  }
 486  
 487  /**
 488   * Bake issued badge.
 489   *
 490   * @param string $hash Unique hash of an issued badge.
 491   * @param int $badgeid ID of the original badge.
 492   * @param int $userid ID of badge recipient (optional).
 493   * @param boolean $pathhash Return file pathhash instead of image url (optional).
 494   * @return string|url Returns either new file path hash or new file URL
 495   */
 496  function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
 497      global $CFG, $USER;
 498      require_once (__DIR__ . '/../badges/lib/bakerlib.php');
 499  
 500      $badge = new badge($badgeid);
 501      $badge_context = $badge->get_context();
 502      $userid = ($userid) ? $userid : $USER->id;
 503      $user_context = context_user::instance($userid);
 504  
 505      $fs = get_file_storage();
 506      if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
 507          if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
 508              $contents = $file->get_content();
 509  
 510              $filehandler = new PNG_MetaDataHandler($contents);
 511              // For now, the site backpack OB version will be used as default.
 512              $obversion = badges_open_badges_backpack_api();
 513              $assertion = new core_badges_assertion($hash, $obversion);
 514              $assertionjson = json_encode($assertion->get_badge_assertion());
 515              if ($filehandler->check_chunks("iTXt", "openbadges")) {
 516                  // Add assertion URL iTXt chunk.
 517                  $newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
 518                  $fileinfo = array(
 519                          'contextid' => $user_context->id,
 520                          'component' => 'badges',
 521                          'filearea' => 'userbadge',
 522                          'itemid' => $badge->id,
 523                          'filepath' => '/',
 524                          'filename' => $hash . '.png',
 525                  );
 526  
 527                  // Create a file with added contents.
 528                  $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
 529                  if ($pathhash) {
 530                      return $newfile->get_pathnamehash();
 531                  }
 532              }
 533          } else {
 534              debugging('Error baking badge image!', DEBUG_DEVELOPER);
 535              return;
 536          }
 537      }
 538  
 539      // If file exists and we just need its path hash, return it.
 540      if ($pathhash) {
 541          $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
 542          return $file->get_pathnamehash();
 543      }
 544  
 545      $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
 546      return $fileurl;
 547  }
 548  
 549  /**
 550   * Returns external backpack settings and badges from this backpack.
 551   *
 552   * This function first checks if badges for the user are cached and
 553   * tries to retrieve them from the cache. Otherwise, badges are obtained
 554   * through curl request to the backpack.
 555   *
 556   * @param int $userid Backpack user ID.
 557   * @param boolean $refresh Refresh badges collection in cache.
 558   * @return null|object Returns null is there is no backpack or object with backpack settings.
 559   */
 560  function get_backpack_settings($userid, $refresh = false) {
 561      global $DB;
 562  
 563      // Try to get badges from cache first.
 564      $badgescache = cache::make('core', 'externalbadges');
 565      $out = $badgescache->get($userid);
 566      if ($out !== false && !$refresh) {
 567          return $out;
 568      }
 569      // Get badges through curl request to the backpack.
 570      $record = $DB->get_record('badge_backpack', array('userid' => $userid));
 571      if ($record) {
 572          $sitebackpack = badges_get_site_backpack($record->externalbackpackid);
 573          $backpack = new \core_badges\backpack_api($sitebackpack, $record);
 574          $out = new stdClass();
 575          $out->backpackid = $sitebackpack->id;
 576  
 577          if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
 578              $out->totalcollections = count($collections);
 579              $out->totalbadges = 0;
 580              $out->badges = array();
 581              foreach ($collections as $collection) {
 582                  $badges = $backpack->get_badges($collection, true);
 583                  if (!empty($badges)) {
 584                      $out->badges = array_merge($out->badges, $badges);
 585                      $out->totalbadges += count($badges);
 586                  } else {
 587                      $out->badges = array_merge($out->badges, array());
 588                  }
 589              }
 590          } else {
 591              $out->totalbadges = 0;
 592              $out->totalcollections = 0;
 593          }
 594  
 595          $badgescache->set($userid, $out);
 596          return $out;
 597      }
 598  
 599      return null;
 600  }
 601  
 602  /**
 603   * Download all user badges in zip archive.
 604   *
 605   * @param int $userid ID of badge owner.
 606   */
 607  function badges_download($userid) {
 608      global $CFG, $DB;
 609      $context = context_user::instance($userid);
 610      $records = $DB->get_records('badge_issued', array('userid' => $userid));
 611  
 612      // Get list of files to download.
 613      $fs = get_file_storage();
 614      $filelist = array();
 615      foreach ($records as $issued) {
 616          $badge = new badge($issued->badgeid);
 617          // Need to make image name user-readable and unique using filename safe characters.
 618          $name =  $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
 619          $name = str_replace(' ', '_', $name);
 620          $name = clean_param($name, PARAM_FILE);
 621          if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
 622              $filelist[$name . '.png'] = $file;
 623          }
 624      }
 625  
 626      // Zip files and sent them to a user.
 627      $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
 628      $zipper = new zip_packer();
 629      if ($zipper->archive_to_pathname($filelist, $tempzip)) {
 630          send_temp_file($tempzip, 'badges.zip');
 631      } else {
 632          debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
 633          die;
 634      }
 635  }
 636  
 637  /**
 638   * Checks if badges can be pushed to external backpack.
 639   *
 640   * @return string Code of backpack accessibility status.
 641   */
 642  function badges_check_backpack_accessibility() {
 643      if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
 644          // For behat sites, do not poll the remote badge site.
 645          // Behat sites should not be available, but we should pretend as though they are.
 646          return 'available';
 647      }
 648  
 649      if (badges_open_badges_backpack_api() == OPEN_BADGES_V2) {
 650          return 'available';
 651      }
 652  
 653      global $CFG;
 654      include_once $CFG->libdir . '/filelib.php';
 655  
 656      // Using fake assertion url to check whether backpack can access the web site.
 657      $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
 658  
 659      // Curl request to backpack baker.
 660      $curl = new curl();
 661      $options = array(
 662          'FRESH_CONNECT' => true,
 663          'RETURNTRANSFER' => true,
 664          'HEADER' => 0,
 665          'CONNECTTIMEOUT' => 2,
 666      );
 667      // BADGE_BACKPACKURL and the "baker" API is deprecated and should never be used in future.
 668      $location = BADGE_BACKPACKURL . '/baker';
 669      $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
 670  
 671      $data = json_decode($out);
 672      if (!empty($curl->error)) {
 673          return 'curl-request-timeout';
 674      } else {
 675          if (isset($data->code) && $data->code == 'http-unreachable') {
 676              return 'http-unreachable';
 677          } else {
 678              return 'available';
 679          }
 680      }
 681  
 682      return false;
 683  }
 684  
 685  /**
 686   * Checks if user has external backpack connected.
 687   *
 688   * @param int $userid ID of a user.
 689   * @return bool True|False whether backpack connection exists.
 690   */
 691  function badges_user_has_backpack($userid) {
 692      global $DB;
 693      return $DB->record_exists('badge_backpack', array('userid' => $userid));
 694  }
 695  
 696  /**
 697   * Handles what happens to the course badges when a course is deleted.
 698   *
 699   * @param int $courseid course ID.
 700   * @return void.
 701   */
 702  function badges_handle_course_deletion($courseid) {
 703      global $CFG, $DB;
 704      include_once $CFG->libdir . '/filelib.php';
 705  
 706      $systemcontext = context_system::instance();
 707      $coursecontext = context_course::instance($courseid);
 708      $fs = get_file_storage();
 709  
 710      // Move badges images to the system context.
 711      $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
 712  
 713      // Get all course badges.
 714      $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
 715      foreach ($badges as $badge) {
 716          // Archive badges in this course.
 717          $toupdate = new stdClass();
 718          $toupdate->id = $badge->id;
 719          $toupdate->type = BADGE_TYPE_SITE;
 720          $toupdate->courseid = null;
 721          $toupdate->status = BADGE_STATUS_ARCHIVED;
 722          $DB->update_record('badge', $toupdate);
 723      }
 724  }
 725  
 726  /**
 727   * Loads JS files required for backpack support.
 728   *
 729   * @uses   $CFG, $PAGE
 730   * @return void
 731   */
 732  function badges_setup_backpack_js() {
 733      global $CFG, $PAGE;
 734      if (!empty($CFG->badges_allowexternalbackpack)) {
 735          if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
 736              $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
 737              // The issuer.js API is deprecated and should not be used in future.
 738              $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
 739              // The backpack.js file is deprecated and should not be used in future.
 740              $PAGE->requires->js('/badges/backpack.js', true);
 741          }
 742      }
 743  }
 744  
 745  /**
 746   * No js files are required for backpack support.
 747   * This only exists to directly support the custom V1 backpack api.
 748   *
 749   * @param boolean $checksite Call check site function.
 750   * @return void
 751   */
 752  function badges_local_backpack_js($checksite = false) {
 753      global $CFG, $PAGE;
 754      if (!empty($CFG->badges_allowexternalbackpack)) {
 755          if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
 756              $PAGE->requires->js('/badges/backpack.js', true);
 757              if ($checksite) {
 758                  $PAGE->requires->js_init_call('check_site_access', null, false);
 759              }
 760          }
 761      }
 762  }
 763  
 764  /**
 765   * Create the site backpack with this data.
 766   *
 767   * @param stdClass $data The new backpack data.
 768   * @return boolean
 769   */
 770  function badges_create_site_backpack($data) {
 771      global $DB;
 772      $context = context_system::instance();
 773      require_capability('moodle/badges:manageglobalsettings', $context);
 774  
 775      $max = $DB->get_field_sql('SELECT MAX(sortorder) FROM {badge_external_backpack}');
 776      $data->sortorder = $max + 1;
 777  
 778      return badges_save_external_backpack($data);
 779  }
 780  
 781  /**
 782   * Update the backpack with this id.
 783   *
 784   * @param integer $id The backpack to edit
 785   * @param stdClass $data The new backpack data.
 786   * @return boolean
 787   */
 788  function badges_update_site_backpack($id, $data) {
 789      global $DB;
 790      $context = context_system::instance();
 791      require_capability('moodle/badges:manageglobalsettings', $context);
 792  
 793      if ($backpack = badges_get_site_backpack($id)) {
 794          $data->id = $id;
 795          return badges_save_external_backpack($data);
 796      }
 797      return false;
 798  }
 799  
 800  
 801  /**
 802   * Delete the backpack with this id.
 803   *
 804   * @param integer $id The backpack to delete.
 805   * @return boolean
 806   */
 807  function badges_delete_site_backpack($id) {
 808      global $DB, $CFG;
 809  
 810      $context = context_system::instance();
 811      require_capability('moodle/badges:manageglobalsettings', $context);
 812  
 813      // Only remove site backpack if it's not the default one.
 814      if ($CFG->badges_site_backpack != $id && $DB->record_exists('badge_external_backpack', ['id' => $id])) {
 815          $transaction = $DB->start_delegated_transaction();
 816  
 817          // Remove connections for users to this backpack.
 818          $sql = "SELECT DISTINCT bb.id
 819                    FROM {badge_backpack} bb
 820                   WHERE bb.externalbackpackid = :backpackid";
 821          $params = ['backpackid' => $id];
 822          $userbackpacks = $DB->get_fieldset_sql($sql, $params);
 823          if ($userbackpacks) {
 824              // Delete user external collections references to this backpack.
 825              list($insql, $params) = $DB->get_in_or_equal($userbackpacks);
 826              $DB->delete_records_select('badge_external', "backpackid $insql", $params);
 827          }
 828          $DB->delete_records('badge_backpack', ['externalbackpackid' => $id]);
 829  
 830          // Delete backpack entry.
 831          $result = $DB->delete_records('badge_external_backpack', ['id' => $id]);
 832  
 833          $transaction->allow_commit();
 834  
 835          return $result;
 836      }
 837  
 838      return false;
 839  }
 840  
 841  /**
 842   * Perform the actual create/update of external bakpacks. Any checks on the validity of the id will need to be
 843   * performed before it reaches this function.
 844   *
 845   * @param stdClass $data The backpack data we are updating/inserting
 846   * @return int Returns the id of the new/updated record
 847   */
 848  function badges_save_external_backpack(stdClass $data) {
 849      global $DB;
 850      $backpack = new stdClass();
 851  
 852      $backpack->apiversion = $data->apiversion;
 853      $backpack->backpackweburl = $data->backpackweburl;
 854      $backpack->backpackapiurl = $data->backpackapiurl;
 855      $backpack->oauth2_issuerid = $data->oauth2_issuerid ?? '';
 856      if (isset($data->sortorder)) {
 857          $backpack->sortorder = $data->sortorder;
 858      }
 859  
 860      if (empty($data->id)) {
 861          $backpack->id = $DB->insert_record('badge_external_backpack', $backpack);
 862      } else {
 863          $backpack->id = $data->id;
 864          $DB->update_record('badge_external_backpack', $backpack);
 865      }
 866      $data->externalbackpackid = $backpack->id;
 867  
 868      unset($data->id);
 869      badges_save_backpack_credentials($data);
 870      return $data->externalbackpackid;
 871  }
 872  
 873  /**
 874   * Create a backpack with the provided details. Stores the auth details of the backpack
 875   *
 876   * @param stdClass $data Backpack specific data.
 877   * @return int The id of the external backpack that the credentials correspond to
 878   */
 879  function badges_save_backpack_credentials(stdClass $data) {
 880      global $DB;
 881  
 882      if (isset($data->backpackemail) && isset($data->password)) {
 883          $backpack = new stdClass();
 884  
 885          $backpack->email = $data->backpackemail;
 886          $backpack->password = !empty($data->password) ? $data->password : '';
 887          $backpack->externalbackpackid = $data->externalbackpackid;
 888          $backpack->userid = $data->userid ?? 0;
 889          $backpack->backpackuid = $data->backpackuid ?? 0;
 890          $backpack->autosync = $data->autosync ?? 0;
 891  
 892          if (!empty($data->badgebackpack)) {
 893              $backpack->id = $data->badgebackpack;
 894          } else if (!empty($data->id)) {
 895              $backpack->id = $data->id;
 896          }
 897  
 898          if (empty($backpack->id)) {
 899              $backpack->id = $DB->insert_record('badge_backpack', $backpack);
 900          } else {
 901              $DB->update_record('badge_backpack', $backpack);
 902          }
 903  
 904          return $backpack->externalbackpackid;
 905      }
 906  
 907      return $data->externalbackpackid ?? 0;
 908  }
 909  
 910  /**
 911   * Is any backpack enabled that supports open badges V1?
 912   * @param int|null $backpackid Check the version of the given id OR if null the sitewide backpack
 913   * @return boolean
 914   */
 915  function badges_open_badges_backpack_api(?int $backpackid = null) {
 916      if (!$backpackid) {
 917          global $CFG;
 918          $backpackid = $CFG->badges_site_backpack;
 919      }
 920  
 921      $backpack = badges_get_site_backpack($backpackid);
 922      if (empty($backpack->apiversion)) {
 923          return OPEN_BADGES_V2;
 924      }
 925      return $backpack->apiversion;
 926  }
 927  
 928  /**
 929   * Get a site backpacks by id for a particular user or site (if userid is 0)
 930   *
 931   * @param int $id The backpack id.
 932   * @param int $userid The owner of the backpack, 0 if it's a sitewide backpack else a user's site backpack
 933   * @return array(stdClass)
 934   */
 935  function badges_get_site_backpack($id, int $userid = 0) {
 936      global $DB;
 937  
 938      $sql = "SELECT beb.*, bb.id AS badgebackpack, bb.password, bb.email AS backpackemail
 939                FROM {badge_external_backpack} beb
 940           LEFT JOIN {badge_backpack} bb ON bb.externalbackpackid = beb.id AND bb.userid=:userid
 941               WHERE beb.id=:id";
 942  
 943      return $DB->get_record_sql($sql, ['id' => $id, 'userid' => $userid]);
 944  }
 945  
 946  /**
 947   * Get the user backpack for the currently logged in user OR the provided user
 948   *
 949   * @param int|null $userid The user whose backpack you're requesting for. If null, get the logged in user's backpack
 950   * @return mixed The user's backpack or none.
 951   * @throws dml_exception
 952   */
 953  function badges_get_user_backpack(?int $userid = 0) {
 954      global $DB;
 955  
 956      if (!$userid) {
 957          global $USER;
 958          $userid = $USER->id;
 959      }
 960  
 961      $sql = "SELECT beb.*, bb.id AS badgebackpack, bb.password, bb.email AS backpackemail
 962                FROM {badge_external_backpack} beb
 963                JOIN {badge_backpack} bb ON bb.externalbackpackid = beb.id AND bb.userid=:userid";
 964  
 965      return $DB->get_record_sql($sql, ['userid' => $userid]);
 966  }
 967  
 968  /**
 969   * Get the primary backpack for the site
 970   *
 971   * @return array(stdClass)
 972   */
 973  function badges_get_site_primary_backpack() {
 974      global $CFG;
 975  
 976      return badges_get_site_backpack($CFG->badges_site_backpack);
 977  }
 978  
 979  /**
 980   * List the backpacks at site level.
 981   *
 982   * @return array(stdClass)
 983   */
 984  function badges_get_site_backpacks() {
 985      global $DB, $CFG;
 986  
 987      $all = $DB->get_records('badge_external_backpack', null, 'sortorder ASC');
 988  
 989      foreach ($all as $key => $bp) {
 990          if ($bp->id == $CFG->badges_site_backpack) {
 991              $all[$key]->sitebackpack = true;
 992          } else {
 993              $all[$key]->sitebackpack = false;
 994          }
 995      }
 996      return $all;
 997  }
 998  
 999  /**
1000   * List the supported badges api versions.
1001   *
1002   * @return array(version)
1003   */
1004  function badges_get_badge_api_versions() {
1005      return [
1006          (string)OPEN_BADGES_V1 => get_string('openbadgesv1', 'badges'),
1007          (string)OPEN_BADGES_V2 => get_string('openbadgesv2', 'badges'),
1008          (string)OPEN_BADGES_V2P1 => get_string('openbadgesv2p1', 'badges')
1009      ];
1010  }
1011  
1012  /**
1013   * Get the default issuer for a badge from this site.
1014   *
1015   * @return array
1016   */
1017  function badges_get_default_issuer() {
1018      global $CFG, $SITE;
1019  
1020      $sitebackpack = badges_get_site_primary_backpack();
1021      $issuer = array();
1022      $issuerurl = new moodle_url('/');
1023      $issuer['name'] = $CFG->badges_defaultissuername;
1024      if (empty($issuer['name'])) {
1025          $issuer['name'] = $SITE->fullname ? $SITE->fullname : $SITE->shortname;
1026      }
1027      $issuer['url'] = $issuerurl->out(false);
1028      $issuer['email'] = $sitebackpack->backpackemail ?: $CFG->badges_defaultissuercontact;
1029      $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
1030      $issuerid = new moodle_url('/badges/issuer_json.php');
1031      $issuer['id'] = $issuerid->out(false);
1032      $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
1033      return $issuer;
1034  }
1035  
1036  /**
1037   * Disconnect from the user backpack by deleting the user preferences.
1038   *
1039   * @param integer $userid The user to diconnect.
1040   * @return boolean
1041   */
1042  function badges_disconnect_user_backpack($userid) {
1043      global $USER;
1044  
1045      // We can only change backpack settings for our own real backpack.
1046      if ($USER->id != $userid ||
1047              \core\session\manager::is_loggedinas()) {
1048  
1049          return false;
1050      }
1051  
1052      unset_user_preference('badges_email_verify_secret');
1053      unset_user_preference('badges_email_verify_address');
1054      unset_user_preference('badges_email_verify_backpackid');
1055      unset_user_preference('badges_email_verify_password');
1056  
1057      return true;
1058  }
1059  
1060  /**
1061   * Used to remember which objects we connected with a backpack before.
1062   *
1063   * @param integer $sitebackpackid The site backpack to connect to.
1064   * @param string $type The type of this remote object.
1065   * @param string $internalid The id for this object on the Moodle site.
1066   * @param string $param The param we need to return. Defaults to the externalid.
1067   * @return mixed The id or false if it doesn't exist.
1068   */
1069  function badges_external_get_mapping($sitebackpackid, $type, $internalid, $param = 'externalid') {
1070      global $DB;
1071      // Return externalid if it exists.
1072      $params = [
1073          'sitebackpackid' => $sitebackpackid,
1074          'type' => $type,
1075          'internalid' => $internalid
1076      ];
1077  
1078      $record = $DB->get_record('badge_external_identifier', $params, $param, IGNORE_MISSING);
1079      if ($record) {
1080          return $record->$param;
1081      }
1082      return false;
1083  }
1084  
1085  /**
1086   * Save the info about which objects we connected with a backpack before.
1087   *
1088   * @param integer $sitebackpackid The site backpack to connect to.
1089   * @param string $type The type of this remote object.
1090   * @param string $internalid The id for this object on the Moodle site.
1091   * @param string $externalid The id of this object on the remote site.
1092   * @return boolean
1093   */
1094  function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
1095      global $DB;
1096  
1097      $params = [
1098          'sitebackpackid' => $sitebackpackid,
1099          'type' => $type,
1100          'internalid' => $internalid,
1101          'externalid' => $externalid
1102      ];
1103  
1104      return $DB->insert_record('badge_external_identifier', $params);
1105  }
1106  
1107  /**
1108   * Delete all external mapping information for a backpack.
1109   *
1110   * @param integer $sitebackpackid The site backpack to connect to.
1111   * @return boolean
1112   */
1113  function badges_external_delete_mappings($sitebackpackid) {
1114      global $DB;
1115  
1116      $params = ['sitebackpackid' => $sitebackpackid];
1117  
1118      return $DB->delete_records('badge_external_identifier', $params);
1119  }
1120  
1121  /**
1122   * Delete a specific external mapping information for a backpack.
1123   *
1124   * @param integer $sitebackpackid The site backpack to connect to.
1125   * @param string $type The type of this remote object.
1126   * @param string $internalid The id for this object on the Moodle site.
1127   * @return boolean
1128   */
1129  function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
1130      global $DB;
1131  
1132      $params = [
1133          'sitebackpackid' => $sitebackpackid,
1134          'type' => $type,
1135          'internalid' => $internalid
1136      ];
1137  
1138      $DB->delete_record('badge_external_identifier', $params);
1139  }
1140  
1141  /**
1142   * Create and send a verification email to the email address supplied.
1143   *
1144   * Since we're not sending this email to a user, email_to_user can't be used
1145   * but this function borrows largely the code from that process.
1146   *
1147   * @param string $email the email address to send the verification email to.
1148   * @param int $backpackid the id of the backpack to connect to
1149   * @param string $backpackpassword the user entered password to connect to this backpack
1150   * @return true if the email was sent successfully, false otherwise.
1151   */
1152  function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1153      global $DB, $USER;
1154  
1155      // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1156      // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1157      // of verification emails to said address.
1158      $secret = random_string(15);
1159      set_user_preference('badges_email_verify_secret', $secret);
1160      set_user_preference('badges_email_verify_address', $email);
1161      set_user_preference('badges_email_verify_backpackid', $backpackid);
1162      set_user_preference('badges_email_verify_password', $backpackpassword);
1163  
1164      // To, from.
1165      $tempuser = $DB->get_record('user', array('id' => $USER->id), '*', MUST_EXIST);
1166      $tempuser->email = $email;
1167      $noreplyuser = core_user::get_noreply_user();
1168  
1169      // Generate the verification email body.
1170      $verificationurl = '/badges/backpackemailverify.php';
1171      $verificationurl = new moodle_url($verificationurl);
1172      $verificationpath = $verificationurl->out(false);
1173  
1174      $site = get_site();
1175      $args = new stdClass();
1176      $args->link = $verificationpath . '?data='. $secret;
1177      $args->sitename = $site->fullname;
1178      $args->admin = generate_email_signoff();
1179  
1180      $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname);
1181      $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1182      $messagehtml = text_to_html($messagetext, false, false, true);
1183  
1184      return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1185  }
1186  
1187  /**
1188   * Return all the enabled criteria types for this site.
1189   *
1190   * @param boolean $enabled
1191   * @return array
1192   */
1193  function badges_list_criteria($enabled = true) {
1194      global $CFG;
1195  
1196      $types = array(
1197          BADGE_CRITERIA_TYPE_OVERALL    => 'overall',
1198          BADGE_CRITERIA_TYPE_ACTIVITY   => 'activity',
1199          BADGE_CRITERIA_TYPE_MANUAL     => 'manual',
1200          BADGE_CRITERIA_TYPE_SOCIAL     => 'social',
1201          BADGE_CRITERIA_TYPE_COURSE     => 'course',
1202          BADGE_CRITERIA_TYPE_COURSESET  => 'courseset',
1203          BADGE_CRITERIA_TYPE_PROFILE    => 'profile',
1204          BADGE_CRITERIA_TYPE_BADGE      => 'badge',
1205          BADGE_CRITERIA_TYPE_COHORT     => 'cohort',
1206          BADGE_CRITERIA_TYPE_COMPETENCY => 'competency',
1207      );
1208      if ($enabled) {
1209          foreach ($types as $key => $type) {
1210              $class = 'award_criteria_' . $type;
1211              $file = $CFG->dirroot . '/badges/criteria/' . $class . '.php';
1212              if (file_exists($file)) {
1213                  require_once($file);
1214  
1215                  if (!$class::is_enabled()) {
1216                      unset($types[$key]);
1217                  }
1218              }
1219          }
1220      }
1221      return $types;
1222  }
1223  
1224  /**
1225   * Check if any badge has records for competencies.
1226   *
1227   * @param array $competencyids Array of competencies ids.
1228   * @return boolean Return true if competencies were found in any badge.
1229   */
1230  function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1231      global $DB;
1232  
1233      list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED);
1234  
1235      $sql = "SELECT DISTINCT bc.badgeid
1236                  FROM {badge_criteria} bc
1237                  JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1238                  WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1239      $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY;
1240  
1241      return $DB->record_exists_sql($sql, $params);
1242  }
1243  
1244  /**
1245   * Creates single message for all notification and sends it out
1246   *
1247   * @param object $badge A badge which is notified about.
1248   */
1249  function badge_assemble_notification(stdClass $badge) {
1250      global $DB;
1251  
1252      $userfrom = core_user::get_noreply_user();
1253      $userfrom->maildisplay = true;
1254  
1255      if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id))) {
1256          // Get badge creator.
1257          $creator = $DB->get_record('user', array('id' => $badge->creator), '*', MUST_EXIST);
1258          $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1259          $creatormessage = '';
1260  
1261          // Put all messages in one digest.
1262          foreach ($msgs as $msg) {
1263              $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash)), $badge->name);
1264              $recipient = $DB->get_record('user', array('id' => $msg->userid), '*', MUST_EXIST);
1265  
1266              $a = new stdClass();
1267              $a->user = fullname($recipient);
1268              $a->link = $issuedlink;
1269              $creatormessage .= get_string('creatorbody', 'badges', $a);
1270              $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid, 'userid' => $msg->userid));
1271          }
1272  
1273          // Create a message object.
1274          $eventdata = new \core\message\message();
1275          $eventdata->courseid          = SITEID;
1276          $eventdata->component         = 'moodle';
1277          $eventdata->name              = 'badgecreatornotice';
1278          $eventdata->userfrom          = $userfrom;
1279          $eventdata->userto            = $creator;
1280          $eventdata->notification      = 1;
1281          $eventdata->subject           = $creatorsubject;
1282          $eventdata->fullmessage       = format_text_email($creatormessage, FORMAT_HTML);
1283          $eventdata->fullmessageformat = FORMAT_PLAIN;
1284          $eventdata->fullmessagehtml   = $creatormessage;
1285          $eventdata->smallmessage      = $creatorsubject;
1286  
1287          message_send($eventdata);
1288      }
1289  }
1290  
1291  /**
1292   * Attempt to authenticate with the site backpack credentials and return an error
1293   * if the authentication fails. If external backpacks are not enabled, this will
1294   * not perform any test.
1295   *
1296   * @return string
1297   */
1298  function badges_verify_site_backpack() {
1299      global $CFG;
1300  
1301      return badges_verify_backpack($CFG->badges_site_backpack);
1302  }
1303  
1304  /**
1305   * Attempt to authenticate with a backpack credentials and return an error
1306   * if the authentication fails.
1307   * If external backpacks are not enabled or the backpack version is different
1308   * from OBv2, this will not perform any test.
1309   *
1310   * @param int $backpackid Backpack identifier to verify.
1311   * @return string The result of the verification process.
1312   */
1313  function badges_verify_backpack(int $backpackid) {
1314      global $OUTPUT, $CFG;
1315  
1316      if (empty($CFG->badges_allowexternalbackpack)) {
1317          return '';
1318      }
1319  
1320      $backpack = badges_get_site_backpack($backpackid);
1321      if (empty($backpack->apiversion) || ($backpack->apiversion == OPEN_BADGES_V2)) {
1322          $backpackapi = new \core_badges\backpack_api($backpack);
1323  
1324          // Clear any cached access tokens in the session.
1325          $backpackapi->clear_system_user_session();
1326  
1327          // Now attempt a login with these credentials.
1328          $result = $backpackapi->authenticate();
1329          if (empty($result) || !empty($result->error)) {
1330              $warning = $backpackapi->get_authentication_error();
1331  
1332              $params = ['id' => $backpack->id, 'action' => 'edit'];
1333              $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1334  
1335              $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1336              $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1337              return $OUTPUT->container($icon . $message, 'text-danger');
1338          }
1339      }
1340  
1341      return '';
1342  }
1343  
1344  /**
1345   * Get OAuth2 services for the external backpack.
1346   *
1347   * @return array
1348   * @throws coding_exception
1349   */
1350  function badges_get_oauth2_service_options() {
1351      global $DB;
1352  
1353      $issuers = core\oauth2\api::get_all_issuers();
1354      $options = ['' => 'None'];
1355      foreach ($issuers as $issuer) {
1356          $options[$issuer->get('id')] = $issuer->get('name');
1357      }
1358  
1359      return $options;
1360  }
1361  
1362  /**
1363   * Generate a public badgr URL that conforms to OBv2. This is done because badgr responses do not currently conform to
1364   * the spec.
1365   *
1366   * WARNING: This is an extremely hacky way of implementing this and should be removed once the standards are conformed to.
1367   *
1368   * @param stdClass $backpack The Badgr backpack we are pushing to
1369   * @param string $type The type of object we are dealing with either Issuer, Assertion OR Badge.
1370   * @param string $externalid The externalid as provided by the backpack
1371   * @return string The public URL to access Badgr objects
1372   */
1373  function badges_generate_badgr_open_url($backpack, $type, $externalid) {
1374      if (badges_open_badges_backpack_api($backpack->id) == OPEN_BADGES_V2) {
1375          $entity = strtolower($type);
1376          if ($type == OPEN_BADGES_V2_TYPE_BADGE) {
1377              $entity = "badge";
1378          }
1379          $url = new moodle_url($backpack->backpackapiurl);
1380          return "{$url->get_scheme()}://{$url->get_host()}/public/{$entity}s/$externalid";
1381  
1382      }
1383  }