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.

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   * Renderer for use with the badges output
  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  require_once($CFG->libdir . '/badgeslib.php');
  28  require_once($CFG->libdir . '/tablelib.php');
  29  
  30  /**
  31   * Standard HTML output renderer for badges
  32   */
  33  class core_badges_renderer extends plugin_renderer_base {
  34  
  35      // Outputs badges list.
  36      public function print_badges_list($badges, $userid, $profile = false, $external = false) {
  37          global $USER, $CFG;
  38          foreach ($badges as $badge) {
  39              if (!$external) {
  40                  $context = ($badge->type == BADGE_TYPE_SITE) ? context_system::instance() : context_course::instance($badge->courseid);
  41                  $bname = $badge->name;
  42                  $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', 'f1', false);
  43              } else {
  44                  $bname = '';
  45                  $imageurl = '';
  46                  if (!empty($badge->name)) {
  47                      $bname = s($badge->name);
  48                  }
  49                  if (!empty($badge->image)) {
  50                      $imageurl = $badge->image;
  51                  }
  52                  if (isset($badge->assertion->badge->name)) {
  53                      $bname = s($badge->assertion->badge->name);
  54                  }
  55                  if (isset($badge->imageUrl)) {
  56                      $imageurl = $badge->imageUrl;
  57                  }
  58              }
  59  
  60              $name = html_writer::tag('span', $bname, array('class' => 'badge-name'));
  61  
  62              $image = html_writer::empty_tag('img', ['src' => $imageurl, 'class' => 'badge-image', 'alt' => $badge->imagecaption]);
  63              if (!empty($badge->dateexpire) && $badge->dateexpire < time()) {
  64                  $image .= $this->output->pix_icon('i/expired',
  65                          get_string('expireddate', 'badges', userdate($badge->dateexpire)),
  66                          'moodle',
  67                          array('class' => 'expireimage'));
  68                  $name .= '(' . get_string('expired', 'badges') . ')';
  69              }
  70  
  71              $download = $status = $push = '';
  72              if (($userid == $USER->id) && !$profile) {
  73                  $params = array(
  74                      'download' => $badge->id,
  75                      'hash' => $badge->uniquehash,
  76                      'sesskey' => sesskey()
  77                  );
  78                  $url = new moodle_url(
  79                      'mybadges.php',
  80                      $params
  81                  );
  82                  $notexpiredbadge = (empty($badge->dateexpire) || $badge->dateexpire > time());
  83                  $userbackpack = badges_get_user_backpack();
  84                  if (!empty($CFG->badges_allowexternalbackpack) && $notexpiredbadge && $userbackpack) {
  85                      $assertion = new moodle_url('/badges/assertion.php', array('b' => $badge->uniquehash));
  86                      $action = null;
  87                      if (badges_open_badges_backpack_api($userbackpack->id) == OPEN_BADGES_V1) {
  88                          $action = new component_action('click', 'addtobackpack', array('assertion' => $assertion->out(false)));
  89                          $addurl = new moodle_url('#');
  90                      } else if (badges_open_badges_backpack_api($userbackpack->id) == OPEN_BADGES_V2P1) {
  91                          $addurl = new moodle_url('/badges/backpack-export.php', array('hash' => $badge->uniquehash));
  92                      } else {
  93                          $addurl = new moodle_url('/badges/backpack-add.php', array('hash' => $badge->uniquehash));
  94                      }
  95                      $icon = new pix_icon('t/backpack', get_string('addtobackpack', 'badges'));
  96                      $push = $this->output->action_icon($addurl, $icon, $action);
  97                  }
  98  
  99                  $download = $this->output->action_icon($url, new pix_icon('t/download', get_string('download')));
 100                  if ($badge->visible) {
 101                      $url = new moodle_url('mybadges.php', array('hide' => $badge->issuedid, 'sesskey' => sesskey()));
 102                      $status = $this->output->action_icon($url, new pix_icon('t/hide', get_string('makeprivate', 'badges')));
 103                  } else {
 104                      $url = new moodle_url('mybadges.php', array('show' => $badge->issuedid, 'sesskey' => sesskey()));
 105                      $status = $this->output->action_icon($url, new pix_icon('t/show', get_string('makepublic', 'badges')));
 106                  }
 107              }
 108  
 109              if (!$profile) {
 110                  $url = new moodle_url('badge.php', array('hash' => $badge->uniquehash));
 111              } else {
 112                  if (!$external) {
 113                      $url = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
 114                  } else {
 115                      $hash = hash('md5', $badge->hostedUrl);
 116                      $url = new moodle_url('/badges/external.php', array('hash' => $hash, 'user' => $userid));
 117                  }
 118              }
 119              $actions = html_writer::tag('div', $push . $download . $status, array('class' => 'badge-actions'));
 120              $items[] = html_writer::link($url, $image . $actions . $name, array('title' => $bname));
 121          }
 122  
 123          return html_writer::alist($items, array('class' => 'badges'));
 124      }
 125  
 126      // Recipients selection form.
 127      public function recipients_selection_form(user_selector_base $existinguc, user_selector_base $potentialuc) {
 128          $output = '';
 129          $formattributes = array();
 130          $formattributes['id'] = 'recipientform';
 131          $formattributes['action'] = $this->page->url;
 132          $formattributes['method'] = 'post';
 133          $output .= html_writer::start_tag('form', $formattributes);
 134          $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
 135  
 136          $existingcell = new html_table_cell();
 137          $existingcell->text = $existinguc->display(true);
 138          $existingcell->attributes['class'] = 'existing';
 139          $actioncell = new html_table_cell();
 140          $actioncell->text  = html_writer::start_tag('div', array());
 141          $actioncell->text .= html_writer::empty_tag('input', array(
 142                      'type' => 'submit',
 143                      'name' => 'award',
 144                      'value' => $this->output->larrow() . ' ' . get_string('award', 'badges'),
 145                      'class' => 'actionbutton btn btn-secondary')
 146                  );
 147          $actioncell->text .= html_writer::empty_tag('input', array(
 148                      'type' => 'submit',
 149                      'name' => 'revoke',
 150                      'value' => get_string('revoke', 'badges') . ' ' . $this->output->rarrow(),
 151                      'class' => 'actionbutton btn btn-secondary')
 152                  );
 153          $actioncell->text .= html_writer::end_tag('div', array());
 154          $actioncell->attributes['class'] = 'actions';
 155          $potentialcell = new html_table_cell();
 156          $potentialcell->text = $potentialuc->display(true);
 157          $potentialcell->attributes['class'] = 'potential';
 158  
 159          $table = new html_table();
 160          $table->attributes['class'] = 'recipienttable boxaligncenter';
 161          $table->data = array(new html_table_row(array($existingcell, $actioncell, $potentialcell)));
 162          $output .= html_writer::table($table);
 163  
 164          $output .= html_writer::end_tag('form');
 165          return $output;
 166      }
 167  
 168      // Prints a badge overview infomation.
 169      public function print_badge_overview($badge, $context) {
 170          $display = "";
 171          $languages = get_string_manager()->get_list_of_languages();
 172  
 173          // Badge details.
 174          $display .= $this->heading(get_string('badgedetails', 'badges'), 3);
 175          $dl = array();
 176          $dl[get_string('name')] = $badge->name;
 177          $dl[get_string('version', 'badges')] = $badge->version;
 178          $dl[get_string('language')] = $languages[$badge->language];
 179          $dl[get_string('description', 'badges')] = $badge->description;
 180          $dl[get_string('createdon', 'search')] = userdate($badge->timecreated);
 181          $dl[get_string('badgeimage', 'badges')] = print_badge_image($badge, $context, 'large');
 182          $dl[get_string('imageauthorname', 'badges')] = $badge->imageauthorname;
 183          $dl[get_string('imageauthoremail', 'badges')] =
 184              html_writer::tag('a', $badge->imageauthoremail, array('href' => 'mailto:' . $badge->imageauthoremail));
 185          $dl[get_string('imageauthorurl', 'badges')] =
 186              html_writer::link($badge->imageauthorurl, $badge->imageauthorurl, array('target' => '_blank'));
 187          $dl[get_string('imagecaption', 'badges')] = $badge->imagecaption;
 188          $display .= $this->definition_list($dl);
 189  
 190          // Issuer details.
 191          $display .= $this->heading(get_string('issuerdetails', 'badges'), 3);
 192          $dl = array();
 193          $dl[get_string('issuername', 'badges')] = $badge->issuername;
 194          $dl[get_string('contact', 'badges')] = html_writer::tag('a', $badge->issuercontact, array('href' => 'mailto:' . $badge->issuercontact));
 195          $display .= $this->definition_list($dl);
 196  
 197          // Issuance details if any.
 198          $display .= $this->heading(get_string('issuancedetails', 'badges'), 3);
 199          if ($badge->can_expire()) {
 200              if ($badge->expiredate) {
 201                  $display .= get_string('expiredate', 'badges', userdate($badge->expiredate));
 202              } else if ($badge->expireperiod) {
 203                  if ($badge->expireperiod < 60) {
 204                      $display .= get_string('expireperiods', 'badges', round($badge->expireperiod, 2));
 205                  } else if ($badge->expireperiod < 60 * 60) {
 206                      $display .= get_string('expireperiodm', 'badges', round($badge->expireperiod / 60, 2));
 207                  } else if ($badge->expireperiod < 60 * 60 * 24) {
 208                      $display .= get_string('expireperiodh', 'badges', round($badge->expireperiod / 60 / 60, 2));
 209                  } else {
 210                      $display .= get_string('expireperiod', 'badges', round($badge->expireperiod / 60 / 60 / 24, 2));
 211                  }
 212              }
 213          } else {
 214              $display .= get_string('noexpiry', 'badges');
 215          }
 216  
 217          // Criteria details if any.
 218          $display .= $this->heading(get_string('bcriteria', 'badges'), 3);
 219          if ($badge->has_criteria()) {
 220              $display .= self::print_badge_criteria($badge);
 221          } else {
 222              $display .= get_string('nocriteria', 'badges');
 223              if (has_capability('moodle/badges:configurecriteria', $context)) {
 224                  $display .= $this->output->single_button(
 225                      new moodle_url('/badges/criteria.php', array('id' => $badge->id)),
 226                      get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
 227              }
 228          }
 229  
 230          // Awards details if any.
 231          if (has_capability('moodle/badges:viewawarded', $context)) {
 232              $display .= $this->heading(get_string('awards', 'badges'), 3);
 233              if ($badge->has_awards()) {
 234                  $url = new moodle_url('/badges/recipients.php', array('id' => $badge->id));
 235                  $a = new stdClass();
 236                  $a->link = $url->out();
 237                  $a->count = count($badge->get_awards());
 238                  $display .= get_string('numawards', 'badges', $a);
 239              } else {
 240                  $display .= get_string('noawards', 'badges');
 241              }
 242  
 243              if (has_capability('moodle/badges:awardbadge', $context) &&
 244                  $badge->has_manual_award_criteria() &&
 245                  $badge->is_active()) {
 246                  $display .= $this->output->single_button(
 247                          new moodle_url('/badges/award.php', array('id' => $badge->id)),
 248                          get_string('award', 'badges'), 'POST', array('class' => 'activatebadge'));
 249              }
 250          }
 251  
 252          $display .= self::print_badge_endorsement($badge);
 253          $display .= self::print_badge_related($badge);
 254          $display .= self::print_badge_alignments($badge);
 255  
 256          return html_writer::div($display, null, array('id' => 'badge-overview'));
 257      }
 258  
 259      // Prints action icons for the badge.
 260      public function print_badge_table_actions($badge, $context) {
 261          $actions = "";
 262  
 263          if (has_capability('moodle/badges:configuredetails', $context) && $badge->has_criteria()) {
 264              // Activate/deactivate badge.
 265              if ($badge->status == BADGE_STATUS_INACTIVE || $badge->status == BADGE_STATUS_INACTIVE_LOCKED) {
 266                  // "Activate" will go to another page and ask for confirmation.
 267                  $url = new moodle_url('/badges/action.php');
 268                  $url->param('id', $badge->id);
 269                  $url->param('activate', true);
 270                  $url->param('sesskey', sesskey());
 271                  $return = new moodle_url(qualified_me());
 272                  $url->param('return', $return->out_as_local_url(false));
 273                  $actions .= $this->output->action_icon($url, new pix_icon('t/show', get_string('activate', 'badges'))) . " ";
 274              } else {
 275                  $url = new moodle_url(qualified_me());
 276                  $url->param('lock', $badge->id);
 277                  $url->param('sesskey', sesskey());
 278                  $actions .= $this->output->action_icon($url, new pix_icon('t/hide', get_string('deactivate', 'badges'))) . " ";
 279              }
 280          }
 281  
 282          // Award badge manually.
 283          if ($badge->has_manual_award_criteria() &&
 284                  has_capability('moodle/badges:awardbadge', $context) &&
 285                  $badge->is_active()) {
 286              $url = new moodle_url('/badges/award.php', array('id' => $badge->id));
 287              $actions .= $this->output->action_icon($url, new pix_icon('t/award', get_string('award', 'badges'))) . " ";
 288          }
 289  
 290          // Edit badge.
 291          if (has_capability('moodle/badges:configuredetails', $context)) {
 292              $url = new moodle_url('/badges/edit.php', array('id' => $badge->id, 'action' => 'badge'));
 293              $actions .= $this->output->action_icon($url, new pix_icon('t/edit', get_string('edit'))) . " ";
 294          }
 295  
 296          // Duplicate badge.
 297          if (has_capability('moodle/badges:createbadge', $context)) {
 298              $url = new moodle_url('/badges/action.php', array('copy' => '1', 'id' => $badge->id, 'sesskey' => sesskey()));
 299              $actions .= $this->output->action_icon($url, new pix_icon('t/copy', get_string('copy'))) . " ";
 300          }
 301  
 302          // Delete badge.
 303          if (has_capability('moodle/badges:deletebadge', $context)) {
 304              $url = new moodle_url(qualified_me());
 305              $url->param('delete', $badge->id);
 306              $actions .= $this->output->action_icon($url, new pix_icon('t/delete', get_string('delete'))) . " ";
 307          }
 308  
 309          return $actions;
 310      }
 311  
 312      /**
 313       * Render an issued badge.
 314       *
 315       * @param \core_badges\output\issued_badge $ibadge
 316       * @return string
 317       */
 318      protected function render_issued_badge(\core_badges\output\issued_badge $ibadge) {
 319          global $USER, $CFG, $DB, $SITE;
 320          $issued = $ibadge->issued;
 321          $userinfo = $ibadge->recipient;
 322          $badgeclass = $ibadge->badgeclass;
 323          $badge = new badge($ibadge->badgeid);
 324          $now = time();
 325          if (isset($issued['expires'])) {
 326              if (!is_numeric($issued['expires'])) {
 327                  $issued['expires'] = strtotime($issued['expires']);
 328              }
 329              $expiration = $issued['expires'];
 330          } else {
 331              $expiration = $now + 86400;
 332          }
 333  
 334          $badgeimage = is_array($badgeclass['image']) ? $badgeclass['image']['id'] : $badgeclass['image'];
 335          $languages = get_string_manager()->get_list_of_languages();
 336  
 337          $output = '';
 338          $output .= html_writer::start_tag('div', array('id' => 'badge'));
 339          $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
 340          $output .= html_writer::empty_tag('img', array('src' => $badgeimage, 'alt' => $badge->imagecaption, 'width' => '100'));
 341          if ($expiration < $now) {
 342              $output .= $this->output->pix_icon('i/expired',
 343              get_string('expireddate', 'badges', userdate($issued['expires'])),
 344                  'moodle',
 345                  array('class' => 'expireimage'));
 346          }
 347  
 348          if ($USER->id == $userinfo->id && !empty($CFG->enablebadges)) {
 349              $output .= $this->output->single_button(
 350                          new moodle_url('/badges/badge.php', array('hash' => $ibadge->hash, 'bake' => true)),
 351                          get_string('download'),
 352                          'POST');
 353              if (!empty($CFG->badges_allowexternalbackpack) && ($expiration > $now)
 354                  && $userbackpack = badges_get_user_backpack($USER->id)) {
 355  
 356                  if (badges_open_badges_backpack_api($userbackpack->id) == OPEN_BADGES_V1) {
 357                      $assertion = new moodle_url('/badges/assertion.php', array('b' => $ibadge->hash));
 358                      $action = new component_action('click', 'addtobackpack', array('assertion' => $assertion->out(false)));
 359                      $attributes = array(
 360                              'type'  => 'button',
 361                              'class' => 'btn btn-secondary m-1',
 362                              'id'    => 'addbutton',
 363                              'value' => get_string('addtobackpack', 'badges'));
 364                      $tobackpack = html_writer::tag('input', '', $attributes);
 365                      $this->output->add_action_handler($action, 'addbutton');
 366                      $output .= $tobackpack;
 367                  } else {
 368                      if (badges_open_badges_backpack_api($userbackpack->id) == OPEN_BADGES_V2P1) {
 369                          $assertion = new moodle_url('/badges/backpack-export.php', array('hash' => $ibadge->hash));
 370                      } else {
 371                          $assertion = new moodle_url('/badges/backpack-add.php', array('hash' => $ibadge->hash));
 372                      }
 373                      $attributes = ['class' => 'btn btn-secondary m-1', 'role' => 'button'];
 374                      $tobackpack = html_writer::link($assertion, get_string('addtobackpack', 'badges'), $attributes);
 375                      $output .= $tobackpack;
 376                  }
 377              }
 378          }
 379          $output .= html_writer::end_tag('div');
 380  
 381          $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
 382          // Recipient information.
 383          $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
 384          $dl = array();
 385          if ($userinfo->deleted) {
 386              $strdata = new stdClass();
 387              $strdata->user = fullname($userinfo);
 388              $strdata->site = format_string($SITE->fullname, true, array('context' => context_system::instance()));
 389  
 390              $dl[get_string('name')] = get_string('error:userdeleted', 'badges', $strdata);
 391          } else {
 392              $dl[get_string('name')] = fullname($userinfo);
 393          }
 394          $output .= $this->definition_list($dl);
 395  
 396          $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
 397          $dl = array();
 398          $dl[get_string('issuername', 'badges')] = format_string($badge->issuername, true,
 399              ['context' => context_system::instance()]);
 400  
 401          if (isset($badge->issuercontact) && !empty($badge->issuercontact)) {
 402              $dl[get_string('contact', 'badges')] = obfuscate_mailto($badge->issuercontact);
 403          }
 404          $output .= $this->definition_list($dl);
 405  
 406          $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
 407          $dl = array();
 408          $dl[get_string('name')] = $badge->name;
 409          if (!empty($badge->version)) {
 410              $dl[get_string('version', 'badges')] = $badge->version;
 411          }
 412          if (!empty($badge->language)) {
 413              $dl[get_string('language')] = $languages[$badge->language];
 414          }
 415          $dl[get_string('description', 'badges')] = $badge->description;
 416          if (!empty($badge->imageauthorname)) {
 417              $dl[get_string('imageauthorname', 'badges')] = $badge->imageauthorname;
 418          }
 419          if (!empty($badge->imageauthoremail)) {
 420              $dl[get_string('imageauthoremail', 'badges')] =
 421                      html_writer::tag('a', $badge->imageauthoremail, array('href' => 'mailto:' . $badge->imageauthoremail));
 422          }
 423          if (!empty($badge->imageauthorurl)) {
 424              $dl[get_string('imageauthorurl', 'badges')] =
 425                      html_writer::link($badge->imageauthorurl, $badge->imageauthorurl, array('target' => '_blank'));
 426          }
 427          if (!empty($badge->imagecaption)) {
 428              $dl[get_string('imagecaption', 'badges')] = $badge->imagecaption;
 429          }
 430  
 431          if ($badge->type == BADGE_TYPE_COURSE && isset($badge->courseid)) {
 432              $coursename = $DB->get_field('course', 'fullname', array('id' => $badge->courseid));
 433              $dl[get_string('course')] = format_string($coursename, true, ['context' => context_course::instance($badge->courseid)]);
 434          }
 435          $dl[get_string('bcriteria', 'badges')] = self::print_badge_criteria($badge);
 436          $output .= $this->definition_list($dl);
 437  
 438          $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
 439          $dl = array();
 440          if (!is_numeric($issued['issuedOn'])) {
 441              $issued['issuedOn'] = strtotime($issued['issuedOn']);
 442          }
 443          $dl[get_string('dateawarded', 'badges')] = userdate($issued['issuedOn']);
 444          if (isset($issued['expires'])) {
 445              if ($issued['expires'] < $now) {
 446                  $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']) . get_string('warnexpired', 'badges');
 447  
 448              } else {
 449                  $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']);
 450              }
 451          }
 452  
 453          // Print evidence.
 454          $agg = $badge->get_aggregation_methods();
 455          $evidence = $badge->get_criteria_completions($userinfo->id);
 456          $eids = array_map(function($o) {
 457              return $o->critid;
 458          }, $evidence);
 459          unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
 460  
 461          $items = array();
 462          foreach ($badge->criteria as $type => $c) {
 463              if (in_array($c->id, $eids)) {
 464                  if (count($c->params) == 1) {
 465                      $items[] = get_string('criteria_descr_single_' . $type , 'badges') . $c->get_details();
 466                  } else {
 467                      $items[] = get_string('criteria_descr_' . $type , 'badges',
 468                              core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) . $c->get_details();
 469                  }
 470              }
 471          }
 472  
 473          $dl[get_string('evidence', 'badges')] = get_string('completioninfo', 'badges') . html_writer::alist($items, array(), 'ul');
 474          $output .= $this->definition_list($dl);
 475          $endorsement = $badge->get_endorsement();
 476          if (!empty($endorsement)) {
 477              $output .= self::print_badge_endorsement($badge);
 478          }
 479  
 480          $relatedbadges = $badge->get_related_badges(true);
 481          $items = array();
 482          foreach ($relatedbadges as $related) {
 483              $relatedurl = new moodle_url('/badges/overview.php', array('id' => $related->id));
 484              $items[] = html_writer::link($relatedurl->out(), $related->name, array('target' => '_blank'));
 485          }
 486          if (!empty($items)) {
 487              $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
 488              $output .= html_writer::alist($items, array(), 'ul');
 489          }
 490  
 491          $alignments = $badge->get_alignments();
 492          if (!empty($alignments)) {
 493              $output .= $this->heading(get_string('alignment', 'badges'), 3);
 494              $items = array();
 495              foreach ($alignments as $alignment) {
 496                  $items[] = html_writer::link($alignment->targeturl, $alignment->targetname, array('target' => '_blank'));
 497              }
 498              $output .= html_writer::alist($items, array(), 'ul');
 499          }
 500          $output .= html_writer::end_tag('div');
 501  
 502          return $output;
 503      }
 504  
 505      /**
 506       * Render an external badge.
 507       *
 508       * @param \core_badges\output\external_badge $ibadge
 509       * @return string
 510       */
 511      protected function render_external_badge(\core_badges\output\external_badge $ibadge) {
 512          $issued = $ibadge->issued;
 513          $assertion = $issued->assertion;
 514          $issuer = $assertion->badge->issuer;
 515          $userinfo = $ibadge->recipient;
 516          $table = new html_table();
 517          $today = strtotime(date('Y-m-d'));
 518  
 519          $output = '';
 520          $output .= html_writer::start_tag('div', array('id' => 'badge'));
 521          $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
 522          if (isset($issued->imageUrl)) {
 523              $issued->image = $issued->imageUrl;
 524          }
 525          $output .= html_writer::empty_tag('img', array('src' => $issued->image, 'width' => '100'));
 526          if (isset($assertion->expires)) {
 527              $expiration = is_numeric($assertion->expires) ? $assertion->expires : strtotime($assertion->expires);
 528              if ($expiration < $today) {
 529                  $output .= $this->output->pix_icon('i/expired',
 530                          get_string('expireddate', 'badges', userdate($expiration)),
 531                          'moodle',
 532                          array('class' => 'expireimage'));
 533              }
 534          }
 535          $output .= html_writer::end_tag('div');
 536  
 537          $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
 538  
 539          // Recipient information.
 540          $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
 541          $dl = array();
 542          // Technically, we should alway have a user at this point, but added an extra check just in case.
 543          if ($userinfo) {
 544              if (!$ibadge->valid) {
 545                  $notify = $this->output->notification(get_string('recipientvalidationproblem', 'badges'), 'notifynotice');
 546                  $dl[get_string('name')] = fullname($userinfo) . $notify;
 547              } else {
 548                  $dl[get_string('name')] = fullname($userinfo);
 549              }
 550          } else {
 551              $notify = $this->output->notification(get_string('recipientidentificationproblem', 'badges'), 'notifynotice');
 552              $dl[get_string('name')] = $notify;
 553          }
 554          $output .= $this->definition_list($dl);
 555  
 556          $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
 557          $dl = array();
 558          $dl[get_string('issuername', 'badges')] = s($issuer->name);
 559          if (isset($issuer->origin)) {
 560              $dl[get_string('issuerurl', 'badges')] = html_writer::tag('a', $issuer->origin, array('href' => $issuer->origin));
 561          }
 562  
 563          if (isset($issuer->contact)) {
 564              $dl[get_string('contact', 'badges')] = obfuscate_mailto($issuer->contact);
 565          }
 566          $output .= $this->definition_list($dl);
 567  
 568          $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
 569          $dl = array();
 570          $dl[get_string('name')] = s($assertion->badge->name);
 571          $dl[get_string('description', 'badges')] = s($assertion->badge->description);
 572          if (isset($assertion->badge->criteria)) {
 573              $dl[get_string('bcriteria', 'badges')] = html_writer::tag(
 574                  'a',
 575                  s($assertion->badge->criteria),
 576                  array('href' => $assertion->badge->criteria)
 577              );
 578          }
 579          $output .= $this->definition_list($dl);
 580  
 581          $dl = array();
 582          if (isset($assertion->issued_on)) {
 583              $issuedate = is_numeric($assertion->issued_on) ? $assertion->issued_on : strtotime($assertion->issued_on);
 584              $dl[get_string('dateawarded', 'badges')] = userdate($issuedate);
 585          }
 586          if (isset($assertion->expires)) {
 587              if ($expiration < $today) {
 588                  $dl[get_string('expirydate', 'badges')] = userdate($expiration) . get_string('warnexpired', 'badges');
 589              } else {
 590                  $dl[get_string('expirydate', 'badges')] = userdate($expiration);
 591              }
 592          }
 593          if (isset($assertion->evidence)) {
 594              $dl[get_string('evidence', 'badges')] = html_writer::tag(
 595                  'a',
 596                  s($assertion->evidence),
 597                  array('href' => $assertion->evidence)
 598              );
 599          }
 600          if (!empty($dl)) {
 601              $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
 602              $output .= $this->definition_list($dl);
 603          }
 604          $output .= html_writer::end_tag('div');
 605  
 606          return $output;
 607      }
 608  
 609      /**
 610       * Render a collection of user badges.
 611       *
 612       * @param \core_badges\output\badge_user_collection $badges
 613       * @return string
 614       */
 615      protected function render_badge_user_collection(\core_badges\output\badge_user_collection $badges) {
 616          global $CFG, $USER, $SITE;
 617          $backpack = $badges->backpack;
 618          $mybackpack = new moodle_url('/badges/mybackpack.php');
 619  
 620          $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
 621          $htmlpagingbar = $this->render($paging);
 622  
 623          // Set backpack connection string.
 624          $backpackconnect = '';
 625          if (!empty($CFG->badges_allowexternalbackpack) && is_null($backpack)) {
 626              $backpackconnect = $this->output->box(get_string('localconnectto', 'badges', $mybackpack->out()), 'noticebox');
 627          }
 628          // Search box.
 629          $searchform = $this->output->box($this->helper_search_form($badges->search), 'boxwidthwide boxaligncenter');
 630  
 631          // Download all button.
 632          $actionhtml = $this->output->single_button(
 633                      new moodle_url('/badges/mybadges.php', array('downloadall' => true, 'sesskey' => sesskey())),
 634                      get_string('downloadall'), 'POST', array('class' => 'activatebadge'));
 635          $downloadall = $this->output->box('', 'col-md-3');
 636          $downloadall .= $this->output->box($actionhtml, 'col-md-9');
 637          $downloadall = $this->output->box($downloadall, 'row ml-5');
 638  
 639          // Local badges.
 640          $localhtml = html_writer::start_tag('div', array('id' => 'issued-badge-table', 'class' => 'generalbox'));
 641          $sitename = format_string($SITE->fullname, true, array('context' => context_system::instance()));
 642          $heading = get_string('localbadges', 'badges', $sitename);
 643          $localhtml .= $this->output->heading_with_help($heading, 'localbadgesh', 'badges');
 644          if ($badges->badges) {
 645              $countmessage = $this->output->box(get_string('badgesearned', 'badges', $badges->totalcount));
 646  
 647              $htmllist = $this->print_badges_list($badges->badges, $USER->id);
 648              $localhtml .= $backpackconnect . $countmessage . $searchform;
 649              $localhtml .= $htmlpagingbar . $htmllist . $htmlpagingbar . $downloadall;
 650          } else {
 651              $localhtml .= $searchform . $this->output->notification(get_string('nobadges', 'badges'));
 652          }
 653          $localhtml .= html_writer::end_tag('div');
 654  
 655          // External badges.
 656          $externalhtml = "";
 657          if (!empty($CFG->badges_allowexternalbackpack)) {
 658              $externalhtml .= html_writer::start_tag('div', array('class' => 'generalbox'));
 659              $externalhtml .= $this->output->heading_with_help(get_string('externalbadges', 'badges'), 'externalbadges', 'badges');
 660              if (!is_null($backpack)) {
 661                  if ($backpack->totalcollections == 0) {
 662                      $externalhtml .= get_string('nobackpackcollectionssummary', 'badges', $backpack);
 663                  } else {
 664                      if ($backpack->totalbadges == 0) {
 665                          $externalhtml .= get_string('nobackpackbadgessummary', 'badges', $backpack);
 666                      } else {
 667                          $externalhtml .= get_string('backpackbadgessummary', 'badges', $backpack);
 668                          $externalhtml .= '<br/><br/>' . $this->print_badges_list($backpack->badges, $USER->id, true, true);
 669                      }
 670                  }
 671              } else {
 672                  $externalhtml .= get_string('externalconnectto', 'badges', $mybackpack->out());
 673              }
 674  
 675              $externalhtml .= html_writer::end_tag('div');
 676              $attr = ['class' => 'btn btn-secondary'];
 677              $label = get_string('backpackbadgessettings', 'badges');
 678              $backpacksettings = html_writer::link(new moodle_url('/badges/mybackpack.php'), $label, $attr);
 679              $actionshtml = $this->output->box('', 'col-md-3');
 680              $actionshtml .= $this->output->box($backpacksettings, 'col-md-9');
 681              $actionshtml = $this->output->box($actionshtml, 'row ml-5');
 682              $externalhtml .= $actionshtml;
 683          }
 684  
 685          return $localhtml . $externalhtml;
 686      }
 687  
 688      /**
 689       * Render a collection of badges.
 690       *
 691       * @param \core_badges\output\badge_collection $badges
 692       * @return string
 693       */
 694      protected function render_badge_collection(\core_badges\output\badge_collection $badges) {
 695          $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
 696          $htmlpagingbar = $this->render($paging);
 697          $table = new html_table();
 698          $table->attributes['class'] = 'table table-bordered table-striped';
 699  
 700          $sortbyname = $this->helper_sortable_heading(get_string('name'),
 701                  'name', $badges->sort, $badges->dir);
 702          $sortbyawarded = $this->helper_sortable_heading(get_string('awardedtoyou', 'badges'),
 703                  'dateissued', $badges->sort, $badges->dir);
 704          $table->head = array(
 705                      get_string('badgeimage', 'badges'),
 706                      $sortbyname,
 707                      get_string('description', 'badges'),
 708                      get_string('bcriteria', 'badges'),
 709                      $sortbyawarded
 710                  );
 711          $table->colclasses = array('badgeimage', 'name', 'description', 'criteria', 'awards');
 712  
 713          foreach ($badges->badges as $badge) {
 714              $badgeimage = print_badge_image($badge, $this->page->context, 'large');
 715              $name = $badge->name;
 716              $description = $badge->description;
 717              $criteria = self::print_badge_criteria($badge);
 718              if ($badge->dateissued) {
 719                  $icon = new pix_icon('i/valid',
 720                              get_string('dateearned', 'badges',
 721                                  userdate($badge->dateissued, get_string('strftimedatefullshort', 'core_langconfig'))));
 722                  $badgeurl = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
 723                  $awarded = $this->output->action_icon($badgeurl, $icon, null, null, true);
 724              } else {
 725                  $awarded = "";
 726              }
 727              $row = array($badgeimage, $name, $description, $criteria, $awarded);
 728              $table->data[] = $row;
 729          }
 730  
 731          $htmltable = html_writer::table($table);
 732  
 733          return $htmlpagingbar . $htmltable . $htmlpagingbar;
 734      }
 735  
 736      /**
 737       * Render a table of badges.
 738       *
 739       * @param \core_badges\output\badge_management $badges
 740       * @return string
 741       */
 742      protected function render_badge_management(\core_badges\output\badge_management $badges) {
 743          $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
 744  
 745          // New badge button.
 746          $htmlnew = '';
 747          if (has_capability('moodle/badges:createbadge', $this->page->context)) {
 748              $n['type'] = $this->page->url->get_param('type');
 749              $n['id'] = $this->page->url->get_param('id');
 750              $btn = $this->output->single_button(new moodle_url('newbadge.php', $n), get_string('newbadge', 'badges'));
 751              $htmlnew = $this->output->box($btn);
 752          }
 753  
 754          $htmlpagingbar = $this->render($paging);
 755          $table = new html_table();
 756          $table->attributes['class'] = 'table table-bordered table-striped';
 757  
 758          $sortbyname = $this->helper_sortable_heading(get_string('name'),
 759                  'name', $badges->sort, $badges->dir);
 760          $sortbystatus = $this->helper_sortable_heading(get_string('status', 'badges'),
 761                  'status', $badges->sort, $badges->dir);
 762          $table->head = array(
 763                  $sortbyname,
 764                  $sortbystatus,
 765                  get_string('bcriteria', 'badges'),
 766                  get_string('awards', 'badges'),
 767                  get_string('actions')
 768              );
 769          $table->colclasses = array('name', 'status', 'criteria', 'awards', 'actions');
 770  
 771          foreach ($badges->badges as $b) {
 772              $style = !$b->is_active() ? array('class' => 'dimmed') : array();
 773              $forlink =  print_badge_image($b, $this->page->context) . ' ' .
 774                          html_writer::start_tag('span') . $b->name . html_writer::end_tag('span');
 775              $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $b->id)), $forlink, $style);
 776              $status = $b->statstring;
 777              $criteria = self::print_badge_criteria($b, 'short');
 778  
 779              if (has_capability('moodle/badges:viewawarded', $this->page->context)) {
 780                  $awards = html_writer::link(new moodle_url('/badges/recipients.php', array('id' => $b->id)), $b->awards);
 781              } else {
 782                  $awards = $b->awards;
 783              }
 784  
 785              $actions = self::print_badge_table_actions($b, $this->page->context);
 786  
 787              $row = array($name, $status, $criteria, $awards, $actions);
 788              $table->data[] = $row;
 789          }
 790          $htmltable = html_writer::table($table);
 791  
 792          return $htmlnew . $htmlpagingbar . $htmltable . $htmlpagingbar;
 793      }
 794  
 795      /**
 796       * Prints tabs for badge editing.
 797       *
 798       * @param integer $badgeid The badgeid to edit.
 799       * @param context $context The current context.
 800       * @param string $current The currently selected tab.
 801       * @return string
 802       */
 803      public function print_badge_tabs($badgeid, $context, $current = 'overview') {
 804          global $DB;
 805  
 806          $badge = new badge($badgeid);
 807          $row = array();
 808  
 809          $row[] = new tabobject('overview',
 810                      new moodle_url('/badges/overview.php', array('id' => $badgeid)),
 811                      get_string('boverview', 'badges')
 812                  );
 813  
 814          if (has_capability('moodle/badges:configuredetails', $context)) {
 815              $row[] = new tabobject('badge',
 816                          new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'badge')),
 817                          get_string('bdetails', 'badges')
 818                      );
 819          }
 820  
 821          if (has_capability('moodle/badges:configurecriteria', $context)) {
 822              $row[] = new tabobject('criteria',
 823                          new moodle_url('/badges/criteria.php', array('id' => $badgeid)),
 824                          get_string('bcriteria', 'badges')
 825                      );
 826          }
 827  
 828          if (has_capability('moodle/badges:configuremessages', $context)) {
 829              $row[] = new tabobject('message',
 830                          new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'message')),
 831                          get_string('bmessage', 'badges')
 832                      );
 833          }
 834  
 835          if (has_capability('moodle/badges:viewawarded', $context)) {
 836              $awarded = $DB->count_records_sql('SELECT COUNT(b.userid)
 837                                                 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
 838                                                 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badgeid));
 839              $row[] = new tabobject('awards',
 840                          new moodle_url('/badges/recipients.php', array('id' => $badgeid)),
 841                          get_string('bawards', 'badges', $awarded)
 842                      );
 843          }
 844  
 845          if (has_capability('moodle/badges:configuredetails', $context)) {
 846              $row[] = new tabobject('bendorsement',
 847                  new moodle_url('/badges/endorsement.php', array('id' => $badgeid)),
 848                  get_string('bendorsement', 'badges')
 849              );
 850          }
 851  
 852          if (has_capability('moodle/badges:configuredetails', $context)) {
 853              $sql = "SELECT COUNT(br.badgeid)
 854                        FROM {badge_related} br
 855                       WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2)";
 856              $related = $DB->count_records_sql($sql, ['badgeid' => $badgeid, 'badgeid2' => $badgeid]);
 857              $row[] = new tabobject('brelated',
 858                  new moodle_url('/badges/related.php', array('id' => $badgeid)),
 859                  get_string('brelated', 'badges', $related)
 860              );
 861          }
 862  
 863          if (has_capability('moodle/badges:configuredetails', $context)) {
 864              $alignments = $DB->count_records_sql("SELECT COUNT(bc.id)
 865                        FROM {badge_alignment} bc WHERE bc.badgeid = :badgeid", array('badgeid' => $badgeid));
 866              $row[] = new tabobject('alignment',
 867                  new moodle_url('/badges/alignment.php', array('id' => $badgeid)),
 868                  get_string('balignment', 'badges', $alignments)
 869              );
 870          }
 871  
 872          echo $this->tabtree($row, $current);
 873      }
 874  
 875      /**
 876       * Prints badge status box.
 877       *
 878       * @param badge $badge
 879       * @return Either the status box html as a string or null
 880       */
 881      public function print_badge_status_box(badge $badge) {
 882          if (has_capability('moodle/badges:configurecriteria', $badge->get_context())) {
 883  
 884              if (!$badge->has_criteria()) {
 885                  $criteriaurl = new moodle_url('/badges/criteria.php', array('id' => $badge->id));
 886                  $status = get_string('nocriteria', 'badges');
 887                  if ($this->page->url != $criteriaurl) {
 888                      $action = $this->output->single_button(
 889                          $criteriaurl,
 890                          get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
 891                  } else {
 892                      $action = '';
 893                  }
 894  
 895                  $message = $status . $action;
 896              } else {
 897                  $status = get_string('statusmessage_' . $badge->status, 'badges');
 898                  if ($badge->is_active()) {
 899                      $action = $this->output->single_button(new moodle_url('/badges/action.php',
 900                                  array('id' => $badge->id, 'lock' => 1, 'sesskey' => sesskey(),
 901                                        'return' => $this->page->url->out_as_local_url(false))),
 902                              get_string('deactivate', 'badges'), 'POST', array('class' => 'activatebadge'));
 903                  } else {
 904                      $action = $this->output->single_button(new moodle_url('/badges/action.php',
 905                                  array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(),
 906                                        'return' => $this->page->url->out_as_local_url(false))),
 907                              get_string('activate', 'badges'), 'POST', array('class' => 'activatebadge'));
 908                  }
 909  
 910                  $message = $status . $this->output->help_icon('status', 'badges') . $action;
 911  
 912              }
 913  
 914              $style = $badge->is_active() ? 'generalbox statusbox active' : 'generalbox statusbox inactive';
 915              return $this->output->box($message, $style);
 916          }
 917  
 918          return null;
 919      }
 920  
 921      /**
 922       * Returns information about badge criteria in a list form.
 923       *
 924       * @param badge $badge Badge objects
 925       * @param string $short Indicates whether to print full info about this badge
 926       * @return string $output HTML string to output
 927       */
 928      public function print_badge_criteria(badge $badge, $short = '') {
 929          $agg = $badge->get_aggregation_methods();
 930          if (empty($badge->criteria)) {
 931              return get_string('nocriteria', 'badges');
 932          }
 933  
 934          $overalldescr = '';
 935          $overall = $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL];
 936          if (!$short && !empty($overall->description)) {
 937              $overalldescr = $this->output->box(
 938                  format_text($overall->description, $overall->descriptionformat, array('context' => $badge->get_context())),
 939                  'criteria-description'
 940                  );
 941          }
 942  
 943          // Get the condition string.
 944          if (count($badge->criteria) == 2) {
 945              $condition = '';
 946              if (!$short) {
 947                  $condition = get_string('criteria_descr', 'badges');
 948              }
 949          } else {
 950              $condition = get_string('criteria_descr_' . $short . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
 951                                        core_text::strtoupper($agg[$badge->get_aggregation_method()]));
 952          }
 953  
 954          unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
 955  
 956          $items = array();
 957          // If only one criterion left, make sure its description goe to the top.
 958          if (count($badge->criteria) == 1) {
 959              $c = reset($badge->criteria);
 960              if (!$short && !empty($c->description)) {
 961                  $overalldescr = $this->output->box(
 962                      format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
 963                      'criteria-description'
 964                      );
 965              }
 966              if (count($c->params) == 1) {
 967                  $items[] = get_string('criteria_descr_single_' . $short . $c->criteriatype , 'badges') .
 968                             $c->get_details($short);
 969              } else {
 970                  $items[] = get_string('criteria_descr_' . $short . $c->criteriatype, 'badges',
 971                          core_text::strtoupper($agg[$badge->get_aggregation_method($c->criteriatype)])) .
 972                          $c->get_details($short);
 973              }
 974          } else {
 975              foreach ($badge->criteria as $type => $c) {
 976                  $criteriadescr = '';
 977                  if (!$short && !empty($c->description)) {
 978                      $criteriadescr = $this->output->box(
 979                          format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
 980                          'criteria-description'
 981                          );
 982                  }
 983                  if (count($c->params) == 1) {
 984                      $items[] = get_string('criteria_descr_single_' . $short . $type , 'badges') .
 985                                 $c->get_details($short) . $criteriadescr;
 986                  } else {
 987                      $items[] = get_string('criteria_descr_' . $short . $type , 'badges',
 988                              core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) .
 989                              $c->get_details($short) .
 990                              $criteriadescr;
 991                  }
 992              }
 993          }
 994  
 995          return $overalldescr . $condition . html_writer::alist($items, array(), 'ul');;
 996      }
 997  
 998      /**
 999       * Prints criteria actions for badge editing.
1000       *
1001       * @param badge $badge
1002       * @return string
1003       */
1004      public function print_criteria_actions(badge $badge) {
1005          $output = '';
1006          if (!$badge->is_active() && !$badge->is_locked()) {
1007              $accepted = $badge->get_accepted_criteria();
1008              $potential = array_diff($accepted, array_keys($badge->criteria));
1009  
1010              if (!empty($potential)) {
1011                  foreach ($potential as $p) {
1012                      if ($p != 0) {
1013                          $select[$p] = get_string('criteria_' . $p, 'badges');
1014                      }
1015                  }
1016                  $output .= $this->output->single_select(
1017                      new moodle_url('/badges/criteria_settings.php', array('badgeid' => $badge->id, 'add' => true)),
1018                      'type',
1019                      $select,
1020                      '',
1021                      array('' => 'choosedots'),
1022                      null,
1023                      array('label' => get_string('addbadgecriteria', 'badges'))
1024                  );
1025              } else {
1026                  $output .= $this->output->box(get_string('nothingtoadd', 'badges'), 'clearfix');
1027              }
1028          }
1029  
1030          return $output;
1031      }
1032  
1033      /**
1034       * Renders a table with users who have earned the badge.
1035       * Based on stamps collection plugin.
1036       *
1037       * @param \core_badges\output\badge_recipients $recipients
1038       * @return string
1039       */
1040      protected function render_badge_recipients(\core_badges\output\badge_recipients $recipients) {
1041          $paging = new paging_bar($recipients->totalcount, $recipients->page, $recipients->perpage, $this->page->url, 'page');
1042          $htmlpagingbar = $this->render($paging);
1043          $table = new html_table();
1044          $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1045  
1046          $sortbyfirstname = $this->helper_sortable_heading(get_string('firstname'),
1047                  'firstname', $recipients->sort, $recipients->dir);
1048          $sortbylastname = $this->helper_sortable_heading(get_string('lastname'),
1049                  'lastname', $recipients->sort, $recipients->dir);
1050          if ($this->helper_fullname_format() == 'lf') {
1051              $sortbyname = $sortbylastname . ' / ' . $sortbyfirstname;
1052          } else {
1053              $sortbyname = $sortbyfirstname . ' / ' . $sortbylastname;
1054          }
1055  
1056          $sortbydate = $this->helper_sortable_heading(get_string('dateawarded', 'badges'),
1057                  'dateissued', $recipients->sort, $recipients->dir);
1058  
1059          $table->head = array($sortbyname, $sortbydate, '');
1060  
1061          foreach ($recipients->userids as $holder) {
1062              $fullname = fullname($holder);
1063              $fullname = html_writer::link(
1064                              new moodle_url('/user/profile.php', array('id' => $holder->userid)),
1065                              $fullname
1066                          );
1067              $awarded  = userdate($holder->dateissued);
1068              $badgeurl = html_writer::link(
1069                              new moodle_url('/badges/badge.php', array('hash' => $holder->uniquehash)),
1070                              get_string('viewbadge', 'badges')
1071                          );
1072  
1073              $row = array($fullname, $awarded, $badgeurl);
1074              $table->data[] = $row;
1075          }
1076  
1077          $htmltable = html_writer::table($table);
1078  
1079          return $htmlpagingbar . $htmltable . $htmlpagingbar;
1080      }
1081  
1082      ////////////////////////////////////////////////////////////////////////////
1083      // Helper methods
1084      // Reused from stamps collection plugin
1085      ////////////////////////////////////////////////////////////////////////////
1086  
1087      /**
1088       * Renders a text with icons to sort by the given column
1089       *
1090       * This is intended for table headings.
1091       *
1092       * @param string $text    The heading text
1093       * @param string $sortid  The column id used for sorting
1094       * @param string $sortby  Currently sorted by (column id)
1095       * @param string $sorthow Currently sorted how (ASC|DESC)
1096       *
1097       * @return string
1098       */
1099      protected function helper_sortable_heading($text, $sortid = null, $sortby = null, $sorthow = null) {
1100          $out = html_writer::tag('span', $text, array('class' => 'text'));
1101  
1102          if (!is_null($sortid)) {
1103              if ($sortby !== $sortid || $sorthow !== 'ASC') {
1104                  $url = new moodle_url($this->page->url);
1105                  $url->params(array('sort' => $sortid, 'dir' => 'ASC'));
1106                  $out .= $this->output->action_icon($url,
1107                          new pix_icon('t/sort_asc', get_string('sortbyx', 'core', s($text)), null, array('class' => 'iconsort')));
1108              }
1109              if ($sortby !== $sortid || $sorthow !== 'DESC') {
1110                  $url = new moodle_url($this->page->url);
1111                  $url->params(array('sort' => $sortid, 'dir' => 'DESC'));
1112                  $out .= $this->output->action_icon($url,
1113                          new pix_icon('t/sort_desc', get_string('sortbyxreverse', 'core', s($text)), null, array('class' => 'iconsort')));
1114              }
1115          }
1116          return $out;
1117      }
1118      /**
1119       * Tries to guess the fullname format set at the site
1120       *
1121       * @return string fl|lf
1122       */
1123      protected function helper_fullname_format() {
1124          $fake = new stdClass();
1125          $fake->lastname = 'LLLL';
1126          $fake->firstname = 'FFFF';
1127          $fullname = get_string('fullnamedisplay', '', $fake);
1128          if (strpos($fullname, 'LLLL') < strpos($fullname, 'FFFF')) {
1129              return 'lf';
1130          } else {
1131              return 'fl';
1132          }
1133      }
1134      /**
1135       * Renders a search form
1136       *
1137       * @param string $search Search string
1138       * @return string HTML
1139       */
1140      protected function helper_search_form($search) {
1141          global $CFG;
1142          require_once($CFG->libdir . '/formslib.php');
1143  
1144          $mform = new MoodleQuickForm('searchform', 'POST', $this->page->url);
1145  
1146          $mform->addElement('hidden', 'sesskey', sesskey());
1147  
1148          $el[] = $mform->createElement('text', 'search', get_string('search'), array('size' => 20));
1149          $mform->setDefault('search', $search);
1150          $el[] = $mform->createElement('submit', 'submitsearch', get_string('search'));
1151          $el[] = $mform->createElement('submit', 'clearsearch', get_string('clear'));
1152          $mform->addGroup($el, 'searchgroup', get_string('searchname', 'badges'), ' ', false);
1153  
1154          ob_start();
1155          $mform->display();
1156          $out = ob_get_clean();
1157  
1158          return $out;
1159      }
1160  
1161      /**
1162       * Renders a definition list
1163       *
1164       * @param array $items the list of items to define
1165       * @param array
1166       */
1167      protected function definition_list(array $items, array $attributes = array()) {
1168          $output = html_writer::start_tag('dl', $attributes);
1169          foreach ($items as $label => $value) {
1170              $output .= html_writer::tag('dt', $label);
1171              $output .= html_writer::tag('dd', $value);
1172          }
1173          $output .= html_writer::end_tag('dl');
1174          return $output;
1175      }
1176  
1177      /**
1178       * Outputs list en badges.
1179       *
1180       * @param badge $badge Badge object.
1181       * @return string $output content endorsement to output.
1182       */
1183      protected function print_badge_endorsement(badge $badge) {
1184          $output = '';
1185          $endorsement = $badge->get_endorsement();
1186          $dl = array();
1187          $output .= $this->heading(get_string('endorsement', 'badges'), 3);
1188          if (!empty($endorsement)) {
1189              $dl[get_string('issuername', 'badges')] = $endorsement->issuername;
1190              $dl[get_string('issueremail', 'badges')] =
1191                  html_writer::tag('a', $endorsement->issueremail, array('href' => 'mailto:' . $endorsement->issueremail));
1192              $dl[get_string('issuerurl', 'badges')] = html_writer::link($endorsement->issuerurl, $endorsement->issuerurl,
1193                  array('target' => '_blank'));
1194              $dl[get_string('dateawarded', 'badges')] = userdate($endorsement->dateissued);
1195              $dl[get_string('claimid', 'badges')] = html_writer::link($endorsement->claimid, $endorsement->claimid,
1196              array('target' => '_blank'));
1197              $dl[get_string('claimcomment', 'badges')] = $endorsement->claimcomment;
1198              $output .= $this->definition_list($dl);
1199          } else {
1200              $output .= get_string('noendorsement', 'badges');
1201          }
1202          return $output;
1203      }
1204  
1205      /**
1206       * Print list badges related.
1207       *
1208       * @param badge $badge Badge objects.
1209       * @return string $output List related badges to output.
1210       */
1211      protected function print_badge_related(badge $badge) {
1212          $output = '';
1213          $relatedbadges = $badge->get_related_badges();
1214          $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
1215          if (!empty($relatedbadges)) {
1216              $items = array();
1217              foreach ($relatedbadges as $related) {
1218                  $relatedurl = new moodle_url('/badges/overview.php', array('id' => $related->id));
1219                  $items[] = html_writer::link($relatedurl->out(), $related->name, array('target' => '_blank'));
1220              }
1221              $output .= html_writer::alist($items, array(), 'ul');
1222          } else {
1223              $output .= get_string('norelated', 'badges');
1224          }
1225          return $output;
1226      }
1227  
1228      /**
1229       * Print list badge alignments.
1230       *
1231       * @param badge $badge Badge objects.
1232       * @return string $output List alignments to output.
1233       */
1234      protected function print_badge_alignments(badge $badge) {
1235          $output = '';
1236          $output .= $this->heading(get_string('alignment', 'badges'), 3);
1237          $alignments = $badge->get_alignments();
1238          if (!empty($alignments)) {
1239              $items = array();
1240              foreach ($alignments as $alignment) {
1241                  $urlaligment = new moodle_url('alignment.php',
1242                      array('id' => $badge->id, 'alignmentid' => $alignment->id)
1243                  );
1244                  $items[] = html_writer::link($urlaligment, $alignment->targetname, array('target' => '_blank'));
1245              }
1246              $output .= html_writer::alist($items, array(), 'ul');
1247          } else {
1248              $output .= get_string('noalignment', 'badges');
1249          }
1250          return $output;
1251      }
1252  
1253      /**
1254       * Renders a table for related badges.
1255       *
1256       * @param \core_badges\output\badge_related $related list related badges.
1257       * @return string list related badges to output.
1258       */
1259      protected function render_badge_related(\core_badges\output\badge_related $related) {
1260          $currentbadge = new badge($related->currentbadgeid);
1261          $languages = get_string_manager()->get_list_of_languages();
1262          $paging = new paging_bar($related->totalcount, $related->page, $related->perpage, $this->page->url, 'page');
1263          $htmlpagingbar = $this->render($paging);
1264          $table = new html_table();
1265          $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1266          $table->head = array(
1267              get_string('name'),
1268              get_string('version', 'badges'),
1269              get_string('language', 'badges'),
1270              get_string('type', 'badges')
1271          );
1272          if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1273              array_push($table->head, '');
1274          }
1275  
1276          foreach ($related->badges as $badge) {
1277              $badgeobject = new badge($badge->id);
1278              $style = array('title' => $badgeobject->name);
1279              if (!$badgeobject->is_active()) {
1280                  $style['class'] = 'dimmed';
1281              }
1282              $context = ($badgeobject->type == BADGE_TYPE_SITE) ?
1283                  context_system::instance() : context_course::instance($badgeobject->courseid);
1284              $forlink = print_badge_image($badgeobject, $context) . ' ' .
1285                  html_writer::start_tag('span') . $badgeobject->name . html_writer::end_tag('span');
1286              $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $badgeobject->id)), $forlink, $style);
1287  
1288              $row = array(
1289                  $name,
1290                  $badge->version,
1291                  $badge->language ? $languages[$badge->language] : '',
1292                  $badge->type == BADGE_TYPE_COURSE ? get_string('badgesview', 'badges') : get_string('sitebadges', 'badges')
1293              );
1294              if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1295                  $action = $this->output->action_icon(
1296                      new moodle_url('/badges/related_action.php', [
1297                          'badgeid' => $related->currentbadgeid,
1298                          'relatedid' => $badge->id,
1299                          'sesskey' => sesskey(),
1300                          'action' => 'remove'
1301                      ]),
1302                      new pix_icon('t/delete', get_string('delete')));
1303                  $actions = html_writer::tag('div', $action, array('class' => 'badge-actions'));
1304                  array_push($row, $actions);
1305              }
1306              $table->data[] = $row;
1307          }
1308          $htmltable = html_writer::table($table);
1309  
1310          return $htmlpagingbar . $htmltable . $htmlpagingbar;
1311      }
1312  
1313      /**
1314       * Renders a table with alignment.
1315       *
1316       * @param core_badges\output\badge_alignments $alignments List alignments.
1317       * @return string List alignment to output.
1318       */
1319      protected function render_badge_alignments(\core_badges\output\badge_alignments $alignments) {
1320          $currentbadge = new badge($alignments->currentbadgeid);
1321          $paging = new paging_bar($alignments->totalcount, $alignments->page, $alignments->perpage, $this->page->url, 'page');
1322          $htmlpagingbar = $this->render($paging);
1323          $table = new html_table();
1324          $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1325          $table->head = array('Name', 'URL', '');
1326  
1327          foreach ($alignments->alignments as $item) {
1328              $urlaligment = new moodle_url('alignment.php',
1329                  array(
1330                      'id' => $currentbadge->id,
1331                      'alignmentid' => $item->id,
1332                  )
1333              );
1334              $row = array(
1335                  html_writer::link($urlaligment, $item->targetname),
1336                  html_writer::link($item->targeturl, $item->targeturl, array('target' => '_blank'))
1337              );
1338              if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1339                  $delete = $this->output->action_icon(
1340                      new moodle_url('/badges/alignment_action.php', [
1341                          'id' => $currentbadge->id,
1342                          'alignmentid' => $item->id,
1343                          'sesskey' => sesskey(),
1344                          'action' => 'remove'
1345                      ]),
1346                      new pix_icon('t/delete', get_string('delete'))
1347                  );
1348                  $edit = $this->output->action_icon(
1349                      new moodle_url('alignment.php',
1350                          array(
1351                              'id' => $currentbadge->id,
1352                              'alignmentid' => $item->id,
1353                              'action' => 'edit'
1354                          )
1355                      ), new pix_icon('t/edit', get_string('edit')));
1356                  $actions = html_writer::tag('div', $edit . $delete, array('class' => 'badge-actions'));
1357                  array_push($row, $actions);
1358              }
1359              $table->data[] = $row;
1360          }
1361          $htmltable = html_writer::table($table);
1362  
1363          return $htmlpagingbar . $htmltable . $htmlpagingbar;
1364      }
1365  
1366      /**
1367       * Defer to template.
1368       *
1369       * @param \core_badges\output\external_backpacks_page $page
1370       * @return bool|string
1371       */
1372      public function render_external_backpacks_page(\core_badges\output\external_backpacks_page $page) {
1373          $data = $page->export_for_template($this);
1374          return parent::render_from_template('core_badges/external_backpacks_page', $data);
1375      }
1376  
1377      /**
1378       * Get the result of a backpack validation with its settings. It returns:
1379       * - A informative message if the backpack version is different from OBv2.
1380       * - A warning with the error if it's not possible to connect to this backpack.
1381       * - A successful message if the connection has worked.
1382       *
1383       * @param  int    $backpackid The backpack identifier.
1384       * @return string A message with the validation result.
1385       */
1386      public function render_test_backpack_result(int $backpackid): string {
1387          // Get the backpack.
1388          $backpack = badges_get_site_backpack($backpackid);
1389  
1390          // Add the header to the result.
1391          $result = $this->heading(get_string('testbackpack', 'badges', $backpack->backpackweburl));
1392  
1393          if ($backpack->apiversion != OPEN_BADGES_V2) {
1394              // Only OBv2 supports this validation.
1395              $result .= get_string('backpackconnectionnottested', 'badges');
1396          } else {
1397              $message = badges_verify_backpack($backpackid);
1398              if (empty($message)) {
1399                  $result .= get_string('backpackconnectionok', 'badges');
1400              } else {
1401                  $result .= $message;
1402              }
1403          }
1404  
1405          return $result;
1406      }
1407  }