MDL-66940 badges: simplify badges page
[moodle.git] / badges / renderer.php
blob1369d176b59e0affaab3e7797a77859098fc8240
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.
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/>.
17 /**
18 * Renderer for use with the badges output
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>
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->libdir . '/badgeslib.php');
30 require_once($CFG->libdir . '/tablelib.php');
32 /**
33 * Standard HTML output renderer for badges
35 class core_badges_renderer extends plugin_renderer_base {
37 // Outputs badges list.
38 public function print_badges_list($badges, $userid, $profile = false, $external = false) {
39 global $USER, $CFG;
40 foreach ($badges as $badge) {
41 if (!$external) {
42 $context = ($badge->type == BADGE_TYPE_SITE) ? context_system::instance() : context_course::instance($badge->courseid);
43 $bname = $badge->name;
44 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3', false);
45 } else {
46 $bname = '';
47 $imageurl = '';
48 if (!empty($badge->name)) {
49 $bname = s($badge->name);
51 if (!empty($badge->image)) {
52 if (is_object($badge->image)) {
53 if (!empty($badge->image->caption)) {
54 $badge->imagecaption = $badge->image->caption;
56 $imageurl = $badge->image->id;
57 } else {
58 $imageurl = $badge->image;
61 if (isset($badge->assertion->badge->name)) {
62 $bname = s($badge->assertion->badge->name);
64 if (isset($badge->imageUrl)) {
65 $imageurl = $badge->imageUrl;
69 $name = html_writer::tag('span', $bname, array('class' => 'badge-name'));
71 $imagecaption = $badge->imagecaption ?? '';
72 $image = html_writer::empty_tag('img', ['src' => $imageurl, 'class' => 'badge-image', 'alt' => $imagecaption]);
73 if (!empty($badge->dateexpire) && $badge->dateexpire < time()) {
74 $image .= $this->output->pix_icon('i/expired',
75 get_string('expireddate', 'badges', userdate($badge->dateexpire)),
76 'moodle',
77 array('class' => 'expireimage'));
78 $name .= '(' . get_string('expired', 'badges') . ')';
81 $download = $status = $push = '';
82 if (($userid == $USER->id) && !$profile) {
83 $params = array(
84 'download' => $badge->id,
85 'hash' => $badge->uniquehash,
86 'sesskey' => sesskey()
88 $url = new moodle_url(
89 'mybadges.php',
90 $params
92 $notexpiredbadge = (empty($badge->dateexpire) || $badge->dateexpire > time());
93 $userbackpack = badges_get_user_backpack();
94 if (!empty($CFG->badges_allowexternalbackpack) && $notexpiredbadge && $userbackpack) {
95 $assertion = new moodle_url('/badges/assertion.php', array('b' => $badge->uniquehash));
96 $icon = new pix_icon('t/backpack', get_string('addtobackpack', 'badges'));
97 if (badges_open_badges_backpack_api($userbackpack->id) == OPEN_BADGES_V2) {
98 $addurl = new moodle_url('/badges/backpack-add.php', array('hash' => $badge->uniquehash));
99 $push = $this->output->action_icon($addurl, $icon);
100 } else if (badges_open_badges_backpack_api($userbackpack->id) == OPEN_BADGES_V2P1) {
101 $addurl = new moodle_url('/badges/backpack-export.php', array('hash' => $badge->uniquehash));
102 $push = $this->output->action_icon($addurl, $icon);
106 $download = $this->output->action_icon($url, new pix_icon('t/download', get_string('download')));
107 if ($badge->visible) {
108 $url = new moodle_url('mybadges.php', array('hide' => $badge->issuedid, 'sesskey' => sesskey()));
109 $status = $this->output->action_icon($url, new pix_icon('t/hide', get_string('makeprivate', 'badges')));
110 } else {
111 $url = new moodle_url('mybadges.php', array('show' => $badge->issuedid, 'sesskey' => sesskey()));
112 $status = $this->output->action_icon($url, new pix_icon('t/show', get_string('makepublic', 'badges')));
116 if (!$profile) {
117 $url = new moodle_url('badge.php', array('hash' => $badge->uniquehash));
118 } else {
119 if (!$external) {
120 $url = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
121 } else {
122 $hash = hash('md5', $badge->hostedUrl);
123 $url = new moodle_url('/badges/external.php', array('hash' => $hash, 'user' => $userid));
126 $actions = html_writer::tag('div', $push . $download . $status, array('class' => 'badge-actions'));
127 $items[] = html_writer::link($url, $image . $actions . $name, array('title' => $bname));
130 return html_writer::alist($items, array('class' => 'badges'));
133 // Recipients selection form.
134 public function recipients_selection_form(user_selector_base $existinguc, user_selector_base $potentialuc) {
135 $output = '';
136 $formattributes = array();
137 $formattributes['id'] = 'recipientform';
138 $formattributes['action'] = $this->page->url;
139 $formattributes['method'] = 'post';
140 $output .= html_writer::start_tag('form', $formattributes);
141 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
143 $existingcell = new html_table_cell();
144 $existingcell->text = $existinguc->display(true);
145 $existingcell->attributes['class'] = 'existing';
146 $actioncell = new html_table_cell();
147 $actioncell->text = html_writer::start_tag('div', array());
148 $actioncell->text .= html_writer::empty_tag('input', array(
149 'type' => 'submit',
150 'name' => 'award',
151 'value' => $this->output->larrow() . ' ' . get_string('award', 'badges'),
152 'class' => 'actionbutton btn btn-secondary')
154 $actioncell->text .= html_writer::empty_tag('input', array(
155 'type' => 'submit',
156 'name' => 'revoke',
157 'value' => get_string('revoke', 'badges') . ' ' . $this->output->rarrow(),
158 'class' => 'actionbutton btn btn-secondary')
160 $actioncell->text .= html_writer::end_tag('div', array());
161 $actioncell->attributes['class'] = 'actions';
162 $potentialcell = new html_table_cell();
163 $potentialcell->text = $potentialuc->display(true);
164 $potentialcell->attributes['class'] = 'potential';
166 $table = new html_table();
167 $table->attributes['class'] = 'recipienttable boxaligncenter';
168 $table->data = array(new html_table_row(array($existingcell, $actioncell, $potentialcell)));
169 $output .= html_writer::table($table);
171 $output .= html_writer::end_tag('form');
172 return $output;
175 // Prints a badge overview infomation.
176 public function print_badge_overview($badge, $context) {
177 $display = "";
178 $languages = get_string_manager()->get_list_of_languages();
180 // Badge details.
181 $display .= $this->heading(get_string('badgedetails', 'badges'), 3);
182 $dl = array();
183 $dl[get_string('name')] = $badge->name;
184 $dl[get_string('version', 'badges')] = $badge->version;
185 $dl[get_string('language')] = $languages[$badge->language];
186 $dl[get_string('description', 'badges')] = $badge->description;
187 $dl[get_string('createdon', 'search')] = userdate($badge->timecreated);
188 $dl[get_string('badgeimage', 'badges')] = print_badge_image($badge, $context, 'large');
189 $dl[get_string('imageauthorname', 'badges')] = $badge->imageauthorname;
190 $dl[get_string('imageauthoremail', 'badges')] =
191 html_writer::tag('a', $badge->imageauthoremail, array('href' => 'mailto:' . $badge->imageauthoremail));
192 $dl[get_string('imageauthorurl', 'badges')] =
193 html_writer::link($badge->imageauthorurl, $badge->imageauthorurl, array('target' => '_blank'));
194 $dl[get_string('imagecaption', 'badges')] = $badge->imagecaption;
195 $display .= $this->definition_list($dl);
197 // Issuer details.
198 $display .= $this->heading(get_string('issuerdetails', 'badges'), 3);
199 $dl = array();
200 $dl[get_string('issuername', 'badges')] = $badge->issuername;
201 $dl[get_string('contact', 'badges')] = html_writer::tag('a', $badge->issuercontact, array('href' => 'mailto:' . $badge->issuercontact));
202 $display .= $this->definition_list($dl);
204 // Issuance details if any.
205 $display .= $this->heading(get_string('issuancedetails', 'badges'), 3);
206 if ($badge->can_expire()) {
207 if ($badge->expiredate) {
208 $display .= get_string('expiredate', 'badges', userdate($badge->expiredate));
209 } else if ($badge->expireperiod) {
210 if ($badge->expireperiod < 60) {
211 $display .= get_string('expireperiods', 'badges', round($badge->expireperiod, 2));
212 } else if ($badge->expireperiod < 60 * 60) {
213 $display .= get_string('expireperiodm', 'badges', round($badge->expireperiod / 60, 2));
214 } else if ($badge->expireperiod < 60 * 60 * 24) {
215 $display .= get_string('expireperiodh', 'badges', round($badge->expireperiod / 60 / 60, 2));
216 } else {
217 $display .= get_string('expireperiod', 'badges', round($badge->expireperiod / 60 / 60 / 24, 2));
220 } else {
221 $display .= get_string('noexpiry', 'badges');
224 // Criteria details if any.
225 $display .= $this->heading(get_string('bcriteria', 'badges'), 3);
226 if ($badge->has_criteria()) {
227 $display .= self::print_badge_criteria($badge);
228 } else {
229 $display .= get_string('nocriteria', 'badges');
230 if (has_capability('moodle/badges:configurecriteria', $context)) {
231 $display .= $this->output->single_button(
232 new moodle_url('/badges/criteria.php', array('id' => $badge->id)),
233 get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
237 // Awards details if any.
238 if (has_capability('moodle/badges:viewawarded', $context)) {
239 $display .= $this->heading(get_string('awards', 'badges'), 3);
240 if ($badge->has_awards()) {
241 $url = new moodle_url('/badges/recipients.php', array('id' => $badge->id));
242 $a = new stdClass();
243 $a->link = $url->out();
244 $a->count = count($badge->get_awards());
245 $display .= get_string('numawards', 'badges', $a);
246 } else {
247 $display .= get_string('noawards', 'badges');
250 if (has_capability('moodle/badges:awardbadge', $context) &&
251 $badge->has_manual_award_criteria() &&
252 $badge->is_active()) {
253 $display .= $this->output->single_button(
254 new moodle_url('/badges/award.php', array('id' => $badge->id)),
255 get_string('award', 'badges'), 'POST', array('class' => 'activatebadge'));
259 $display .= self::print_badge_endorsement($badge);
260 $display .= self::print_badge_related($badge);
261 $display .= self::print_badge_alignments($badge);
263 return html_writer::div($display, null, array('id' => 'badge-overview'));
266 // Prints action icons for the badge.
267 public function print_badge_table_actions($badge, $context) {
268 $actions = "";
270 if (has_capability('moodle/badges:configuredetails', $context) && $badge->has_criteria()) {
271 // Activate/deactivate badge.
272 if ($badge->status == BADGE_STATUS_INACTIVE || $badge->status == BADGE_STATUS_INACTIVE_LOCKED) {
273 // "Activate" will go to another page and ask for confirmation.
274 $url = new moodle_url('/badges/action.php');
275 $url->param('id', $badge->id);
276 $url->param('activate', true);
277 $url->param('sesskey', sesskey());
278 $return = new moodle_url(qualified_me());
279 $url->param('return', $return->out_as_local_url(false));
280 $actions .= $this->output->action_icon($url, new pix_icon('t/show', get_string('activate', 'badges'))) . " ";
281 } else {
282 $url = new moodle_url(qualified_me());
283 $url->param('lock', $badge->id);
284 $url->param('sesskey', sesskey());
285 $actions .= $this->output->action_icon($url, new pix_icon('t/hide', get_string('deactivate', 'badges'))) . " ";
289 // Award badge manually.
290 if ($badge->has_manual_award_criteria() &&
291 has_capability('moodle/badges:awardbadge', $context) &&
292 $badge->is_active()) {
293 $url = new moodle_url('/badges/award.php', array('id' => $badge->id));
294 $actions .= $this->output->action_icon($url, new pix_icon('t/award', get_string('award', 'badges'))) . " ";
297 // Edit badge.
298 if (has_capability('moodle/badges:configuredetails', $context)) {
299 $url = new moodle_url('/badges/edit.php', array('id' => $badge->id, 'action' => 'badge'));
300 $actions .= $this->output->action_icon($url, new pix_icon('t/edit', get_string('edit'))) . " ";
303 // Duplicate badge.
304 if (has_capability('moodle/badges:createbadge', $context)) {
305 $url = new moodle_url('/badges/action.php', array('copy' => '1', 'id' => $badge->id, 'sesskey' => sesskey()));
306 $actions .= $this->output->action_icon($url, new pix_icon('t/copy', get_string('copy'))) . " ";
309 // Delete badge.
310 if (has_capability('moodle/badges:deletebadge', $context)) {
311 $url = new moodle_url(qualified_me());
312 $url->param('delete', $badge->id);
313 $actions .= $this->output->action_icon($url, new pix_icon('t/delete', get_string('delete'))) . " ";
316 return $actions;
320 * Render an issued badge.
322 * @param \core_badges\output\issued_badge $ibadge
323 * @return string
325 protected function render_issued_badge(\core_badges\output\issued_badge $ibadge) {
326 $data = $ibadge->export_for_template($this);
327 return parent::render_from_template('core_badges/issued_badge', $data);
331 * Render an external badge.
333 * @param \core_badges\output\external_badge $ibadge
334 * @return string
336 protected function render_external_badge(\core_badges\output\external_badge $ibadge) {
337 $issued = $ibadge->issued;
338 $assertion = $issued->assertion;
339 $issuer = $assertion->badge->issuer;
340 $userinfo = $ibadge->recipient;
341 $table = new html_table();
342 $today = strtotime(date('Y-m-d'));
344 $output = '';
345 $output .= html_writer::start_tag('div', array('id' => 'badge'));
346 $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
347 if (isset($issued->imageUrl)) {
348 $issued->image = $issued->imageUrl;
350 if (is_object($issued->image)) {
351 if (!empty($issued->image->caption)) {
352 $issued->imagecaption = $issued->image->caption;
354 $issued->image = $issued->image->id;
356 $imagecaption = $issued->imagecaption ?? '';
357 $output .= html_writer::empty_tag('img', ['src' => $issued->image, 'width' => '100', 'alt' => $imagecaption]);
358 if (isset($assertion->expires)) {
359 $expiration = is_numeric($assertion->expires) ? $assertion->expires : strtotime($assertion->expires);
360 if ($expiration < $today) {
361 $output .= $this->output->pix_icon('i/expired',
362 get_string('expireddate', 'badges', userdate($expiration)),
363 'moodle',
364 array('class' => 'expireimage'));
367 $output .= html_writer::end_tag('div');
369 $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
371 // Recipient information.
372 $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
373 $dl = array();
374 // Technically, we should alway have a user at this point, but added an extra check just in case.
375 if ($userinfo) {
376 if (!$ibadge->valid) {
377 $notify = $this->output->notification(get_string('recipientvalidationproblem', 'badges'), 'notifynotice');
378 $dl[get_string('name')] = fullname($userinfo) . $notify;
379 } else {
380 $dl[get_string('name')] = fullname($userinfo);
382 } else {
383 $notify = $this->output->notification(get_string('recipientidentificationproblem', 'badges'), 'notifynotice');
384 $dl[get_string('name')] = $notify;
386 $output .= $this->definition_list($dl);
388 $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
389 $dl = array();
390 $dl[get_string('issuername', 'badges')] = s($issuer->name);
391 if (isset($issuer->origin)) {
392 $dl[get_string('issuerurl', 'badges')] = html_writer::tag('a', $issuer->origin, array('href' => $issuer->origin));
395 if (isset($issuer->contact)) {
396 $dl[get_string('contact', 'badges')] = obfuscate_mailto($issuer->contact);
398 $output .= $this->definition_list($dl);
400 $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
401 $dl = array();
402 $dl[get_string('name')] = s($assertion->badge->name);
403 $dl[get_string('description', 'badges')] = s($assertion->badge->description);
404 if (isset($assertion->badge->criteria)) {
405 $dl[get_string('bcriteria', 'badges')] = html_writer::tag(
406 'a',
407 s($assertion->badge->criteria),
408 array('href' => $assertion->badge->criteria)
411 $output .= $this->definition_list($dl);
413 $dl = array();
414 if (isset($assertion->issued_on)) {
415 $issuedate = is_numeric($assertion->issued_on) ? $assertion->issued_on : strtotime($assertion->issued_on);
416 $dl[get_string('dateawarded', 'badges')] = userdate($issuedate);
418 if (isset($assertion->expires)) {
419 if ($expiration < $today) {
420 $dl[get_string('expirydate', 'badges')] = userdate($expiration) . get_string('warnexpired', 'badges');
421 } else {
422 $dl[get_string('expirydate', 'badges')] = userdate($expiration);
425 if (isset($assertion->evidence)) {
426 $dl[get_string('evidence', 'badges')] = html_writer::tag(
427 'a',
428 s($assertion->evidence),
429 array('href' => $assertion->evidence)
432 if (!empty($dl)) {
433 $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
434 $output .= $this->definition_list($dl);
436 $output .= html_writer::end_tag('div');
438 return $output;
442 * Render a collection of user badges.
444 * @param \core_badges\output\badge_user_collection $badges
445 * @return string
447 protected function render_badge_user_collection(\core_badges\output\badge_user_collection $badges) {
448 global $CFG, $USER, $SITE;
449 $backpack = $badges->backpack;
450 $mybackpack = new moodle_url('/badges/mybackpack.php');
452 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
453 $htmlpagingbar = $this->render($paging);
455 // Set backpack connection string.
456 $backpackconnect = '';
457 if (!empty($CFG->badges_allowexternalbackpack) && is_null($backpack)) {
458 $backpackconnect = $this->output->box(get_string('localconnectto', 'badges', $mybackpack->out()), 'noticebox');
460 // Search box.
461 $searchform = $this->output->box($this->helper_search_form($badges->search), 'boxwidthwide boxaligncenter');
463 // Download all button.
464 $actionhtml = $this->output->single_button(
465 new moodle_url('/badges/mybadges.php', array('downloadall' => true, 'sesskey' => sesskey())),
466 get_string('downloadall'), 'POST', array('class' => 'activatebadge'));
467 $downloadall = $this->output->box('', 'col-md-3');
468 $downloadall .= $this->output->box($actionhtml, 'col-md-9');
469 $downloadall = $this->output->box($downloadall, 'row ml-5');
471 // Local badges.
472 $localhtml = html_writer::start_tag('div', array('id' => 'issued-badge-table', 'class' => 'generalbox'));
473 $sitename = format_string($SITE->fullname, true, array('context' => context_system::instance()));
474 $heading = get_string('localbadges', 'badges', $sitename);
475 $localhtml .= $this->output->heading_with_help($heading, 'localbadgesh', 'badges');
476 if ($badges->badges) {
477 $countmessage = $this->output->box(get_string('badgesearned', 'badges', $badges->totalcount));
479 $htmllist = $this->print_badges_list($badges->badges, $USER->id);
480 $localhtml .= $backpackconnect . $countmessage . $searchform;
481 $localhtml .= $htmlpagingbar . $htmllist . $htmlpagingbar . $downloadall;
482 } else {
483 $localhtml .= $searchform . $this->output->notification(get_string('nobadges', 'badges'));
485 $localhtml .= html_writer::end_tag('div');
487 // External badges.
488 $externalhtml = "";
489 if (!empty($CFG->badges_allowexternalbackpack)) {
490 $externalhtml .= html_writer::start_tag('div', array('class' => 'generalbox'));
491 $externalhtml .= $this->output->heading_with_help(get_string('externalbadges', 'badges'), 'externalbadges', 'badges');
492 if (!is_null($backpack)) {
493 if ($backpack->totalcollections == 0) {
494 $externalhtml .= get_string('nobackpackcollectionssummary', 'badges', $backpack);
495 } else {
496 if ($backpack->totalbadges == 0) {
497 $externalhtml .= get_string('nobackpackbadgessummary', 'badges', $backpack);
498 } else {
499 $externalhtml .= get_string('backpackbadgessummary', 'badges', $backpack);
500 $externalhtml .= '<br/><br/>' . $this->print_badges_list($backpack->badges, $USER->id, true, true);
503 } else {
504 $externalhtml .= get_string('externalconnectto', 'badges', $mybackpack->out());
507 $externalhtml .= html_writer::end_tag('div');
508 $attr = ['class' => 'btn btn-secondary'];
509 $label = get_string('backpackbadgessettings', 'badges');
510 $backpacksettings = html_writer::link(new moodle_url('/badges/mybackpack.php'), $label, $attr);
511 $actionshtml = $this->output->box('', 'col-md-3');
512 $actionshtml .= $this->output->box($backpacksettings, 'col-md-9');
513 $actionshtml = $this->output->box($actionshtml, 'row ml-5');
514 $externalhtml .= $actionshtml;
517 return $localhtml . $externalhtml;
521 * Render a collection of badges.
523 * @param \core_badges\output\badge_collection $badges
524 * @return string
526 protected function render_badge_collection(\core_badges\output\badge_collection $badges) {
527 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
528 $htmlpagingbar = $this->render($paging);
529 $table = new html_table();
530 $table->attributes['class'] = 'table table-bordered table-striped';
532 $sortbyname = $this->helper_sortable_heading(get_string('name'),
533 'name', $badges->sort, $badges->dir);
534 $sortbyawarded = $this->helper_sortable_heading(get_string('awardedtoyou', 'badges'),
535 'dateissued', $badges->sort, $badges->dir);
536 $table->head = array(
537 get_string('badgeimage', 'badges'),
538 $sortbyname,
539 get_string('description', 'badges'),
540 get_string('bcriteria', 'badges'),
541 $sortbyawarded
543 $table->colclasses = array('badgeimage', 'name', 'description', 'criteria', 'awards');
545 foreach ($badges->badges as $badge) {
546 $badgeimage = print_badge_image($badge, $this->page->context, 'large');
547 $name = $badge->name;
548 $description = $badge->description;
549 $criteria = self::print_badge_criteria($badge);
550 if ($badge->dateissued) {
551 $icon = new pix_icon('i/valid',
552 get_string('dateearned', 'badges',
553 userdate($badge->dateissued, get_string('strftimedatefullshort', 'core_langconfig'))));
554 $badgeurl = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
555 $awarded = $this->output->action_icon($badgeurl, $icon, null, null, true);
556 } else {
557 $awarded = "";
559 $row = array($badgeimage, $name, $description, $criteria, $awarded);
560 $table->data[] = $row;
563 $htmltable = html_writer::table($table);
565 return $htmlpagingbar . $htmltable . $htmlpagingbar;
569 * Render a table of badges.
571 * @param \core_badges\output\badge_management $badges
572 * @return string
574 protected function render_badge_management(\core_badges\output\badge_management $badges) {
575 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
577 // New badge button.
578 $htmlnew = '';
579 if (has_capability('moodle/badges:createbadge', $this->page->context)) {
580 $n['type'] = $this->page->url->get_param('type');
581 $n['id'] = $this->page->url->get_param('id');
582 $btn = $this->output->single_button(new moodle_url('newbadge.php', $n), get_string('newbadge', 'badges'));
583 $htmlnew = $this->output->box($btn);
586 $htmlpagingbar = $this->render($paging);
587 $table = new html_table();
588 $table->attributes['class'] = 'table table-bordered table-striped';
590 $sortbyname = $this->helper_sortable_heading(get_string('name'),
591 'name', $badges->sort, $badges->dir);
592 $sortbystatus = $this->helper_sortable_heading(get_string('status', 'badges'),
593 'status', $badges->sort, $badges->dir);
594 $table->head = array(
595 $sortbyname,
596 $sortbystatus,
597 get_string('bcriteria', 'badges'),
598 get_string('awards', 'badges'),
599 get_string('actions')
601 $table->colclasses = array('name', 'status', 'criteria', 'awards', 'actions');
603 foreach ($badges->badges as $b) {
604 $style = !$b->is_active() ? array('class' => 'dimmed') : array();
605 $forlink = print_badge_image($b, $this->page->context) . ' ' .
606 html_writer::start_tag('span') . $b->name . html_writer::end_tag('span');
607 $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $b->id)), $forlink, $style);
608 $status = $b->statstring;
609 $criteria = self::print_badge_criteria($b, 'short');
611 if (has_capability('moodle/badges:viewawarded', $this->page->context)) {
612 $awards = html_writer::link(new moodle_url('/badges/recipients.php', array('id' => $b->id)), $b->awards);
613 } else {
614 $awards = $b->awards;
617 $actions = self::print_badge_table_actions($b, $this->page->context);
619 $row = array($name, $status, $criteria, $awards, $actions);
620 $table->data[] = $row;
622 $htmltable = html_writer::table($table);
624 return $htmlnew . $htmlpagingbar . $htmltable . $htmlpagingbar;
628 * Prints tabs for badge editing.
630 * @param integer $badgeid The badgeid to edit.
631 * @param context $context The current context.
632 * @param string $current The currently selected tab.
633 * @return string
635 public function print_badge_tabs($badgeid, $context, $current = 'overview') {
636 global $DB;
638 $badge = new badge($badgeid);
639 $row = array();
641 $row[] = new tabobject('overview',
642 new moodle_url('/badges/overview.php', array('id' => $badgeid)),
643 get_string('boverview', 'badges')
646 if (has_capability('moodle/badges:configuredetails', $context)) {
647 $row[] = new tabobject('badge',
648 new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'badge')),
649 get_string('bdetails', 'badges')
653 if (has_capability('moodle/badges:configurecriteria', $context)) {
654 $row[] = new tabobject('criteria',
655 new moodle_url('/badges/criteria.php', array('id' => $badgeid)),
656 get_string('bcriteria', 'badges')
660 if (has_capability('moodle/badges:configuremessages', $context)) {
661 $row[] = new tabobject('message',
662 new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'message')),
663 get_string('bmessage', 'badges')
667 if (has_capability('moodle/badges:viewawarded', $context)) {
668 $awarded = $DB->count_records_sql('SELECT COUNT(b.userid)
669 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
670 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badgeid));
671 $row[] = new tabobject('awards',
672 new moodle_url('/badges/recipients.php', array('id' => $badgeid)),
673 get_string('bawards', 'badges', $awarded)
677 if (has_capability('moodle/badges:configuredetails', $context)) {
678 $row[] = new tabobject('bendorsement',
679 new moodle_url('/badges/endorsement.php', array('id' => $badgeid)),
680 get_string('bendorsement', 'badges')
684 if (has_capability('moodle/badges:configuredetails', $context)) {
685 $sql = "SELECT COUNT(br.badgeid)
686 FROM {badge_related} br
687 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2)";
688 $related = $DB->count_records_sql($sql, ['badgeid' => $badgeid, 'badgeid2' => $badgeid]);
689 $row[] = new tabobject('brelated',
690 new moodle_url('/badges/related.php', array('id' => $badgeid)),
691 get_string('brelated', 'badges', $related)
695 if (has_capability('moodle/badges:configuredetails', $context)) {
696 $alignments = $DB->count_records_sql("SELECT COUNT(bc.id)
697 FROM {badge_alignment} bc WHERE bc.badgeid = :badgeid", array('badgeid' => $badgeid));
698 $row[] = new tabobject('alignment',
699 new moodle_url('/badges/alignment.php', array('id' => $badgeid)),
700 get_string('balignment', 'badges', $alignments)
704 echo $this->tabtree($row, $current);
708 * Prints badge status box.
710 * @param badge $badge
711 * @return Either the status box html as a string or null
713 public function print_badge_status_box(badge $badge) {
714 if (has_capability('moodle/badges:configurecriteria', $badge->get_context())) {
716 if (!$badge->has_criteria()) {
717 $criteriaurl = new moodle_url('/badges/criteria.php', array('id' => $badge->id));
718 $status = get_string('nocriteria', 'badges');
719 if ($this->page->url != $criteriaurl) {
720 $action = $this->output->single_button(
721 $criteriaurl,
722 get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
723 } else {
724 $action = '';
727 $message = $status . $action;
728 } else {
729 $status = get_string('statusmessage_' . $badge->status, 'badges');
730 if ($badge->is_active()) {
731 $action = $this->output->single_button(new moodle_url('/badges/action.php',
732 array('id' => $badge->id, 'lock' => 1, 'sesskey' => sesskey(),
733 'return' => $this->page->url->out_as_local_url(false))),
734 get_string('deactivate', 'badges'), 'POST', array('class' => 'activatebadge'));
735 } else {
736 $action = $this->output->single_button(new moodle_url('/badges/action.php',
737 array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(),
738 'return' => $this->page->url->out_as_local_url(false))),
739 get_string('activate', 'badges'), 'POST', array('class' => 'activatebadge'));
742 $message = $status . $this->output->help_icon('status', 'badges') . $action;
746 $style = $badge->is_active() ? 'generalbox statusbox active' : 'generalbox statusbox inactive';
747 return $this->output->box($message, $style);
750 return null;
754 * Returns information about badge criteria in a list form.
756 * @param badge $badge Badge objects
757 * @param string $short Indicates whether to print full info about this badge
758 * @return string $output HTML string to output
760 public function print_badge_criteria(badge $badge, $short = '') {
761 $agg = $badge->get_aggregation_methods();
762 if (empty($badge->criteria)) {
763 return get_string('nocriteria', 'badges');
766 $overalldescr = '';
767 $overall = $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL];
768 if (!$short && !empty($overall->description)) {
769 $overalldescr = $this->output->box(
770 format_text($overall->description, $overall->descriptionformat, array('context' => $badge->get_context())),
771 'criteria-description'
775 // Get the condition string.
776 $condition = '';
777 if (count($badge->criteria) != 2) {
778 $condition = get_string('criteria_descr_' . $short . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
779 core_text::strtoupper($agg[$badge->get_aggregation_method()]));
782 unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
784 $items = array();
785 // If only one criterion left, make sure its description goe to the top.
786 if (count($badge->criteria) == 1) {
787 $c = reset($badge->criteria);
788 if (!$short && !empty($c->description)) {
789 $overalldescr = $this->output->box(
790 format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
791 'criteria-description'
794 if (count($c->params) == 1) {
795 $items[] = get_string('criteria_descr_single_' . $short . $c->criteriatype , 'badges') .
796 $c->get_details($short);
797 } else {
798 $items[] = get_string('criteria_descr_' . $short . $c->criteriatype, 'badges',
799 core_text::strtoupper($agg[$badge->get_aggregation_method($c->criteriatype)])) .
800 $c->get_details($short);
802 } else {
803 foreach ($badge->criteria as $type => $c) {
804 $criteriadescr = '';
805 if (!$short && !empty($c->description)) {
806 $criteriadescr = $this->output->box(
807 format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
808 'criteria-description'
811 if (count($c->params) == 1) {
812 $items[] = get_string('criteria_descr_single_' . $short . $type , 'badges') .
813 $c->get_details($short) . $criteriadescr;
814 } else {
815 $items[] = get_string('criteria_descr_' . $short . $type , 'badges',
816 core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) .
817 $c->get_details($short) .
818 $criteriadescr;
823 return $overalldescr . $condition . html_writer::alist($items, array(), 'ul');;
827 * Prints criteria actions for badge editing.
829 * @param badge $badge
830 * @return string
832 public function print_criteria_actions(badge $badge) {
833 $output = '';
834 if (!$badge->is_active() && !$badge->is_locked()) {
835 $accepted = $badge->get_accepted_criteria();
836 $potential = array_diff($accepted, array_keys($badge->criteria));
838 if (!empty($potential)) {
839 foreach ($potential as $p) {
840 if ($p != 0) {
841 $select[$p] = get_string('criteria_' . $p, 'badges');
844 $output .= $this->output->single_select(
845 new moodle_url('/badges/criteria_settings.php', array('badgeid' => $badge->id, 'add' => true)),
846 'type',
847 $select,
849 array('' => 'choosedots'),
850 null,
851 array('label' => get_string('addbadgecriteria', 'badges'))
853 } else {
854 $output .= $this->output->box(get_string('nothingtoadd', 'badges'), 'clearfix');
858 return $output;
862 * Renders a table with users who have earned the badge.
863 * Based on stamps collection plugin.
865 * @param \core_badges\output\badge_recipients $recipients
866 * @return string
868 protected function render_badge_recipients(\core_badges\output\badge_recipients $recipients) {
869 $paging = new paging_bar($recipients->totalcount, $recipients->page, $recipients->perpage, $this->page->url, 'page');
870 $htmlpagingbar = $this->render($paging);
871 $table = new html_table();
872 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
874 $sortbyfirstname = $this->helper_sortable_heading(get_string('firstname'),
875 'firstname', $recipients->sort, $recipients->dir);
876 $sortbylastname = $this->helper_sortable_heading(get_string('lastname'),
877 'lastname', $recipients->sort, $recipients->dir);
878 if ($this->helper_fullname_format() == 'lf') {
879 $sortbyname = $sortbylastname . ' / ' . $sortbyfirstname;
880 } else {
881 $sortbyname = $sortbyfirstname . ' / ' . $sortbylastname;
884 $sortbydate = $this->helper_sortable_heading(get_string('dateawarded', 'badges'),
885 'dateissued', $recipients->sort, $recipients->dir);
887 $table->head = array($sortbyname, $sortbydate, '');
889 foreach ($recipients->userids as $holder) {
890 $fullname = fullname($holder);
891 $fullname = html_writer::link(
892 new moodle_url('/user/profile.php', array('id' => $holder->userid)),
893 $fullname
895 $awarded = userdate($holder->dateissued);
896 $badgeurl = html_writer::link(
897 new moodle_url('/badges/badge.php', array('hash' => $holder->uniquehash)),
898 get_string('viewbadge', 'badges')
901 $row = array($fullname, $awarded, $badgeurl);
902 $table->data[] = $row;
905 $htmltable = html_writer::table($table);
907 return $htmlpagingbar . $htmltable . $htmlpagingbar;
910 ////////////////////////////////////////////////////////////////////////////
911 // Helper methods
912 // Reused from stamps collection plugin
913 ////////////////////////////////////////////////////////////////////////////
916 * Renders a text with icons to sort by the given column
918 * This is intended for table headings.
920 * @param string $text The heading text
921 * @param string $sortid The column id used for sorting
922 * @param string $sortby Currently sorted by (column id)
923 * @param string $sorthow Currently sorted how (ASC|DESC)
925 * @return string
927 protected function helper_sortable_heading($text, $sortid = null, $sortby = null, $sorthow = null) {
928 $out = html_writer::tag('span', $text, array('class' => 'text'));
930 if (!is_null($sortid)) {
931 if ($sortby !== $sortid || $sorthow !== 'ASC') {
932 $url = new moodle_url($this->page->url);
933 $url->params(array('sort' => $sortid, 'dir' => 'ASC'));
934 $out .= $this->output->action_icon($url,
935 new pix_icon('t/sort_asc', get_string('sortbyx', 'core', s($text)), null, array('class' => 'iconsort')));
937 if ($sortby !== $sortid || $sorthow !== 'DESC') {
938 $url = new moodle_url($this->page->url);
939 $url->params(array('sort' => $sortid, 'dir' => 'DESC'));
940 $out .= $this->output->action_icon($url,
941 new pix_icon('t/sort_desc', get_string('sortbyxreverse', 'core', s($text)), null, array('class' => 'iconsort')));
944 return $out;
947 * Tries to guess the fullname format set at the site
949 * @return string fl|lf
951 protected function helper_fullname_format() {
952 $fake = new stdClass();
953 $fake->lastname = 'LLLL';
954 $fake->firstname = 'FFFF';
955 $fullname = get_string('fullnamedisplay', '', $fake);
956 if (strpos($fullname, 'LLLL') < strpos($fullname, 'FFFF')) {
957 return 'lf';
958 } else {
959 return 'fl';
963 * Renders a search form
965 * @param string $search Search string
966 * @return string HTML
968 protected function helper_search_form($search) {
969 global $CFG;
970 require_once($CFG->libdir . '/formslib.php');
972 $mform = new MoodleQuickForm('searchform', 'POST', $this->page->url);
974 $mform->addElement('hidden', 'sesskey', sesskey());
976 $el[] = $mform->createElement('text', 'search', get_string('search'), array('size' => 20));
977 $mform->setDefault('search', $search);
978 $el[] = $mform->createElement('submit', 'submitsearch', get_string('search'));
979 $el[] = $mform->createElement('submit', 'clearsearch', get_string('clear'));
980 $mform->addGroup($el, 'searchgroup', get_string('searchname', 'badges'), ' ', false);
982 ob_start();
983 $mform->display();
984 $out = ob_get_clean();
986 return $out;
990 * Renders a definition list
992 * @param array $items the list of items to define
993 * @param array
995 protected function definition_list(array $items, array $attributes = array()) {
996 $output = html_writer::start_tag('dl', $attributes);
997 foreach ($items as $label => $value) {
998 $output .= html_writer::tag('dt', $label);
999 $output .= html_writer::tag('dd', $value);
1001 $output .= html_writer::end_tag('dl');
1002 return $output;
1006 * Outputs list en badges.
1008 * @param badge $badge Badge object.
1009 * @return string $output content endorsement to output.
1011 protected function print_badge_endorsement(badge $badge) {
1012 $output = '';
1013 $endorsement = $badge->get_endorsement();
1014 $dl = array();
1015 $output .= $this->heading(get_string('endorsement', 'badges'), 3);
1016 if (!empty($endorsement)) {
1017 $dl[get_string('issuername', 'badges')] = $endorsement->issuername;
1018 $dl[get_string('issueremail', 'badges')] =
1019 html_writer::tag('a', $endorsement->issueremail, array('href' => 'mailto:' . $endorsement->issueremail));
1020 $dl[get_string('issuerurl', 'badges')] = html_writer::link($endorsement->issuerurl, $endorsement->issuerurl,
1021 array('target' => '_blank'));
1022 $dl[get_string('dateawarded', 'badges')] = userdate($endorsement->dateissued);
1023 $dl[get_string('claimid', 'badges')] = html_writer::link($endorsement->claimid, $endorsement->claimid,
1024 array('target' => '_blank'));
1025 $dl[get_string('claimcomment', 'badges')] = $endorsement->claimcomment;
1026 $output .= $this->definition_list($dl);
1027 } else {
1028 $output .= get_string('noendorsement', 'badges');
1030 return $output;
1034 * Print list badges related.
1036 * @param badge $badge Badge objects.
1037 * @return string $output List related badges to output.
1039 protected function print_badge_related(badge $badge) {
1040 $output = '';
1041 $relatedbadges = $badge->get_related_badges();
1042 $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
1043 if (!empty($relatedbadges)) {
1044 $items = array();
1045 foreach ($relatedbadges as $related) {
1046 $relatedurl = new moodle_url('/badges/overview.php', array('id' => $related->id));
1047 $items[] = html_writer::link($relatedurl->out(), $related->name, array('target' => '_blank'));
1049 $output .= html_writer::alist($items, array(), 'ul');
1050 } else {
1051 $output .= get_string('norelated', 'badges');
1053 return $output;
1057 * Print list badge alignments.
1059 * @param badge $badge Badge objects.
1060 * @return string $output List alignments to output.
1062 protected function print_badge_alignments(badge $badge) {
1063 $output = '';
1064 $output .= $this->heading(get_string('alignment', 'badges'), 3);
1065 $alignments = $badge->get_alignments();
1066 if (!empty($alignments)) {
1067 $items = array();
1068 foreach ($alignments as $alignment) {
1069 $urlaligment = new moodle_url('alignment.php',
1070 array('id' => $badge->id, 'alignmentid' => $alignment->id)
1072 $items[] = html_writer::link($urlaligment, $alignment->targetname, array('target' => '_blank'));
1074 $output .= html_writer::alist($items, array(), 'ul');
1075 } else {
1076 $output .= get_string('noalignment', 'badges');
1078 return $output;
1082 * Renders a table for related badges.
1084 * @param \core_badges\output\badge_related $related list related badges.
1085 * @return string list related badges to output.
1087 protected function render_badge_related(\core_badges\output\badge_related $related) {
1088 $currentbadge = new badge($related->currentbadgeid);
1089 $languages = get_string_manager()->get_list_of_languages();
1090 $paging = new paging_bar($related->totalcount, $related->page, $related->perpage, $this->page->url, 'page');
1091 $htmlpagingbar = $this->render($paging);
1092 $table = new html_table();
1093 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1094 $table->head = array(
1095 get_string('name'),
1096 get_string('version', 'badges'),
1097 get_string('language', 'badges'),
1098 get_string('type', 'badges')
1100 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1101 array_push($table->head, '');
1104 foreach ($related->badges as $badge) {
1105 $badgeobject = new badge($badge->id);
1106 $style = array('title' => $badgeobject->name);
1107 if (!$badgeobject->is_active()) {
1108 $style['class'] = 'dimmed';
1110 $context = ($badgeobject->type == BADGE_TYPE_SITE) ?
1111 context_system::instance() : context_course::instance($badgeobject->courseid);
1112 $forlink = print_badge_image($badgeobject, $context) . ' ' .
1113 html_writer::start_tag('span') . $badgeobject->name . html_writer::end_tag('span');
1114 $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $badgeobject->id)), $forlink, $style);
1116 $row = array(
1117 $name,
1118 $badge->version,
1119 $badge->language ? $languages[$badge->language] : '',
1120 $badge->type == BADGE_TYPE_COURSE ? get_string('badgesview', 'badges') : get_string('sitebadges', 'badges')
1122 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1123 $action = $this->output->action_icon(
1124 new moodle_url('/badges/related_action.php', [
1125 'badgeid' => $related->currentbadgeid,
1126 'relatedid' => $badge->id,
1127 'sesskey' => sesskey(),
1128 'action' => 'remove'
1130 new pix_icon('t/delete', get_string('delete')));
1131 $actions = html_writer::tag('div', $action, array('class' => 'badge-actions'));
1132 array_push($row, $actions);
1134 $table->data[] = $row;
1136 $htmltable = html_writer::table($table);
1138 return $htmlpagingbar . $htmltable . $htmlpagingbar;
1142 * Renders a table with alignment.
1144 * @param core_badges\output\badge_alignments $alignments List alignments.
1145 * @return string List alignment to output.
1147 protected function render_badge_alignments(\core_badges\output\badge_alignments $alignments) {
1148 $currentbadge = new badge($alignments->currentbadgeid);
1149 $paging = new paging_bar($alignments->totalcount, $alignments->page, $alignments->perpage, $this->page->url, 'page');
1150 $htmlpagingbar = $this->render($paging);
1151 $table = new html_table();
1152 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1153 $table->head = array('Name', 'URL', '');
1155 foreach ($alignments->alignments as $item) {
1156 $urlaligment = new moodle_url('alignment.php',
1157 array(
1158 'id' => $currentbadge->id,
1159 'alignmentid' => $item->id,
1162 $row = array(
1163 html_writer::link($urlaligment, $item->targetname),
1164 html_writer::link($item->targeturl, $item->targeturl, array('target' => '_blank'))
1166 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1167 $delete = $this->output->action_icon(
1168 new moodle_url('/badges/alignment_action.php', [
1169 'id' => $currentbadge->id,
1170 'alignmentid' => $item->id,
1171 'sesskey' => sesskey(),
1172 'action' => 'remove'
1174 new pix_icon('t/delete', get_string('delete'))
1176 $edit = $this->output->action_icon(
1177 new moodle_url('alignment.php',
1178 array(
1179 'id' => $currentbadge->id,
1180 'alignmentid' => $item->id,
1181 'action' => 'edit'
1183 ), new pix_icon('t/edit', get_string('edit')));
1184 $actions = html_writer::tag('div', $edit . $delete, array('class' => 'badge-actions'));
1185 array_push($row, $actions);
1187 $table->data[] = $row;
1189 $htmltable = html_writer::table($table);
1191 return $htmlpagingbar . $htmltable . $htmlpagingbar;
1195 * Defer to template.
1197 * @param \core_badges\output\external_backpacks_page $page
1198 * @return bool|string
1200 public function render_external_backpacks_page(\core_badges\output\external_backpacks_page $page) {
1201 $data = $page->export_for_template($this);
1202 return parent::render_from_template('core_badges/external_backpacks_page', $data);
1206 * Get the result of a backpack validation with its settings. It returns:
1207 * - A informative message if the backpack version is different from OBv2.
1208 * - A warning with the error if it's not possible to connect to this backpack.
1209 * - A successful message if the connection has worked.
1211 * @param int $backpackid The backpack identifier.
1212 * @return string A message with the validation result.
1214 public function render_test_backpack_result(int $backpackid): string {
1215 // Get the backpack.
1216 $backpack = badges_get_site_backpack($backpackid);
1218 // Add the header to the result.
1219 $result = $this->heading(get_string('testbackpack', 'badges', $backpack->backpackweburl));
1221 if ($backpack->apiversion != OPEN_BADGES_V2) {
1222 // Only OBv2 supports this validation.
1223 $result .= get_string('backpackconnectionnottested', 'badges');
1224 } else {
1225 $message = badges_verify_backpack($backpackid);
1226 if (empty($message)) {
1227 $result .= get_string('backpackconnectionok', 'badges');
1228 } else {
1229 $result .= $message;
1233 return $result;