5810e572d61fbe2892129e89b13d54a23b068ef8
[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')] =
154             html_writer::link($badge->imageauthorname, $badge->imageauthorname, array('target' => '_blank'));
155         $dl[get_string('imageauthoremail', 'badges')] =
156             html_writer::tag('a', $badge->imageauthoremail, array('href' => 'mailto:' . $badge->imageauthoremail));
157         $dl[get_string('imageauthorurl', 'badges')] =
158             html_writer::link($badge->imageauthorurl, $badge->imageauthorurl, array('target' => '_blank'));
159         $dl[get_string('imagecaption', 'badges')] = $badge->imagecaption;
160         $display .= $this->definition_list($dl);
162         // Issuer details.
163         $display .= $this->heading(get_string('issuerdetails', 'badges'), 3);
164         $dl = array();
165         $dl[get_string('issuername', 'badges')] = $badge->issuername;
166         $dl[get_string('contact', 'badges')] = html_writer::tag('a', $badge->issuercontact, array('href' => 'mailto:' . $badge->issuercontact));
167         $display .= $this->definition_list($dl);
169         // Issuance details if any.
170         $display .= $this->heading(get_string('issuancedetails', 'badges'), 3);
171         if ($badge->can_expire()) {
172             if ($badge->expiredate) {
173                 $display .= get_string('expiredate', 'badges', userdate($badge->expiredate));
174             } else if ($badge->expireperiod) {
175                 if ($badge->expireperiod < 60) {
176                     $display .= get_string('expireperiods', 'badges', round($badge->expireperiod, 2));
177                 } else if ($badge->expireperiod < 60 * 60) {
178                     $display .= get_string('expireperiodm', 'badges', round($badge->expireperiod / 60, 2));
179                 } else if ($badge->expireperiod < 60 * 60 * 24) {
180                     $display .= get_string('expireperiodh', 'badges', round($badge->expireperiod / 60 / 60, 2));
181                 } else {
182                     $display .= get_string('expireperiod', 'badges', round($badge->expireperiod / 60 / 60 / 24, 2));
183                 }
184             }
185         } else {
186             $display .= get_string('noexpiry', 'badges');
187         }
189         // Criteria details if any.
190         $display .= $this->heading(get_string('bcriteria', 'badges'), 3);
191         if ($badge->has_criteria()) {
192             $display .= self::print_badge_criteria($badge);
193         } else {
194             $display .= get_string('nocriteria', 'badges');
195             if (has_capability('moodle/badges:configurecriteria', $context)) {
196                 $display .= $this->output->single_button(
197                     new moodle_url('/badges/criteria.php', array('id' => $badge->id)),
198                     get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
199             }
200         }
202         // Awards details if any.
203         if (has_capability('moodle/badges:viewawarded', $context)) {
204             $display .= $this->heading(get_string('awards', 'badges'), 3);
205             if ($badge->has_awards()) {
206                 $url = new moodle_url('/badges/recipients.php', array('id' => $badge->id));
207                 $a = new stdClass();
208                 $a->link = $url->out();
209                 $a->count = count($badge->get_awards());
210                 $display .= get_string('numawards', 'badges', $a);
211             } else {
212                 $display .= get_string('noawards', 'badges');
213             }
215             if (has_capability('moodle/badges:awardbadge', $context) &&
216                 $badge->has_manual_award_criteria() &&
217                 $badge->is_active()) {
218                 $display .= $this->output->single_button(
219                         new moodle_url('/badges/award.php', array('id' => $badge->id)),
220                         get_string('award', 'badges'), 'POST', array('class' => 'activatebadge'));
221             }
222         }
224         $display .= self::print_badge_endorsement($badge);
225         $display .= self::print_badge_related($badge);
226         $display .= self::print_badge_competencies($badge);
228         return html_writer::div($display, null, array('id' => 'badge-overview'));
229     }
231     // Prints action icons for the badge.
232     public function print_badge_table_actions($badge, $context) {
233         $actions = "";
235         if (has_capability('moodle/badges:configuredetails', $context) && $badge->has_criteria()) {
236             // Activate/deactivate badge.
237             if ($badge->status == BADGE_STATUS_INACTIVE || $badge->status == BADGE_STATUS_INACTIVE_LOCKED) {
238                 // "Activate" will go to another page and ask for confirmation.
239                 $url = new moodle_url('/badges/action.php');
240                 $url->param('id', $badge->id);
241                 $url->param('activate', true);
242                 $url->param('sesskey', sesskey());
243                 $return = new moodle_url(qualified_me());
244                 $url->param('return', $return->out_as_local_url(false));
245                 $actions .= $this->output->action_icon($url, new pix_icon('t/show', get_string('activate', 'badges'))) . " ";
246             } else {
247                 $url = new moodle_url(qualified_me());
248                 $url->param('lock', $badge->id);
249                 $url->param('sesskey', sesskey());
250                 $actions .= $this->output->action_icon($url, new pix_icon('t/hide', get_string('deactivate', 'badges'))) . " ";
251             }
252         }
254         // Award badge manually.
255         if ($badge->has_manual_award_criteria() &&
256                 has_capability('moodle/badges:awardbadge', $context) &&
257                 $badge->is_active()) {
258             $url = new moodle_url('/badges/award.php', array('id' => $badge->id));
259             $actions .= $this->output->action_icon($url, new pix_icon('t/award', get_string('award', 'badges'))) . " ";
260         }
262         // Edit badge.
263         if (has_capability('moodle/badges:configuredetails', $context)) {
264             $url = new moodle_url('/badges/edit.php', array('id' => $badge->id, 'action' => 'details'));
265             $actions .= $this->output->action_icon($url, new pix_icon('t/edit', get_string('edit'))) . " ";
266         }
268         // Duplicate badge.
269         if (has_capability('moodle/badges:createbadge', $context)) {
270             $url = new moodle_url('/badges/action.php', array('copy' => '1', 'id' => $badge->id, 'sesskey' => sesskey()));
271             $actions .= $this->output->action_icon($url, new pix_icon('t/copy', get_string('copy'))) . " ";
272         }
274         // Delete badge.
275         if (has_capability('moodle/badges:deletebadge', $context)) {
276             $url = new moodle_url(qualified_me());
277             $url->param('delete', $badge->id);
278             $actions .= $this->output->action_icon($url, new pix_icon('t/delete', get_string('delete'))) . " ";
279         }
281         return $actions;
282     }
284     // Outputs issued badge with actions available.
285     protected function render_issued_badge(issued_badge $ibadge) {
286         global $USER, $CFG, $DB, $SITE;
287         $issued = $ibadge->issued;
288         $userinfo = $ibadge->recipient;
289         $badgeclass = $ibadge->badgeclass;
290         $badge = new badge($ibadge->badgeid);
291         $now = time();
292         $expiration = isset($issued['expires']) ? $issued['expires'] : $now + 86400;
293         $badgeimage = is_array($badgeclass['image']) ? $badgeclass['image']['id'] : $badgeclass['image'];
294         $languages = get_string_manager()->get_list_of_languages();
296         $output = '';
297         $output .= html_writer::start_tag('div', array('id' => 'badge'));
298         $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
299         $output .= html_writer::empty_tag('img', array('src' => $badgeimage, 'alt' => $badge->name));
300         if ($expiration < $now) {
301             $output .= $this->output->pix_icon('i/expired',
302             get_string('expireddate', 'badges', userdate($issued['expires'])),
303                 'moodle',
304                 array('class' => 'expireimage'));
305         }
307         if ($USER->id == $userinfo->id && !empty($CFG->enablebadges)) {
308             $output .= $this->output->single_button(
309                         new moodle_url('/badges/badge.php', array('hash' => $issued['uid'], 'bake' => true)),
310                         get_string('download'),
311                         'POST');
312             if (!empty($CFG->badges_allowexternalbackpack) && ($expiration > $now) && badges_user_has_backpack($USER->id)) {
313                 $assertion = new moodle_url('/badges/assertion.php', array('b' => $issued['uid']));
314                 $action = new component_action('click', 'addtobackpack', array('assertion' => $assertion->out(false)));
315                 $attributes = array(
316                         'type'  => 'button',
317                         'id'    => 'addbutton',
318                         'value' => get_string('addtobackpack', 'badges'));
319                 $tobackpack = html_writer::tag('input', '', $attributes);
320                 $this->output->add_action_handler($action, 'addbutton');
321                 $output .= $tobackpack;
322             }
323         }
324         $output .= html_writer::end_tag('div');
326         $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
327         // Recipient information.
328         $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
329         $dl = array();
330         if ($userinfo->deleted) {
331             $strdata = new stdClass();
332             $strdata->user = fullname($userinfo);
333             $strdata->site = format_string($SITE->fullname, true, array('context' => context_system::instance()));
335             $dl[get_string('name')] = get_string('error:userdeleted', 'badges', $strdata);
336         } else {
337             $dl[get_string('name')] = fullname($userinfo);
338         }
339         $output .= $this->definition_list($dl);
341         $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
342         $dl = array();
343         $dl[get_string('issuername', 'badges')] = $badge->issuername;
344         if (isset($badge->issuercontact) && !empty($badge->issuercontact)) {
345             $dl[get_string('contact', 'badges')] = obfuscate_mailto($badge->issuercontact);
346         }
347         $output .= $this->definition_list($dl);
349         $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
350         $dl = array();
351         $dl[get_string('name')] = $badge->name;
352         $dl[get_string('version', 'badges')] = $badge->version;
353         $dl[get_string('language')] = $languages[$badge->language];
354         $dl[get_string('description', 'badges')] = $badge->description;
355         $dl[get_string('imageauthorname', 'badges')] =
356             html_writer::link($badge->imageauthorname, $badge->imageauthorname, array('target' => '_blank'));
357         $dl[get_string('imageauthoremail', 'badges')] =
358             html_writer::tag('a', $badge->imageauthoremail, array('href' => 'mailto:' . $badge->imageauthoremail));
359         $dl[get_string('imageauthorurl', 'badges')] =
360             html_writer::link($badge->imageauthorurl, $badge->imageauthorurl, array('target' => '_blank'));
361         $dl[get_string('imagecaption', 'badges')] = $badge->imagecaption;
363         if ($badge->type == BADGE_TYPE_COURSE && isset($badge->courseid)) {
364             $coursename = $DB->get_field('course', 'fullname', array('id' => $badge->courseid));
365             $dl[get_string('course')] = $coursename;
366         }
367         $dl[get_string('bcriteria', 'badges')] = self::print_badge_criteria($badge);
368         $output .= $this->definition_list($dl);
370         $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
371         $dl = array();
372         $issued['issuedOn'] = !preg_match( '~^[1-9][0-9]*$~', $issued['issuedOn'] ) ?
373             strtotime($issued['issuedOn']) : $issued['issuedOn'];
374         $dl[get_string('dateawarded', 'badges')] = userdate($issued['issuedOn']);
375         if (isset($issued['expires'])) {
376             $issued['expires'] = !preg_match( '~^[1-9][0-9]*$~', $issued['expires'] ) ?
377                 strtotime($issued['expires']) : $issued['expires'];
378             if ($issued['expires'] < $now) {
379                 $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']) . get_string('warnexpired', 'badges');
381             } else {
382                 $dl[get_string('expirydate', 'badges')] = userdate($issued['expires']);
383             }
384         }
386         // Print evidence.
387         $agg = $badge->get_aggregation_methods();
388         $evidence = $badge->get_criteria_completions($userinfo->id);
389         $eids = array_map(function($o) {
390             return $o->critid;
391         }, $evidence);
392         unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
394         $items = array();
395         foreach ($badge->criteria as $type => $c) {
396             if (in_array($c->id, $eids)) {
397                 if (count($c->params) == 1) {
398                     $items[] = get_string('criteria_descr_single_' . $type , 'badges') . $c->get_details();
399                 } else {
400                     $items[] = get_string('criteria_descr_' . $type , 'badges',
401                             core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) . $c->get_details();
402                 }
403             }
404         }
406         $dl[get_string('evidence', 'badges')] = get_string('completioninfo', 'badges') . html_writer::alist($items, array(), 'ul');
407         $output .= $this->definition_list($dl);
408         $output .= self::print_badge_endorsement($badge);
409         $relatedbadges = $badge->get_related_badges();
410         $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
411         if (!empty($relatedbadges)) {
412             $items = array();
413             foreach ($relatedbadges as $related) {
414                 $items[] = $related->name;
415             }
416             $output .= html_writer::alist($items, array(), 'ul');
417         } else {
418             $output .= get_string('norelated', 'badges');
419         }
420         $output .= $this->heading(get_string('alignment', 'badges'), 3);
421         $competencies = $badge->get_alignment();
422         if (!empty($competencies)) {
423             $items = array();
424             foreach ($competencies as $competency) {
425                 $items[] = html_writer::link($competency->targeturl, $competency->targetname, array('target' => '_blank'));
426             }
427             $output .= html_writer::alist($items, array(), 'ul');
428         } else {
429             $output .= get_string('noalignment', 'badges');
430         }
431         $output .= html_writer::end_tag('div');
433         return $output;
434     }
436     // Outputs external badge.
437     protected function render_external_badge(external_badge $ibadge) {
438         $issued = $ibadge->issued;
439         $assertion = $issued->assertion;
440         $issuer = $assertion->badge->issuer;
441         $userinfo = $ibadge->recipient;
442         $table = new html_table();
443         $today = strtotime(date('Y-m-d'));
445         $output = '';
446         $output .= html_writer::start_tag('div', array('id' => 'badge'));
447         $output .= html_writer::start_tag('div', array('id' => 'badge-image'));
448         $output .= html_writer::empty_tag('img', array('src' => $issued->imageUrl));
449         if (isset($assertion->expires)) {
450             $expiration = !strtotime($assertion->expires) ? s($assertion->expires) : strtotime($assertion->expires);
451             if ($expiration < $today) {
452                 $output .= $this->output->pix_icon('i/expired',
453                         get_string('expireddate', 'badges', userdate($expiration)),
454                         'moodle',
455                         array('class' => 'expireimage'));
456             }
457         }
458         $output .= html_writer::end_tag('div');
460         $output .= html_writer::start_tag('div', array('id' => 'badge-details'));
462         // Recipient information.
463         $output .= $this->output->heading(get_string('recipientdetails', 'badges'), 3);
464         $dl = array();
465         // Technically, we should alway have a user at this point, but added an extra check just in case.
466         if ($userinfo) {
467             if (!$ibadge->valid) {
468                 $notify = $this->output->notification(get_string('recipientvalidationproblem', 'badges'), 'notifynotice');
469                 $dl[get_string('name')] = fullname($userinfo) . $notify;
470             } else {
471                 $dl[get_string('name')] = fullname($userinfo);
472             }
473         } else {
474             $notify = $this->output->notification(get_string('recipientidentificationproblem', 'badges'), 'notifynotice');
475             $dl[get_string('name')] = $notify;
476         }
477         $output .= $this->definition_list($dl);
479         $output .= $this->output->heading(get_string('issuerdetails', 'badges'), 3);
480         $dl = array();
481         $dl[get_string('issuername', 'badges')] = s($issuer->name);
482         $dl[get_string('issuerurl', 'badges')] = html_writer::tag('a', $issuer->origin, array('href' => $issuer->origin));
484         if (isset($issuer->contact)) {
485             $dl[get_string('contact', 'badges')] = obfuscate_mailto($issuer->contact);
486         }
487         $output .= $this->definition_list($dl);
489         $output .= $this->output->heading(get_string('badgedetails', 'badges'), 3);
490         $dl = array();
491         $dl[get_string('name')] = s($assertion->badge->name);
492         $dl[get_string('description', 'badges')] = s($assertion->badge->description);
493         $dl[get_string('bcriteria', 'badges')] = html_writer::tag('a', s($assertion->badge->criteria), array('href' => $assertion->badge->criteria));
494         $output .= $this->definition_list($dl);
496         $output .= $this->output->heading(get_string('issuancedetails', 'badges'), 3);
497         $dl = array();
498         if (isset($assertion->issued_on)) {
499             $issuedate = !strtotime($assertion->issued_on) ? s($assertion->issued_on) : strtotime($assertion->issued_on);
500             $dl[get_string('dateawarded', 'badges')] = userdate($issuedate);
501         }
502         if (isset($assertion->expires)) {
503             if ($expiration < $today) {
504                 $dl[get_string('expirydate', 'badges')] = userdate($expiration) . get_string('warnexpired', 'badges');
505             } else {
506                 $dl[get_string('expirydate', 'badges')] = userdate($expiration);
507             }
508         }
509         if (isset($assertion->evidence)) {
510             $dl[get_string('evidence', 'badges')] = html_writer::tag('a', s($assertion->evidence), array('href' => $assertion->evidence));
511         }
512         $output .= $this->definition_list($dl);
513         $output .= html_writer::end_tag('div');
515         return $output;
516     }
518     // Displays the user badges.
519     protected function render_badge_user_collection(badge_user_collection $badges) {
520         global $CFG, $USER, $SITE;
521         $backpack = $badges->backpack;
522         $mybackpack = new moodle_url('/badges/mybackpack.php');
524         $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
525         $htmlpagingbar = $this->render($paging);
527         // Set backpack connection string.
528         $backpackconnect = '';
529         if (!empty($CFG->badges_allowexternalbackpack) && is_null($backpack)) {
530             $backpackconnect = $this->output->box(get_string('localconnectto', 'badges', $mybackpack->out()), 'noticebox');
531         }
532         // Search box.
533         $searchform = $this->output->box($this->helper_search_form($badges->search), 'boxwidthwide boxaligncenter');
535         // Download all button.
536         $downloadall = $this->output->single_button(
537                     new moodle_url('/badges/mybadges.php', array('downloadall' => true, 'sesskey' => sesskey())),
538                     get_string('downloadall'), 'POST', array('class' => 'activatebadge'));
540         // Local badges.
541         $localhtml = html_writer::start_tag('div', array('id' => 'issued-badge-table', 'class' => 'generalbox'));
542         $heading = get_string('localbadges', 'badges', format_string($SITE->fullname, true, array('context' => context_system::instance())));
543         $localhtml .= $this->output->heading_with_help($heading, 'localbadgesh', 'badges');
544         if ($badges->badges) {
545             $downloadbutton = $this->output->heading(get_string('badgesearned', 'badges', $badges->totalcount), 4, 'activatebadge');
546             $downloadbutton .= $downloadall;
548             $htmllist = $this->print_badges_list($badges->badges, $USER->id);
549             $localhtml .= $backpackconnect . $downloadbutton . $searchform . $htmlpagingbar . $htmllist . $htmlpagingbar;
550         } else {
551             $localhtml .= $searchform . $this->output->notification(get_string('nobadges', 'badges'));
552         }
553         $localhtml .= html_writer::end_tag('div');
555         // External badges.
556         $externalhtml = "";
557         if (!empty($CFG->badges_allowexternalbackpack)) {
558             $externalhtml .= html_writer::start_tag('div', array('class' => 'generalbox'));
559             $externalhtml .= $this->output->heading_with_help(get_string('externalbadges', 'badges'), 'externalbadges', 'badges');
560             if (!is_null($backpack)) {
561                 if ($backpack->totalcollections == 0) {
562                     $externalhtml .= get_string('nobackpackcollections', 'badges', $backpack);
563                 } else {
564                     if ($backpack->totalbadges == 0) {
565                         $externalhtml .= get_string('nobackpackbadges', 'badges', $backpack);
566                     } else {
567                         $externalhtml .= get_string('backpackbadges', 'badges', $backpack);
568                         $externalhtml .= '<br/><br/>' . $this->print_badges_list($backpack->badges, $USER->id, true, true);
569                     }
570                 }
571             } else {
572                 $externalhtml .= get_string('externalconnectto', 'badges', $mybackpack->out());
573             }
575             $externalhtml .= html_writer::end_tag('div');
576         }
578         return $localhtml . $externalhtml;
579     }
581     // Displays the available badges.
582     protected function render_badge_collection(badge_collection $badges) {
583         $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
584         $htmlpagingbar = $this->render($paging);
585         $table = new html_table();
586         $table->attributes['class'] = 'collection';
588         $sortbyname = $this->helper_sortable_heading(get_string('name'),
589                 'name', $badges->sort, $badges->dir);
590         $sortbyawarded = $this->helper_sortable_heading(get_string('awardedtoyou', 'badges'),
591                 'dateissued', $badges->sort, $badges->dir);
592         $table->head = array(
593                     get_string('badgeimage', 'badges'),
594                     $sortbyname,
595                     get_string('description', 'badges'),
596                     get_string('bcriteria', 'badges'),
597                     $sortbyawarded
598                 );
599         $table->colclasses = array('badgeimage', 'name', 'description', 'criteria', 'awards');
601         foreach ($badges->badges as $badge) {
602             $badgeimage = print_badge_image($badge, $this->page->context, 'large');
603             $name = $badge->name;
604             $description = $badge->description;
605             $criteria = self::print_badge_criteria($badge);
606             if ($badge->dateissued) {
607                 $icon = new pix_icon('i/valid',
608                             get_string('dateearned', 'badges',
609                                 userdate($badge->dateissued, get_string('strftimedatefullshort', 'core_langconfig'))));
610                 $badgeurl = new moodle_url('/badges/badge.php', array('hash' => $badge->uniquehash));
611                 $awarded = $this->output->action_icon($badgeurl, $icon, null, null, true);
612             } else {
613                 $awarded = "";
614             }
615             $row = array($badgeimage, $name, $description, $criteria, $awarded);
616             $table->data[] = $row;
617         }
619         $htmltable = html_writer::table($table);
621         return $htmlpagingbar . $htmltable . $htmlpagingbar;
622     }
624     // Outputs table of badges with actions available.
625     protected function render_badge_management(badge_management $badges) {
626         $paging = new paging_bar($badges->totalcount, $badges->page, $badges->perpage, $this->page->url, 'page');
628         // New badge button.
629         $htmlnew = '';
630         if (has_capability('moodle/badges:createbadge', $this->page->context)) {
631             $n['type'] = $this->page->url->get_param('type');
632             $n['id'] = $this->page->url->get_param('id');
633             $htmlnew = $this->output->single_button(new moodle_url('newbadge.php', $n), get_string('newbadge', 'badges'));
634         }
636         $htmlpagingbar = $this->render($paging);
637         $table = new html_table();
638         $table->attributes['class'] = 'collection';
640         $sortbyname = $this->helper_sortable_heading(get_string('name'),
641                 'name', $badges->sort, $badges->dir);
642         $sortbystatus = $this->helper_sortable_heading(get_string('status', 'badges'),
643                 'status', $badges->sort, $badges->dir);
644         $table->head = array(
645                 $sortbyname,
646                 $sortbystatus,
647                 get_string('bcriteria', 'badges'),
648                 get_string('awards', 'badges'),
649                 get_string('actions')
650             );
651         $table->colclasses = array('name', 'status', 'criteria', 'awards', 'actions');
653         foreach ($badges->badges as $b) {
654             $style = !$b->is_active() ? array('class' => 'dimmed') : array();
655             $forlink =  print_badge_image($b, $this->page->context) . ' ' .
656                         html_writer::start_tag('span') . $b->name . html_writer::end_tag('span');
657             $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $b->id)), $forlink, $style);
658             $status = $b->statstring;
659             $criteria = self::print_badge_criteria($b, 'short');
661             if (has_capability('moodle/badges:viewawarded', $this->page->context)) {
662                 $awards = html_writer::link(new moodle_url('/badges/recipients.php', array('id' => $b->id)), $b->awards);
663             } else {
664                 $awards = $b->awards;
665             }
667             $actions = self::print_badge_table_actions($b, $this->page->context);
669             $row = array($name, $status, $criteria, $awards, $actions);
670             $table->data[] = $row;
671         }
672         $htmltable = html_writer::table($table);
674         return $htmlnew . $htmlpagingbar . $htmltable . $htmlpagingbar;
675     }
677     // Prints tabs for badge editing.
678     public function print_badge_tabs($badgeid, $context, $current = 'overview') {
679         global $DB;
681         $badge = new badge($badgeid);
682         $row = array();
684         $row[] = new tabobject('overview',
685                     new moodle_url('/badges/overview.php', array('id' => $badgeid)),
686                     get_string('boverview', 'badges')
687                 );
689         if (has_capability('moodle/badges:configuredetails', $context)) {
690             $row[] = new tabobject('details',
691                         new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'details')),
692                         get_string('bdetails', 'badges')
693                     );
694         }
696         if (has_capability('moodle/badges:configurecriteria', $context)) {
697             $row[] = new tabobject('criteria',
698                         new moodle_url('/badges/criteria.php', array('id' => $badgeid)),
699                         get_string('bcriteria', 'badges')
700                     );
701         }
703         if (has_capability('moodle/badges:configuremessages', $context)) {
704             $row[] = new tabobject('message',
705                         new moodle_url('/badges/edit.php', array('id' => $badgeid, 'action' => 'message')),
706                         get_string('bmessage', 'badges')
707                     );
708         }
710         if (has_capability('moodle/badges:viewawarded', $context)) {
711             $awarded = $DB->count_records_sql('SELECT COUNT(b.userid)
712                                                FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
713                                                WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badgeid));
714             $row[] = new tabobject('awards',
715                         new moodle_url('/badges/recipients.php', array('id' => $badgeid)),
716                         get_string('bawards', 'badges', $awarded)
717                     );
718         }
720         if (has_capability('moodle/badges:configuredetails', $context)) {
721             $row[] = new tabobject('bendorsement',
722                 new moodle_url('/badges/endorsement.php', array('id' => $badgeid)),
723                 get_string('bendorsement', 'badges')
724             );
725         }
727         if (has_capability('moodle/badges:configuredetails', $context)) {
728             $related = $DB->count_records_sql("SELECT COUNT(br.badgeid)
729                       FROM {badge_related} br WHERE br.badgeid = :badgeid", array('badgeid' => $badgeid));
730             $row[] = new tabobject('brelated',
731                 new moodle_url('/badges/related.php', array('id' => $badgeid)),
732                 get_string('brelated', 'badges', $related)
733             );
734         }
736         if (has_capability('moodle/badges:configuredetails', $context)) {
737             $competencies = $DB->count_records_sql("SELECT COUNT(bc.id)
738                       FROM {badge_competencies} bc WHERE bc.badgeid = :badgeid", array('badgeid' => $badgeid));
739             $row[] = new tabobject('balignment',
740                 new moodle_url('/badges/competency.php', array('id' => $badgeid)),
741                 get_string('balignment', 'badges', $competencies)
742             );
743         }
745         echo $this->tabtree($row, $current);
746     }
748     /**
749      * Prints badge status box.
750      * @return Either the status box html as a string or null
751      */
752     public function print_badge_status_box(badge $badge) {
753         if (has_capability('moodle/badges:configurecriteria', $badge->get_context())) {
755             if (!$badge->has_criteria()) {
756                 $criteriaurl = new moodle_url('/badges/criteria.php', array('id' => $badge->id));
757                 $status = get_string('nocriteria', 'badges');
758                 if ($this->page->url != $criteriaurl) {
759                     $action = $this->output->single_button(
760                         $criteriaurl,
761                         get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
762                 } else {
763                     $action = '';
764                 }
766                 $message = $status . $action;
767             } else {
768                 $status = get_string('statusmessage_' . $badge->status, 'badges');
769                 if ($badge->is_active()) {
770                     $action = $this->output->single_button(new moodle_url('/badges/action.php',
771                                 array('id' => $badge->id, 'lock' => 1, 'sesskey' => sesskey(),
772                                       'return' => $this->page->url->out_as_local_url(false))),
773                             get_string('deactivate', 'badges'), 'POST', array('class' => 'activatebadge'));
774                 } else {
775                     $action = $this->output->single_button(new moodle_url('/badges/action.php',
776                                 array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(),
777                                       'return' => $this->page->url->out_as_local_url(false))),
778                             get_string('activate', 'badges'), 'POST', array('class' => 'activatebadge'));
779                 }
781                 $message = $status . $this->output->help_icon('status', 'badges') . $action;
783             }
785             $style = $badge->is_active() ? 'generalbox statusbox active' : 'generalbox statusbox inactive';
786             return $this->output->box($message, $style);
787         }
789         return null;
790     }
792     /**
793      * Returns information about badge criteria in a list form.
794      *
795      * @param badge $badge Badge objects
796      * @param string $short Indicates whether to print full info about this badge
797      * @return string $output HTML string to output
798      */
799     public function print_badge_criteria(badge $badge, $short = '') {
800         $agg = $badge->get_aggregation_methods();
801         if (empty($badge->criteria)) {
802             return get_string('nocriteria', 'badges');
803         }
805         $overalldescr = '';
806         $overall = $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL];
807         if (!$short && !empty($overall->description)) {
808             $overalldescr = $this->output->box(
809                 format_text($overall->description, $overall->descriptionformat, array('context' => $badge->get_context())),
810                 'criteria-description'
811                 );
812         }
814         // Get the condition string.
815         if (count($badge->criteria) == 2) {
816             $condition = '';
817             if (!$short) {
818                 $condition = get_string('criteria_descr', 'badges');
819             }
820         } else {
821             $condition = get_string('criteria_descr_' . $short . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
822                                       core_text::strtoupper($agg[$badge->get_aggregation_method()]));
823         }
825         unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
827         $items = array();
828         // If only one criterion left, make sure its description goe to the top.
829         if (count($badge->criteria) == 1) {
830             $c = reset($badge->criteria);
831             if (!$short && !empty($c->description)) {
832                 $overalldescr = $this->output->box(
833                     format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
834                     'criteria-description'
835                     );
836             }
837             if (count($c->params) == 1) {
838                 $items[] = get_string('criteria_descr_single_' . $short . $c->criteriatype , 'badges') .
839                            $c->get_details($short);
840             } else {
841                 $items[] = get_string('criteria_descr_' . $short . $c->criteriatype, 'badges',
842                         core_text::strtoupper($agg[$badge->get_aggregation_method($c->criteriatype)])) .
843                         $c->get_details($short);
844             }
845         } else {
846             foreach ($badge->criteria as $type => $c) {
847                 $criteriadescr = '';
848                 if (!$short && !empty($c->description)) {
849                     $criteriadescr = $this->output->box(
850                         format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
851                         'criteria-description'
852                         );
853                 }
854                 if (count($c->params) == 1) {
855                     $items[] = get_string('criteria_descr_single_' . $short . $type , 'badges') .
856                                $c->get_details($short) . $criteriadescr;
857                 } else {
858                     $items[] = get_string('criteria_descr_' . $short . $type , 'badges',
859                             core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) .
860                             $c->get_details($short) .
861                             $criteriadescr;
862                 }
863             }
864         }
866         return $overalldescr . $condition . html_writer::alist($items, array(), 'ul');;
867     }
869     // Prints criteria actions for badge editing.
870     public function print_criteria_actions(badge $badge) {
871         $output = '';
872         if (!$badge->is_active() && !$badge->is_locked()) {
873             $accepted = $badge->get_accepted_criteria();
874             $potential = array_diff($accepted, array_keys($badge->criteria));
876             if (!empty($potential)) {
877                 foreach ($potential as $p) {
878                     if ($p != 0) {
879                         $select[$p] = get_string('criteria_' . $p, 'badges');
880                     }
881                 }
882                 $output .= $this->output->single_select(
883                     new moodle_url('/badges/criteria_settings.php', array('badgeid' => $badge->id, 'add' => true)),
884                     'type',
885                     $select,
886                     '',
887                     array('' => 'choosedots'),
888                     null,
889                     array('label' => get_string('addbadgecriteria', 'badges'))
890                 );
891             } else {
892                 $output .= $this->output->box(get_string('nothingtoadd', 'badges'), 'clearfix');
893             }
894         }
896         return $output;
897     }
899     // Renders a table with users who have earned the badge.
900     // Based on stamps collection plugin.
901     protected function render_badge_recipients(badge_recipients $recipients) {
902         $paging = new paging_bar($recipients->totalcount, $recipients->page, $recipients->perpage, $this->page->url, 'page');
903         $htmlpagingbar = $this->render($paging);
904         $table = new html_table();
905         $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
907         $sortbyfirstname = $this->helper_sortable_heading(get_string('firstname'),
908                 'firstname', $recipients->sort, $recipients->dir);
909         $sortbylastname = $this->helper_sortable_heading(get_string('lastname'),
910                 'lastname', $recipients->sort, $recipients->dir);
911         if ($this->helper_fullname_format() == 'lf') {
912             $sortbyname = $sortbylastname . ' / ' . $sortbyfirstname;
913         } else {
914             $sortbyname = $sortbyfirstname . ' / ' . $sortbylastname;
915         }
917         $sortbydate = $this->helper_sortable_heading(get_string('dateawarded', 'badges'),
918                 'dateissued', $recipients->sort, $recipients->dir);
920         $table->head = array($sortbyname, $sortbydate, '');
922         foreach ($recipients->userids as $holder) {
923             $fullname = fullname($holder);
924             $fullname = html_writer::link(
925                             new moodle_url('/user/profile.php', array('id' => $holder->userid)),
926                             $fullname
927                         );
928             $awarded  = userdate($holder->dateissued);
929             $badgeurl = html_writer::link(
930                             new moodle_url('/badges/badge.php', array('hash' => $holder->uniquehash)),
931                             get_string('viewbadge', 'badges')
932                         );
934             $row = array($fullname, $awarded, $badgeurl);
935             $table->data[] = $row;
936         }
938         $htmltable = html_writer::table($table);
940         return $htmlpagingbar . $htmltable . $htmlpagingbar;
941     }
943     ////////////////////////////////////////////////////////////////////////////
944     // Helper methods
945     // Reused from stamps collection plugin
946     ////////////////////////////////////////////////////////////////////////////
948     /**
949      * Renders a text with icons to sort by the given column
950      *
951      * This is intended for table headings.
952      *
953      * @param string $text    The heading text
954      * @param string $sortid  The column id used for sorting
955      * @param string $sortby  Currently sorted by (column id)
956      * @param string $sorthow Currently sorted how (ASC|DESC)
957      *
958      * @return string
959      */
960     protected function helper_sortable_heading($text, $sortid = null, $sortby = null, $sorthow = null) {
961         $out = html_writer::tag('span', $text, array('class' => 'text'));
963         if (!is_null($sortid)) {
964             if ($sortby !== $sortid || $sorthow !== 'ASC') {
965                 $url = new moodle_url($this->page->url);
966                 $url->params(array('sort' => $sortid, 'dir' => 'ASC'));
967                 $out .= $this->output->action_icon($url,
968                         new pix_icon('t/sort_asc', get_string('sortbyx', 'core', s($text)), null, array('class' => 'iconsort')));
969             }
970             if ($sortby !== $sortid || $sorthow !== 'DESC') {
971                 $url = new moodle_url($this->page->url);
972                 $url->params(array('sort' => $sortid, 'dir' => 'DESC'));
973                 $out .= $this->output->action_icon($url,
974                         new pix_icon('t/sort_desc', get_string('sortbyxreverse', 'core', s($text)), null, array('class' => 'iconsort')));
975             }
976         }
977         return $out;
978     }
979     /**
980      * Tries to guess the fullname format set at the site
981      *
982      * @return string fl|lf
983      */
984     protected function helper_fullname_format() {
985         $fake = new stdClass();
986         $fake->lastname = 'LLLL';
987         $fake->firstname = 'FFFF';
988         $fullname = get_string('fullnamedisplay', '', $fake);
989         if (strpos($fullname, 'LLLL') < strpos($fullname, 'FFFF')) {
990             return 'lf';
991         } else {
992             return 'fl';
993         }
994     }
995     /**
996      * Renders a search form
997      *
998      * @param string $search Search string
999      * @return string HTML
1000      */
1001     protected function helper_search_form($search) {
1002         global $CFG;
1003         require_once($CFG->libdir . '/formslib.php');
1005         $mform = new MoodleQuickForm('searchform', 'POST', $this->page->url);
1007         $mform->addElement('hidden', 'sesskey', sesskey());
1009         $el[] = $mform->createElement('text', 'search', get_string('search'), array('size' => 20));
1010         $mform->setDefault('search', $search);
1011         $el[] = $mform->createElement('submit', 'submitsearch', get_string('search'));
1012         $el[] = $mform->createElement('submit', 'clearsearch', get_string('clear'));
1013         $mform->addGroup($el, 'searchgroup', get_string('searchname', 'badges'), ' ', false);
1015         ob_start();
1016         $mform->display();
1017         $out = ob_get_clean();
1019         return $out;
1020     }
1022     /**
1023      * Renders a definition list
1024      *
1025      * @param array $items the list of items to define
1026      * @param array
1027      */
1028     protected function definition_list(array $items, array $attributes = array()) {
1029         $output = html_writer::start_tag('dl', $attributes);
1030         foreach ($items as $label => $value) {
1031             $output .= html_writer::tag('dt', $label);
1032             $output .= html_writer::tag('dd', $value);
1033         }
1034         $output .= html_writer::end_tag('dl');
1035         return $output;
1036     }
1038     /**
1039      * Outputs list en badges.
1040      *
1041      * @param badge $badge Badge object.
1042      * @return string $output content endorsement to output.
1043      */
1044     protected function print_badge_endorsement(badge $badge) {
1045         $output = '';
1046         $endorsement = $badge->get_endorsement();
1047         $dl = array();
1048         $output .= $this->heading(get_string('endorsement', 'badges'), 3);
1049         if (!empty($endorsement)) {
1050             $dl[get_string('issuername', 'badges')] = $endorsement->issuername;
1051             $dl[get_string('issueremail', 'badges')] = $endorsement->issueremail;
1052             $dl[get_string('issuerurl', 'badges')] = html_writer::link($endorsement->issuerurl, $endorsement->issuerurl,
1053                 array('target' => '_blank'));
1054             $dl[get_string('dateawarded', 'badges')] = date('c', $endorsement->dateissued);
1055             $dl[get_string('claimid', 'badges')] = html_writer::link($endorsement->claimid, $endorsement->claimid,
1056             array('target' => '_blank'));
1057             $dl[get_string('claimcomment', 'badges')] = $endorsement->claimcomment;
1058             $output .= $this->definition_list($dl);
1059         } else {
1060             $output .= get_string('noendorsement', 'badges');
1061         }
1062         return $output;
1063     }
1065     /**
1066      * Print list badges related.
1067      *
1068      * @param badge $badge Badge objects.
1069      * @return string $output List related badges to output.
1070      */
1071     protected function print_badge_related(badge $badge) {
1072         $output = '';
1073         $relatedbadges = $badge->get_related_badges();
1074         $output .= $this->heading(get_string('relatedbages', 'badges'), 3);
1075         if (!empty($relatedbadges)) {
1076             $items = array();
1077             foreach ($relatedbadges as $related) {
1078                 $relatedurl = new moodle_url('/badges/overview.php', array('id' => $related->id));
1079                 $items[] = html_writer::link($relatedurl->out(), $related->name, array('target' => '_blank'));
1080             }
1081             $output .= html_writer::alist($items, array(), 'ul');
1082         } else {
1083             $output .= get_string('norelated', 'badges');
1084         }
1085         return $output;
1086     }
1088     /**
1089      * Print list badge competencies.
1090      *
1091      * @param badge $badge Badge objects.
1092      * @return string $output List competencies to output.
1093      */
1094     protected function print_badge_competencies(badge $badge) {
1095         $output = '';
1096         $output .= $this->heading(get_string('alignment', 'badges'), 3);
1097         $competencies = $badge->get_alignment();
1098         if (!empty($competencies)) {
1099             $items = array();
1100             foreach ($competencies as $competency) {
1101                 $urlaligment = new moodle_url('competency.php',
1102                     array('id' => $badge->id, 'alignmentid' => $competency->id)
1103                 );
1104                 $items[] = html_writer::link($urlaligment, $competency->targetname, array('target' => '_blank'));
1105             }
1106             $output .= html_writer::alist($items, array(), 'ul');
1107         } else {
1108             $output .= get_string('noalignment', 'badges');
1109         }
1110         return $output;
1111     }
1113     /**
1114      * Renders a table for related badges.
1115      *
1116      * @param badge_related $related list related badges.
1117      * @return string list related badges to output.
1118      */
1119     protected function render_badge_related(badge_related $related) {
1120         $currentbadge = new badge($related->currentbadgeid);
1121         $languages = get_string_manager()->get_list_of_languages();
1122         $paging = new paging_bar($related->totalcount, $related->page, $related->perpage, $this->page->url, 'page');
1123         $htmlpagingbar = $this->render($paging);
1124         $table = new html_table();
1125         $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1126         $table->head = array(
1127             get_string('name'),
1128             get_string('version', 'badges'),
1129             get_string('language', 'badges'),
1130             get_string('type', 'badges')
1131         );
1132         if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1133             array_push($table->head, '');
1134         }
1136         foreach ($related->badges as $badge) {
1137             $badgeobject = new badge($badge->id);
1138             $style = array('title' => $badgeobject->name);
1139             if (!$badgeobject->is_active()) {
1140                 $style['class'] = 'dimmed';
1141             }
1142             $context = ($badgeobject->type == BADGE_TYPE_SITE) ?
1143                 context_system::instance() : context_course::instance($badgeobject->courseid);
1144             $forlink = print_badge_image($badgeobject, $context) . ' ' .
1145                 html_writer::start_tag('span') . $badgeobject->name . html_writer::end_tag('span');
1146             $name = html_writer::link(new moodle_url('/badges/overview.php', array('id' => $badgeobject->id)), $forlink, $style);
1148             $row = array(
1149                 $name,
1150                 $badge->version,
1151                 $badge->language ? $languages[$badge->language] : '',
1152                 $badge->type == BADGE_TYPE_COURSE ? get_string('badgesview', 'badges') : get_string('sitebadges', 'badges')
1153             );
1154             if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1155                 $action = $this->output->action_icon(
1156                     new moodle_url('related_action.php',
1157                         array(
1158                             'badgeid' => $related->currentbadgeid,
1159                             'relatedid' => $badge->id,
1160                             'action' => 'remove'
1161                         )
1162                     ), new pix_icon('t/delete', get_string('delete')));
1163                 $actions = html_writer::tag('div', $action, array('class' => 'badge-actions'));
1164                 array_push($row, $actions);
1165             }
1166             $table->data[] = $row;
1167         }
1168         $htmltable = html_writer::table($table);
1170         return $htmlpagingbar . $htmltable . $htmlpagingbar;
1171     }
1173     /**
1174      * Renders a table with competencies alignment.
1175      *
1176      * @param badge_competencies_alignment $alignment List competencies alignment.
1177      * @return string List competencies aligment to output.
1178      */
1179     protected function render_badge_competencies_alignment(badge_competencies_alignment $alignment) {
1180         $currentbadge = new badge($alignment->currentbadgeid);
1181         $paging = new paging_bar($alignment->totalcount, $alignment->page, $alignment->perpage, $this->page->url, 'page');
1182         $htmlpagingbar = $this->render($paging);
1183         $table = new html_table();
1184         $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
1185         $table->head = array('Name', 'URL', '');
1187         foreach ($alignment->alignments as $item) {
1188             $urlaligment = new moodle_url('competency.php',
1189                 array(
1190                     'id' => $currentbadge->id,
1191                     'alignmentid' => $item->id,
1192                 )
1193             );
1194             $row = array(
1195                 html_writer::link($urlaligment, $item->targetname),
1196                 html_writer::link($item->targeturl, $item->targeturl, array('target' => '_blank'))
1197             );
1198             if (!$currentbadge->is_active() && !$currentbadge->is_locked()) {
1199                 $delete = $this->output->action_icon(
1200                     new moodle_url('competency_action.php',
1201                         array(
1202                             'id' => $currentbadge->id,
1203                             'alignmentid' => $item->id,
1204                             'action' => 'remove'
1205                         )
1206                     ), new pix_icon('t/delete', get_string('delete')));
1207                 $edit = $this->output->action_icon(
1208                     new moodle_url('competency.php',
1209                         array(
1210                             'id' => $currentbadge->id,
1211                             'alignmentid' => $item->id,
1212                             'action' => 'edit'
1213                         )
1214                     ), new pix_icon('t/edit', get_string('edit')));
1215                 $actions = html_writer::tag('div', $edit . $delete, array('class' => 'badge-actions'));
1216                 array_push($row, $actions);
1217             }
1218             $table->data[] = $row;
1219         }
1220         $htmltable = html_writer::table($table);
1222         return $htmlpagingbar . $htmltable . $htmlpagingbar;
1223     }
1226 /**
1227  * An issued badges for badge.php page
1228  */
1229 class issued_badge implements renderable {
1230     /** @var issued badge */
1231     public $issued;
1233     /** @var badge recipient */
1234     public $recipient;
1236     /** @var badge class */
1237     public $badgeclass;
1239     /** @var badge visibility to others */
1240     public $visible = 0;
1242     /** @var badge class */
1243     public $badgeid = 0;
1245     /**
1246      * Initializes the badge to display
1247      *
1248      * @param string $hash Issued badge hash
1249      */
1250     public function __construct($hash) {
1251         global $DB;
1253         $assertion = new core_badges_assertion($hash);
1254         $this->issued = $assertion->get_badge_assertion();
1255         $this->badgeclass = $assertion->get_badge_class();
1257         $rec = $DB->get_record_sql('SELECT userid, visible, badgeid
1258                 FROM {badge_issued}
1259                 WHERE ' . $DB->sql_compare_text('uniquehash', 40) . ' = ' . $DB->sql_compare_text(':hash', 40),
1260                 array('hash' => $hash), IGNORE_MISSING);
1261         if ($rec) {
1262             // Get a recipient from database.
1263             $namefields = get_all_user_name_fields(true, 'u');
1264             $user = $DB->get_record_sql("SELECT u.id, $namefields, u.deleted, u.email
1265                         FROM {user} u WHERE u.id = :userid", array('userid' => $rec->userid));
1266             $this->recipient = $user;
1267             $this->visible = $rec->visible;
1268             $this->badgeid = $rec->badgeid;
1269         }
1270     }
1273 /**
1274  * An external badges for external.php page
1275  */
1276 class external_badge implements renderable {
1277     /** @var issued badge */
1278     public $issued;
1280     /** @var User ID */
1281     public $recipient;
1283     /** @var validation of external badge */
1284     public $valid = true;
1286     /**
1287      * Initializes the badge to display
1288      *
1289      * @param object $badge External badge information.
1290      * @param int $recipient User id.
1291      */
1292     public function __construct($badge, $recipient) {
1293         global $DB;
1294         // At this point a user has connected a backpack. So, we are going to get
1295         // their backpack email rather than their account email.
1296         $namefields = get_all_user_name_fields(true, 'u');
1297         $user = $DB->get_record_sql("SELECT {$namefields}, b.email
1298                     FROM {user} u INNER JOIN {badge_backpack} b ON u.id = b.userid
1299                     WHERE userid = :userid", array('userid' => $recipient), IGNORE_MISSING);
1301         $this->issued = $badge;
1302         $this->recipient = $user;
1304         // Check if recipient is valid.
1305         // There is no way to be 100% sure that a badge belongs to a user.
1306         // Backpack does not return any recipient information.
1307         // All we can do is compare that backpack email hashed using salt
1308         // provided in the assertion matches a badge recipient from the assertion.
1309         if ($user) {
1310             if (validate_email($badge->assertion->recipient) && $badge->assertion->recipient == $user->email) {
1311                 // If we have email, compare emails.
1312                 $this->valid = true;
1313             } else if ($badge->assertion->recipient == 'sha256$' . hash('sha256', $user->email)) {
1314                 // If recipient is hashed, but no salt, compare hashes without salt.
1315                 $this->valid = true;
1316             } else if ($badge->assertion->recipient == 'sha256$' . hash('sha256', $user->email . $badge->assertion->salt)) {
1317                 // If recipient is hashed, compare hashes.
1318                 $this->valid = true;
1319             } else {
1320                 // Otherwise, we cannot be sure that this user is a recipient.
1321                 $this->valid = false;
1322             }
1323         } else {
1324             $this->valid = false;
1325         }
1326     }
1329 /**
1330  * Badge recipients rendering class
1331  */
1332 class badge_recipients implements renderable {
1333     /** @var string how are the data sorted */
1334     public $sort = 'lastname';
1336     /** @var string how are the data sorted */
1337     public $dir = 'ASC';
1339     /** @var int page number to display */
1340     public $page = 0;
1342     /** @var int number of badge recipients to display per page */
1343     public $perpage = 30;
1345     /** @var int the total number or badge recipients to display */
1346     public $totalcount = null;
1348     /** @var array internal list of  badge recipients ids */
1349     public $userids = array();
1350     /**
1351      * Initializes the list of users to display
1352      *
1353      * @param array $holders List of badge holders
1354      */
1355     public function __construct($holders) {
1356         $this->userids = $holders;
1357     }
1360 /**
1361  * Collection of all badges for view.php page
1362  */
1363 class badge_collection implements renderable {
1365     /** @var string how are the data sorted */
1366     public $sort = 'name';
1368     /** @var string how are the data sorted */
1369     public $dir = 'ASC';
1371     /** @var int page number to display */
1372     public $page = 0;
1374     /** @var int number of badges to display per page */
1375     public $perpage = BADGE_PERPAGE;
1377     /** @var int the total number of badges to display */
1378     public $totalcount = null;
1380     /** @var array list of badges */
1381     public $badges = array();
1383     /**
1384      * Initializes the list of badges to display
1385      *
1386      * @param array $badges Badges to render
1387      */
1388     public function __construct($badges) {
1389         $this->badges = $badges;
1390     }
1393 /**
1394  * Collection of badges used at the index.php page
1395  */
1396 class badge_management extends badge_collection implements renderable {
1399 /**
1400  * Collection of user badges used at the mybadges.php page
1401  */
1402 class badge_user_collection extends badge_collection implements renderable {
1403     /** @var array backpack settings */
1404     public $backpack = null;
1406     /** @var string search */
1407     public $search = '';
1409     /**
1410      * Initializes user badge collection.
1411      *
1412      * @param array $badges Badges to render
1413      * @param int $userid Badges owner
1414      */
1415     public function __construct($badges, $userid) {
1416         global $CFG;
1417         parent::__construct($badges);
1419         if (!empty($CFG->badges_allowexternalbackpack)) {
1420             $this->backpack = get_backpack_settings($userid, true);
1421         }
1422     }
1425 /**
1426  * Collection of all related badges.
1427  *
1428  * @copyright  2018 Tung Thai
1429  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1430  * @author     Tung Thai <Tung.ThaiDuc@nashtechglobal.com>
1431  */
1432 class badge_related implements renderable {
1434     /** @var string how are the data sorted. */
1435     public $sort = 'name';
1437     /** @var string how are the data sorted. */
1438     public $dir = 'ASC';
1440     /** @var int page number to display. */
1441     public $page = 0;
1443     /** @var int number of badges to display per page. */
1444     public $perpage = BADGE_PERPAGE;
1446     /** @var int the total number of badges to display. */
1447     public $totalcount = null;
1449     /** @var int the current badge. */
1450     public $currentbadgeid = 0;
1452     /** @var array list of badges. */
1453     public $badges = array();
1455     /**
1456      * Initializes the list of badges to display.
1457      *
1458      * @param array $badges related badges to render.
1459      * @param int $currentbadgeid ID current badge.
1460      */
1461     public function __construct($badges, $currentbadgeid) {
1462         $this->badges = $badges;
1463         $this->currentbadgeid = $currentbadgeid;
1464     }
1467 /**
1468  * Collection of all competencies.
1469  *
1470  * @copyright  2018 Tung Thai
1471  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1472  * @author     Tung Thai <Tung.ThaiDuc@nashtechglobal.com>
1473  */
1474 class badge_competencies_alignment implements renderable
1476     /** @var string how are the data sorted. */
1477     public $sort = 'name';
1479     /** @var string how are the data sorted. */
1480     public $dir = 'ASC';
1482     /** @var int page number to display. */
1483     public $page = 0;
1485     /** @var int number of badges to display per page. */
1486     public $perpage = BADGE_PERPAGE;
1488     /** @var int the total number of badges to display. */
1489     public $totalcount = null;
1491     /** @var array list of badges. */
1492     public $alignments = array();
1494     /** @var array list of badges. */
1495     public $currentbadgeid = 0;
1497     /**
1498      * Initializes the list of competencies to display.
1499      *
1500      * @param array $alignments List competencies alignment to render.
1501      * @param int $currentbadgeid ID current badge.
1502      */
1503     public function __construct($alignments, $currentbadgeid) {
1504         $this->alignments = $alignments;
1505         $this->currentbadgeid = $currentbadgeid;
1506     }