MDL-57696 mod_lesson: Move code to lesson methods
[moodle.git] / badges / renderer.php
blobd23ff4e7b8b06e2616062c8af2864e3d0a888311
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')
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')
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 = "";
143 // 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('description', 'badges')] = $badge->description;
149 $dl[get_string('createdon', 'search')] = userdate($badge->timecreated);
150 $dl[get_string('badgeimage', 'badges')] = print_badge_image($badge, $context, 'large');
151 $display .= $this->definition_list($dl);
153 // Issuer details.
154 $display .= $this->heading(get_string('issuerdetails', 'badges'), 3);
155 $dl = array();
156 $dl[get_string('issuername', 'badges')] = $badge->issuername;
157 $dl[get_string('contact', 'badges')] = html_writer::tag('a', $badge->issuercontact, array('href' => 'mailto:' . $badge->issuercontact));
158 $display .= $this->definition_list($dl);
160 // Issuance details if any.
161 $display .= $this->heading(get_string('issuancedetails', 'badges'), 3);
162 if ($badge->can_expire()) {
163 if ($badge->expiredate) {
164 $display .= get_string('expiredate', 'badges', userdate($badge->expiredate));
165 } else if ($badge->expireperiod) {
166 if ($badge->expireperiod < 60) {
167 $display .= get_string('expireperiods', 'badges', round($badge->expireperiod, 2));
168 } else if ($badge->expireperiod < 60 * 60) {
169 $display .= get_string('expireperiodm', 'badges', round($badge->expireperiod / 60, 2));
170 } else if ($badge->expireperiod < 60 * 60 * 24) {
171 $display .= get_string('expireperiodh', 'badges', round($badge->expireperiod / 60 / 60, 2));
172 } else {
173 $display .= get_string('expireperiod', 'badges', round($badge->expireperiod / 60 / 60 / 24, 2));
176 } else {
177 $display .= get_string('noexpiry', 'badges');
180 // Criteria details if any.
181 $display .= $this->heading(get_string('bcriteria', 'badges'), 3);
182 if ($badge->has_criteria()) {
183 $display .= self::print_badge_criteria($badge);
184 } else {
185 $display .= get_string('nocriteria', 'badges');
186 if (has_capability('moodle/badges:configurecriteria', $context)) {
187 $display .= $this->output->single_button(
188 new moodle_url('/badges/criteria.php', array('id' => $badge->id)),
189 get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
193 // Awards details if any.
194 if (has_capability('moodle/badges:viewawarded', $context)) {
195 $display .= $this->heading(get_string('awards', 'badges'), 3);
196 if ($badge->has_awards()) {
197 $url = new moodle_url('/badges/recipients.php', array('id' => $badge->id));
198 $a = new stdClass();
199 $a->link = $url->out();
200 $a->count = count($badge->get_awards());
201 $display .= get_string('numawards', 'badges', $a);
202 } else {
203 $display .= get_string('noawards', 'badges');
206 if (has_capability('moodle/badges:awardbadge', $context) &&
207 $badge->has_manual_award_criteria() &&
208 $badge->is_active()) {
209 $display .= $this->output->single_button(
210 new moodle_url('/badges/award.php', array('id' => $badge->id)),
211 get_string('award', 'badges'), 'POST', array('class' => 'activatebadge'));
215 return html_writer::div($display, null, array('id' => 'badge-overview'));
218 // Prints action icons for the badge.
219 public function print_badge_table_actions($badge, $context) {
220 $actions = "";
222 if (has_capability('moodle/badges:configuredetails', $context) && $badge->has_criteria()) {
223 // Activate/deactivate badge.
224 if ($badge->status == BADGE_STATUS_INACTIVE || $badge->status == BADGE_STATUS_INACTIVE_LOCKED) {
225 // "Activate" will go to another page and ask for confirmation.
226 $url = new moodle_url('/badges/action.php');
227 $url->param('id', $badge->id);
228 $url->param('activate', true);
229 $url->param('sesskey', sesskey());
230 $return = new moodle_url(qualified_me());
231 $url->param('return', $return->out_as_local_url(false));
232 $actions .= $this->output->action_icon($url, new pix_icon('t/show', get_string('activate', 'badges'))) . " ";
233 } else {
234 $url = new moodle_url(qualified_me());
235 $url->param('lock', $badge->id);
236 $url->param('sesskey', sesskey());
237 $actions .= $this->output->action_icon($url, new pix_icon('t/hide', get_string('deactivate', 'badges'))) . " ";
241 // Award badge manually.
242 if ($badge->has_manual_award_criteria() &&
243 has_capability('moodle/badges:awardbadge', $context) &&
244 $badge->is_active()) {
245 $url = new moodle_url('/badges/award.php', array('id' => $badge->id));
246 $actions .= $this->output->action_icon($url, new pix_icon('t/award', get_string('award', 'badges'))) . " ";
249 // Edit badge.
250 if (has_capability('moodle/badges:configuredetails', $context)) {
251 $url = new moodle_url('/badges/edit.php', array('id' => $badge->id, 'action' => 'details'));
252 $actions .= $this->output->action_icon($url, new pix_icon('t/edit', get_string('edit'))) . " ";
255 // Duplicate badge.
256 if (has_capability('moodle/badges:createbadge', $context)) {
257 $url = new moodle_url('/badges/action.php', array('copy' => '1', 'id' => $badge->id, 'sesskey' => sesskey()));
258 $actions .= $this->output->action_icon($url, new pix_icon('t/copy', get_string('copy'))) . " ";
261 // Delete badge.
262 if (has_capability('moodle/badges:deletebadge', $context)) {
263 $url = new moodle_url(qualified_me());
264 $url->param('delete', $badge->id);
265 $actions .= $this->output->action_icon($url, new pix_icon('t/delete', get_string('delete'))) . " ";
268 return $actions;
271 // Outputs issued badge with actions available.
272 protected function render_issued_badge(issued_badge $ibadge) {
273 global $USER, $CFG, $DB, $SITE;
274 $issued = $ibadge->issued;
275 $userinfo = $ibadge->recipient;
276 $badgeclass = $ibadge->badgeclass;
277 $badge = new badge($ibadge->badgeid);
278 $now = time();
279 $expiration = isset($issued['expires']) ? $issued['expires'] : $now + 86400;
281 $output = '';
282 $output .= html_writer::start_tag('div', array('id' => 'badge'));
283 $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
284 $output .= html_writer::empty_tag('img', array('src' => $badgeclass['image'], 'alt' => $badge->name));
285 if ($expiration < $now) {
286 $output .= $this->output->pix_icon('i/expired',
287 get_string('expireddate', 'badges', userdate($issued['expires'])),
288 'moodle',
289 array('class' => 'expireimage'));
292 if ($USER->id == $userinfo->id && !empty($CFG->enablebadges)) {
293 $output .= $this->output->single_button(
294 new moodle_url('/badges/badge.php', array('hash' => $issued['uid'], 'bake' => true)),
295 get_string('download'),
296 'POST');
297 if (!empty($CFG->badges_allowexternalbackpack) && ($expiration > $now) && badges_user_has_backpack($USER->id)) {
298 $assertion = new moodle_url('/badges/assertion.php', array('b' => $issued['uid']));
299 $action = new component_action('click', 'addtobackpack', array('assertion' => $assertion->out(false)));
300 $attributes = array(
301 'type' => 'button',
302 'id' => 'addbutton',
303 'value' => get_string('addtobackpack', 'badges'));
304 $tobackpack = html_writer::tag('input', '', $attributes);
305 $this->output->add_action_handler($action, 'addbutton');
306 $output .= $tobackpack;
309 $output .= html_writer::end_tag('div');
311 $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
312 // Recipient information.
313 $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
314 $dl = array();
315 if ($userinfo->deleted) {
316 $strdata = new stdClass();
317 $strdata->user = fullname($userinfo);
318 $strdata->site = format_string($SITE->fullname, true, array('context' => context_system::instance()));
320 $dl[get_string('name')] = get_string('error:userdeleted', 'badges', $strdata);
321 } else {
322 $dl[get_string('name')] = fullname($userinfo);
324 $output .= $this->definition_list($dl);
326 $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
327 $dl = array();
328 $dl[get_string('issuername', 'badges')] = $badge->issuername;
329 if (isset($badge->issuercontact) && !empty($badge->issuercontact)) {
330 $dl[get_string('contact', 'badges')] = obfuscate_mailto($badge->issuercontact);
332 $output .= $this->definition_list($dl);
334 $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
335 $dl = array();
336 $dl[get_string('name')] = $badge->name;
337 $dl[get_string('description', 'badges')] = $badge->description;
339 if ($badge->type == BADGE_TYPE_COURSE && isset($badge->courseid)) {
340 $coursename = $DB->get_field('course', 'fullname', array('id' => $badge->courseid));
341 $dl[get_string('course')] = $coursename;
343 $dl[get_string('bcriteria', 'badges')] = self::print_badge_criteria($badge);
344 $output .= $this->definition_list($dl);
346 $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
347 $dl = array();
348 $dl[get_string('dateawarded', 'badges')] = userdate($issued['issuedOn']);
349 if (isset($issued['expires'])) {
350 if ($issued['expires'] < $now) {
351 $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']) . get_string('warnexpired', 'badges');
353 } else {
354 $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']);
358 // Print evidence.
359 $agg = $badge->get_aggregation_methods();
360 $evidence = $badge->get_criteria_completions($userinfo->id);
361 $eids = array_map(create_function('$o', 'return $o->critid;'), $evidence);
362 unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
364 $items = array();
365 foreach ($badge->criteria as $type => $c) {
366 if (in_array($c->id, $eids)) {
367 if (count($c->params) == 1) {
368 $items[] = get_string('criteria_descr_single_' . $type , 'badges') . $c->get_details();
369 } else {
370 $items[] = get_string('criteria_descr_' . $type , 'badges',
371 core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) . $c->get_details();
376 $dl[get_string('evidence', 'badges')] = get_string('completioninfo', 'badges') . html_writer::alist($items, array(), 'ul');
377 $output .= $this->definition_list($dl);
378 $output .= html_writer::end_tag('div');
380 return $output;
383 // Outputs external badge.
384 protected function render_external_badge(external_badge $ibadge) {
385 $issued = $ibadge->issued;
386 $assertion = $issued->assertion;
387 $issuer = $assertion->badge->issuer;
388 $userinfo = $ibadge->recipient;
389 $table = new html_table();
390 $today = strtotime(date('Y-m-d'));
392 $output = '';
393 $output .= html_writer::start_tag('div', array('id' => 'badge'));
394 $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
395 $output .= html_writer::empty_tag('img', array('src' => $issued->imageUrl));
396 if (isset($assertion->expires)) {
397 $expiration = !strtotime($assertion->expires) ? s($assertion->expires) : strtotime($assertion->expires);
398 if ($expiration < $today) {
399 $output .= $this->output->pix_icon('i/expired',
400 get_string('expireddate', 'badges', userdate($expiration)),
401 'moodle',
402 array('class' => 'expireimage'));
405 $output .= html_writer::end_tag('div');
407 $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
409 // Recipient information.
410 $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
411 $dl = array();
412 // Technically, we should alway have a user at this point, but added an extra check just in case.
413 if ($userinfo) {
414 if (!$ibadge->valid) {
415 $notify = $this->output->notification(get_string('recipientvalidationproblem', 'badges'), 'notifynotice');
416 $dl[get_string('name')] = fullname($userinfo) . $notify;
417 } else {
418 $dl[get_string('name')] = fullname($userinfo);
420 } else {
421 $notify = $this->output->notification(get_string('recipientidentificationproblem', 'badges'), 'notifynotice');
422 $dl[get_string('name')] = $notify;
424 $output .= $this->definition_list($dl);
426 $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
427 $dl = array();
428 $dl[get_string('issuername', 'badges')] = s($issuer->name);
429 $dl[get_string('issuerurl', 'badges')] = html_writer::tag('a', $issuer->origin, array('href' => $issuer->origin));
431 if (isset($issuer->contact)) {
432 $dl[get_string('contact', 'badges')] = obfuscate_mailto($issuer->contact);
434 $output .= $this->definition_list($dl);
436 $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
437 $dl = array();
438 $dl[get_string('name')] = s($assertion->badge->name);
439 $dl[get_string('description', 'badges')] = s($assertion->badge->description);
440 $dl[get_string('bcriteria', 'badges')] = html_writer::tag('a', s($assertion->badge->criteria), array('href' => $assertion->badge->criteria));
441 $output .= $this->definition_list($dl);
443 $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
444 $dl = array();
445 if (isset($assertion->issued_on)) {
446 $issuedate = !strtotime($assertion->issued_on) ? s($assertion->issued_on) : strtotime($assertion->issued_on);
447 $dl[get_string('dateawarded', 'badges')] = userdate($issuedate);
449 if (isset($assertion->expires)) {
450 if ($expiration < $today) {
451 $dl[get_string('expirydate', 'badges')] = userdate($expiration) . get_string('warnexpired', 'badges');
452 } else {
453 $dl[get_string('expirydate', 'badges')] = userdate($expiration);
456 if (isset($assertion->evidence)) {
457 $dl[get_string('evidence', 'badges')] = html_writer::tag('a', s($assertion->evidence), array('href' => $assertion->evidence));
459 $output .= $this->definition_list($dl);
460 $output .= html_writer::end_tag('div');
462 return $output;
465 // Displays the user badges.
466 protected function render_badge_user_collection(badge_user_collection $badges) {
467 global $CFG, $USER, $SITE;
468 $backpack = $badges->backpack;
469 $mybackpack = new moodle_url('/badges/mybackpack.php');
471 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
472 $htmlpagingbar = $this->render($paging);
474 // Set backpack connection string.
475 $backpackconnect = '';
476 if (!empty($CFG->badges_allowexternalbackpack) && is_null($backpack)) {
477 $backpackconnect = $this->output->box(get_string('localconnectto', 'badges', $mybackpack->out()), 'noticebox');
479 // Search box.
480 $searchform = $this->output->box($this->helper_search_form($badges->search), 'boxwidthwide boxaligncenter');
482 // Download all button.
483 $downloadall = $this->output->single_button(
484 new moodle_url('/badges/mybadges.php', array('downloadall' => true, 'sesskey' => sesskey())),
485 get_string('downloadall'), 'POST', array('class' => 'activatebadge'));
487 // Local badges.
488 $localhtml = html_writer::start_tag('div', array('id' => 'issued-badge-table', 'class' => 'generalbox'));
489 $heading = get_string('localbadges', 'badges', format_string($SITE->fullname, true, array('context' => context_system::instance())));
490 $localhtml .= $this->output->heading_with_help($heading, 'localbadgesh', 'badges');
491 if ($badges->badges) {
492 $downloadbutton = $this->output->heading(get_string('badgesearned', 'badges', $badges->totalcount), 4, 'activatebadge');
493 $downloadbutton .= $downloadall;
495 $htmllist = $this->print_badges_list($badges->badges, $USER->id);
496 $localhtml .= $backpackconnect . $downloadbutton . $searchform . $htmlpagingbar . $htmllist . $htmlpagingbar;
497 } else {
498 $localhtml .= $searchform . $this->output->notification(get_string('nobadges', 'badges'));
500 $localhtml .= html_writer::end_tag('div');
502 // External badges.
503 $externalhtml = "";
504 if (!empty($CFG->badges_allowexternalbackpack)) {
505 $externalhtml .= html_writer::start_tag('div', array('class' => 'generalbox'));
506 $externalhtml .= $this->output->heading_with_help(get_string('externalbadges', 'badges'), 'externalbadges', 'badges');
507 if (!is_null($backpack)) {
508 if ($backpack->totalcollections == 0) {
509 $externalhtml .= get_string('nobackpackcollections', 'badges', $backpack);
510 } else {
511 if ($backpack->totalbadges == 0) {
512 $externalhtml .= get_string('nobackpackbadges', 'badges', $backpack);
513 } else {
514 $externalhtml .= get_string('backpackbadges', 'badges', $backpack);
515 $externalhtml .= '<br/><br/>' . $this->print_badges_list($backpack->badges, $USER->id, true, true);
518 } else {
519 $externalhtml .= get_string('externalconnectto', 'badges', $mybackpack->out());
522 $externalhtml .= html_writer::end_tag('div');
525 return $localhtml . $externalhtml;
528 // Displays the available badges.
529 protected function render_badge_collection(badge_collection $badges) {
530 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
531 $htmlpagingbar = $this->render($paging);
532 $table = new html_table();
533 $table->attributes['class'] = 'collection';
535 $sortbyname = $this->helper_sortable_heading(get_string('name'),
536 'name', $badges->sort, $badges->dir);
537 $sortbyawarded = $this->helper_sortable_heading(get_string('awardedtoyou', 'badges'),
538 'dateissued', $badges->sort, $badges->dir);
539 $table->head = array(
540 get_string('badgeimage', 'badges'),
541 $sortbyname,
542 get_string('description', 'badges'),
543 get_string('bcriteria', 'badges'),
544 $sortbyawarded
546 $table->colclasses = array('badgeimage', 'name', 'description', 'criteria', 'awards');
548 foreach ($badges->badges as $badge) {
549 $badgeimage = print_badge_image($badge, $this->page->context, 'large');
550 $name = $badge->name;
551 $description = $badge->description;
552 $criteria = self::print_badge_criteria($badge);
553 if ($badge->dateissued) {
554 $icon = new pix_icon('i/valid',
555 get_string('dateearned', 'badges',
556 userdate($badge->dateissued, get_string('strftimedatefullshort', 'core_langconfig'))));
557 $badgeurl = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
558 $awarded = $this->output->action_icon($badgeurl, $icon, null, null, true);
559 } else {
560 $awarded = "";
562 $row = array($badgeimage, $name, $description, $criteria, $awarded);
563 $table->data[] = $row;
566 $htmltable = html_writer::table($table);
568 return $htmlpagingbar . $htmltable . $htmlpagingbar;
571 // Outputs table of badges with actions available.
572 protected function render_badge_management(badge_management $badges) {
573 $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
575 // New badge button.
576 $htmlnew = '';
577 if (has_capability('moodle/badges:createbadge', $this->page->context)) {
578 $n['type'] = $this->page->url->get_param('type');
579 $n['id'] = $this->page->url->get_param('id');
580 $htmlnew = $this->output->single_button(new moodle_url('newbadge.php', $n), get_string('newbadge', 'badges'));
583 $htmlpagingbar = $this->render($paging);
584 $table = new html_table();
585 $table->attributes['class'] = 'collection';
587 $sortbyname = $this->helper_sortable_heading(get_string('name'),
588 'name', $badges->sort, $badges->dir);
589 $sortbystatus = $this->helper_sortable_heading(get_string('status', 'badges'),
590 'status', $badges->sort, $badges->dir);
591 $table->head = array(
592 $sortbyname,
593 $sortbystatus,
594 get_string('bcriteria', 'badges'),
595 get_string('awards', 'badges'),
596 get_string('actions')
598 $table->colclasses = array('name', 'status', 'criteria', 'awards', 'actions');
600 foreach ($badges->badges as $b) {
601 $style = !$b->is_active() ? array('class' => 'dimmed') : array();
602 $forlink = print_badge_image($b, $this->page->context) . ' ' .
603 html_writer::start_tag('span') . $b->name . html_writer::end_tag('span');
604 $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $b->id)), $forlink, $style);
605 $status = $b->statstring;
606 $criteria = self::print_badge_criteria($b, 'short');
608 if (has_capability('moodle/badges:viewawarded', $this->page->context)) {
609 $awards = html_writer::link(new moodle_url('/badges/recipients.php', array('id' => $b->id)), $b->awards);
610 } else {
611 $awards = $b->awards;
614 $actions = self::print_badge_table_actions($b, $this->page->context);
616 $row = array($name, $status, $criteria, $awards, $actions);
617 $table->data[] = $row;
619 $htmltable = html_writer::table($table);
621 return $htmlnew . $htmlpagingbar . $htmltable . $htmlpagingbar;
624 // Prints tabs for badge editing.
625 public function print_badge_tabs($badgeid, $context, $current = 'overview') {
626 global $DB;
628 $row = array();
630 $row[] = new tabobject('overview',
631 new moodle_url('/badges/overview.php', array('id' => $badgeid)),
632 get_string('boverview', 'badges')
635 if (has_capability('moodle/badges:configuredetails', $context)) {
636 $row[] = new tabobject('details',
637 new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'details')),
638 get_string('bdetails', 'badges')
642 if (has_capability('moodle/badges:configurecriteria', $context)) {
643 $row[] = new tabobject('criteria',
644 new moodle_url('/badges/criteria.php', array('id' => $badgeid)),
645 get_string('bcriteria', 'badges')
649 if (has_capability('moodle/badges:configuremessages', $context)) {
650 $row[] = new tabobject('message',
651 new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'message')),
652 get_string('bmessage', 'badges')
656 if (has_capability('moodle/badges:viewawarded', $context)) {
657 $awarded = $DB->count_records_sql('SELECT COUNT(b.userid)
658 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
659 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badgeid));
660 $row[] = new tabobject('awards',
661 new moodle_url('/badges/recipients.php', array('id' => $badgeid)),
662 get_string('bawards', 'badges', $awarded)
666 echo $this->tabtree($row, $current);
670 * Prints badge status box.
671 * @return Either the status box html as a string or null
673 public function print_badge_status_box(badge $badge) {
674 if (has_capability('moodle/badges:configurecriteria', $badge->get_context())) {
676 if (!$badge->has_criteria()) {
677 $criteriaurl = new moodle_url('/badges/criteria.php', array('id' => $badge->id));
678 $status = get_string('nocriteria', 'badges');
679 if ($this->page->url != $criteriaurl) {
680 $action = $this->output->single_button(
681 $criteriaurl,
682 get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
683 } else {
684 $action = '';
687 $message = $status . $action;
688 } else {
689 $status = get_string('statusmessage_' . $badge->status, 'badges');
690 if ($badge->is_active()) {
691 $action = $this->output->single_button(new moodle_url('/badges/action.php',
692 array('id' => $badge->id, 'lock' => 1, 'sesskey' => sesskey(),
693 'return' => $this->page->url->out_as_local_url(false))),
694 get_string('deactivate', 'badges'), 'POST', array('class' => 'activatebadge'));
695 } else {
696 $action = $this->output->single_button(new moodle_url('/badges/action.php',
697 array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(),
698 'return' => $this->page->url->out_as_local_url(false))),
699 get_string('activate', 'badges'), 'POST', array('class' => 'activatebadge'));
702 $message = $status . $this->output->help_icon('status', 'badges') . $action;
706 $style = $badge->is_active() ? 'generalbox statusbox active' : 'generalbox statusbox inactive';
707 return $this->output->box($message, $style);
710 return null;
714 * Returns information about badge criteria in a list form.
716 * @param badge $badge Badge objects
717 * @param string $short Indicates whether to print full info about this badge
718 * @return string $output HTML string to output
720 public function print_badge_criteria(badge $badge, $short = '') {
721 $agg = $badge->get_aggregation_methods();
722 if (empty($badge->criteria)) {
723 return get_string('nocriteria', 'badges');
726 $overalldescr = '';
727 $overall = $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL];
728 if (!$short && !empty($overall->description)) {
729 $overalldescr = $this->output->box(
730 format_text($overall->description, $overall->descriptionformat, array('context' => $badge->get_context())),
731 'criteria-description'
735 // Get the condition string.
736 if (count($badge->criteria) == 2) {
737 $condition = '';
738 if (!$short) {
739 $condition = get_string('criteria_descr', 'badges');
741 } else {
742 $condition = get_string('criteria_descr_' . $short . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
743 core_text::strtoupper($agg[$badge->get_aggregation_method()]));
746 unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
748 $items = array();
749 // If only one criterion left, make sure its description goe to the top.
750 if (count($badge->criteria) == 1) {
751 $c = reset($badge->criteria);
752 if (!$short && !empty($c->description)) {
753 $overalldescr = $this->output->box(
754 format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
755 'criteria-description'
758 if (count($c->params) == 1) {
759 $items[] = get_string('criteria_descr_single_' . $short . $c->criteriatype , 'badges') .
760 $c->get_details($short);
761 } else {
762 $items[] = get_string('criteria_descr_' . $short . $c->criteriatype, 'badges',
763 core_text::strtoupper($agg[$badge->get_aggregation_method($c->criteriatype)])) .
764 $c->get_details($short);
766 } else {
767 foreach ($badge->criteria as $type => $c) {
768 $criteriadescr = '';
769 if (!$short && !empty($c->description)) {
770 $criteriadescr = $this->output->box(
771 format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
772 'criteria-description'
775 if (count($c->params) == 1) {
776 $items[] = get_string('criteria_descr_single_' . $short . $type , 'badges') .
777 $c->get_details($short) . $criteriadescr;
778 } else {
779 $items[] = get_string('criteria_descr_' . $short . $type , 'badges',
780 core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) .
781 $c->get_details($short) .
782 $criteriadescr;
787 return $overalldescr . $condition . html_writer::alist($items, array(), 'ul');;
790 // Prints criteria actions for badge editing.
791 public function print_criteria_actions(badge $badge) {
792 $output = '';
793 if (!$badge->is_active() && !$badge->is_locked()) {
794 $accepted = $badge->get_accepted_criteria();
795 $potential = array_diff($accepted, array_keys($badge->criteria));
797 if (!empty($potential)) {
798 foreach ($potential as $p) {
799 if ($p != 0) {
800 $select[$p] = get_string('criteria_' . $p, 'badges');
803 $output .= $this->output->single_select(
804 new moodle_url('/badges/criteria_settings.php', array('badgeid' => $badge->id, 'add' => true)),
805 'type',
806 $select,
808 array('' => 'choosedots'),
809 null,
810 array('label' => get_string('addbadgecriteria', 'badges'))
812 } else {
813 $output .= $this->output->box(get_string('nothingtoadd', 'badges'), 'clearfix');
817 return $output;
820 // Renders a table with users who have earned the badge.
821 // Based on stamps collection plugin.
822 protected function render_badge_recipients(badge_recipients $recipients) {
823 $paging = new paging_bar($recipients->totalcount, $recipients->page, $recipients->perpage, $this->page->url, 'page');
824 $htmlpagingbar = $this->render($paging);
825 $table = new html_table();
826 $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
828 $sortbyfirstname = $this->helper_sortable_heading(get_string('firstname'),
829 'firstname', $recipients->sort, $recipients->dir);
830 $sortbylastname = $this->helper_sortable_heading(get_string('lastname'),
831 'lastname', $recipients->sort, $recipients->dir);
832 if ($this->helper_fullname_format() == 'lf') {
833 $sortbyname = $sortbylastname . ' / ' . $sortbyfirstname;
834 } else {
835 $sortbyname = $sortbyfirstname . ' / ' . $sortbylastname;
838 $sortbydate = $this->helper_sortable_heading(get_string('dateawarded', 'badges'),
839 'dateissued', $recipients->sort, $recipients->dir);
841 $table->head = array($sortbyname, $sortbydate, '');
843 foreach ($recipients->userids as $holder) {
844 $fullname = fullname($holder);
845 $fullname = html_writer::link(
846 new moodle_url('/user/profile.php', array('id' => $holder->userid)),
847 $fullname
849 $awarded = userdate($holder->dateissued);
850 $badgeurl = html_writer::link(
851 new moodle_url('/badges/badge.php', array('hash' => $holder->uniquehash)),
852 get_string('viewbadge', 'badges')
855 $row = array($fullname, $awarded, $badgeurl);
856 $table->data[] = $row;
859 $htmltable = html_writer::table($table);
861 return $htmlpagingbar . $htmltable . $htmlpagingbar;
864 ////////////////////////////////////////////////////////////////////////////
865 // Helper methods
866 // Reused from stamps collection plugin
867 ////////////////////////////////////////////////////////////////////////////
870 * Renders a text with icons to sort by the given column
872 * This is intended for table headings.
874 * @param string $text The heading text
875 * @param string $sortid The column id used for sorting
876 * @param string $sortby Currently sorted by (column id)
877 * @param string $sorthow Currently sorted how (ASC|DESC)
879 * @return string
881 protected function helper_sortable_heading($text, $sortid = null, $sortby = null, $sorthow = null) {
882 $out = html_writer::tag('span', $text, array('class' => 'text'));
884 if (!is_null($sortid)) {
885 if ($sortby !== $sortid || $sorthow !== 'ASC') {
886 $url = new moodle_url($this->page->url);
887 $url->params(array('sort' => $sortid, 'dir' => 'ASC'));
888 $out .= $this->output->action_icon($url,
889 new pix_icon('t/sort_asc', get_string('sortbyx', 'core', s($text)), null, array('class' => 'iconsort')));
891 if ($sortby !== $sortid || $sorthow !== 'DESC') {
892 $url = new moodle_url($this->page->url);
893 $url->params(array('sort' => $sortid, 'dir' => 'DESC'));
894 $out .= $this->output->action_icon($url,
895 new pix_icon('t/sort_desc', get_string('sortbyxreverse', 'core', s($text)), null, array('class' => 'iconsort')));
898 return $out;
901 * Tries to guess the fullname format set at the site
903 * @return string fl|lf
905 protected function helper_fullname_format() {
906 $fake = new stdClass();
907 $fake->lastname = 'LLLL';
908 $fake->firstname = 'FFFF';
909 $fullname = get_string('fullnamedisplay', '', $fake);
910 if (strpos($fullname, 'LLLL') < strpos($fullname, 'FFFF')) {
911 return 'lf';
912 } else {
913 return 'fl';
917 * Renders a search form
919 * @param string $search Search string
920 * @return string HTML
922 protected function helper_search_form($search) {
923 global $CFG;
924 require_once($CFG->libdir . '/formslib.php');
926 $mform = new MoodleQuickForm('searchform', 'POST', $this->page->url);
928 $mform->addElement('hidden', 'sesskey', sesskey());
930 $el[] = $mform->createElement('text', 'search', get_string('search'), array('size' => 20));
931 $mform->setDefault('search', $search);
932 $el[] = $mform->createElement('submit', 'submitsearch', get_string('search'));
933 $el[] = $mform->createElement('submit', 'clearsearch', get_string('clear'));
934 $mform->addGroup($el, 'searchgroup', get_string('searchname', 'badges'), ' ', false);
936 ob_start();
937 $mform->display();
938 $out = ob_get_clean();
940 return $out;
944 * Renders a definition list
946 * @param array $items the list of items to define
947 * @param array
949 protected function definition_list(array $items, array $attributes = array()) {
950 $output = html_writer::start_tag('dl', $attributes);
951 foreach ($items as $label => $value) {
952 $output .= html_writer::tag('dt', $label);
953 $output .= html_writer::tag('dd', $value);
955 $output .= html_writer::end_tag('dl');
956 return $output;
961 * An issued badges for badge.php page
963 class issued_badge implements renderable {
964 /** @var issued badge */
965 public $issued;
967 /** @var badge recipient */
968 public $recipient;
970 /** @var badge class */
971 public $badgeclass;
973 /** @var badge visibility to others */
974 public $visible = 0;
976 /** @var badge class */
977 public $badgeid = 0;
980 * Initializes the badge to display
982 * @param string $hash Issued badge hash
984 public function __construct($hash) {
985 global $DB;
987 $assertion = new core_badges_assertion($hash);
988 $this->issued = $assertion->get_badge_assertion();
989 $this->badgeclass = $assertion->get_badge_class();
991 $rec = $DB->get_record_sql('SELECT userid, visible, badgeid
992 FROM {badge_issued}
993 WHERE ' . $DB->sql_compare_text('uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40),
994 array('hash' => $hash), IGNORE_MISSING);
995 if ($rec) {
996 // Get a recipient from database.
997 $namefields = get_all_user_name_fields(true, 'u');
998 $user = $DB->get_record_sql("SELECT u.id, $namefields, u.deleted, u.email
999 FROM {user} u WHERE u.id = :userid", array('userid' => $rec->userid));
1000 $this->recipient = $user;
1001 $this->visible = $rec->visible;
1002 $this->badgeid = $rec->badgeid;
1008 * An external badges for external.php page
1010 class external_badge implements renderable {
1011 /** @var issued badge */
1012 public $issued;
1014 /** @var User ID */
1015 public $recipient;
1017 /** @var validation of external badge */
1018 public $valid = true;
1021 * Initializes the badge to display
1023 * @param object $badge External badge information.
1024 * @param int $recipient User id.
1026 public function __construct($badge, $recipient) {
1027 global $DB;
1028 // At this point a user has connected a backpack. So, we are going to get
1029 // their backpack email rather than their account email.
1030 $namefields = get_all_user_name_fields(true, 'u');
1031 $user = $DB->get_record_sql("SELECT {$namefields}, b.email
1032 FROM {user} u INNER JOIN {badge_backpack} b ON u.id = b.userid
1033 WHERE userid = :userid", array('userid' => $recipient), IGNORE_MISSING);
1035 $this->issued = $badge;
1036 $this->recipient = $user;
1038 // Check if recipient is valid.
1039 // There is no way to be 100% sure that a badge belongs to a user.
1040 // Backpack does not return any recipient information.
1041 // All we can do is compare that backpack email hashed using salt
1042 // provided in the assertion matches a badge recipient from the assertion.
1043 if ($user) {
1044 if (validate_email($badge->assertion->recipient) && $badge->assertion->recipient == $user->email) {
1045 // If we have email, compare emails.
1046 $this->valid = true;
1047 } else if ($badge->assertion->recipient == 'sha256$' . hash('sha256', $user->email)) {
1048 // If recipient is hashed, but no salt, compare hashes without salt.
1049 $this->valid = true;
1050 } else if ($badge->assertion->recipient == 'sha256$' . hash('sha256', $user->email . $badge->assertion->salt)) {
1051 // If recipient is hashed, compare hashes.
1052 $this->valid = true;
1053 } else {
1054 // Otherwise, we cannot be sure that this user is a recipient.
1055 $this->valid = false;
1057 } else {
1058 $this->valid = false;
1064 * Badge recipients rendering class
1066 class badge_recipients implements renderable {
1067 /** @var string how are the data sorted */
1068 public $sort = 'lastname';
1070 /** @var string how are the data sorted */
1071 public $dir = 'ASC';
1073 /** @var int page number to display */
1074 public $page = 0;
1076 /** @var int number of badge recipients to display per page */
1077 public $perpage = 30;
1079 /** @var int the total number or badge recipients to display */
1080 public $totalcount = null;
1082 /** @var array internal list of badge recipients ids */
1083 public $userids = array();
1085 * Initializes the list of users to display
1087 * @param array $holders List of badge holders
1089 public function __construct($holders) {
1090 $this->userids = $holders;
1095 * Collection of all badges for view.php page
1097 class badge_collection implements renderable {
1099 /** @var string how are the data sorted */
1100 public $sort = 'name';
1102 /** @var string how are the data sorted */
1103 public $dir = 'ASC';
1105 /** @var int page number to display */
1106 public $page = 0;
1108 /** @var int number of badges to display per page */
1109 public $perpage = BADGE_PERPAGE;
1111 /** @var int the total number of badges to display */
1112 public $totalcount = null;
1114 /** @var array list of badges */
1115 public $badges = array();
1118 * Initializes the list of badges to display
1120 * @param array $badges Badges to render
1122 public function __construct($badges) {
1123 $this->badges = $badges;
1128 * Collection of badges used at the index.php page
1130 class badge_management extends badge_collection implements renderable {
1134 * Collection of user badges used at the mybadges.php page
1136 class badge_user_collection extends badge_collection implements renderable {
1137 /** @var array backpack settings */
1138 public $backpack = null;
1140 /** @var string search */
1141 public $search = '';
1144 * Initializes user badge collection.
1146 * @param array $badges Badges to render
1147 * @param int $userid Badges owner
1149 public function __construct($badges, $userid) {
1150 global $CFG;
1151 parent::__construct($badges);
1153 if (!empty($CFG->badges_allowexternalbackpack)) {
1154 $this->backpack = get_backpack_settings($userid, true);