307675db55ce3e997cc027c4bcc8bdb9ead1e2b9
[moodle.git] / badges / renderer.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Renderer for use with the badges output
19  *
20  * @package    core
21  * @subpackage badges
22  * @copyright  2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  * @author     Yuliya Bozhko <yuliya.bozhko@totaralms.com>
25  */
27 require_once($CFG->libdir . '/badgeslib.php');
28 require_once($CFG->libdir . '/tablelib.php');
30 /**
31  * Standard HTML output renderer for badges
32  */
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;
46             }
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') . ')';
57             }
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);
68                 }
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')));
77                 }
78             }
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));
88                 }
89             }
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));
92         }
94         return html_writer::alist($items, array('class' => 'badges'));
95     }
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')
117                 );
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')
123                 );
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;
137     }
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));
182                 }
183             }
184         } else {
185             $display .= get_string('noexpiry', 'badges');
186         }
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'));
198             }
199         }
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');
212             }
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'));
220             }
221         }
223         $display .= self::print_badge_endorsement($badge);
224         $display .= self::print_badge_related($badge);
225         $display .= self::print_badge_competencies($badge);
227         return html_writer::div($display, null, array('id' => 'badge-overview'));
228     }
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'))) . " ";
250             }
251         }
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'))) . " ";
259         }
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'))) . " ";
265         }
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'))) . " ";
271         }
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'))) . " ";
278         }
280         return $actions;
281     }
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'));
304         }
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;
321             }
322         }
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);
337         }
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);
345         }
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         $dl[get_string('version', 'badges')] = $badge->version;
352         $dl[get_string('language')] = $languages[$badge->language];
353         $dl[get_string('description', 'badges')] = $badge->description;
354         $dl[get_string('imageauthorname', 'badges')] = $badge->imageauthorname;
355         $dl[get_string('imageauthoremail', 'badges')] =
356             html_writer::tag('a', $badge->imageauthoremail, array('href' => 'mailto:' . $badge->imageauthoremail));
357         $dl[get_string('imageauthorurl', 'badges')] =
358             html_writer::link($badge->imageauthorurl, $badge->imageauthorurl, array('target' => '_blank'));
359         $dl[get_string('imagecaption', 'badges')] = $badge->imagecaption;
361         if ($badge->type == BADGE_TYPE_COURSE && isset($badge->courseid)) {
362             $coursename = $DB->get_field('course', 'fullname', array('id' => $badge->courseid));
363             $dl[get_string('course')] = $coursename;
364         }
365         $dl[get_string('bcriteria', 'badges')] = self::print_badge_criteria($badge);
366         $output .= $this->definition_list($dl);
368         $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
369         $dl = array();
370         $issued['issuedOn'] = !preg_match( '~^[1-9][0-9]*$~', $issued['issuedOn'] ) ?
371             strtotime($issued['issuedOn']) : $issued['issuedOn'];
372         $dl[get_string('dateawarded', 'badges')] = userdate($issued['issuedOn']);
373         if (isset($issued['expires'])) {
374             $issued['expires'] = !preg_match( '~^[1-9][0-9]*$~', $issued['expires'] ) ?
375                 strtotime($issued['expires']) : $issued['expires'];
376             if ($issued['expires'] < $now) {
377                 $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']) . get_string('warnexpired', 'badges');
379             } else {
380                 $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']);
381             }
382         }
384         // Print evidence.
385         $agg = $badge->get_aggregation_methods();
386         $evidence = $badge->get_criteria_completions($userinfo->id);
387         $eids = array_map(function($o) {
388             return $o->critid;
389         }, $evidence);
390         unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
392         $items = array();
393         foreach ($badge->criteria as $type => $c) {
394             if (in_array($c->id, $eids)) {
395                 if (count($c->params) == 1) {
396                     $items[] = get_string('criteria_descr_single_' . $type , 'badges') . $c->get_details();
397                 } else {
398                     $items[] = get_string('criteria_descr_' . $type , 'badges',
399                             core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) . $c->get_details();
400                 }
401             }
402         }
404         $dl[get_string('evidence', 'badges')] = get_string('completioninfo', 'badges') . html_writer::alist($items, array(), 'ul');
405         $output .= $this->definition_list($dl);
406         $endorsement = $badge->get_endorsement();
407         if (!empty($endorsement)) {
408             $output .= self::print_badge_endorsement($badge);
409         }
410         $relatedbadges = $badge->get_related_badges();
411         if (!empty($relatedbadges)) {
412             $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
413             $items = array();
414             foreach ($relatedbadges as $related) {
415                 $items[] = $related->name;
416             }
417             $output .= html_writer::alist($items, array(), 'ul');
418         }
419         $competencies = $badge->get_alignment();
420         if (!empty($competencies)) {
421             $output .= $this->heading(get_string('alignment', 'badges'), 3);
422             $items = array();
423             foreach ($competencies as $competency) {
424                 $items[] = html_writer::link($competency->targeturl, $competency->targetname, array('target' => '_blank'));
425             }
426             $output .= html_writer::alist($items, array(), 'ul');
427         }
428         $output .= html_writer::end_tag('div');
430         return $output;
431     }
433     // Outputs external badge.
434     protected function render_external_badge(external_badge $ibadge) {
435         $issued = $ibadge->issued;
436         $assertion = $issued->assertion;
437         $issuer = $assertion->badge->issuer;
438         $userinfo = $ibadge->recipient;
439         $table = new html_table();
440         $today = strtotime(date('Y-m-d'));
442         $output = '';
443         $output .= html_writer::start_tag('div', array('id' => 'badge'));
444         $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
445         $output .= html_writer::empty_tag('img', array('src' => $issued->imageUrl));
446         if (isset($assertion->expires)) {
447             $expiration = !strtotime($assertion->expires) ? s($assertion->expires) : strtotime($assertion->expires);
448             if ($expiration < $today) {
449                 $output .= $this->output->pix_icon('i/expired',
450                         get_string('expireddate', 'badges', userdate($expiration)),
451                         'moodle',
452                         array('class' => 'expireimage'));
453             }
454         }
455         $output .= html_writer::end_tag('div');
457         $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
459         // Recipient information.
460         $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
461         $dl = array();
462         // Technically, we should alway have a user at this point, but added an extra check just in case.
463         if ($userinfo) {
464             if (!$ibadge->valid) {
465                 $notify = $this->output->notification(get_string('recipientvalidationproblem', 'badges'), 'notifynotice');
466                 $dl[get_string('name')] = fullname($userinfo) . $notify;
467             } else {
468                 $dl[get_string('name')] = fullname($userinfo);
469             }
470         } else {
471             $notify = $this->output->notification(get_string('recipientidentificationproblem', 'badges'), 'notifynotice');
472             $dl[get_string('name')] = $notify;
473         }
474         $output .= $this->definition_list($dl);
476         $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
477         $dl = array();
478         $dl[get_string('issuername', 'badges')] = s($issuer->name);
479         $dl[get_string('issuerurl', 'badges')] = html_writer::tag('a', $issuer->origin, array('href' => $issuer->origin));
481         if (isset($issuer->contact)) {
482             $dl[get_string('contact', 'badges')] = obfuscate_mailto($issuer->contact);
483         }
484         $output .= $this->definition_list($dl);
486         $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
487         $dl = array();
488         $dl[get_string('name')] = s($assertion->badge->name);
489         $dl[get_string('description', 'badges')] = s($assertion->badge->description);
490         $dl[get_string('bcriteria', 'badges')] = html_writer::tag('a', s($assertion->badge->criteria), array('href' => $assertion->badge->criteria));
491         $output .= $this->definition_list($dl);
493         $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
494         $dl = array();
495         if (isset($assertion->issued_on)) {
496             $issuedate = !strtotime($assertion->issued_on) ? s($assertion->issued_on) : strtotime($assertion->issued_on);
497             $dl[get_string('dateawarded', 'badges')] = userdate($issuedate);
498         }
499         if (isset($assertion->expires)) {
500             if ($expiration < $today) {
501                 $dl[get_string('expirydate', 'badges')] = userdate($expiration) . get_string('warnexpired', 'badges');
502             } else {
503                 $dl[get_string('expirydate', 'badges')] = userdate($expiration);
504             }
505         }
506         if (isset($assertion->evidence)) {
507             $dl[get_string('evidence', 'badges')] = html_writer::tag('a', s($assertion->evidence), array('href' => $assertion->evidence));
508         }
509         $output .= $this->definition_list($dl);
510         $output .= html_writer::end_tag('div');
512         return $output;
513     }
515     // Displays the user badges.
516     protected function render_badge_user_collection(badge_user_collection $badges) {
517         global $CFG, $USER, $SITE;
518         $backpack = $badges->backpack;
519         $mybackpack = new moodle_url('/badges/mybackpack.php');
521         $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
522         $htmlpagingbar = $this->render($paging);
524         // Set backpack connection string.
525         $backpackconnect = '';
526         if (!empty($CFG->badges_allowexternalbackpack) && is_null($backpack)) {
527             $backpackconnect = $this->output->box(get_string('localconnectto', 'badges', $mybackpack->out()), 'noticebox');
528         }
529         // Search box.
530         $searchform = $this->output->box($this->helper_search_form($badges->search), 'boxwidthwide boxaligncenter');
532         // Download all button.
533         $downloadall = $this->output->single_button(
534                     new moodle_url('/badges/mybadges.php', array('downloadall' => true, 'sesskey' => sesskey())),
535                     get_string('downloadall'), 'POST', array('class' => 'activatebadge'));
537         // Local badges.
538         $localhtml = html_writer::start_tag('div', array('id' => 'issued-badge-table', 'class' => 'generalbox'));
539         $heading = get_string('localbadges', 'badges', format_string($SITE->fullname, true, array('context' => context_system::instance())));
540         $localhtml .= $this->output->heading_with_help($heading, 'localbadgesh', 'badges');
541         if ($badges->badges) {
542             $downloadbutton = $this->output->heading(get_string('badgesearned', 'badges', $badges->totalcount), 4, 'activatebadge');
543             $downloadbutton .= $downloadall;
545             $htmllist = $this->print_badges_list($badges->badges, $USER->id);
546             $localhtml .= $backpackconnect . $downloadbutton . $searchform . $htmlpagingbar . $htmllist . $htmlpagingbar;
547         } else {
548             $localhtml .= $searchform . $this->output->notification(get_string('nobadges', 'badges'));
549         }
550         $localhtml .= html_writer::end_tag('div');
552         // External badges.
553         $externalhtml = "";
554         if (!empty($CFG->badges_allowexternalbackpack)) {
555             $externalhtml .= html_writer::start_tag('div', array('class' => 'generalbox'));
556             $externalhtml .= $this->output->heading_with_help(get_string('externalbadges', 'badges'), 'externalbadges', 'badges');
557             if (!is_null($backpack)) {
558                 if ($backpack->totalcollections == 0) {
559                     $externalhtml .= get_string('nobackpackcollections', 'badges', $backpack);
560                 } else {
561                     if ($backpack->totalbadges == 0) {
562                         $externalhtml .= get_string('nobackpackbadges', 'badges', $backpack);
563                     } else {
564                         $externalhtml .= get_string('backpackbadges', 'badges', $backpack);
565                         $externalhtml .= '<br/><br/>' . $this->print_badges_list($backpack->badges, $USER->id, true, true);
566                     }
567                 }
568             } else {
569                 $externalhtml .= get_string('externalconnectto', 'badges', $mybackpack->out());
570             }
572             $externalhtml .= html_writer::end_tag('div');
573         }
575         return $localhtml . $externalhtml;
576     }
578     // Displays the available badges.
579     protected function render_badge_collection(badge_collection $badges) {
580         $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
581         $htmlpagingbar = $this->render($paging);
582         $table = new html_table();
583         $table->attributes['class'] = 'collection';
585         $sortbyname = $this->helper_sortable_heading(get_string('name'),
586                 'name', $badges->sort, $badges->dir);
587         $sortbyawarded = $this->helper_sortable_heading(get_string('awardedtoyou', 'badges'),
588                 'dateissued', $badges->sort, $badges->dir);
589         $table->head = array(
590                     get_string('badgeimage', 'badges'),
591                     $sortbyname,
592                     get_string('description', 'badges'),
593                     get_string('bcriteria', 'badges'),
594                     $sortbyawarded
595                 );
596         $table->colclasses = array('badgeimage', 'name', 'description', 'criteria', 'awards');
598         foreach ($badges->badges as $badge) {
599             $badgeimage = print_badge_image($badge, $this->page->context, 'large');
600             $name = $badge->name;
601             $description = $badge->description;
602             $criteria = self::print_badge_criteria($badge);
603             if ($badge->dateissued) {
604                 $icon = new pix_icon('i/valid',
605                             get_string('dateearned', 'badges',
606                                 userdate($badge->dateissued, get_string('strftimedatefullshort', 'core_langconfig'))));
607                 $badgeurl = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
608                 $awarded = $this->output->action_icon($badgeurl, $icon, null, null, true);
609             } else {
610                 $awarded = "";
611             }
612             $row = array($badgeimage, $name, $description, $criteria, $awarded);
613             $table->data[] = $row;
614         }
616         $htmltable = html_writer::table($table);
618         return $htmlpagingbar . $htmltable . $htmlpagingbar;
619     }
621     // Outputs table of badges with actions available.
622     protected function render_badge_management(badge_management $badges) {
623         $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
625         // New badge button.
626         $htmlnew = '';
627         if (has_capability('moodle/badges:createbadge', $this->page->context)) {
628             $n['type'] = $this->page->url->get_param('type');
629             $n['id'] = $this->page->url->get_param('id');
630             $htmlnew = $this->output->single_button(new moodle_url('newbadge.php', $n), get_string('newbadge', 'badges'));
631         }
633         $htmlpagingbar = $this->render($paging);
634         $table = new html_table();
635         $table->attributes['class'] = 'collection';
637         $sortbyname = $this->helper_sortable_heading(get_string('name'),
638                 'name', $badges->sort, $badges->dir);
639         $sortbystatus = $this->helper_sortable_heading(get_string('status', 'badges'),
640                 'status', $badges->sort, $badges->dir);
641         $table->head = array(
642                 $sortbyname,
643                 $sortbystatus,
644                 get_string('bcriteria', 'badges'),
645                 get_string('awards', 'badges'),
646                 get_string('actions')
647             );
648         $table->colclasses = array('name', 'status', 'criteria', 'awards', 'actions');
650         foreach ($badges->badges as $b) {
651             $style = !$b->is_active() ? array('class' => 'dimmed') : array();
652             $forlink =  print_badge_image($b, $this->page->context) . ' ' .
653                         html_writer::start_tag('span') . $b->name . html_writer::end_tag('span');
654             $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $b->id)), $forlink, $style);
655             $status = $b->statstring;
656             $criteria = self::print_badge_criteria($b, 'short');
658             if (has_capability('moodle/badges:viewawarded', $this->page->context)) {
659                 $awards = html_writer::link(new moodle_url('/badges/recipients.php', array('id' => $b->id)), $b->awards);
660             } else {
661                 $awards = $b->awards;
662             }
664             $actions = self::print_badge_table_actions($b, $this->page->context);
666             $row = array($name, $status, $criteria, $awards, $actions);
667             $table->data[] = $row;
668         }
669         $htmltable = html_writer::table($table);
671         return $htmlnew . $htmlpagingbar . $htmltable . $htmlpagingbar;
672     }
674     // Prints tabs for badge editing.
675     public function print_badge_tabs($badgeid, $context, $current = 'overview') {
676         global $DB;
678         $badge = new badge($badgeid);
679         $row = array();
681         $row[] = new tabobject('overview',
682                     new moodle_url('/badges/overview.php', array('id' => $badgeid)),
683                     get_string('boverview', 'badges')
684                 );
686         if (has_capability('moodle/badges:configuredetails', $context)) {
687             $row[] = new tabobject('details',
688                         new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'details')),
689                         get_string('bdetails', 'badges')
690                     );
691         }
693         if (has_capability('moodle/badges:configurecriteria', $context)) {
694             $row[] = new tabobject('criteria',
695                         new moodle_url('/badges/criteria.php', array('id' => $badgeid)),
696                         get_string('bcriteria', 'badges')
697                     );
698         }
700         if (has_capability('moodle/badges:configuremessages', $context)) {
701             $row[] = new tabobject('message',
702                         new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'message')),
703                         get_string('bmessage', 'badges')
704                     );
705         }
707         if (has_capability('moodle/badges:viewawarded', $context)) {
708             $awarded = $DB->count_records_sql('SELECT COUNT(b.userid)
709                                                FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
710                                                WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badgeid));
711             $row[] = new tabobject('awards',
712                         new moodle_url('/badges/recipients.php', array('id' => $badgeid)),
713                         get_string('bawards', 'badges', $awarded)
714                     );
715         }
717         if (has_capability('moodle/badges:configuredetails', $context)) {
718             $row[] = new tabobject('bendorsement',
719                 new moodle_url('/badges/endorsement.php', array('id' => $badgeid)),
720                 get_string('bendorsement', 'badges')
721             );
722         }
724         if (has_capability('moodle/badges:configuredetails', $context)) {
725             $related = $DB->count_records_sql("SELECT COUNT(br.badgeid)
726                       FROM {badge_related} br WHERE br.badgeid = :badgeid", array('badgeid' => $badgeid));
727             $row[] = new tabobject('brelated',
728                 new moodle_url('/badges/related.php', array('id' => $badgeid)),
729                 get_string('brelated', 'badges', $related)
730             );
731         }
733         if (has_capability('moodle/badges:configuredetails', $context)) {
734             $competencies = $DB->count_records_sql("SELECT COUNT(bc.id)
735                       FROM {badge_competencies} bc WHERE bc.badgeid = :badgeid", array('badgeid' => $badgeid));
736             $row[] = new tabobject('balignment',
737                 new moodle_url('/badges/competency.php', array('id' => $badgeid)),
738                 get_string('balignment', 'badges', $competencies)
739             );
740         }
742         echo $this->tabtree($row, $current);
743     }
745     /**
746      * Prints badge status box.
747      * @return Either the status box html as a string or null
748      */
749     public function print_badge_status_box(badge $badge) {
750         if (has_capability('moodle/badges:configurecriteria', $badge->get_context())) {
752             if (!$badge->has_criteria()) {
753                 $criteriaurl = new moodle_url('/badges/criteria.php', array('id' => $badge->id));
754                 $status = get_string('nocriteria', 'badges');
755                 if ($this->page->url != $criteriaurl) {
756                     $action = $this->output->single_button(
757                         $criteriaurl,
758                         get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
759                 } else {
760                     $action = '';
761                 }
763                 $message = $status . $action;
764             } else {
765                 $status = get_string('statusmessage_' . $badge->status, 'badges');
766                 if ($badge->is_active()) {
767                     $action = $this->output->single_button(new moodle_url('/badges/action.php',
768                                 array('id' => $badge->id, 'lock' => 1, 'sesskey' => sesskey(),
769                                       'return' => $this->page->url->out_as_local_url(false))),
770                             get_string('deactivate', 'badges'), 'POST', array('class' => 'activatebadge'));
771                 } else {
772                     $action = $this->output->single_button(new moodle_url('/badges/action.php',
773                                 array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(),
774                                       'return' => $this->page->url->out_as_local_url(false))),
775                             get_string('activate', 'badges'), 'POST', array('class' => 'activatebadge'));
776                 }
778                 $message = $status . $this->output->help_icon('status', 'badges') . $action;
780             }
782             $style = $badge->is_active() ? 'generalbox statusbox active' : 'generalbox statusbox inactive';
783             return $this->output->box($message, $style);
784         }
786         return null;
787     }
789     /**
790      * Returns information about badge criteria in a list form.
791      *
792      * @param badge $badge Badge objects
793      * @param string $short Indicates whether to print full info about this badge
794      * @return string $output HTML string to output
795      */
796     public function print_badge_criteria(badge $badge, $short = '') {
797         $agg = $badge->get_aggregation_methods();
798         if (empty($badge->criteria)) {
799             return get_string('nocriteria', 'badges');
800         }
802         $overalldescr = '';
803         $overall = $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL];
804         if (!$short && !empty($overall->description)) {
805             $overalldescr = $this->output->box(
806                 format_text($overall->description, $overall->descriptionformat, array('context' => $badge->get_context())),
807                 'criteria-description'
808                 );
809         }
811         // Get the condition string.
812         if (count($badge->criteria) == 2) {
813             $condition = '';
814             if (!$short) {
815                 $condition = get_string('criteria_descr', 'badges');
816             }
817         } else {
818             $condition = get_string('criteria_descr_' . $short . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
819                                       core_text::strtoupper($agg[$badge->get_aggregation_method()]));
820         }
822         unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
824         $items = array();
825         // If only one criterion left, make sure its description goe to the top.
826         if (count($badge->criteria) == 1) {
827             $c = reset($badge->criteria);
828             if (!$short && !empty($c->description)) {
829                 $overalldescr = $this->output->box(
830                     format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
831                     'criteria-description'
832                     );
833             }
834             if (count($c->params) == 1) {
835                 $items[] = get_string('criteria_descr_single_' . $short . $c->criteriatype , 'badges') .
836                            $c->get_details($short);
837             } else {
838                 $items[] = get_string('criteria_descr_' . $short . $c->criteriatype, 'badges',
839                         core_text::strtoupper($agg[$badge->get_aggregation_method($c->criteriatype)])) .
840                         $c->get_details($short);
841             }
842         } else {
843             foreach ($badge->criteria as $type => $c) {
844                 $criteriadescr = '';
845                 if (!$short && !empty($c->description)) {
846                     $criteriadescr = $this->output->box(
847                         format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
848                         'criteria-description'
849                         );
850                 }
851                 if (count($c->params) == 1) {
852                     $items[] = get_string('criteria_descr_single_' . $short . $type , 'badges') .
853                                $c->get_details($short) . $criteriadescr;
854                 } else {
855                     $items[] = get_string('criteria_descr_' . $short . $type , 'badges',
856                             core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) .
857                             $c->get_details($short) .
858                             $criteriadescr;
859                 }
860             }
861         }
863         return $overalldescr . $condition . html_writer::alist($items, array(), 'ul');;
864     }
866     // Prints criteria actions for badge editing.
867     public function print_criteria_actions(badge $badge) {
868         $output = '';
869         if (!$badge->is_active() && !$badge->is_locked()) {
870             $accepted = $badge->get_accepted_criteria();
871             $potential = array_diff($accepted, array_keys($badge->criteria));
873             if (!empty($potential)) {
874                 foreach ($potential as $p) {
875                     if ($p != 0) {
876                         $select[$p] = get_string('criteria_' . $p, 'badges');
877                     }
878                 }
879                 $output .= $this->output->single_select(
880                     new moodle_url('/badges/criteria_settings.php', array('badgeid' => $badge->id, 'add' => true)),
881                     'type',
882                     $select,
883                     '',
884                     array('' => 'choosedots'),
885                     null,
886                     array('label' => get_string('addbadgecriteria', 'badges'))
887                 );
888             } else {
889                 $output .= $this->output->box(get_string('nothingtoadd', 'badges'), 'clearfix');
890             }
891         }
893         return $output;
894     }
896     // Renders a table with users who have earned the badge.
897     // Based on stamps collection plugin.
898     protected function render_badge_recipients(badge_recipients $recipients) {
899         $paging = new paging_bar($recipients->totalcount, $recipients->page, $recipients->perpage, $this->page->url, 'page');
900         $htmlpagingbar = $this->render($paging);
901         $table = new html_table();
902         $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
904         $sortbyfirstname = $this->helper_sortable_heading(get_string('firstname'),
905                 'firstname', $recipients->sort, $recipients->dir);
906         $sortbylastname = $this->helper_sortable_heading(get_string('lastname'),
907                 'lastname', $recipients->sort, $recipients->dir);
908         if ($this->helper_fullname_format() == 'lf') {
909             $sortbyname = $sortbylastname . ' / ' . $sortbyfirstname;
910         } else {
911             $sortbyname = $sortbyfirstname . ' / ' . $sortbylastname;
912         }
914         $sortbydate = $this->helper_sortable_heading(get_string('dateawarded', 'badges'),
915                 'dateissued', $recipients->sort, $recipients->dir);
917         $table->head = array($sortbyname, $sortbydate, '');
919         foreach ($recipients->userids as $holder) {
920             $fullname = fullname($holder);
921             $fullname = html_writer::link(
922                             new moodle_url('/user/profile.php', array('id' => $holder->userid)),
923                             $fullname
924                         );
925             $awarded  = userdate($holder->dateissued);
926             $badgeurl = html_writer::link(
927                             new moodle_url('/badges/badge.php', array('hash' => $holder->uniquehash)),
928                             get_string('viewbadge', 'badges')
929                         );
931             $row = array($fullname, $awarded, $badgeurl);
932             $table->data[] = $row;
933         }
935         $htmltable = html_writer::table($table);
937         return $htmlpagingbar . $htmltable . $htmlpagingbar;
938     }
940     ////////////////////////////////////////////////////////////////////////////
941     // Helper methods
942     // Reused from stamps collection plugin
943     ////////////////////////////////////////////////////////////////////////////
945     /**
946      * Renders a text with icons to sort by the given column
947      *
948      * This is intended for table headings.
949      *
950      * @param string $text    The heading text
951      * @param string $sortid  The column id used for sorting
952      * @param string $sortby  Currently sorted by (column id)
953      * @param string $sorthow Currently sorted how (ASC|DESC)
954      *
955      * @return string
956      */
957     protected function helper_sortable_heading($text, $sortid = null, $sortby = null, $sorthow = null) {
958         $out = html_writer::tag('span', $text, array('class' => 'text'));
960         if (!is_null($sortid)) {
961             if ($sortby !== $sortid || $sorthow !== 'ASC') {
962                 $url = new moodle_url($this->page->url);
963                 $url->params(array('sort' => $sortid, 'dir' => 'ASC'));
964                 $out .= $this->output->action_icon($url,
965                         new pix_icon('t/sort_asc', get_string('sortbyx', 'core', s($text)), null, array('class' => 'iconsort')));
966             }
967             if ($sortby !== $sortid || $sorthow !== 'DESC') {
968                 $url = new moodle_url($this->page->url);
969                 $url->params(array('sort' => $sortid, 'dir' => 'DESC'));
970                 $out .= $this->output->action_icon($url,
971                         new pix_icon('t/sort_desc', get_string('sortbyxreverse', 'core', s($text)), null, array('class' => 'iconsort')));
972             }
973         }
974         return $out;
975     }
976     /**
977      * Tries to guess the fullname format set at the site
978      *
979      * @return string fl|lf
980      */
981     protected function helper_fullname_format() {
982         $fake = new stdClass();
983         $fake->lastname = 'LLLL';
984         $fake->firstname = 'FFFF';
985         $fullname = get_string('fullnamedisplay', '', $fake);
986         if (strpos($fullname, 'LLLL') < strpos($fullname, 'FFFF')) {
987             return 'lf';
988         } else {
989             return 'fl';
990         }
991     }
992     /**
993      * Renders a search form
994      *
995      * @param string $search Search string
996      * @return string HTML
997      */
998     protected function helper_search_form($search) {
999         global $CFG;
1000         require_once($CFG->libdir . '/formslib.php');
1002         $mform = new MoodleQuickForm('searchform', 'POST', $this->page->url);
1004         $mform->addElement('hidden', 'sesskey', sesskey());
1006         $el[] = $mform->createElement('text', 'search', get_string('search'), array('size' => 20));
1007         $mform->setDefault('search', $search);
1008         $el[] = $mform->createElement('submit', 'submitsearch', get_string('search'));
1009         $el[] = $mform->createElement('submit', 'clearsearch', get_string('clear'));
1010         $mform->addGroup($el, 'searchgroup', get_string('searchname', 'badges'), ' ', false);
1012         ob_start();
1013         $mform->display();
1014         $out = ob_get_clean();
1016         return $out;
1017     }
1019     /**
1020      * Renders a definition list
1021      *
1022      * @param array $items the list of items to define
1023      * @param array
1024      */
1025     protected function definition_list(array $items, array $attributes = array()) {
1026         $output = html_writer::start_tag('dl', $attributes);
1027         foreach ($items as $label => $value) {
1028             $output .= html_writer::tag('dt', $label);
1029             $output .= html_writer::tag('dd', $value);
1030         }
1031         $output .= html_writer::end_tag('dl');
1032         return $output;
1033     }
1035     /**
1036      * Outputs list en badges.
1037      *
1038      * @param badge $badge Badge object.
1039      * @return string $output content endorsement to output.
1040      */
1041     protected function print_badge_endorsement(badge $badge) {
1042         $output = '';
1043         $endorsement = $badge->get_endorsement();
1044         $dl = array();
1045         $output .= $this->heading(get_string('endorsement', 'badges'), 3);
1046         if (!empty($endorsement)) {
1047             $dl[get_string('issuername', 'badges')] = $endorsement->issuername;
1048             $dl[get_string('issueremail', 'badges')] =
1049                 html_writer::tag('a', $endorsement->issueremail, array('href' => 'mailto:' . $endorsement->issueremail));
1050             $dl[get_string('issuerurl', 'badges')] = html_writer::link($endorsement->issuerurl, $endorsement->issuerurl,
1051                 array('target' => '_blank'));
1052             $dl[get_string('dateawarded', 'badges')] = userdate($endorsement->dateissued);
1053             $dl[get_string('claimid', 'badges')] = html_writer::link($endorsement->claimid, $endorsement->claimid,
1054             array('target' => '_blank'));
1055             $dl[get_string('claimcomment', 'badges')] = $endorsement->claimcomment;
1056             $output .= $this->definition_list($dl);
1057         } else {
1058             $output .= get_string('noendorsement', 'badges');
1059         }
1060         return $output;
1061     }
1063     /**
1064      * Print list badges related.
1065      *
1066      * @param badge $badge Badge objects.
1067      * @return string $output List related badges to output.
1068      */
1069     protected function print_badge_related(badge $badge) {
1070         $output = '';
1071         $relatedbadges = $badge->get_related_badges();
1072         $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
1073         if (!empty($relatedbadges)) {
1074             $items = array();
1075             foreach ($relatedbadges as $related) {
1076                 $relatedurl = new moodle_url('/badges/overview.php', array('id' => $related->id));
1077                 $items[] = html_writer::link($relatedurl->out(), $related->name, array('target' => '_blank'));
1078             }
1079             $output .= html_writer::alist($items, array(), 'ul');
1080         } else {
1081             $output .= get_string('norelated', 'badges');
1082         }
1083         return $output;
1084     }
1086     /**
1087      * Print list badge competencies.
1088      *
1089      * @param badge $badge Badge objects.
1090      * @return string $output List competencies to output.
1091      */
1092     protected function print_badge_competencies(badge $badge) {
1093         $output = '';
1094         $output .= $this->heading(get_string('alignment', 'badges'), 3);
1095         $competencies = $badge->get_alignment();
1096         if (!empty($competencies)) {
1097             $items = array();
1098             foreach ($competencies as $competency) {
1099                 $urlaligment = new moodle_url('competency.php',
1100                     array('id' => $badge->id, 'alignmentid' => $competency->id)
1101                 );
1102                 $items[] = html_writer::link($urlaligment, $competency->targetname, array('target' => '_blank'));
1103             }
1104             $output .= html_writer::alist($items, array(), 'ul');
1105         } else {
1106             $output .= get_string('noalignment', 'badges');
1107         }
1108         return $output;
1109     }
1111     /**
1112      * Renders a table for related badges.
1113      *
1114      * @param badge_related $related list related badges.
1115      * @return string list related badges to output.
1116      */
1117     protected function render_badge_related(badge_related $related) {
1118         $currentbadge = new badge($related->currentbadgeid);
1119         $languages = get_string_manager()->get_list_of_languages();
1120         $paging = new paging_bar($related->totalcount, $related->page, $related->perpage, $this->page->url, 'page');
1121         $htmlpagingbar = $this->render($paging);
1122         $table = new html_table();
1123         $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1124         $table->head = array(
1125             get_string('name'),
1126             get_string('version', 'badges'),
1127             get_string('language', 'badges'),
1128             get_string('type', 'badges')
1129         );
1130         if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1131             array_push($table->head, '');
1132         }
1134         foreach ($related->badges as $badge) {
1135             $badgeobject = new badge($badge->id);
1136             $style = array('title' => $badgeobject->name);
1137             if (!$badgeobject->is_active()) {
1138                 $style['class'] = 'dimmed';
1139             }
1140             $context = ($badgeobject->type == BADGE_TYPE_SITE) ?
1141                 context_system::instance() : context_course::instance($badgeobject->courseid);
1142             $forlink = print_badge_image($badgeobject, $context) . ' ' .
1143                 html_writer::start_tag('span') . $badgeobject->name . html_writer::end_tag('span');
1144             $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $badgeobject->id)), $forlink, $style);
1146             $row = array(
1147                 $name,
1148                 $badge->version,
1149                 $badge->language ? $languages[$badge->language] : '',
1150                 $badge->type == BADGE_TYPE_COURSE ? get_string('badgesview', 'badges') : get_string('sitebadges', 'badges')
1151             );
1152             if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1153                 $action = $this->output->action_icon(
1154                     new moodle_url('related_action.php',
1155                         array(
1156                             'badgeid' => $related->currentbadgeid,
1157                             'relatedid' => $badge->id,
1158                             'action' => 'remove'
1159                         )
1160                     ), new pix_icon('t/delete', get_string('delete')));
1161                 $actions = html_writer::tag('div', $action, array('class' => 'badge-actions'));
1162                 array_push($row, $actions);
1163             }
1164             $table->data[] = $row;
1165         }
1166         $htmltable = html_writer::table($table);
1168         return $htmlpagingbar . $htmltable . $htmlpagingbar;
1169     }
1171     /**
1172      * Renders a table with competencies alignment.
1173      *
1174      * @param badge_competencies_alignment $alignment List competencies alignment.
1175      * @return string List competencies aligment to output.
1176      */
1177     protected function render_badge_competencies_alignment(badge_competencies_alignment $alignment) {
1178         $currentbadge = new badge($alignment->currentbadgeid);
1179         $paging = new paging_bar($alignment->totalcount, $alignment->page, $alignment->perpage, $this->page->url, 'page');
1180         $htmlpagingbar = $this->render($paging);
1181         $table = new html_table();
1182         $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1183         $table->head = array('Name', 'URL', '');
1185         foreach ($alignment->alignments as $item) {
1186             $urlaligment = new moodle_url('competency.php',
1187                 array(
1188                     'id' => $currentbadge->id,
1189                     'alignmentid' => $item->id,
1190                 )
1191             );
1192             $row = array(
1193                 html_writer::link($urlaligment, $item->targetname),
1194                 html_writer::link($item->targeturl, $item->targeturl, array('target' => '_blank'))
1195             );
1196             if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1197                 $delete = $this->output->action_icon(
1198                     new moodle_url('competency_action.php',
1199                         array(
1200                             'id' => $currentbadge->id,
1201                             'alignmentid' => $item->id,
1202                             'action' => 'remove'
1203                         )
1204                     ), new pix_icon('t/delete', get_string('delete')));
1205                 $edit = $this->output->action_icon(
1206                     new moodle_url('competency.php',
1207                         array(
1208                             'id' => $currentbadge->id,
1209                             'alignmentid' => $item->id,
1210                             'action' => 'edit'
1211                         )
1212                     ), new pix_icon('t/edit', get_string('edit')));
1213                 $actions = html_writer::tag('div', $edit . $delete, array('class' => 'badge-actions'));
1214                 array_push($row, $actions);
1215             }
1216             $table->data[] = $row;
1217         }
1218         $htmltable = html_writer::table($table);
1220         return $htmlpagingbar . $htmltable . $htmlpagingbar;
1221     }
1224 /**
1225  * An issued badges for badge.php page
1226  */
1227 class issued_badge implements renderable {
1228     /** @var issued badge */
1229     public $issued;
1231     /** @var badge recipient */
1232     public $recipient;
1234     /** @var badge class */
1235     public $badgeclass;
1237     /** @var badge visibility to others */
1238     public $visible = 0;
1240     /** @var badge class */
1241     public $badgeid = 0;
1243     /**
1244      * Initializes the badge to display
1245      *
1246      * @param string $hash Issued badge hash
1247      */
1248     public function __construct($hash) {
1249         global $DB;
1251         $assertion = new core_badges_assertion($hash);
1252         $this->issued = $assertion->get_badge_assertion();
1253         $this->badgeclass = $assertion->get_badge_class();
1255         $rec = $DB->get_record_sql('SELECT userid, visible, badgeid
1256                 FROM {badge_issued}
1257                 WHERE ' . $DB->sql_compare_text('uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40),
1258                 array('hash' => $hash), IGNORE_MISSING);
1259         if ($rec) {
1260             // Get a recipient from database.
1261             $namefields = get_all_user_name_fields(true, 'u');
1262             $user = $DB->get_record_sql("SELECT u.id, $namefields, u.deleted, u.email
1263                         FROM {user} u WHERE u.id = :userid", array('userid' => $rec->userid));
1264             $this->recipient = $user;
1265             $this->visible = $rec->visible;
1266             $this->badgeid = $rec->badgeid;
1267         }
1268     }
1271 /**
1272  * An external badges for external.php page
1273  */
1274 class external_badge implements renderable {
1275     /** @var issued badge */
1276     public $issued;
1278     /** @var User ID */
1279     public $recipient;
1281     /** @var validation of external badge */
1282     public $valid = true;
1284     /**
1285      * Initializes the badge to display
1286      *
1287      * @param object $badge External badge information.
1288      * @param int $recipient User id.
1289      */
1290     public function __construct($badge, $recipient) {
1291         global $DB;
1292         // At this point a user has connected a backpack. So, we are going to get
1293         // their backpack email rather than their account email.
1294         $namefields = get_all_user_name_fields(true, 'u');
1295         $user = $DB->get_record_sql("SELECT {$namefields}, b.email
1296                     FROM {user} u INNER JOIN {badge_backpack} b ON u.id = b.userid
1297                     WHERE userid = :userid", array('userid' => $recipient), IGNORE_MISSING);
1299         $this->issued = $badge;
1300         $this->recipient = $user;
1302         // Check if recipient is valid.
1303         // There is no way to be 100% sure that a badge belongs to a user.
1304         // Backpack does not return any recipient information.
1305         // All we can do is compare that backpack email hashed using salt
1306         // provided in the assertion matches a badge recipient from the assertion.
1307         if ($user) {
1308             if (validate_email($badge->assertion->recipient) && $badge->assertion->recipient == $user->email) {
1309                 // If we have email, compare emails.
1310                 $this->valid = true;
1311             } else if ($badge->assertion->recipient == 'sha256$' . hash('sha256', $user->email)) {
1312                 // If recipient is hashed, but no salt, compare hashes without salt.
1313                 $this->valid = true;
1314             } else if ($badge->assertion->recipient == 'sha256$' . hash('sha256', $user->email . $badge->assertion->salt)) {
1315                 // If recipient is hashed, compare hashes.
1316                 $this->valid = true;
1317             } else {
1318                 // Otherwise, we cannot be sure that this user is a recipient.
1319                 $this->valid = false;
1320             }
1321         } else {
1322             $this->valid = false;
1323         }
1324     }
1327 /**
1328  * Badge recipients rendering class
1329  */
1330 class badge_recipients implements renderable {
1331     /** @var string how are the data sorted */
1332     public $sort = 'lastname';
1334     /** @var string how are the data sorted */
1335     public $dir = 'ASC';
1337     /** @var int page number to display */
1338     public $page = 0;
1340     /** @var int number of badge recipients to display per page */
1341     public $perpage = 30;
1343     /** @var int the total number or badge recipients to display */
1344     public $totalcount = null;
1346     /** @var array internal list of  badge recipients ids */
1347     public $userids = array();
1348     /**
1349      * Initializes the list of users to display
1350      *
1351      * @param array $holders List of badge holders
1352      */
1353     public function __construct($holders) {
1354         $this->userids = $holders;
1355     }
1358 /**
1359  * Collection of all badges for view.php page
1360  */
1361 class badge_collection implements renderable {
1363     /** @var string how are the data sorted */
1364     public $sort = 'name';
1366     /** @var string how are the data sorted */
1367     public $dir = 'ASC';
1369     /** @var int page number to display */
1370     public $page = 0;
1372     /** @var int number of badges to display per page */
1373     public $perpage = BADGE_PERPAGE;
1375     /** @var int the total number of badges to display */
1376     public $totalcount = null;
1378     /** @var array list of badges */
1379     public $badges = array();
1381     /**
1382      * Initializes the list of badges to display
1383      *
1384      * @param array $badges Badges to render
1385      */
1386     public function __construct($badges) {
1387         $this->badges = $badges;
1388     }
1391 /**
1392  * Collection of badges used at the index.php page
1393  */
1394 class badge_management extends badge_collection implements renderable {
1397 /**
1398  * Collection of user badges used at the mybadges.php page
1399  */
1400 class badge_user_collection extends badge_collection implements renderable {
1401     /** @var array backpack settings */
1402     public $backpack = null;
1404     /** @var string search */
1405     public $search = '';
1407     /**
1408      * Initializes user badge collection.
1409      *
1410      * @param array $badges Badges to render
1411      * @param int $userid Badges owner
1412      */
1413     public function __construct($badges, $userid) {
1414         global $CFG;
1415         parent::__construct($badges);
1417         if (!empty($CFG->badges_allowexternalbackpack)) {
1418             $this->backpack = get_backpack_settings($userid, true);
1419         }
1420     }
1423 /**
1424  * Collection of all related badges.
1425  *
1426  * @copyright  2018 Tung Thai
1427  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1428  * @author     Tung Thai <Tung.ThaiDuc@nashtechglobal.com>
1429  */
1430 class badge_related implements renderable {
1432     /** @var string how are the data sorted. */
1433     public $sort = 'name';
1435     /** @var string how are the data sorted. */
1436     public $dir = 'ASC';
1438     /** @var int page number to display. */
1439     public $page = 0;
1441     /** @var int number of badges to display per page. */
1442     public $perpage = BADGE_PERPAGE;
1444     /** @var int the total number of badges to display. */
1445     public $totalcount = null;
1447     /** @var int the current badge. */
1448     public $currentbadgeid = 0;
1450     /** @var array list of badges. */
1451     public $badges = array();
1453     /**
1454      * Initializes the list of badges to display.
1455      *
1456      * @param array $badges related badges to render.
1457      * @param int $currentbadgeid ID current badge.
1458      */
1459     public function __construct($badges, $currentbadgeid) {
1460         $this->badges = $badges;
1461         $this->currentbadgeid = $currentbadgeid;
1462     }
1465 /**
1466  * Collection of all competencies.
1467  *
1468  * @copyright  2018 Tung Thai
1469  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1470  * @author     Tung Thai <Tung.ThaiDuc@nashtechglobal.com>
1471  */
1472 class badge_competencies_alignment implements renderable
1474     /** @var string how are the data sorted. */
1475     public $sort = 'name';
1477     /** @var string how are the data sorted. */
1478     public $dir = 'ASC';
1480     /** @var int page number to display. */
1481     public $page = 0;
1483     /** @var int number of badges to display per page. */
1484     public $perpage = BADGE_PERPAGE;
1486     /** @var int the total number of badges to display. */
1487     public $totalcount = null;
1489     /** @var array list of badges. */
1490     public $alignments = array();
1492     /** @var array list of badges. */
1493     public $currentbadgeid = 0;
1495     /**
1496      * Initializes the list of competencies to display.
1497      *
1498      * @param array $alignments List competencies alignment to render.
1499      * @param int $currentbadgeid ID current badge.
1500      */
1501     public function __construct($alignments, $currentbadgeid) {
1502         $this->alignments = $alignments;
1503         $this->currentbadgeid = $currentbadgeid;
1504     }