Merge branch 'MDL-64676-master' of https://github.com/aanabit/moodle
[moodle.git] / badges / renderer.php
bloba401c950cc39a461c718072c236b25c4db3740f5
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 require_once($CFG->libdir . '/badgeslib.php');
28 require_once($CFG->libdir . '/tablelib.php');
30 /**
31 * Standard HTML output renderer for badges
33 class core_badges_renderer extends plugin_renderer_base {
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 = s($badge->assertion->badge->name);
45 $imageurl = $badge->imageUrl;
48 $name = html_writer::tag('span', $bname, array('class' => 'badge-name'));
50 $image = html_writer::empty_tag('img', array('src' => $imageurl, 'class' => 'badge-image'));
51 if (!empty($badge->dateexpire) && $badge->dateexpire < time()) {
52 $image .= $this->output->pix_icon('i/expired',
53 get_string('expireddate', 'badges', userdate($badge->dateexpire)),
54 'moodle',
55 array('class' => 'expireimage'));
56 $name .= '(' . get_string('expired', 'badges') . ')';
59 $download = $status = $push = '';
60 if (($userid == $USER->id) && !$profile) {
61 $url = new moodle_url('mybadges.php', array('download' => $badge->id, 'hash' => $badge->uniquehash, 'sesskey' => sesskey()));
62 $notexpiredbadge = (empty($badge->dateexpire) || $badge->dateexpire > time());
63 $backpackexists = badges_user_has_backpack($USER->id);
64 if (!empty($CFG->badges_allowexternalbackpack) && $notexpiredbadge && $backpackexists) {
65 $assertion = new moodle_url('/badges/assertion.php', array('b' => $badge->uniquehash));
66 $action = new component_action('click', 'addtobackpack', array('assertion' => $assertion->out(false)));
67 $push = $this->output->action_icon(new moodle_url('#'), new pix_icon('t/backpack', get_string('addtobackpack', 'badges')), $action);
70 $download = $this->output->action_icon($url, new pix_icon('t/download', get_string('download')));
71 if ($badge->visible) {
72 $url = new moodle_url('mybadges.php', array('hide' => $badge->issuedid, 'sesskey' => sesskey()));
73 $status = $this->output->action_icon($url, new pix_icon('t/hide', get_string('makeprivate', 'badges')));
74 } else {
75 $url = new moodle_url('mybadges.php', array('show' => $badge->issuedid, 'sesskey' => sesskey()));
76 $status = $this->output->action_icon($url, new pix_icon('t/show', get_string('makepublic', 'badges')));
80 if (!$profile) {
81 $url = new moodle_url('badge.php', array('hash' => $badge->uniquehash));
82 } else {
83 if (!$external) {
84 $url = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
85 } else {
86 $hash = hash('md5', $badge->hostedUrl);
87 $url = new moodle_url('/badges/external.php', array('hash' => $hash, 'user' => $userid));
90 $actions = html_writer::tag('div', $push . $download . $status, array('class' => 'badge-actions'));
91 $items[] = html_writer::link($url, $image . $actions . $name, array('title' => $bname));
94 return html_writer::alist($items, array('class' => 'badges'));
97 // Recipients selection form.
98 public function recipients_selection_form(user_selector_base $existinguc, user_selector_base $potentialuc) {
99 $output = '';
100 $formattributes = array();
101 $formattributes['id'] = 'recipientform';
102 $formattributes['action'] = $this->page->url;
103 $formattributes['method'] = 'post';
104 $output .= html_writer::start_tag('form', $formattributes);
105 $output .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
107 $existingcell = new html_table_cell();
108 $existingcell->text = $existinguc->display(true);
109 $existingcell->attributes['class'] = 'existing';
110 $actioncell = new html_table_cell();
111 $actioncell->text = html_writer::start_tag('div', array());
112 $actioncell->text .= html_writer::empty_tag('input', array(
113 'type' => 'submit',
114 'name' => 'award',
115 'value' => $this->output->larrow() . ' ' . get_string('award', 'badges'),
116 'class' => 'actionbutton btn btn-secondary')
118 $actioncell->text .= html_writer::empty_tag('input', array(
119 'type' => 'submit',
120 'name' => 'revoke',
121 'value' => get_string('revoke', 'badges') . ' ' . $this->output->rarrow(),
122 'class' => 'actionbutton btn btn-secondary')
124 $actioncell->text .= html_writer::end_tag('div', array());
125 $actioncell->attributes['class'] = 'actions';
126 $potentialcell = new html_table_cell();
127 $potentialcell->text = $potentialuc->display(true);
128 $potentialcell->attributes['class'] = 'potential';
130 $table = new html_table();
131 $table->attributes['class'] = 'recipienttable boxaligncenter';
132 $table->data = array(new html_table_row(array($existingcell, $actioncell, $potentialcell)));
133 $output .= html_writer::table($table);
135 $output .= html_writer::end_tag('form');
136 return $output;
139 // Prints a badge overview infomation.
140 public function print_badge_overview($badge, $context) {
141 $display = "";
142 $languages = get_string_manager()->get_list_of_languages();
144 // Badge details.
145 $display .= $this->heading(get_string('badgedetails', 'badges'), 3);
146 $dl = array();
147 $dl[get_string('name')] = $badge->name;
148 $dl[get_string('version', 'badges')] = $badge->version;
149 $dl[get_string('language')] = $languages[$badge->language];
150 $dl[get_string('description', 'badges')] = $badge->description;
151 $dl[get_string('createdon', 'search')] = userdate($badge->timecreated);
152 $dl[get_string('badgeimage', 'badges')] = print_badge_image($badge, $context, 'large');
153 $dl[get_string('imageauthorname', 'badges')] = $badge->imageauthorname;
154 $dl[get_string('imageauthoremail', 'badges')] =
155 html_writer::tag('a', $badge->imageauthoremail, array('href' => 'mailto:' . $badge->imageauthoremail));
156 $dl[get_string('imageauthorurl', 'badges')] =
157 html_writer::link($badge->imageauthorurl, $badge->imageauthorurl, array('target' => '_blank'));
158 $dl[get_string('imagecaption', 'badges')] = $badge->imagecaption;
159 $display .= $this->definition_list($dl);
161 // Issuer details.
162 $display .= $this->heading(get_string('issuerdetails', 'badges'), 3);
163 $dl = array();
164 $dl[get_string('issuername', 'badges')] = $badge->issuername;
165 $dl[get_string('contact', 'badges')] = html_writer::tag('a', $badge->issuercontact, array('href' => 'mailto:' . $badge->issuercontact));
166 $display .= $this->definition_list($dl);
168 // Issuance details if any.
169 $display .= $this->heading(get_string('issuancedetails', 'badges'), 3);
170 if ($badge->can_expire()) {
171 if ($badge->expiredate) {
172 $display .= get_string('expiredate', 'badges', userdate($badge->expiredate));
173 } else if ($badge->expireperiod) {
174 if ($badge->expireperiod < 60) {
175 $display .= get_string('expireperiods', 'badges', round($badge->expireperiod, 2));
176 } else if ($badge->expireperiod < 60 * 60) {
177 $display .= get_string('expireperiodm', 'badges', round($badge->expireperiod / 60, 2));
178 } else if ($badge->expireperiod < 60 * 60 * 24) {
179 $display .= get_string('expireperiodh', 'badges', round($badge->expireperiod / 60 / 60, 2));
180 } else {
181 $display .= get_string('expireperiod', 'badges', round($badge->expireperiod / 60 / 60 / 24, 2));
184 } else {
185 $display .= get_string('noexpiry', 'badges');
188 // Criteria details if any.
189 $display .= $this->heading(get_string('bcriteria', 'badges'), 3);
190 if ($badge->has_criteria()) {
191 $display .= self::print_badge_criteria($badge);
192 } else {
193 $display .= get_string('nocriteria', 'badges');
194 if (has_capability('moodle/badges:configurecriteria', $context)) {
195 $display .= $this->output->single_button(
196 new moodle_url('/badges/criteria.php', array('id' => $badge->id)),
197 get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
201 // Awards details if any.
202 if (has_capability('moodle/badges:viewawarded', $context)) {
203 $display .= $this->heading(get_string('awards', 'badges'), 3);
204 if ($badge->has_awards()) {
205 $url = new moodle_url('/badges/recipients.php', array('id' => $badge->id));
206 $a = new stdClass();
207 $a->link = $url->out();
208 $a->count = count($badge->get_awards());
209 $display .= get_string('numawards', 'badges', $a);
210 } else {
211 $display .= get_string('noawards', 'badges');
214 if (has_capability('moodle/badges:awardbadge', $context) &&
215 $badge->has_manual_award_criteria() &&
216 $badge->is_active()) {
217 $display .= $this->output->single_button(
218 new moodle_url('/badges/award.php', array('id' => $badge->id)),
219 get_string('award', 'badges'), 'POST', array('class' => 'activatebadge'));
223 $display .= self::print_badge_endorsement($badge);
224 $display .= self::print_badge_related($badge);
225 $display .= self::print_badge_alignments($badge);
227 return html_writer::div($display, null, array('id' => 'badge-overview'));
230 // Prints action icons for the badge.
231 public function print_badge_table_actions($badge, $context) {
232 $actions = "";
234 if (has_capability('moodle/badges:configuredetails', $context) && $badge->has_criteria()) {
235 // Activate/deactivate badge.
236 if ($badge->status == BADGE_STATUS_INACTIVE || $badge->status == BADGE_STATUS_INACTIVE_LOCKED) {
237 // "Activate" will go to another page and ask for confirmation.
238 $url = new moodle_url('/badges/action.php');
239 $url->param('id', $badge->id);
240 $url->param('activate', true);
241 $url->param('sesskey', sesskey());
242 $return = new moodle_url(qualified_me());
243 $url->param('return', $return->out_as_local_url(false));
244 $actions .= $this->output->action_icon($url, new pix_icon('t/show', get_string('activate', 'badges'))) . " ";
245 } else {
246 $url = new moodle_url(qualified_me());
247 $url->param('lock', $badge->id);
248 $url->param('sesskey', sesskey());
249 $actions .= $this->output->action_icon($url, new pix_icon('t/hide', get_string('deactivate', 'badges'))) . " ";
253 // Award badge manually.
254 if ($badge->has_manual_award_criteria() &&
255 has_capability('moodle/badges:awardbadge', $context) &&
256 $badge->is_active()) {
257 $url = new moodle_url('/badges/award.php', array('id' => $badge->id));
258 $actions .= $this->output->action_icon($url, new pix_icon('t/award', get_string('award', 'badges'))) . " ";
261 // Edit badge.
262 if (has_capability('moodle/badges:configuredetails', $context)) {
263 $url = new moodle_url('/badges/edit.php', array('id' => $badge->id, 'action' => 'details'));
264 $actions .= $this->output->action_icon($url, new pix_icon('t/edit', get_string('edit'))) . " ";
267 // Duplicate badge.
268 if (has_capability('moodle/badges:createbadge', $context)) {
269 $url = new moodle_url('/badges/action.php', array('copy' => '1', 'id' => $badge->id, 'sesskey' => sesskey()));
270 $actions .= $this->output->action_icon($url, new pix_icon('t/copy', get_string('copy'))) . " ";
273 // Delete badge.
274 if (has_capability('moodle/badges:deletebadge', $context)) {
275 $url = new moodle_url(qualified_me());
276 $url->param('delete', $badge->id);
277 $actions .= $this->output->action_icon($url, new pix_icon('t/delete', get_string('delete'))) . " ";
280 return $actions;
283 // Outputs issued badge with actions available.
284 protected function render_issued_badge(issued_badge $ibadge) {
285 global $USER, $CFG, $DB, $SITE;
286 $issued = $ibadge->issued;
287 $userinfo = $ibadge->recipient;
288 $badgeclass = $ibadge->badgeclass;
289 $badge = new badge($ibadge->badgeid);
290 $now = time();
291 $expiration = isset($issued['expires']) ? $issued['expires'] : $now + 86400;
292 $badgeimage = is_array($badgeclass['image']) ? $badgeclass['image']['id'] : $badgeclass['image'];
293 $languages = get_string_manager()->get_list_of_languages();
295 $output = '';
296 $output .= html_writer::start_tag('div', array('id' => 'badge'));
297 $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
298 $output .= html_writer::empty_tag('img', array('src' => $badgeimage, 'alt' => $badge->name));
299 if ($expiration < $now) {
300 $output .= $this->output->pix_icon('i/expired',
301 get_string('expireddate', 'badges', userdate($issued['expires'])),
302 'moodle',
303 array('class' => 'expireimage'));
306 if ($USER->id == $userinfo->id && !empty($CFG->enablebadges)) {
307 $output .= $this->output->single_button(
308 new moodle_url('/badges/badge.php', array('hash' => $issued['uid'], 'bake' => true)),
309 get_string('download'),
310 'POST');
311 if (!empty($CFG->badges_allowexternalbackpack) && ($expiration > $now) && badges_user_has_backpack($USER->id)) {
312 $assertion = new moodle_url('/badges/assertion.php', array('b' => $issued['uid']));
313 $action = new component_action('click', 'addtobackpack', array('assertion' => $assertion->out(false)));
314 $attributes = array(
315 'type' => 'button',
316 'id' => 'addbutton',
317 'value' => get_string('addtobackpack', 'badges'));
318 $tobackpack = html_writer::tag('input', '', $attributes);
319 $this->output->add_action_handler($action, 'addbutton');
320 $output .= $tobackpack;
323 $output .= html_writer::end_tag('div');
325 $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
326 // Recipient information.
327 $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
328 $dl = array();
329 if ($userinfo->deleted) {
330 $strdata = new stdClass();
331 $strdata->user = fullname($userinfo);
332 $strdata->site = format_string($SITE->fullname, true, array('context' => context_system::instance()));
334 $dl[get_string('name')] = get_string('error:userdeleted', 'badges', $strdata);
335 } else {
336 $dl[get_string('name')] = fullname($userinfo);
338 $output .= $this->definition_list($dl);
340 $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
341 $dl = array();
342 $dl[get_string('issuername', 'badges')] = $badge->issuername;
343 if (isset($badge->issuercontact) && !empty($badge->issuercontact)) {
344 $dl[get_string('contact', 'badges')] = obfuscate_mailto($badge->issuercontact);
346 $output .= $this->definition_list($dl);
348 $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
349 $dl = array();
350 $dl[get_string('name')] = $badge->name;
351 if (!empty($badge->version)) {
352 $dl[get_string('version', 'badges')] = $badge->version;
354 if (!empty($badge->language)) {
355 $dl[get_string('language')] = $languages[$badge->language];
357 $dl[get_string('description', 'badges')] = $badge->description;
358 if (!empty($badge->imageauthorname)) {
359 $dl[get_string('imageauthorname', 'badges')] = $badge->imageauthorname;
361 if (!empty($badge->imageauthoremail)) {
362 $dl[get_string('imageauthoremail', 'badges')] =
363 html_writer::tag('a', $badge->imageauthoremail, array('href' => 'mailto:' . $badge->imageauthoremail));
365 if (!empty($badge->imageauthorurl)) {
366 $dl[get_string('imageauthorurl', 'badges')] =
367 html_writer::link($badge->imageauthorurl, $badge->imageauthorurl, array('target' => '_blank'));
369 if (!empty($badge->imagecaption)) {
370 $dl[get_string('imagecaption', 'badges')] = $badge->imagecaption;
373 if ($badge->type == BADGE_TYPE_COURSE && isset($badge->courseid)) {
374 $coursename = $DB->get_field('course', 'fullname', array('id' => $badge->courseid));
375 $dl[get_string('course')] = $coursename;
377 $dl[get_string('bcriteria', 'badges')] = self::print_badge_criteria($badge);
378 $output .= $this->definition_list($dl);
380 $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
381 $dl = array();
382 $issued['issuedOn'] = !preg_match( '~^[1-9][0-9]*$~', $issued['issuedOn'] ) ?
383 strtotime($issued['issuedOn']) : $issued['issuedOn'];
384 $dl[get_string('dateawarded', 'badges')] = userdate($issued['issuedOn']);
385 if (isset($issued['expires'])) {
386 $issued['expires'] = !preg_match( '~^[1-9][0-9]*$~', $issued['expires'] ) ?
387 strtotime($issued['expires']) : $issued['expires'];
388 if ($issued['expires'] < $now) {
389 $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']) . get_string('warnexpired', 'badges');
391 } else {
392 $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']);
396 // Print evidence.
397 $agg = $badge->get_aggregation_methods();
398 $evidence = $badge->get_criteria_completions($userinfo->id);
399 $eids = array_map(function($o) {
400 return $o->critid;
401 }, $evidence);
402 unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
404 $items = array();
405 foreach ($badge->criteria as $type => $c) {
406 if (in_array($c->id, $eids)) {
407 if (count($c->params) == 1) {
408 $items[] = get_string('criteria_descr_single_' . $type , 'badges') . $c->get_details();
409 } else {
410 $items[] = get_string('criteria_descr_' . $type , 'badges',
411 core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) . $c->get_details();
416 $dl[get_string('evidence', 'badges')] = get_string('completioninfo', 'badges') . html_writer::alist($items, array(), 'ul');
417 $output .= $this->definition_list($dl);
418 $endorsement = $badge->get_endorsement();
419 if (!empty($endorsement)) {
420 $output .= self::print_badge_endorsement($badge);
423 $relatedbadges = $badge->get_related_badges(true);
424 $items = array();
425 foreach ($relatedbadges as $related) {
426 $relatedurl = new moodle_url('/badges/overview.php', array('id' => $related->id));
427 $items[] = html_writer::link($relatedurl->out(), $related->name, array('target' => '_blank'));
429 if (!empty($items)) {
430 $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
431 $output .= html_writer::alist($items, array(), 'ul');
434 $alignments = $badge->get_alignments();
435 if (!empty($alignments)) {
436 $output .= $this->heading(get_string('alignment', 'badges'), 3);
437 $items = array();
438 foreach ($alignments as $alignment) {
439 $items[] = html_writer::link($alignment->targeturl, $alignment->targetname, array('target' => '_blank'));
441 $output .= html_writer::alist($items, array(), 'ul');
443 $output .= html_writer::end_tag('div');
445 return $output;
448 // Outputs external badge.
449 protected function render_external_badge(external_badge $ibadge) {
450 $issued = $ibadge->issued;
451 $assertion = $issued->assertion;
452 $issuer = $assertion->badge->issuer;
453 $userinfo = $ibadge->recipient;
454 $table = new html_table();
455 $today = strtotime(date('Y-m-d'));
457 $output = '';
458 $output .= html_writer::start_tag('div', array('id' => 'badge'));
459 $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
460 $output .= html_writer::empty_tag('img', array('src' => $issued->imageUrl));
461 if (isset($assertion->expires)) {
462 $expiration = !strtotime($assertion->expires) ? s($assertion->expires) : strtotime($assertion->expires);
463 if ($expiration < $today) {
464 $output .= $this->output->pix_icon('i/expired',
465 get_string('expireddate', 'badges', userdate($expiration)),
466 'moodle',
467 array('class' => 'expireimage'));
470 $output .= html_writer::end_tag('div');
472 $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
474 // Recipient information.
475 $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
476 $dl = array();
477 // Technically, we should alway have a user at this point, but added an extra check just in case.
478 if ($userinfo) {
479 if (!$ibadge->valid) {
480 $notify = $this->output->notification(get_string('recipientvalidationproblem', 'badges'), 'notifynotice');
481 $dl[get_string('name')] = fullname($userinfo) . $notify;
482 } else {
483 $dl[get_string('name')] = fullname($userinfo);
485 } else {
486 $notify = $this->output->notification(get_string('recipientidentificationproblem', 'badges'), 'notifynotice');
487 $dl[get_string('name')] = $notify;
489 $output .= $this->definition_list($dl);
491 $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
492 $dl = array();
493 $dl[get_string('issuername', 'badges')] = s($issuer->name);
494 $dl[get_string('issuerurl', 'badges')] = html_writer::tag('a', $issuer->origin, array('href' => $issuer->origin));
496 if (isset($issuer->contact)) {
497 $dl[get_string('contact', 'badges')] = obfuscate_mailto($issuer->contact);
499 $output .= $this->definition_list($dl);
501 $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
502 $dl = array();
503 $dl[get_string('name')] = s($assertion->badge->name);
504 $dl[get_string('description', 'badges')] = s($assertion->badge->description);
505 $dl[get_string('bcriteria', 'badges')] = html_writer::tag('a', s($assertion->badge->criteria), array('href' => $assertion->badge->criteria));
506 $output .= $this->definition_list($dl);
508 $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
509 $dl = array();
510 if (isset($assertion->issued_on)) {
511 $issuedate = !strtotime($assertion->issued_on) ? s($assertion->issued_on) : strtotime($assertion->issued_on);
512 $dl[get_string('dateawarded', 'badges')] = userdate($issuedate);
514 if (isset($assertion->expires)) {
515 if ($expiration < $today) {
516 $dl[get_string('expirydate', 'badges')] = userdate($expiration) . get_string('warnexpired', 'badges');
517 } else {
518 $dl[get_string('expirydate', 'badges')] = userdate($expiration);
521 if (isset($assertion->evidence)) {
522 $dl[get_string('evidence', 'badges')] = html_writer::tag('a', s($assertion->evidence), array('href' => $assertion->evidence));
524 $output .= $this->definition_list($dl);
525 $output .= html_writer::end_tag('div');
527 return $output;
530 // Displays the user badges.
531 protected function render_badge_user_collection(badge_user_collection $badges) {
532 global $CFG, $USER, $SITE;
533 $backpack = $badges->backpack;
534 $mybackpack = new moodle_url('/badges/mybackpack.php');
536 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
537 $htmlpagingbar = $this->render($paging);
539 // Set backpack connection string.
540 $backpackconnect = '';
541 if (!empty($CFG->badges_allowexternalbackpack) && is_null($backpack)) {
542 $backpackconnect = $this->output->box(get_string('localconnectto', 'badges', $mybackpack->out()), 'noticebox');
544 // Search box.
545 $searchform = $this->output->box($this->helper_search_form($badges->search), 'boxwidthwide boxaligncenter');
547 // Download all button.
548 $downloadall = $this->output->single_button(
549 new moodle_url('/badges/mybadges.php', array('downloadall' => true, 'sesskey' => sesskey())),
550 get_string('downloadall'), 'POST', array('class' => 'activatebadge'));
552 // Local badges.
553 $localhtml = html_writer::start_tag('div', array('id' => 'issued-badge-table', 'class' => 'generalbox'));
554 $heading = get_string('localbadges', 'badges', format_string($SITE->fullname, true, array('context' => context_system::instance())));
555 $localhtml .= $this->output->heading_with_help($heading, 'localbadgesh', 'badges');
556 if ($badges->badges) {
557 $downloadbutton = $this->output->heading(get_string('badgesearned', 'badges', $badges->totalcount), 4, 'activatebadge');
558 $downloadbutton .= $downloadall;
560 $htmllist = $this->print_badges_list($badges->badges, $USER->id);
561 $localhtml .= $backpackconnect . $downloadbutton . $searchform . $htmlpagingbar . $htmllist . $htmlpagingbar;
562 } else {
563 $localhtml .= $searchform . $this->output->notification(get_string('nobadges', 'badges'));
565 $localhtml .= html_writer::end_tag('div');
567 // External badges.
568 $externalhtml = "";
569 if (!empty($CFG->badges_allowexternalbackpack)) {
570 $externalhtml .= html_writer::start_tag('div', array('class' => 'generalbox'));
571 $externalhtml .= $this->output->heading_with_help(get_string('externalbadges', 'badges'), 'externalbadges', 'badges');
572 if (!is_null($backpack)) {
573 if ($backpack->totalcollections == 0) {
574 $externalhtml .= get_string('nobackpackcollections', 'badges', $backpack);
575 } else {
576 if ($backpack->totalbadges == 0) {
577 $externalhtml .= get_string('nobackpackbadges', 'badges', $backpack);
578 } else {
579 $externalhtml .= get_string('backpackbadges', 'badges', $backpack);
580 $externalhtml .= '<br/><br/>' . $this->print_badges_list($backpack->badges, $USER->id, true, true);
583 } else {
584 $externalhtml .= get_string('externalconnectto', 'badges', $mybackpack->out());
587 $externalhtml .= html_writer::end_tag('div');
590 return $localhtml . $externalhtml;
593 // Displays the available badges.
594 protected function render_badge_collection(badge_collection $badges) {
595 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
596 $htmlpagingbar = $this->render($paging);
597 $table = new html_table();
598 $table->attributes['class'] = 'collection';
600 $sortbyname = $this->helper_sortable_heading(get_string('name'),
601 'name', $badges->sort, $badges->dir);
602 $sortbyawarded = $this->helper_sortable_heading(get_string('awardedtoyou', 'badges'),
603 'dateissued', $badges->sort, $badges->dir);
604 $table->head = array(
605 get_string('badgeimage', 'badges'),
606 $sortbyname,
607 get_string('description', 'badges'),
608 get_string('bcriteria', 'badges'),
609 $sortbyawarded
611 $table->colclasses = array('badgeimage', 'name', 'description', 'criteria', 'awards');
613 foreach ($badges->badges as $badge) {
614 $badgeimage = print_badge_image($badge, $this->page->context, 'large');
615 $name = $badge->name;
616 $description = $badge->description;
617 $criteria = self::print_badge_criteria($badge);
618 if ($badge->dateissued) {
619 $icon = new pix_icon('i/valid',
620 get_string('dateearned', 'badges',
621 userdate($badge->dateissued, get_string('strftimedatefullshort', 'core_langconfig'))));
622 $badgeurl = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
623 $awarded = $this->output->action_icon($badgeurl, $icon, null, null, true);
624 } else {
625 $awarded = "";
627 $row = array($badgeimage, $name, $description, $criteria, $awarded);
628 $table->data[] = $row;
631 $htmltable = html_writer::table($table);
633 return $htmlpagingbar . $htmltable . $htmlpagingbar;
636 // Outputs table of badges with actions available.
637 protected function render_badge_management(badge_management $badges) {
638 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
640 // New badge button.
641 $htmlnew = '';
642 if (has_capability('moodle/badges:createbadge', $this->page->context)) {
643 $n['type'] = $this->page->url->get_param('type');
644 $n['id'] = $this->page->url->get_param('id');
645 $htmlnew = $this->output->single_button(new moodle_url('newbadge.php', $n), get_string('newbadge', 'badges'));
648 $htmlpagingbar = $this->render($paging);
649 $table = new html_table();
650 $table->attributes['class'] = 'collection';
652 $sortbyname = $this->helper_sortable_heading(get_string('name'),
653 'name', $badges->sort, $badges->dir);
654 $sortbystatus = $this->helper_sortable_heading(get_string('status', 'badges'),
655 'status', $badges->sort, $badges->dir);
656 $table->head = array(
657 $sortbyname,
658 $sortbystatus,
659 get_string('bcriteria', 'badges'),
660 get_string('awards', 'badges'),
661 get_string('actions')
663 $table->colclasses = array('name', 'status', 'criteria', 'awards', 'actions');
665 foreach ($badges->badges as $b) {
666 $style = !$b->is_active() ? array('class' => 'dimmed') : array();
667 $forlink = print_badge_image($b, $this->page->context) . ' ' .
668 html_writer::start_tag('span') . $b->name . html_writer::end_tag('span');
669 $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $b->id)), $forlink, $style);
670 $status = $b->statstring;
671 $criteria = self::print_badge_criteria($b, 'short');
673 if (has_capability('moodle/badges:viewawarded', $this->page->context)) {
674 $awards = html_writer::link(new moodle_url('/badges/recipients.php', array('id' => $b->id)), $b->awards);
675 } else {
676 $awards = $b->awards;
679 $actions = self::print_badge_table_actions($b, $this->page->context);
681 $row = array($name, $status, $criteria, $awards, $actions);
682 $table->data[] = $row;
684 $htmltable = html_writer::table($table);
686 return $htmlnew . $htmlpagingbar . $htmltable . $htmlpagingbar;
689 // Prints tabs for badge editing.
690 public function print_badge_tabs($badgeid, $context, $current = 'overview') {
691 global $DB;
693 $badge = new badge($badgeid);
694 $row = array();
696 $row[] = new tabobject('overview',
697 new moodle_url('/badges/overview.php', array('id' => $badgeid)),
698 get_string('boverview', 'badges')
701 if (has_capability('moodle/badges:configuredetails', $context)) {
702 $row[] = new tabobject('details',
703 new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'details')),
704 get_string('bdetails', 'badges')
708 if (has_capability('moodle/badges:configurecriteria', $context)) {
709 $row[] = new tabobject('criteria',
710 new moodle_url('/badges/criteria.php', array('id' => $badgeid)),
711 get_string('bcriteria', 'badges')
715 if (has_capability('moodle/badges:configuremessages', $context)) {
716 $row[] = new tabobject('message',
717 new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'message')),
718 get_string('bmessage', 'badges')
722 if (has_capability('moodle/badges:viewawarded', $context)) {
723 $awarded = $DB->count_records_sql('SELECT COUNT(b.userid)
724 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
725 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badgeid));
726 $row[] = new tabobject('awards',
727 new moodle_url('/badges/recipients.php', array('id' => $badgeid)),
728 get_string('bawards', 'badges', $awarded)
732 if (has_capability('moodle/badges:configuredetails', $context)) {
733 $row[] = new tabobject('bendorsement',
734 new moodle_url('/badges/endorsement.php', array('id' => $badgeid)),
735 get_string('bendorsement', 'badges')
739 if (has_capability('moodle/badges:configuredetails', $context)) {
740 $sql = "SELECT COUNT(br.badgeid)
741 FROM {badge_related} br
742 WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2)";
743 $related = $DB->count_records_sql($sql, ['badgeid' => $badgeid, 'badgeid2' => $badgeid]);
744 $row[] = new tabobject('brelated',
745 new moodle_url('/badges/related.php', array('id' => $badgeid)),
746 get_string('brelated', 'badges', $related)
750 if (has_capability('moodle/badges:configuredetails', $context)) {
751 $alignments = $DB->count_records_sql("SELECT COUNT(bc.id)
752 FROM {badge_alignment} bc WHERE bc.badgeid = :badgeid", array('badgeid' => $badgeid));
753 $row[] = new tabobject('balignment',
754 new moodle_url('/badges/alignment.php', array('id' => $badgeid)),
755 get_string('balignment', 'badges', $alignments)
759 echo $this->tabtree($row, $current);
763 * Prints badge status box.
764 * @return Either the status box html as a string or null
766 public function print_badge_status_box(badge $badge) {
767 if (has_capability('moodle/badges:configurecriteria', $badge->get_context())) {
769 if (!$badge->has_criteria()) {
770 $criteriaurl = new moodle_url('/badges/criteria.php', array('id' => $badge->id));
771 $status = get_string('nocriteria', 'badges');
772 if ($this->page->url != $criteriaurl) {
773 $action = $this->output->single_button(
774 $criteriaurl,
775 get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
776 } else {
777 $action = '';
780 $message = $status . $action;
781 } else {
782 $status = get_string('statusmessage_' . $badge->status, 'badges');
783 if ($badge->is_active()) {
784 $action = $this->output->single_button(new moodle_url('/badges/action.php',
785 array('id' => $badge->id, 'lock' => 1, 'sesskey' => sesskey(),
786 'return' => $this->page->url->out_as_local_url(false))),
787 get_string('deactivate', 'badges'), 'POST', array('class' => 'activatebadge'));
788 } else {
789 $action = $this->output->single_button(new moodle_url('/badges/action.php',
790 array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(),
791 'return' => $this->page->url->out_as_local_url(false))),
792 get_string('activate', 'badges'), 'POST', array('class' => 'activatebadge'));
795 $message = $status . $this->output->help_icon('status', 'badges') . $action;
799 $style = $badge->is_active() ? 'generalbox statusbox active' : 'generalbox statusbox inactive';
800 return $this->output->box($message, $style);
803 return null;
807 * Returns information about badge criteria in a list form.
809 * @param badge $badge Badge objects
810 * @param string $short Indicates whether to print full info about this badge
811 * @return string $output HTML string to output
813 public function print_badge_criteria(badge $badge, $short = '') {
814 $agg = $badge->get_aggregation_methods();
815 if (empty($badge->criteria)) {
816 return get_string('nocriteria', 'badges');
819 $overalldescr = '';
820 $overall = $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL];
821 if (!$short && !empty($overall->description)) {
822 $overalldescr = $this->output->box(
823 format_text($overall->description, $overall->descriptionformat, array('context' => $badge->get_context())),
824 'criteria-description'
828 // Get the condition string.
829 if (count($badge->criteria) == 2) {
830 $condition = '';
831 if (!$short) {
832 $condition = get_string('criteria_descr', 'badges');
834 } else {
835 $condition = get_string('criteria_descr_' . $short . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
836 core_text::strtoupper($agg[$badge->get_aggregation_method()]));
839 unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
841 $items = array();
842 // If only one criterion left, make sure its description goe to the top.
843 if (count($badge->criteria) == 1) {
844 $c = reset($badge->criteria);
845 if (!$short && !empty($c->description)) {
846 $overalldescr = $this->output->box(
847 format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
848 'criteria-description'
851 if (count($c->params) == 1) {
852 $items[] = get_string('criteria_descr_single_' . $short . $c->criteriatype , 'badges') .
853 $c->get_details($short);
854 } else {
855 $items[] = get_string('criteria_descr_' . $short . $c->criteriatype, 'badges',
856 core_text::strtoupper($agg[$badge->get_aggregation_method($c->criteriatype)])) .
857 $c->get_details($short);
859 } else {
860 foreach ($badge->criteria as $type => $c) {
861 $criteriadescr = '';
862 if (!$short && !empty($c->description)) {
863 $criteriadescr = $this->output->box(
864 format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
865 'criteria-description'
868 if (count($c->params) == 1) {
869 $items[] = get_string('criteria_descr_single_' . $short . $type , 'badges') .
870 $c->get_details($short) . $criteriadescr;
871 } else {
872 $items[] = get_string('criteria_descr_' . $short . $type , 'badges',
873 core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) .
874 $c->get_details($short) .
875 $criteriadescr;
880 return $overalldescr . $condition . html_writer::alist($items, array(), 'ul');;
883 // Prints criteria actions for badge editing.
884 public function print_criteria_actions(badge $badge) {
885 $output = '';
886 if (!$badge->is_active() && !$badge->is_locked()) {
887 $accepted = $badge->get_accepted_criteria();
888 $potential = array_diff($accepted, array_keys($badge->criteria));
890 if (!empty($potential)) {
891 foreach ($potential as $p) {
892 if ($p != 0) {
893 $select[$p] = get_string('criteria_' . $p, 'badges');
896 $output .= $this->output->single_select(
897 new moodle_url('/badges/criteria_settings.php', array('badgeid' => $badge->id, 'add' => true)),
898 'type',
899 $select,
901 array('' => 'choosedots'),
902 null,
903 array('label' => get_string('addbadgecriteria', 'badges'))
905 } else {
906 $output .= $this->output->box(get_string('nothingtoadd', 'badges'), 'clearfix');
910 return $output;
913 // Renders a table with users who have earned the badge.
914 // Based on stamps collection plugin.
915 protected function render_badge_recipients(badge_recipients $recipients) {
916 $paging = new paging_bar($recipients->totalcount, $recipients->page, $recipients->perpage, $this->page->url, 'page');
917 $htmlpagingbar = $this->render($paging);
918 $table = new html_table();
919 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
921 $sortbyfirstname = $this->helper_sortable_heading(get_string('firstname'),
922 'firstname', $recipients->sort, $recipients->dir);
923 $sortbylastname = $this->helper_sortable_heading(get_string('lastname'),
924 'lastname', $recipients->sort, $recipients->dir);
925 if ($this->helper_fullname_format() == 'lf') {
926 $sortbyname = $sortbylastname . ' / ' . $sortbyfirstname;
927 } else {
928 $sortbyname = $sortbyfirstname . ' / ' . $sortbylastname;
931 $sortbydate = $this->helper_sortable_heading(get_string('dateawarded', 'badges'),
932 'dateissued', $recipients->sort, $recipients->dir);
934 $table->head = array($sortbyname, $sortbydate, '');
936 foreach ($recipients->userids as $holder) {
937 $fullname = fullname($holder);
938 $fullname = html_writer::link(
939 new moodle_url('/user/profile.php', array('id' => $holder->userid)),
940 $fullname
942 $awarded = userdate($holder->dateissued);
943 $badgeurl = html_writer::link(
944 new moodle_url('/badges/badge.php', array('hash' => $holder->uniquehash)),
945 get_string('viewbadge', 'badges')
948 $row = array($fullname, $awarded, $badgeurl);
949 $table->data[] = $row;
952 $htmltable = html_writer::table($table);
954 return $htmlpagingbar . $htmltable . $htmlpagingbar;
957 ////////////////////////////////////////////////////////////////////////////
958 // Helper methods
959 // Reused from stamps collection plugin
960 ////////////////////////////////////////////////////////////////////////////
963 * Renders a text with icons to sort by the given column
965 * This is intended for table headings.
967 * @param string $text The heading text
968 * @param string $sortid The column id used for sorting
969 * @param string $sortby Currently sorted by (column id)
970 * @param string $sorthow Currently sorted how (ASC|DESC)
972 * @return string
974 protected function helper_sortable_heading($text, $sortid = null, $sortby = null, $sorthow = null) {
975 $out = html_writer::tag('span', $text, array('class' => 'text'));
977 if (!is_null($sortid)) {
978 if ($sortby !== $sortid || $sorthow !== 'ASC') {
979 $url = new moodle_url($this->page->url);
980 $url->params(array('sort' => $sortid, 'dir' => 'ASC'));
981 $out .= $this->output->action_icon($url,
982 new pix_icon('t/sort_asc', get_string('sortbyx', 'core', s($text)), null, array('class' => 'iconsort')));
984 if ($sortby !== $sortid || $sorthow !== 'DESC') {
985 $url = new moodle_url($this->page->url);
986 $url->params(array('sort' => $sortid, 'dir' => 'DESC'));
987 $out .= $this->output->action_icon($url,
988 new pix_icon('t/sort_desc', get_string('sortbyxreverse', 'core', s($text)), null, array('class' => 'iconsort')));
991 return $out;
994 * Tries to guess the fullname format set at the site
996 * @return string fl|lf
998 protected function helper_fullname_format() {
999 $fake = new stdClass();
1000 $fake->lastname = 'LLLL';
1001 $fake->firstname = 'FFFF';
1002 $fullname = get_string('fullnamedisplay', '', $fake);
1003 if (strpos($fullname, 'LLLL') < strpos($fullname, 'FFFF')) {
1004 return 'lf';
1005 } else {
1006 return 'fl';
1010 * Renders a search form
1012 * @param string $search Search string
1013 * @return string HTML
1015 protected function helper_search_form($search) {
1016 global $CFG;
1017 require_once($CFG->libdir . '/formslib.php');
1019 $mform = new MoodleQuickForm('searchform', 'POST', $this->page->url);
1021 $mform->addElement('hidden', 'sesskey', sesskey());
1023 $el[] = $mform->createElement('text', 'search', get_string('search'), array('size' => 20));
1024 $mform->setDefault('search', $search);
1025 $el[] = $mform->createElement('submit', 'submitsearch', get_string('search'));
1026 $el[] = $mform->createElement('submit', 'clearsearch', get_string('clear'));
1027 $mform->addGroup($el, 'searchgroup', get_string('searchname', 'badges'), ' ', false);
1029 ob_start();
1030 $mform->display();
1031 $out = ob_get_clean();
1033 return $out;
1037 * Renders a definition list
1039 * @param array $items the list of items to define
1040 * @param array
1042 protected function definition_list(array $items, array $attributes = array()) {
1043 $output = html_writer::start_tag('dl', $attributes);
1044 foreach ($items as $label => $value) {
1045 $output .= html_writer::tag('dt', $label);
1046 $output .= html_writer::tag('dd', $value);
1048 $output .= html_writer::end_tag('dl');
1049 return $output;
1053 * Outputs list en badges.
1055 * @param badge $badge Badge object.
1056 * @return string $output content endorsement to output.
1058 protected function print_badge_endorsement(badge $badge) {
1059 $output = '';
1060 $endorsement = $badge->get_endorsement();
1061 $dl = array();
1062 $output .= $this->heading(get_string('endorsement', 'badges'), 3);
1063 if (!empty($endorsement)) {
1064 $dl[get_string('issuername', 'badges')] = $endorsement->issuername;
1065 $dl[get_string('issueremail', 'badges')] =
1066 html_writer::tag('a', $endorsement->issueremail, array('href' => 'mailto:' . $endorsement->issueremail));
1067 $dl[get_string('issuerurl', 'badges')] = html_writer::link($endorsement->issuerurl, $endorsement->issuerurl,
1068 array('target' => '_blank'));
1069 $dl[get_string('dateawarded', 'badges')] = userdate($endorsement->dateissued);
1070 $dl[get_string('claimid', 'badges')] = html_writer::link($endorsement->claimid, $endorsement->claimid,
1071 array('target' => '_blank'));
1072 $dl[get_string('claimcomment', 'badges')] = $endorsement->claimcomment;
1073 $output .= $this->definition_list($dl);
1074 } else {
1075 $output .= get_string('noendorsement', 'badges');
1077 return $output;
1081 * Print list badges related.
1083 * @param badge $badge Badge objects.
1084 * @return string $output List related badges to output.
1086 protected function print_badge_related(badge $badge) {
1087 $output = '';
1088 $relatedbadges = $badge->get_related_badges();
1089 $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
1090 if (!empty($relatedbadges)) {
1091 $items = array();
1092 foreach ($relatedbadges as $related) {
1093 $relatedurl = new moodle_url('/badges/overview.php', array('id' => $related->id));
1094 $items[] = html_writer::link($relatedurl->out(), $related->name, array('target' => '_blank'));
1096 $output .= html_writer::alist($items, array(), 'ul');
1097 } else {
1098 $output .= get_string('norelated', 'badges');
1100 return $output;
1104 * Print list badge alignments.
1106 * @param badge $badge Badge objects.
1107 * @return string $output List alignments to output.
1109 protected function print_badge_alignments(badge $badge) {
1110 $output = '';
1111 $output .= $this->heading(get_string('alignment', 'badges'), 3);
1112 $alignments = $badge->get_alignments();
1113 if (!empty($alignments)) {
1114 $items = array();
1115 foreach ($alignments as $alignment) {
1116 $urlaligment = new moodle_url('alignment.php',
1117 array('id' => $badge->id, 'alignmentid' => $alignment->id)
1119 $items[] = html_writer::link($urlaligment, $alignment->targetname, array('target' => '_blank'));
1121 $output .= html_writer::alist($items, array(), 'ul');
1122 } else {
1123 $output .= get_string('noalignment', 'badges');
1125 return $output;
1129 * Renders a table for related badges.
1131 * @param badge_related $related list related badges.
1132 * @return string list related badges to output.
1134 protected function render_badge_related(badge_related $related) {
1135 $currentbadge = new badge($related->currentbadgeid);
1136 $languages = get_string_manager()->get_list_of_languages();
1137 $paging = new paging_bar($related->totalcount, $related->page, $related->perpage, $this->page->url, 'page');
1138 $htmlpagingbar = $this->render($paging);
1139 $table = new html_table();
1140 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1141 $table->head = array(
1142 get_string('name'),
1143 get_string('version', 'badges'),
1144 get_string('language', 'badges'),
1145 get_string('type', 'badges')
1147 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1148 array_push($table->head, '');
1151 foreach ($related->badges as $badge) {
1152 $badgeobject = new badge($badge->id);
1153 $style = array('title' => $badgeobject->name);
1154 if (!$badgeobject->is_active()) {
1155 $style['class'] = 'dimmed';
1157 $context = ($badgeobject->type == BADGE_TYPE_SITE) ?
1158 context_system::instance() : context_course::instance($badgeobject->courseid);
1159 $forlink = print_badge_image($badgeobject, $context) . ' ' .
1160 html_writer::start_tag('span') . $badgeobject->name . html_writer::end_tag('span');
1161 $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $badgeobject->id)), $forlink, $style);
1163 $row = array(
1164 $name,
1165 $badge->version,
1166 $badge->language ? $languages[$badge->language] : '',
1167 $badge->type == BADGE_TYPE_COURSE ? get_string('badgesview', 'badges') : get_string('sitebadges', 'badges')
1169 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1170 $action = $this->output->action_icon(
1171 new moodle_url('related_action.php',
1172 array(
1173 'badgeid' => $related->currentbadgeid,
1174 'relatedid' => $badge->id,
1175 'action' => 'remove'
1177 ), new pix_icon('t/delete', get_string('delete')));
1178 $actions = html_writer::tag('div', $action, array('class' => 'badge-actions'));
1179 array_push($row, $actions);
1181 $table->data[] = $row;
1183 $htmltable = html_writer::table($table);
1185 return $htmlpagingbar . $htmltable . $htmlpagingbar;
1189 * Renders a table with alignment.
1191 * @param badge_alignments $alignments List alignments.
1192 * @return string List alignment to output.
1194 protected function render_badge_alignments(badge_alignments $alignments) {
1195 $currentbadge = new badge($alignments->currentbadgeid);
1196 $paging = new paging_bar($alignments->totalcount, $alignments->page, $alignments->perpage, $this->page->url, 'page');
1197 $htmlpagingbar = $this->render($paging);
1198 $table = new html_table();
1199 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1200 $table->head = array('Name', 'URL', '');
1202 foreach ($alignments->alignments as $item) {
1203 $urlaligment = new moodle_url('alignment.php',
1204 array(
1205 'id' => $currentbadge->id,
1206 'alignmentid' => $item->id,
1209 $row = array(
1210 html_writer::link($urlaligment, $item->targetname),
1211 html_writer::link($item->targeturl, $item->targeturl, array('target' => '_blank'))
1213 if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1214 $delete = $this->output->action_icon(
1215 new moodle_url('alignment_action.php',
1216 array(
1217 'id' => $currentbadge->id,
1218 'alignmentid' => $item->id,
1219 'action' => 'remove'
1221 ), new pix_icon('t/delete', get_string('delete')));
1222 $edit = $this->output->action_icon(
1223 new moodle_url('alignment.php',
1224 array(
1225 'id' => $currentbadge->id,
1226 'alignmentid' => $item->id,
1227 'action' => 'edit'
1229 ), new pix_icon('t/edit', get_string('edit')));
1230 $actions = html_writer::tag('div', $edit . $delete, array('class' => 'badge-actions'));
1231 array_push($row, $actions);
1233 $table->data[] = $row;
1235 $htmltable = html_writer::table($table);
1237 return $htmlpagingbar . $htmltable . $htmlpagingbar;
1242 * An issued badges for badge.php page
1244 class issued_badge implements renderable {
1245 /** @var issued badge */
1246 public $issued;
1248 /** @var badge recipient */
1249 public $recipient;
1251 /** @var badge class */
1252 public $badgeclass;
1254 /** @var badge visibility to others */
1255 public $visible = 0;
1257 /** @var badge class */
1258 public $badgeid = 0;
1261 * Initializes the badge to display
1263 * @param string $hash Issued badge hash
1265 public function __construct($hash) {
1266 global $DB;
1268 $assertion = new core_badges_assertion($hash);
1269 $this->issued = $assertion->get_badge_assertion();
1270 $this->badgeclass = $assertion->get_badge_class();
1272 $rec = $DB->get_record_sql('SELECT userid, visible, badgeid
1273 FROM {badge_issued}
1274 WHERE ' . $DB->sql_compare_text('uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40),
1275 array('hash' => $hash), IGNORE_MISSING);
1276 if ($rec) {
1277 // Get a recipient from database.
1278 $namefields = get_all_user_name_fields(true, 'u');
1279 $user = $DB->get_record_sql("SELECT u.id, $namefields, u.deleted, u.email
1280 FROM {user} u WHERE u.id = :userid", array('userid' => $rec->userid));
1281 $this->recipient = $user;
1282 $this->visible = $rec->visible;
1283 $this->badgeid = $rec->badgeid;
1289 * An external badges for external.php page
1291 class external_badge implements renderable {
1292 /** @var issued badge */
1293 public $issued;
1295 /** @var User ID */
1296 public $recipient;
1298 /** @var validation of external badge */
1299 public $valid = true;
1302 * Initializes the badge to display
1304 * @param object $badge External badge information.
1305 * @param int $recipient User id.
1307 public function __construct($badge, $recipient) {
1308 global $DB;
1309 // At this point a user has connected a backpack. So, we are going to get
1310 // their backpack email rather than their account email.
1311 $namefields = get_all_user_name_fields(true, 'u');
1312 $user = $DB->get_record_sql("SELECT {$namefields}, b.email
1313 FROM {user} u INNER JOIN {badge_backpack} b ON u.id = b.userid
1314 WHERE userid = :userid", array('userid' => $recipient), IGNORE_MISSING);
1316 $this->issued = $badge;
1317 $this->recipient = $user;
1319 // Check if recipient is valid.
1320 // There is no way to be 100% sure that a badge belongs to a user.
1321 // Backpack does not return any recipient information.
1322 // All we can do is compare that backpack email hashed using salt
1323 // provided in the assertion matches a badge recipient from the assertion.
1324 if ($user) {
1325 if (validate_email($badge->assertion->recipient) && $badge->assertion->recipient == $user->email) {
1326 // If we have email, compare emails.
1327 $this->valid = true;
1328 } else if ($badge->assertion->recipient == 'sha256$' . hash('sha256', $user->email)) {
1329 // If recipient is hashed, but no salt, compare hashes without salt.
1330 $this->valid = true;
1331 } else if ($badge->assertion->recipient == 'sha256$' . hash('sha256', $user->email . $badge->assertion->salt)) {
1332 // If recipient is hashed, compare hashes.
1333 $this->valid = true;
1334 } else {
1335 // Otherwise, we cannot be sure that this user is a recipient.
1336 $this->valid = false;
1338 } else {
1339 $this->valid = false;
1345 * Badge recipients rendering class
1347 class badge_recipients implements renderable {
1348 /** @var string how are the data sorted */
1349 public $sort = 'lastname';
1351 /** @var string how are the data sorted */
1352 public $dir = 'ASC';
1354 /** @var int page number to display */
1355 public $page = 0;
1357 /** @var int number of badge recipients to display per page */
1358 public $perpage = 30;
1360 /** @var int the total number or badge recipients to display */
1361 public $totalcount = null;
1363 /** @var array internal list of badge recipients ids */
1364 public $userids = array();
1366 * Initializes the list of users to display
1368 * @param array $holders List of badge holders
1370 public function __construct($holders) {
1371 $this->userids = $holders;
1376 * Collection of all badges for view.php page
1378 class badge_collection implements renderable {
1380 /** @var string how are the data sorted */
1381 public $sort = 'name';
1383 /** @var string how are the data sorted */
1384 public $dir = 'ASC';
1386 /** @var int page number to display */
1387 public $page = 0;
1389 /** @var int number of badges to display per page */
1390 public $perpage = BADGE_PERPAGE;
1392 /** @var int the total number of badges to display */
1393 public $totalcount = null;
1395 /** @var array list of badges */
1396 public $badges = array();
1399 * Initializes the list of badges to display
1401 * @param array $badges Badges to render
1403 public function __construct($badges) {
1404 $this->badges = $badges;
1409 * Collection of badges used at the index.php page
1411 class badge_management extends badge_collection implements renderable {
1415 * Collection of user badges used at the mybadges.php page
1417 class badge_user_collection extends badge_collection implements renderable {
1418 /** @var array backpack settings */
1419 public $backpack = null;
1421 /** @var string search */
1422 public $search = '';
1425 * Initializes user badge collection.
1427 * @param array $badges Badges to render
1428 * @param int $userid Badges owner
1430 public function __construct($badges, $userid) {
1431 global $CFG;
1432 parent::__construct($badges);
1434 if (!empty($CFG->badges_allowexternalbackpack)) {
1435 $this->backpack = get_backpack_settings($userid, true);
1441 * Collection of all related badges.
1443 * @copyright 2018 Tung Thai
1444 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1445 * @author Tung Thai <Tung.ThaiDuc@nashtechglobal.com>
1447 class badge_related implements renderable {
1449 /** @var string how are the data sorted. */
1450 public $sort = 'name';
1452 /** @var string how are the data sorted. */
1453 public $dir = 'ASC';
1455 /** @var int page number to display. */
1456 public $page = 0;
1458 /** @var int number of badges to display per page. */
1459 public $perpage = BADGE_PERPAGE;
1461 /** @var int the total number of badges to display. */
1462 public $totalcount = null;
1464 /** @var int the current badge. */
1465 public $currentbadgeid = 0;
1467 /** @var array list of badges. */
1468 public $badges = array();
1471 * Initializes the list of badges to display.
1473 * @param array $badges related badges to render.
1474 * @param int $currentbadgeid ID current badge.
1476 public function __construct($badges, $currentbadgeid) {
1477 $this->badges = $badges;
1478 $this->currentbadgeid = $currentbadgeid;
1483 * Collection of all alignments.
1485 * @copyright 2018 Tung Thai
1486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1487 * @author Tung Thai <Tung.ThaiDuc@nashtechglobal.com>
1489 class badge_alignments implements renderable
1491 /** @var string how are the data sorted. */
1492 public $sort = 'name';
1494 /** @var string how are the data sorted. */
1495 public $dir = 'ASC';
1497 /** @var int page number to display. */
1498 public $page = 0;
1500 /** @var int number of badges to display per page. */
1501 public $perpage = BADGE_PERPAGE;
1503 /** @var int the total number of badges to display. */
1504 public $totalcount = null;
1506 /** @var array list of badges. */
1507 public $alignments = array();
1509 /** @var array list of badges. */
1510 public $currentbadgeid = 0;
1513 * Initializes the list of alignments to display.
1515 * @param array $alignments List alignments to render.
1516 * @param int $currentbadgeid ID current badge.
1518 public function __construct($alignments, $currentbadgeid) {
1519 $this->alignments = $alignments;
1520 $this->currentbadgeid = $currentbadgeid;