MDL-63973 core_badges: fix related badges count in the badges tabs
[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             $sql = "SELECT COUNT(br.badgeid)
726                       FROM {badge_related} br
727                      WHERE (br.badgeid = :badgeid OR br.relatedbadgeid = :badgeid2)";
728             $related = $DB->count_records_sql($sql, ['badgeid' => $badgeid, 'badgeid2' => $badgeid]);
729             $row[] = new tabobject('brelated',
730                 new moodle_url('/badges/related.php', array('id' => $badgeid)),
731                 get_string('brelated', 'badges', $related)
732             );
733         }
735         if (has_capability('moodle/badges:configuredetails', $context)) {
736             $competencies = $DB->count_records_sql("SELECT COUNT(bc.id)
737                       FROM {badge_competencies} bc WHERE bc.badgeid = :badgeid", array('badgeid' => $badgeid));
738             $row[] = new tabobject('balignment',
739                 new moodle_url('/badges/competency.php', array('id' => $badgeid)),
740                 get_string('balignment', 'badges', $competencies)
741             );
742         }
744         echo $this->tabtree($row, $current);
745     }
747     /**
748      * Prints badge status box.
749      * @return Either the status box html as a string or null
750      */
751     public function print_badge_status_box(badge $badge) {
752         if (has_capability('moodle/badges:configurecriteria', $badge->get_context())) {
754             if (!$badge->has_criteria()) {
755                 $criteriaurl = new moodle_url('/badges/criteria.php', array('id' => $badge->id));
756                 $status = get_string('nocriteria', 'badges');
757                 if ($this->page->url != $criteriaurl) {
758                     $action = $this->output->single_button(
759                         $criteriaurl,
760                         get_string('addcriteria', 'badges'), 'POST', array('class' => 'activatebadge'));
761                 } else {
762                     $action = '';
763                 }
765                 $message = $status . $action;
766             } else {
767                 $status = get_string('statusmessage_' . $badge->status, 'badges');
768                 if ($badge->is_active()) {
769                     $action = $this->output->single_button(new moodle_url('/badges/action.php',
770                                 array('id' => $badge->id, 'lock' => 1, 'sesskey' => sesskey(),
771                                       'return' => $this->page->url->out_as_local_url(false))),
772                             get_string('deactivate', 'badges'), 'POST', array('class' => 'activatebadge'));
773                 } else {
774                     $action = $this->output->single_button(new moodle_url('/badges/action.php',
775                                 array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(),
776                                       'return' => $this->page->url->out_as_local_url(false))),
777                             get_string('activate', 'badges'), 'POST', array('class' => 'activatebadge'));
778                 }
780                 $message = $status . $this->output->help_icon('status', 'badges') . $action;
782             }
784             $style = $badge->is_active() ? 'generalbox statusbox active' : 'generalbox statusbox inactive';
785             return $this->output->box($message, $style);
786         }
788         return null;
789     }
791     /**
792      * Returns information about badge criteria in a list form.
793      *
794      * @param badge $badge Badge objects
795      * @param string $short Indicates whether to print full info about this badge
796      * @return string $output HTML string to output
797      */
798     public function print_badge_criteria(badge $badge, $short = '') {
799         $agg = $badge->get_aggregation_methods();
800         if (empty($badge->criteria)) {
801             return get_string('nocriteria', 'badges');
802         }
804         $overalldescr = '';
805         $overall = $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL];
806         if (!$short && !empty($overall->description)) {
807             $overalldescr = $this->output->box(
808                 format_text($overall->description, $overall->descriptionformat, array('context' => $badge->get_context())),
809                 'criteria-description'
810                 );
811         }
813         // Get the condition string.
814         if (count($badge->criteria) == 2) {
815             $condition = '';
816             if (!$short) {
817                 $condition = get_string('criteria_descr', 'badges');
818             }
819         } else {
820             $condition = get_string('criteria_descr_' . $short . BADGE_CRITERIA_TYPE_OVERALL, 'badges',
821                                       core_text::strtoupper($agg[$badge->get_aggregation_method()]));
822         }
824         unset($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]);
826         $items = array();
827         // If only one criterion left, make sure its description goe to the top.
828         if (count($badge->criteria) == 1) {
829             $c = reset($badge->criteria);
830             if (!$short && !empty($c->description)) {
831                 $overalldescr = $this->output->box(
832                     format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
833                     'criteria-description'
834                     );
835             }
836             if (count($c->params) == 1) {
837                 $items[] = get_string('criteria_descr_single_' . $short . $c->criteriatype , 'badges') .
838                            $c->get_details($short);
839             } else {
840                 $items[] = get_string('criteria_descr_' . $short . $c->criteriatype, 'badges',
841                         core_text::strtoupper($agg[$badge->get_aggregation_method($c->criteriatype)])) .
842                         $c->get_details($short);
843             }
844         } else {
845             foreach ($badge->criteria as $type => $c) {
846                 $criteriadescr = '';
847                 if (!$short && !empty($c->description)) {
848                     $criteriadescr = $this->output->box(
849                         format_text($c->description, $c->descriptionformat, array('context' => $badge->get_context())),
850                         'criteria-description'
851                         );
852                 }
853                 if (count($c->params) == 1) {
854                     $items[] = get_string('criteria_descr_single_' . $short . $type , 'badges') .
855                                $c->get_details($short) . $criteriadescr;
856                 } else {
857                     $items[] = get_string('criteria_descr_' . $short . $type , 'badges',
858                             core_text::strtoupper($agg[$badge->get_aggregation_method($type)])) .
859                             $c->get_details($short) .
860                             $criteriadescr;
861                 }
862             }
863         }
865         return $overalldescr . $condition . html_writer::alist($items, array(), 'ul');;
866     }
868     // Prints criteria actions for badge editing.
869     public function print_criteria_actions(badge $badge) {
870         $output = '';
871         if (!$badge->is_active() && !$badge->is_locked()) {
872             $accepted = $badge->get_accepted_criteria();
873             $potential = array_diff($accepted, array_keys($badge->criteria));
875             if (!empty($potential)) {
876                 foreach ($potential as $p) {
877                     if ($p != 0) {
878                         $select[$p] = get_string('criteria_' . $p, 'badges');
879                     }
880                 }
881                 $output .= $this->output->single_select(
882                     new moodle_url('/badges/criteria_settings.php', array('badgeid' => $badge->id, 'add' => true)),
883                     'type',
884                     $select,
885                     '',
886                     array('' => 'choosedots'),
887                     null,
888                     array('label' => get_string('addbadgecriteria', 'badges'))
889                 );
890             } else {
891                 $output .= $this->output->box(get_string('nothingtoadd', 'badges'), 'clearfix');
892             }
893         }
895         return $output;
896     }
898     // Renders a table with users who have earned the badge.
899     // Based on stamps collection plugin.
900     protected function render_badge_recipients(badge_recipients $recipients) {
901         $paging = new paging_bar($recipients->totalcount, $recipients->page, $recipients->perpage, $this->page->url, 'page');
902         $htmlpagingbar = $this->render($paging);
903         $table = new html_table();
904         $table->attributes['class'] = 'generaltable boxaligncenter boxwidthwide';
906         $sortbyfirstname = $this->helper_sortable_heading(get_string('firstname'),
907                 'firstname', $recipients->sort, $recipients->dir);
908         $sortbylastname = $this->helper_sortable_heading(get_string('lastname'),
909                 'lastname', $recipients->sort, $recipients->dir);
910         if ($this->helper_fullname_format() == 'lf') {
911             $sortbyname = $sortbylastname . ' / ' . $sortbyfirstname;
912         } else {
913             $sortbyname = $sortbyfirstname . ' / ' . $sortbylastname;
914         }
916         $sortbydate = $this->helper_sortable_heading(get_string('dateawarded', 'badges'),
917                 'dateissued', $recipients->sort, $recipients->dir);
919         $table->head = array($sortbyname, $sortbydate, '');
921         foreach ($recipients->userids as $holder) {
922             $fullname = fullname($holder);
923             $fullname = html_writer::link(
924                             new moodle_url('/user/profile.php', array('id' => $holder->userid)),
925                             $fullname
926                         );
927             $awarded  = userdate($holder->dateissued);
928             $badgeurl = html_writer::link(
929                             new moodle_url('/badges/badge.php', array('hash' => $holder->uniquehash)),
930                             get_string('viewbadge', 'badges')
931                         );
933             $row = array($fullname, $awarded, $badgeurl);
934             $table->data[] = $row;
935         }
937         $htmltable = html_writer::table($table);
939         return $htmlpagingbar . $htmltable . $htmlpagingbar;
940     }
942     ////////////////////////////////////////////////////////////////////////////
943     // Helper methods
944     // Reused from stamps collection plugin
945     ////////////////////////////////////////////////////////////////////////////
947     /**
948      * Renders a text with icons to sort by the given column
949      *
950      * This is intended for table headings.
951      *
952      * @param string $text    The heading text
953      * @param string $sortid  The column id used for sorting
954      * @param string $sortby  Currently sorted by (column id)
955      * @param string $sorthow Currently sorted how (ASC|DESC)
956      *
957      * @return string
958      */
959     protected function helper_sortable_heading($text, $sortid = null, $sortby = null, $sorthow = null) {
960         $out = html_writer::tag('span', $text, array('class' => 'text'));
962         if (!is_null($sortid)) {
963             if ($sortby !== $sortid || $sorthow !== 'ASC') {
964                 $url = new moodle_url($this->page->url);
965                 $url->params(array('sort' => $sortid, 'dir' => 'ASC'));
966                 $out .= $this->output->action_icon($url,
967                         new pix_icon('t/sort_asc', get_string('sortbyx', 'core', s($text)), null, array('class' => 'iconsort')));
968             }
969             if ($sortby !== $sortid || $sorthow !== 'DESC') {
970                 $url = new moodle_url($this->page->url);
971                 $url->params(array('sort' => $sortid, 'dir' => 'DESC'));
972                 $out .= $this->output->action_icon($url,
973                         new pix_icon('t/sort_desc', get_string('sortbyxreverse', 'core', s($text)), null, array('class' => 'iconsort')));
974             }
975         }
976         return $out;
977     }
978     /**
979      * Tries to guess the fullname format set at the site
980      *
981      * @return string fl|lf
982      */
983     protected function helper_fullname_format() {
984         $fake = new stdClass();
985         $fake->lastname = 'LLLL';
986         $fake->firstname = 'FFFF';
987         $fullname = get_string('fullnamedisplay', '', $fake);
988         if (strpos($fullname, 'LLLL') < strpos($fullname, 'FFFF')) {
989             return 'lf';
990         } else {
991             return 'fl';
992         }
993     }
994     /**
995      * Renders a search form
996      *
997      * @param string $search Search string
998      * @return string HTML
999      */
1000     protected function helper_search_form($search) {
1001         global $CFG;
1002         require_once($CFG->libdir . '/formslib.php');
1004         $mform = new MoodleQuickForm('searchform', 'POST', $this->page->url);
1006         $mform->addElement('hidden', 'sesskey', sesskey());
1008         $el[] = $mform->createElement('text', 'search', get_string('search'), array('size' => 20));
1009         $mform->setDefault('search', $search);
1010         $el[] = $mform->createElement('submit', 'submitsearch', get_string('search'));
1011         $el[] = $mform->createElement('submit', 'clearsearch', get_string('clear'));
1012         $mform->addGroup($el, 'searchgroup', get_string('searchname', 'badges'), ' ', false);
1014         ob_start();
1015         $mform->display();
1016         $out = ob_get_clean();
1018         return $out;
1019     }
1021     /**
1022      * Renders a definition list
1023      *
1024      * @param array $items the list of items to define
1025      * @param array
1026      */
1027     protected function definition_list(array $items, array $attributes = array()) {
1028         $output = html_writer::start_tag('dl', $attributes);
1029         foreach ($items as $label => $value) {
1030             $output .= html_writer::tag('dt', $label);
1031             $output .= html_writer::tag('dd', $value);
1032         }
1033         $output .= html_writer::end_tag('dl');
1034         return $output;
1035     }
1037     /**
1038      * Outputs list en badges.
1039      *
1040      * @param badge $badge Badge object.
1041      * @return string $output content endorsement to output.
1042      */
1043     protected function print_badge_endorsement(badge $badge) {
1044         $output = '';
1045         $endorsement = $badge->get_endorsement();
1046         $dl = array();
1047         $output .= $this->heading(get_string('endorsement', 'badges'), 3);
1048         if (!empty($endorsement)) {
1049             $dl[get_string('issuername', 'badges')] = $endorsement->issuername;
1050             $dl[get_string('issueremail', 'badges')] =
1051                 html_writer::tag('a', $endorsement->issueremail, array('href' => 'mailto:' . $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')] = userdate($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     }