Merge branch 'MDL-67966-311' of https://github.com/junpataleta/moodle into MOODLE_311...
[moodle.git] / badges / renderer.php
blobbdc2dbd7023e1dd71bed2165cb8eddd2fa5e6d0b
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 issued badge.
333 * @param \core_badges\output\badgeclass $badge
334 * @return string
336 protected function render_badgeclass(\core_badges\output\badgeclass $badge) {
337 $data = $badge->export_for_template($this);
338 return parent::render_from_template('core_badges/issued_badge', $data);
342 * Render an external badge.
344 * @param \core_badges\output\external_badge $ibadge
345 * @return string
347 protected function render_external_badge(\core_badges\output\external_badge $ibadge) {
348 $data = $ibadge->export_for_template($this);
349 return parent::render_from_template('core_badges/issued_badge', $data);
353 * Render a collection of user badges.
355 * @param \core_badges\output\badge_user_collection $badges
356 * @return string
358 protected function render_badge_user_collection(\core_badges\output\badge_user_collection $badges) {
359 global $CFG, $USER, $SITE;
360 $backpack = $badges->backpack;
361 $mybackpack = new moodle_url('/badges/mybackpack.php');
363 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
364 $htmlpagingbar = $this->render($paging);
366 // Set backpack connection string.
367 $backpackconnect = '';
368 if (!empty($CFG->badges_allowexternalbackpack) && is_null($backpack)) {
369 $backpackconnect = $this->output->box(get_string('localconnectto', 'badges', $mybackpack->out()), 'noticebox');
371 // Search box.
372 $searchform = $this->output->box($this->helper_search_form($badges->search), 'boxwidthwide boxaligncenter');
374 // Download all button.
375 $actionhtml = $this->output->single_button(
376 new moodle_url('/badges/mybadges.php', array('downloadall' => true, 'sesskey' => sesskey())),
377 get_string('downloadall'), 'POST', array('class' => 'activatebadge'));
378 $downloadall = $this->output->box('', 'col-md-3');
379 $downloadall .= $this->output->box($actionhtml, 'col-md-9');
380 $downloadall = $this->output->box($downloadall, 'row ml-5');
382 // Local badges.
383 $localhtml = html_writer::start_tag('div', array('id' => 'issued-badge-table', 'class' => 'generalbox'));
384 $sitename = format_string($SITE->fullname, true, array('context' => context_system::instance()));
385 $heading = get_string('localbadges', 'badges', $sitename);
386 $localhtml .= $this->output->heading_with_help($heading, 'localbadgesh', 'badges');
387 if ($badges->badges) {
388 $countmessage = $this->output->box(get_string('badgesearned', 'badges', $badges->totalcount));
390 $htmllist = $this->print_badges_list($badges->badges, $USER->id);
391 $localhtml .= $backpackconnect . $countmessage . $searchform;
392 $localhtml .= $htmlpagingbar . $htmllist . $htmlpagingbar . $downloadall;
393 } else {
394 $localhtml .= $searchform . $this->output->notification(get_string('nobadges', 'badges'));
396 $localhtml .= html_writer::end_tag('div');
398 // External badges.
399 $externalhtml = "";
400 if (!empty($CFG->badges_allowexternalbackpack)) {
401 $externalhtml .= html_writer::start_tag('div', array('class' => 'generalbox'));
402 $externalhtml .= $this->output->heading_with_help(get_string('externalbadges', 'badges'), 'externalbadges', 'badges');
403 if (!is_null($backpack)) {
404 if ($backpack->totalcollections == 0) {
405 $externalhtml .= get_string('nobackpackcollectionssummary', 'badges', $backpack);
406 } else {
407 if ($backpack->totalbadges == 0) {
408 $externalhtml .= get_string('nobackpackbadgessummary', 'badges', $backpack);
409 } else {
410 $externalhtml .= get_string('backpackbadgessummary', 'badges', $backpack);
411 $externalhtml .= '<br/><br/>' . $this->print_badges_list($backpack->badges, $USER->id, true, true);
414 } else {
415 $externalhtml .= get_string('externalconnectto', 'badges', $mybackpack->out());
418 $externalhtml .= html_writer::end_tag('div');
419 $attr = ['class' => 'btn btn-secondary'];
420 $label = get_string('backpackbadgessettings', 'badges');
421 $backpacksettings = html_writer::link(new moodle_url('/badges/mybackpack.php'), $label, $attr);
422 $actionshtml = $this->output->box('', 'col-md-3');
423 $actionshtml .= $this->output->box($backpacksettings, 'col-md-9');
424 $actionshtml = $this->output->box($actionshtml, 'row ml-5');
425 $externalhtml .= $actionshtml;
428 return $localhtml . $externalhtml;
432 * Render a collection of badges.
434 * @param \core_badges\output\badge_collection $badges
435 * @return string
437 protected function render_badge_collection(\core_badges\output\badge_collection $badges) {
438 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
439 $htmlpagingbar = $this->render($paging);
440 $table = new html_table();
441 $table->attributes['class'] = 'table table-bordered table-striped';
443 $sortbyname = $this->helper_sortable_heading(get_string('name'),
444 'name', $badges->sort, $badges->dir);
445 $sortbyawarded = $this->helper_sortable_heading(get_string('awardedtoyou', 'badges'),
446 'dateissued', $badges->sort, $badges->dir);
447 $table->head = array(
448 get_string('badgeimage', 'badges'),
449 $sortbyname,
450 get_string('description', 'badges'),
451 get_string('bcriteria', 'badges'),
452 $sortbyawarded
454 $table->colclasses = array('badgeimage', 'name', 'description', 'criteria', 'awards');
456 foreach ($badges->badges as $badge) {
457 $badgeimage = print_badge_image($badge, $this->page->context, 'large');
458 $name = $badge->name;
459 $description = $badge->description;
460 $criteria = self::print_badge_criteria($badge);
461 if ($badge->dateissued) {
462 $icon = new pix_icon('i/valid',
463 get_string('dateearned', 'badges',
464 userdate($badge->dateissued, get_string('strftimedatefullshort', 'core_langconfig'))));
465 $badgeurl = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
466 $awarded = $this->output->action_icon($badgeurl, $icon, null, null, true);
467 } else {
468 $awarded = "";
470 $row = array($badgeimage, $name, $description, $criteria, $awarded);
471 $table->data[] = $row;
474 $htmltable = html_writer::table($table);
476 return $htmlpagingbar . $htmltable . $htmlpagingbar;
480 * Render a table of badges.
482 * @param \core_badges\output\badge_management $badges
483 * @return string
485 protected function render_badge_management(\core_badges\output\badge_management $badges) {
486 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
488 // New badge button.
489 $htmlnew = '';
490 if (has_capability('moodle/badges:createbadge', $this->page->context)) {
491 $n['type'] = $this->page->url->get_param('type');
492 $n['id'] = $this->page->url->get_param('id');
493 $btn = $this->output->single_button(new moodle_url('newbadge.php', $n), get_string('newbadge', 'badges'));
494 $htmlnew = $this->output->box($btn);
497 $htmlpagingbar = $this->render($paging);
498 $table = new html_table();
499 $table->attributes['class'] = 'table table-bordered table-striped';
501 $sortbyname = $this->helper_sortable_heading(get_string('name'),
502 'name', $badges->sort, $badges->dir);
503 $sortbystatus = $this->helper_sortable_heading(get_string('status', 'badges'),
504 'status', $badges->sort, $badges->dir);
505 $table->head = array(
506 $sortbyname,
507 $sortbystatus,
508 get_string('bcriteria', 'badges'),
509 get_string('awards', 'badges'),
510 get_string('actions')
512 $table->colclasses = array('name', 'status', 'criteria', 'awards', 'actions');
514 foreach ($badges->badges as $b) {
515 $style = !$b->is_active() ? array('class' => 'dimmed') : array();
516 $forlink = print_badge_image($b, $this->page->context) . ' ' .
517 html_writer::start_tag('span') . $b->name . html_writer::end_tag('span');
518 $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $b->id)), $forlink, $style);
519 $status = $b->statstring;
520 $criteria = self::print_badge_criteria($b, 'short');
522 if (has_capability('moodle/badges:viewawarded', $this->page->context)) {
523 $awards = html_writer::link(new moodle_url('/badges/recipients.php', array('id' => $b->id)), $b->awards);
524 } else {
525 $awards = $b->awards;
528 $actions = self::print_badge_table_actions($b, $this->page->context);
530 $row = array($name, $status, $criteria, $awards, $actions);
531 $table->data[] = $row;
533 $htmltable = html_writer::table($table);
535 return $htmlnew . $htmlpagingbar . $htmltable . $htmlpagingbar;
539 * Prints tabs for badge editing.
541 * @param integer $badgeid The badgeid to edit.
542 * @param context $context The current context.
543 * @param string $current The currently selected tab.
544 * @return string
546 public function print_badge_tabs($badgeid, $context, $current = 'overview') {
547 global $DB;
549 $badge = new badge($badgeid);
550 $row = array();
552 $row[] = new tabobject('overview',
553 new moodle_url('/badges/overview.php', array('id' => $badgeid)),
554 get_string('boverview', 'badges')
557 if (has_capability('moodle/badges:configuredetails', $context)) {
558 $row[] = new tabobject('badge',
559 new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'badge')),
560 get_string('bdetails', 'badges')
564 if (has_capability('moodle/badges:configurecriteria', $context)) {
565 $row[] = new tabobject('criteria',
566 new moodle_url('/badges/criteria.php', array('id' => $badgeid)),
567 get_string('bcriteria', 'badges')
571 if (has_capability('moodle/badges:configuremessages', $context)) {
572 $row[] = new tabobject('message',
573 new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'message')),
574 get_string('bmessage', 'badges')
578 if (has_capability('moodle/badges:viewawarded', $context)) {
579 $awarded = $DB->count_records_sql('SELECT COUNT(b.userid)
580 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
581 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badgeid));
582 $row[] = new tabobject('awards',
583 new moodle_url('/badges/recipients.php', array('id' => $badgeid)),
584 get_string('bawards', 'badges', $awarded)
588 if (has_capability('moodle/badges:configuredetails', $context)) {
589 $row[] = new tabobject('bendorsement',
590 new moodle_url('/badges/endorsement.php', array('id' => $badgeid)),
591 get_string('bendorsement', 'badges')
595 if (has_capability('moodle/badges:configuredetails', $context)) {
596 $sql = "SELECT COUNT(br.badgeid)
597 FROM {badge_related} br
598 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2)";
599 $related = $DB->count_records_sql($sql, ['badgeid' => $badgeid, 'badgeid2' => $badgeid]);
600 $row[] = new tabobject('brelated',
601 new moodle_url('/badges/related.php', array('id' => $badgeid)),
602 get_string('brelated', 'badges', $related)
606 if (has_capability('moodle/badges:configuredetails', $context)) {
607 $alignments = $DB->count_records_sql("SELECT COUNT(bc.id)
608 FROM {badge_alignment} bc WHERE bc.badgeid = :badgeid", array('badgeid' => $badgeid));
609 $row[] = new tabobject('alignment',
610 new moodle_url('/badges/alignment.php', array('id' => $badgeid)),
611 get_string('balignment', 'badges', $alignments)
615 echo $this->tabtree($row, $current);
619 * Prints badge status box.
621 * @param badge $badge
622 * @return Either the status box html as a string or null
624 public function print_badge_status_box(badge $badge) {
625 if (has_capability('moodle/badges:configurecriteria', $badge->get_context())) {
627 if (!$badge->has_criteria()) {
628 $criteriaurl = new moodle_url('/badges/criteria.php', array('id' => $badge->id));
629 $status = get_string('nocriteria', 'badges');
630 if ($this->page->url != $criteriaurl) {
631 $action = $this->output->single_button(
632 $criteriaurl,
633 get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
634 } else {
635 $action = '';
638 $message = $status . $action;
639 } else {
640 $status = get_string('statusmessage_' . $badge->status, 'badges');
641 if ($badge->is_active()) {
642 $action = $this->output->single_button(new moodle_url('/badges/action.php',
643 array('id' => $badge->id, 'lock' => 1, 'sesskey' => sesskey(),
644 'return' => $this->page->url->out_as_local_url(false))),
645 get_string('deactivate', 'badges'), 'POST', array('class' => 'activatebadge'));
646 } else {
647 $action = $this->output->single_button(new moodle_url('/badges/action.php',
648 array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(),
649 'return' => $this->page->url->out_as_local_url(false))),
650 get_string('activate', 'badges'), 'POST', array('class' => 'activatebadge'));
653 $message = $status . $this->output->help_icon('status', 'badges') . $action;
657 $style = $badge->is_active() ? 'generalbox statusbox active' : 'generalbox statusbox inactive';
658 return $this->output->box($message, $style);
661 return null;
665 * Returns information about badge criteria in a list form.
667 * @param badge $badge Badge objects
668 * @param string $short Indicates whether to print full info about this badge
669 * @return string $output HTML string to output
671 public function print_badge_criteria(badge $badge, $short = '') {
672 $agg = $badge->get_aggregation_methods();
673 if (empty($badge->criteria)) {
674 return get_string('nocriteria', 'badges');
677 $overalldescr = '';
678 $overall = $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL];
679 if (!$short && !empty($overall->description)) {
680 $overalldescr = $this->output->box(
681 format_text($overall->description, $overall->descriptionformat, array('context' => $badge->get_context())),
682 'criteria-description'
686 // Get the condition string.
687 $condition = '';
688 if (count($badge->criteria) != 2) {
689 $condition = get_string('criteria_descr_' . $short . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
690 core_text::strtoupper($agg[$badge->get_aggregation_method()]));
693 unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
695 $items = array();
696 // If only one criterion left, make sure its description goe to the top.
697 if (count($badge->criteria) == 1) {
698 $c = reset($badge->criteria);
699 if (!$short && !empty($c->description)) {
700 $overalldescr = $this->output->box(
701 format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
702 'criteria-description'
705 if (count($c->params) == 1) {
706 $items[] = get_string('criteria_descr_single_' . $short . $c->criteriatype , 'badges') .
707 $c->get_details($short);
708 } else {
709 $items[] = get_string('criteria_descr_' . $short . $c->criteriatype, 'badges',
710 core_text::strtoupper($agg[$badge->get_aggregation_method($c->criteriatype)])) .
711 $c->get_details($short);
713 } else {
714 foreach ($badge->criteria as $type => $c) {
715 $criteriadescr = '';
716 if (!$short && !empty($c->description)) {
717 $criteriadescr = $this->output->box(
718 format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
719 'criteria-description'
722 if (count($c->params) == 1) {
723 $items[] = get_string('criteria_descr_single_' . $short . $type , 'badges') .
724 $c->get_details($short) . $criteriadescr;
725 } else {
726 $items[] = get_string('criteria_descr_' . $short . $type , 'badges',
727 core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) .
728 $c->get_details($short) .
729 $criteriadescr;
734 return $overalldescr . $condition . html_writer::alist($items, array(), 'ul');;
738 * Prints criteria actions for badge editing.
740 * @param badge $badge
741 * @return string
743 public function print_criteria_actions(badge $badge) {
744 $output = '';
745 if (!$badge->is_active() && !$badge->is_locked()) {
746 $accepted = $badge->get_accepted_criteria();
747 $potential = array_diff($accepted, array_keys($badge->criteria));
749 if (!empty($potential)) {
750 foreach ($potential as $p) {
751 if ($p != 0) {
752 $select[$p] = get_string('criteria_' . $p, 'badges');
755 $output .= $this->output->single_select(
756 new moodle_url('/badges/criteria_settings.php', array('badgeid' => $badge->id, 'add' => true)),
757 'type',
758 $select,
760 array('' => 'choosedots'),
761 null,
762 array('label' => get_string('addbadgecriteria', 'badges'))
764 } else {
765 $output .= $this->output->box(get_string('nothingtoadd', 'badges'), 'clearfix');
769 return $output;
773 * Renders a table with users who have earned the badge.
774 * Based on stamps collection plugin.
776 * @param \core_badges\output\badge_recipients $recipients
777 * @return string
779 protected function render_badge_recipients(\core_badges\output\badge_recipients $recipients) {
780 $paging = new paging_bar($recipients->totalcount, $recipients->page, $recipients->perpage, $this->page->url, 'page');
781 $htmlpagingbar = $this->render($paging);
782 $table = new html_table();
783 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
785 $sortbyfirstname = $this->helper_sortable_heading(get_string('firstname'),
786 'firstname', $recipients->sort, $recipients->dir);
787 $sortbylastname = $this->helper_sortable_heading(get_string('lastname'),
788 'lastname', $recipients->sort, $recipients->dir);
789 if ($this->helper_fullname_format() == 'lf') {
790 $sortbyname = $sortbylastname . ' / ' . $sortbyfirstname;
791 } else {
792 $sortbyname = $sortbyfirstname . ' / ' . $sortbylastname;
795 $sortbydate = $this->helper_sortable_heading(get_string('dateawarded', 'badges'),
796 'dateissued', $recipients->sort, $recipients->dir);
798 $table->head = array($sortbyname, $sortbydate, '');
800 foreach ($recipients->userids as $holder) {
801 $fullname = fullname($holder);
802 $fullname = html_writer::link(
803 new moodle_url('/user/profile.php', array('id' => $holder->userid)),
804 $fullname
806 $awarded = userdate($holder->dateissued);
807 $badgeurl = html_writer::link(
808 new moodle_url('/badges/badge.php', array('hash' => $holder->uniquehash)),
809 get_string('viewbadge', 'badges')
812 $row = array($fullname, $awarded, $badgeurl);
813 $table->data[] = $row;
816 $htmltable = html_writer::table($table);
818 return $htmlpagingbar . $htmltable . $htmlpagingbar;
821 ////////////////////////////////////////////////////////////////////////////
822 // Helper methods
823 // Reused from stamps collection plugin
824 ////////////////////////////////////////////////////////////////////////////
827 * Renders a text with icons to sort by the given column
829 * This is intended for table headings.
831 * @param string $text The heading text
832 * @param string $sortid The column id used for sorting
833 * @param string $sortby Currently sorted by (column id)
834 * @param string $sorthow Currently sorted how (ASC|DESC)
836 * @return string
838 protected function helper_sortable_heading($text, $sortid = null, $sortby = null, $sorthow = null) {
839 $out = html_writer::tag('span', $text, array('class' => 'text'));
841 if (!is_null($sortid)) {
842 if ($sortby !== $sortid || $sorthow !== 'ASC') {
843 $url = new moodle_url($this->page->url);
844 $url->params(array('sort' => $sortid, 'dir' => 'ASC'));
845 $out .= $this->output->action_icon($url,
846 new pix_icon('t/sort_asc', get_string('sortbyx', 'core', s($text)), null, array('class' => 'iconsort')));
848 if ($sortby !== $sortid || $sorthow !== 'DESC') {
849 $url = new moodle_url($this->page->url);
850 $url->params(array('sort' => $sortid, 'dir' => 'DESC'));
851 $out .= $this->output->action_icon($url,
852 new pix_icon('t/sort_desc', get_string('sortbyxreverse', 'core', s($text)), null, array('class' => 'iconsort')));
855 return $out;
858 * Tries to guess the fullname format set at the site
860 * @return string fl|lf
862 protected function helper_fullname_format() {
863 $fake = new stdClass();
864 $fake->lastname = 'LLLL';
865 $fake->firstname = 'FFFF';
866 $fullname = get_string('fullnamedisplay', '', $fake);
867 if (strpos($fullname, 'LLLL') < strpos($fullname, 'FFFF')) {
868 return 'lf';
869 } else {
870 return 'fl';
874 * Renders a search form
876 * @param string $search Search string
877 * @return string HTML
879 protected function helper_search_form($search) {
880 global $CFG;
881 require_once($CFG->libdir . '/formslib.php');
883 $mform = new MoodleQuickForm('searchform', 'POST', $this->page->url);
885 $mform->addElement('hidden', 'sesskey', sesskey());
887 $el[] = $mform->createElement('text', 'search', get_string('search'), array('size' => 20));
888 $mform->setDefault('search', $search);
889 $el[] = $mform->createElement('submit', 'submitsearch', get_string('search'));
890 $el[] = $mform->createElement('submit', 'clearsearch', get_string('clear'));
891 $mform->addGroup($el, 'searchgroup', get_string('searchname', 'badges'), ' ', false);
893 ob_start();
894 $mform->display();
895 $out = ob_get_clean();
897 return $out;
901 * Renders a definition list
903 * @param array $items the list of items to define
904 * @param array
906 protected function definition_list(array $items, array $attributes = array()) {
907 $output = html_writer::start_tag('dl', $attributes);
908 foreach ($items as $label => $value) {
909 $output .= html_writer::tag('dt', $label);
910 $output .= html_writer::tag('dd', $value);
912 $output .= html_writer::end_tag('dl');
913 return $output;
917 * Outputs list en badges.
919 * @param badge $badge Badge object.
920 * @return string $output content endorsement to output.
922 protected function print_badge_endorsement(badge $badge) {
923 $output = '';
924 $endorsement = $badge->get_endorsement();
925 $dl = array();
926 $output .= $this->heading(get_string('endorsement', 'badges'), 3);
927 if (!empty($endorsement)) {
928 $dl[get_string('issuername', 'badges')] = $endorsement->issuername;
929 $dl[get_string('issueremail', 'badges')] =
930 html_writer::tag('a', $endorsement->issueremail, array('href' => 'mailto:' . $endorsement->issueremail));
931 $dl[get_string('issuerurl', 'badges')] = html_writer::link($endorsement->issuerurl, $endorsement->issuerurl,
932 array('target' => '_blank'));
933 $dl[get_string('dateawarded', 'badges')] = userdate($endorsement->dateissued);
934 $dl[get_string('claimid', 'badges')] = html_writer::link($endorsement->claimid, $endorsement->claimid,
935 array('target' => '_blank'));
936 $dl[get_string('claimcomment', 'badges')] = $endorsement->claimcomment;
937 $output .= $this->definition_list($dl);
938 } else {
939 $output .= get_string('noendorsement', 'badges');
941 return $output;
945 * Print list badges related.
947 * @param badge $badge Badge objects.
948 * @return string $output List related badges to output.
950 protected function print_badge_related(badge $badge) {
951 $output = '';
952 $relatedbadges = $badge->get_related_badges();
953 $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
954 if (!empty($relatedbadges)) {
955 $items = array();
956 foreach ($relatedbadges as $related) {
957 $relatedurl = new moodle_url('/badges/overview.php', array('id' => $related->id));
958 $items[] = html_writer::link($relatedurl->out(), $related->name, array('target' => '_blank'));
960 $output .= html_writer::alist($items, array(), 'ul');
961 } else {
962 $output .= get_string('norelated', 'badges');
964 return $output;
968 * Print list badge alignments.
970 * @param badge $badge Badge objects.
971 * @return string $output List alignments to output.
973 protected function print_badge_alignments(badge $badge) {
974 $output = '';
975 $output .= $this->heading(get_string('alignment', 'badges'), 3);
976 $alignments = $badge->get_alignments();
977 if (!empty($alignments)) {
978 $items = array();
979 foreach ($alignments as $alignment) {
980 $urlaligment = new moodle_url('alignment.php',
981 array('id' => $badge->id, 'alignmentid' => $alignment->id)
983 $items[] = html_writer::link($urlaligment, $alignment->targetname, array('target' => '_blank'));
985 $output .= html_writer::alist($items, array(), 'ul');
986 } else {
987 $output .= get_string('noalignment', 'badges');
989 return $output;
993 * Renders a table for related badges.
995 * @param \core_badges\output\badge_related $related list related badges.
996 * @return string list related badges to output.
998 protected function render_badge_related(\core_badges\output\badge_related $related) {
999 $currentbadge = new badge($related->currentbadgeid);
1000 $languages = get_string_manager()->get_list_of_languages();
1001 $paging = new paging_bar($related->totalcount, $related->page, $related->perpage, $this->page->url, 'page');
1002 $htmlpagingbar = $this->render($paging);
1003 $table = new html_table();
1004 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1005 $table->head = array(
1006 get_string('name'),
1007 get_string('version', 'badges'),
1008 get_string('language', 'badges'),
1009 get_string('type', 'badges')
1011 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1012 array_push($table->head, '');
1015 foreach ($related->badges as $badge) {
1016 $badgeobject = new badge($badge->id);
1017 $style = array('title' => $badgeobject->name);
1018 if (!$badgeobject->is_active()) {
1019 $style['class'] = 'dimmed';
1021 $context = ($badgeobject->type == BADGE_TYPE_SITE) ?
1022 context_system::instance() : context_course::instance($badgeobject->courseid);
1023 $forlink = print_badge_image($badgeobject, $context) . ' ' .
1024 html_writer::start_tag('span') . $badgeobject->name . html_writer::end_tag('span');
1025 $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $badgeobject->id)), $forlink, $style);
1027 $row = array(
1028 $name,
1029 $badge->version,
1030 $badge->language ? $languages[$badge->language] : '',
1031 $badge->type == BADGE_TYPE_COURSE ? get_string('badgesview', 'badges') : get_string('sitebadges', 'badges')
1033 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1034 $action = $this->output->action_icon(
1035 new moodle_url('/badges/related_action.php', [
1036 'badgeid' => $related->currentbadgeid,
1037 'relatedid' => $badge->id,
1038 'sesskey' => sesskey(),
1039 'action' => 'remove'
1041 new pix_icon('t/delete', get_string('delete')));
1042 $actions = html_writer::tag('div', $action, array('class' => 'badge-actions'));
1043 array_push($row, $actions);
1045 $table->data[] = $row;
1047 $htmltable = html_writer::table($table);
1049 return $htmlpagingbar . $htmltable . $htmlpagingbar;
1053 * Renders a table with alignment.
1055 * @param core_badges\output\badge_alignments $alignments List alignments.
1056 * @return string List alignment to output.
1058 protected function render_badge_alignments(\core_badges\output\badge_alignments $alignments) {
1059 $currentbadge = new badge($alignments->currentbadgeid);
1060 $paging = new paging_bar($alignments->totalcount, $alignments->page, $alignments->perpage, $this->page->url, 'page');
1061 $htmlpagingbar = $this->render($paging);
1062 $table = new html_table();
1063 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1064 $table->head = array('Name', 'URL', '');
1066 foreach ($alignments->alignments as $item) {
1067 $urlaligment = new moodle_url('alignment.php',
1068 array(
1069 'id' => $currentbadge->id,
1070 'alignmentid' => $item->id,
1073 $row = array(
1074 html_writer::link($urlaligment, $item->targetname),
1075 html_writer::link($item->targeturl, $item->targeturl, array('target' => '_blank'))
1077 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1078 $delete = $this->output->action_icon(
1079 new moodle_url('/badges/alignment_action.php', [
1080 'id' => $currentbadge->id,
1081 'alignmentid' => $item->id,
1082 'sesskey' => sesskey(),
1083 'action' => 'remove'
1085 new pix_icon('t/delete', get_string('delete'))
1087 $edit = $this->output->action_icon(
1088 new moodle_url('alignment.php',
1089 array(
1090 'id' => $currentbadge->id,
1091 'alignmentid' => $item->id,
1092 'action' => 'edit'
1094 ), new pix_icon('t/edit', get_string('edit')));
1095 $actions = html_writer::tag('div', $edit . $delete, array('class' => 'badge-actions'));
1096 array_push($row, $actions);
1098 $table->data[] = $row;
1100 $htmltable = html_writer::table($table);
1102 return $htmlpagingbar . $htmltable . $htmlpagingbar;
1106 * Defer to template.
1108 * @param \core_badges\output\external_backpacks_page $page
1109 * @return bool|string
1111 public function render_external_backpacks_page(\core_badges\output\external_backpacks_page $page) {
1112 $data = $page->export_for_template($this);
1113 return parent::render_from_template('core_badges/external_backpacks_page', $data);
1117 * Get the result of a backpack validation with its settings. It returns:
1118 * - A informative message if the backpack version is different from OBv2.
1119 * - A warning with the error if it's not possible to connect to this backpack.
1120 * - A successful message if the connection has worked.
1122 * @param int $backpackid The backpack identifier.
1123 * @return string A message with the validation result.
1125 public function render_test_backpack_result(int $backpackid): string {
1126 // Get the backpack.
1127 $backpack = badges_get_site_backpack($backpackid);
1129 // Add the header to the result.
1130 $result = $this->heading(get_string('testbackpack', 'badges', $backpack->backpackweburl));
1132 if ($backpack->apiversion != OPEN_BADGES_V2) {
1133 // Only OBv2 supports this validation.
1134 $result .= get_string('backpackconnectionnottested', 'badges');
1135 } else {
1136 $message = badges_verify_backpack($backpackid);
1137 if (empty($message)) {
1138 $result .= get_string('backpackconnectionok', 'badges');
1139 } else {
1140 $result .= $message;
1144 return $result;