MDL-69002 core_badges: remove site backpack verification from settings
[moodle.git] / lib / badgeslib.php
CommitLineData
27806552
YB
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/>.
16
17/**
18 * Contains classes, functions and constants used in badges.
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 */
26
27defined('MOODLE_INTERNAL') || die();
28
29/* Include required award criteria library. */
30require_once($CFG->dirroot . '/badges/criteria/award_criteria.php');
31
32/*
33 * Number of records per page.
34*/
35define('BADGE_PERPAGE', 50);
36
37/*
38 * Badge award criteria aggregation method.
39 */
40define('BADGE_CRITERIA_AGGREGATION_ALL', 1);
41
42/*
43 * Badge award criteria aggregation method.
44 */
45define('BADGE_CRITERIA_AGGREGATION_ANY', 2);
46
47/*
48 * Inactive badge means that this badge cannot be earned and has not been awarded
49 * yet. Its award criteria can be changed.
50 */
51define('BADGE_STATUS_INACTIVE', 0);
52
53/*
54 * Active badge means that this badge can we earned, but it has not been awarded
55 * yet. Can be deactivated for the purpose of changing its criteria.
56 */
57define('BADGE_STATUS_ACTIVE', 1);
58
59/*
60 * Inactive badge can no longer be earned, but it has been awarded in the past and
61 * therefore its criteria cannot be changed.
62 */
63define('BADGE_STATUS_INACTIVE_LOCKED', 2);
64
65/*
66 * Active badge means that it can be earned and has already been awarded to users.
67 * Its criteria cannot be changed any more.
68 */
69define('BADGE_STATUS_ACTIVE_LOCKED', 3);
70
71/*
72 * Archived badge is considered deleted and can no longer be earned and is not
73 * displayed in the list of all badges.
74 */
75define('BADGE_STATUS_ARCHIVED', 4);
76
77/*
78 * Badge type for site badges.
79 */
80define('BADGE_TYPE_SITE', 1);
81
82/*
83 * Badge type for course badges.
84 */
85define('BADGE_TYPE_COURSE', 2);
86
87/*
88 * Badge messaging schedule options.
89 */
90define('BADGE_MESSAGE_NEVER', 0);
91define('BADGE_MESSAGE_ALWAYS', 1);
92define('BADGE_MESSAGE_DAILY', 2);
93define('BADGE_MESSAGE_WEEKLY', 3);
94define('BADGE_MESSAGE_MONTHLY', 4);
95
343534a8 96/*
aae219ac 97 * URL of backpack. Custom ones can be added.
343534a8 98 */
aae219ac
DW
99define('BADGRIO_BACKPACKAPIURL', 'https://api.badgr.io/v2');
100define('BADGRIO_BACKPACKWEBURL', 'https://badgr.io');
343534a8 101
7444ba74
DW
102/*
103 * @deprecated since 3.7. Use the urls in the badge_external_backpack table instead.
104 */
105define('BADGE_BACKPACKURL', 'https://backpack.openbadges.org');
106
f958f5c1
SA
107/*
108 * @deprecated since 3.9 (MDL-66357).
109 */
110define('BADGE_BACKPACKAPIURL', 'https://backpack.openbadges.org');
111define('BADGE_BACKPACKWEBURL', 'https://backpack.openbadges.org');
112
5a1ea828
SA
113/*
114 * Open Badges specifications.
115 */
116define('OPEN_BADGES_V1', 1);
117define('OPEN_BADGES_V2', 2);
15a00bea 118define('OPEN_BADGES_V2P1', 2.1);
5a1ea828 119
d363a5c2
TT
120/*
121 * Only use for Open Badges 2.0 specification
122 */
123define('OPEN_BADGES_V2_CONTEXT', 'https://w3id.org/openbadges/v2');
124define('OPEN_BADGES_V2_TYPE_ASSERTION', 'Assertion');
125define('OPEN_BADGES_V2_TYPE_BADGE', 'BadgeClass');
126define('OPEN_BADGES_V2_TYPE_ISSUER', 'Issuer');
127define('OPEN_BADGES_V2_TYPE_ENDORSEMENT', 'Endorsement');
128define('OPEN_BADGES_V2_TYPE_AUTHOR', 'Author');
129
aae219ac
DW
130// Global badge class has been moved to the component namespace.
131class_alias('\core_badges\badge', 'badge');
27806552
YB
132
133/**
134 * Sends notifications to users about awarded badges.
135 *
136 * @param badge $badge Badge that was issued
137 * @param int $userid Recipient ID
138 * @param string $issued Unique hash of an issued badge
139 * @param string $filepathhash File path hash of an issued badge for attachments
140 */
141function badges_notify_badge_award(badge $badge, $userid, $issued, $filepathhash) {
142 global $CFG, $DB;
143
144 $admin = get_admin();
145 $userfrom = new stdClass();
146 $userfrom->id = $admin->id;
147 $userfrom->email = !empty($CFG->badges_defaultissuercontact) ? $CFG->badges_defaultissuercontact : $admin->email;
a327f25e
AG
148 foreach (get_all_user_name_fields() as $addname) {
149 $userfrom->$addname = !empty($CFG->badges_defaultissuername) ? '' : $admin->$addname;
150 }
27806552 151 $userfrom->firstname = !empty($CFG->badges_defaultissuername) ? $CFG->badges_defaultissuername : $admin->firstname;
27806552
YB
152 $userfrom->maildisplay = true;
153
154 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $issued)), $badge->name);
155 $userto = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
156
157 $params = new stdClass();
158 $params->badgename = $badge->name;
159 $params->username = fullname($userto);
160 $params->badgelink = $issuedlink;
161 $message = badge_message_from_template($badge->message, $params);
1f258cd8 162 $plaintext = html_to_text($message);
27806552 163
f5d17c14 164 // Notify recipient.
cc350fd9 165 $eventdata = new \core\message\message();
f593e827 166 $eventdata->courseid = is_null($badge->courseid) ? SITEID : $badge->courseid; // Profile/site come with no courseid.
f5d17c14
YB
167 $eventdata->component = 'moodle';
168 $eventdata->name = 'badgerecipientnotice';
169 $eventdata->userfrom = $userfrom;
170 $eventdata->userto = $userto;
171 $eventdata->notification = 1;
172 $eventdata->subject = $badge->messagesubject;
173 $eventdata->fullmessage = $plaintext;
1f258cd8 174 $eventdata->fullmessageformat = FORMAT_HTML;
f5d17c14 175 $eventdata->fullmessagehtml = $message;
1f258cd8 176 $eventdata->smallmessage = '';
36fa0ec9
JL
177 $eventdata->customdata = [
178 'notificationiconurl' => moodle_url::make_pluginfile_url(
179 $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
180 'hash' => $issued,
181 ];
f5d17c14
YB
182
183 // Attach badge image if possible.
184 if (!empty($CFG->allowattachments) && $badge->attachment && is_string($filepathhash)) {
27806552
YB
185 $fs = get_file_storage();
186 $file = $fs->get_file_by_hash($filepathhash);
f5d17c14
YB
187 $eventdata->attachment = $file;
188 $eventdata->attachname = str_replace(' ', '_', $badge->name) . ".png";
189
190 message_send($eventdata);
27806552 191 } else {
f5d17c14 192 message_send($eventdata);
27806552
YB
193 }
194
195 // Notify badge creator about the award if they receive notifications every time.
196 if ($badge->notification == 1) {
f5d17c14
YB
197 $userfrom = core_user::get_noreply_user();
198 $userfrom->maildisplay = true;
199
27806552
YB
200 $creator = $DB->get_record('user', array('id' => $badge->usercreated), '*', MUST_EXIST);
201 $a = new stdClass();
202 $a->user = fullname($userto);
203 $a->link = $issuedlink;
204 $creatormessage = get_string('creatorbody', 'badges', $a);
205 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
206
cc350fd9
AD
207 $eventdata = new \core\message\message();
208 $eventdata->courseid = $badge->courseid;
27806552 209 $eventdata->component = 'moodle';
f5d17c14 210 $eventdata->name = 'badgecreatornotice';
27806552
YB
211 $eventdata->userfrom = $userfrom;
212 $eventdata->userto = $creator;
213 $eventdata->notification = 1;
214 $eventdata->subject = $creatorsubject;
1f258cd8
YB
215 $eventdata->fullmessage = html_to_text($creatormessage);
216 $eventdata->fullmessageformat = FORMAT_HTML;
f5d17c14 217 $eventdata->fullmessagehtml = $creatormessage;
1f258cd8 218 $eventdata->smallmessage = '';
36fa0ec9
JL
219 $eventdata->customdata = [
220 'notificationiconurl' => moodle_url::make_pluginfile_url(
221 $badge->get_context()->id, 'badges', 'badgeimage', $badge->id, '/', 'f1')->out(),
222 'hash' => $issued,
223 ];
27806552
YB
224
225 message_send($eventdata);
226 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $badge->id, 'userid' => $userid));
227 }
228}
229
230/**
231 * Caclulates date for the next message digest to badge creators.
232 *
233 * @param in $schedule Type of message schedule BADGE_MESSAGE_DAILY|BADGE_MESSAGE_WEEKLY|BADGE_MESSAGE_MONTHLY.
234 * @return int Timestamp for next cron
235 */
236function badges_calculate_message_schedule($schedule) {
237 $nextcron = 0;
238
239 switch ($schedule) {
240 case BADGE_MESSAGE_DAILY:
b0213770
DW
241 $tomorrow = new DateTime("1 day", core_date::get_server_timezone_object());
242 $nextcron = $tomorrow->getTimestamp();
27806552
YB
243 break;
244 case BADGE_MESSAGE_WEEKLY:
b0213770
DW
245 $nextweek = new DateTime("1 week", core_date::get_server_timezone_object());
246 $nextcron = $nextweek->getTimestamp();
27806552
YB
247 break;
248 case BADGE_MESSAGE_MONTHLY:
b0213770
DW
249 $nextmonth = new DateTime("1 month", core_date::get_server_timezone_object());
250 $nextcron = $nextmonth->getTimestamp();
27806552
YB
251 break;
252 }
253
254 return $nextcron;
255}
256
257/**
258 * Replaces variables in a message template and returns text ready to be emailed to a user.
259 *
260 * @param string $message Message body.
261 * @return string Message with replaced values
262 */
263function badge_message_from_template($message, $params) {
264 $msg = $message;
265 foreach ($params as $key => $value) {
266 $msg = str_replace("%$key%", $value, $msg);
267 }
268
269 return $msg;
270}
271
272/**
273 * Get all badges.
274 *
275 * @param int Type of badges to return
276 * @param int Course ID for course badges
277 * @param string $sort An SQL field to sort by
278 * @param string $dir The sort direction ASC|DESC
279 * @param int $page The page or records to return
280 * @param int $perpage The number of records to return per page
281 * @param int $user User specific search
282 * @return array $badge Array of records matching criteria
283 */
284function badges_get_badges($type, $courseid = 0, $sort = '', $dir = '', $page = 0, $perpage = BADGE_PERPAGE, $user = 0) {
285 global $DB;
286 $records = array();
287 $params = array();
288 $where = "b.status != :deleted AND b.type = :type ";
289 $params['deleted'] = BADGE_STATUS_ARCHIVED;
290
291 $userfields = array('b.id, b.name, b.status');
292 $usersql = "";
293 if ($user != 0) {
294 $userfields[] = 'bi.dateissued';
295 $userfields[] = 'bi.uniquehash';
296 $usersql = " LEFT JOIN {badge_issued} bi ON b.id = bi.badgeid AND bi.userid = :userid ";
297 $params['userid'] = $user;
298 $where .= " AND (b.status = 1 OR b.status = 3) ";
299 }
300 $fields = implode(', ', $userfields);
301
302 if ($courseid != 0 ) {
303 $where .= "AND b.courseid = :courseid ";
304 $params['courseid'] = $courseid;
305 }
306
307 $sorting = (($sort != '' && $dir != '') ? 'ORDER BY ' . $sort . ' ' . $dir : '');
308 $params['type'] = $type;
309
310 $sql = "SELECT $fields FROM {badge} b $usersql WHERE $where $sorting";
311 $records = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
312
313 $badges = array();
314 foreach ($records as $r) {
315 $badge = new badge($r->id);
316 $badges[$r->id] = $badge;
317 if ($user != 0) {
318 $badges[$r->id]->dateissued = $r->dateissued;
319 $badges[$r->id]->uniquehash = $r->uniquehash;
320 } else {
7f964cfd
YB
321 $badges[$r->id]->awards = $DB->count_records_sql('SELECT COUNT(b.userid)
322 FROM {badge_issued} b INNER JOIN {user} u ON b.userid = u.id
323 WHERE b.badgeid = :badgeid AND u.deleted = 0', array('badgeid' => $badge->id));
27806552
YB
324 $badges[$r->id]->statstring = $badge->get_status_name();
325 }
326 }
327 return $badges;
328}
329
330/**
331 * Get badges for a specific user.
332 *
333 * @param int $userid User ID
334 * @param int $courseid Badges earned by a user in a specific course
335 * @param int $page The page or records to return
336 * @param int $perpage The number of records to return per page
337 * @param string $search A simple string to search for
338 * @param bool $onlypublic Return only public badges
339 * @return array of badges ordered by decreasing date of issue
340 */
341function badges_get_user_badges($userid, $courseid = 0, $page = 0, $perpage = 0, $search = '', $onlypublic = false) {
b4846b88 342 global $CFG, $DB;
27806552 343
d237385e
SH
344 $params = array(
345 'userid' => $userid
346 );
27806552
YB
347 $sql = 'SELECT
348 bi.uniquehash,
349 bi.dateissued,
350 bi.dateexpire,
351 bi.id as issuedid,
352 bi.visible,
353 u.email,
354 b.*
355 FROM
356 {badge} b,
357 {badge_issued} bi,
358 {user} u
359 WHERE b.id = bi.badgeid
360 AND u.id = bi.userid
d237385e 361 AND bi.userid = :userid';
27806552
YB
362
363 if (!empty($search)) {
d237385e
SH
364 $sql .= ' AND (' . $DB->sql_like('b.name', ':search', false) . ') ';
365 $params['search'] = '%'.$DB->sql_like_escape($search).'%';
27806552
YB
366 }
367 if ($onlypublic) {
368 $sql .= ' AND (bi.visible = 1) ';
369 }
370
b4846b88
AO
371 if (empty($CFG->badges_allowcoursebadges)) {
372 $sql .= ' AND b.courseid IS NULL';
373 } else if ($courseid != 0) {
d237385e
SH
374 $sql .= ' AND (b.courseid = :courseid) ';
375 $params['courseid'] = $courseid;
27806552
YB
376 }
377 $sql .= ' ORDER BY bi.dateissued DESC';
378 $badges = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
379
380 return $badges;
381}
382
27806552
YB
383/**
384 * Extends the course administration navigation with the Badges page
385 *
386 * @param navigation_node $coursenode
387 * @param object $course
388 */
389function badges_add_course_navigation(navigation_node $coursenode, stdClass $course) {
390 global $CFG, $SITE;
391
392 $coursecontext = context_course::instance($course->id);
393 $isfrontpage = (!$coursecontext || $course->id == $SITE->id);
a72c2cd6
YB
394 $canmanage = has_any_capability(array('moodle/badges:viewawarded',
395 'moodle/badges:createbadge',
396 'moodle/badges:awardbadge',
397 'moodle/badges:configurecriteria',
398 'moodle/badges:configuremessages',
399 'moodle/badges:configuredetails',
400 'moodle/badges:deletebadge'), $coursecontext);
27806552 401
a72c2cd6
YB
402 if (!empty($CFG->enablebadges) && !empty($CFG->badges_allowcoursebadges) && !$isfrontpage && $canmanage) {
403 $coursenode->add(get_string('coursebadges', 'badges'), null,
404 navigation_node::TYPE_CONTAINER, null, 'coursebadges',
405 new pix_icon('i/badge', get_string('coursebadges', 'badges')));
27806552 406
a72c2cd6 407 $url = new moodle_url('/badges/index.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
27806552 408
a72c2cd6
YB
409 $coursenode->get('coursebadges')->add(get_string('managebadges', 'badges'), $url,
410 navigation_node::TYPE_SETTING, null, 'coursebadges');
19a9f2ea 411
a72c2cd6
YB
412 if (has_capability('moodle/badges:createbadge', $coursecontext)) {
413 $url = new moodle_url('/badges/newbadge.php', array('type' => BADGE_TYPE_COURSE, 'id' => $course->id));
19a9f2ea 414
a72c2cd6
YB
415 $coursenode->get('coursebadges')->add(get_string('newbadge', 'badges'), $url,
416 navigation_node::TYPE_SETTING, null, 'newbadge');
27806552
YB
417 }
418 }
419}
420
27806552
YB
421/**
422 * Triggered when badge is manually awarded.
423 *
424 * @param object $data
425 * @return boolean
426 */
427function badges_award_handle_manual_criteria_review(stdClass $data) {
428 $criteria = $data->crit;
429 $userid = $data->userid;
430 $badge = new badge($criteria->badgeid);
431
432 if (!$badge->is_active() || $badge->is_issued($userid)) {
433 return true;
434 }
435
436 if ($criteria->review($userid)) {
437 $criteria->mark_complete($userid);
438
439 if ($badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->review($userid)) {
440 $badge->criteria[BADGE_CRITERIA_TYPE_OVERALL]->mark_complete($userid);
441 $badge->issue($userid);
442 }
443 }
444
445 return true;
446}
447
448/**
449 * Process badge image from form data
450 *
451 * @param badge $badge Badge object
452 * @param string $iconfile Original file
453 */
454function badges_process_badge_image(badge $badge, $iconfile) {
455 global $CFG, $USER;
456 require_once($CFG->libdir. '/gdlib.php');
457
458 if (!empty($CFG->gdversion)) {
cda2a827 459 process_new_icon($badge->get_context(), 'badges', 'badgeimage', $badge->id, $iconfile, true);
27806552
YB
460 @unlink($iconfile);
461
462 // Clean up file draft area after badge image has been saved.
463 $context = context_user::instance($USER->id, MUST_EXIST);
464 $fs = get_file_storage();
465 $fs->delete_area_files($context->id, 'user', 'draft');
466 }
467}
468
469/**
470 * Print badge image.
471 *
472 * @param badge $badge Badge object
473 * @param stdClass $context
474 * @param string $size
475 */
476function print_badge_image(badge $badge, stdClass $context, $size = 'small') {
477 $fsize = ($size == 'small') ? 'f2' : 'f1';
478
479 $imageurl = moodle_url::make_pluginfile_url($context->id, 'badges', 'badgeimage', $badge->id, '/', $fsize, false);
480 // Appending a random parameter to image link to forse browser reload the image.
b143259e
YB
481 $imageurl->param('refresh', rand(1, 10000));
482 $attributes = array('src' => $imageurl, 'alt' => s($badge->name), 'class' => 'activatebadge');
27806552
YB
483
484 return html_writer::empty_tag('img', $attributes);
485}
486
487/**
488 * Bake issued badge.
489 *
490 * @param string $hash Unique hash of an issued badge.
491 * @param int $badgeid ID of the original badge.
492 * @param int $userid ID of badge recipient (optional).
493 * @param boolean $pathhash Return file pathhash instead of image url (optional).
494 * @return string|url Returns either new file path hash or new file URL
495 */
496function badges_bake($hash, $badgeid, $userid = 0, $pathhash = false) {
497 global $CFG, $USER;
1fcf0ca8 498 require_once(__DIR__ . '/../badges/lib/bakerlib.php');
27806552
YB
499
500 $badge = new badge($badgeid);
501 $badge_context = $badge->get_context();
502 $userid = ($userid) ? $userid : $USER->id;
503 $user_context = context_user::instance($userid);
504
505 $fs = get_file_storage();
506 if (!$fs->file_exists($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png')) {
49b464f8 507 if ($file = $fs->get_file($badge_context->id, 'badges', 'badgeimage', $badge->id, '/', 'f3.png')) {
27806552
YB
508 $contents = $file->get_content();
509
510 $filehandler = new PNG_MetaDataHandler($contents);
f8d9b1eb
SA
511 // For now, the site backpack OB version will be used as default.
512 $obversion = badges_open_badges_backpack_api();
513 $assertion = new core_badges_assertion($hash, $obversion);
514 $assertionjson = json_encode($assertion->get_badge_assertion());
515 if ($filehandler->check_chunks("iTXt", "openbadges")) {
516 // Add assertion URL iTXt chunk.
517 $newcontents = $filehandler->add_chunks("iTXt", "openbadges", $assertionjson);
27806552
YB
518 $fileinfo = array(
519 'contextid' => $user_context->id,
520 'component' => 'badges',
521 'filearea' => 'userbadge',
522 'itemid' => $badge->id,
523 'filepath' => '/',
524 'filename' => $hash . '.png',
525 );
526
527 // Create a file with added contents.
528 $newfile = $fs->create_file_from_string($fileinfo, $newcontents);
529 if ($pathhash) {
530 return $newfile->get_pathnamehash();
531 }
532 }
533 } else {
be2b37cf
Y
534 debugging('Error baking badge image!', DEBUG_DEVELOPER);
535 return;
27806552
YB
536 }
537 }
538
f5d17c14
YB
539 // If file exists and we just need its path hash, return it.
540 if ($pathhash) {
541 $file = $fs->get_file($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash . '.png');
542 return $file->get_pathnamehash();
543 }
544
27806552
YB
545 $fileurl = moodle_url::make_pluginfile_url($user_context->id, 'badges', 'userbadge', $badge->id, '/', $hash, true);
546 return $fileurl;
547}
548
549/**
e2805314 550 * Returns external backpack settings and badges from this backpack.
27806552 551 *
2d3c0fae
YB
552 * This function first checks if badges for the user are cached and
553 * tries to retrieve them from the cache. Otherwise, badges are obtained
554 * through curl request to the backpack.
555 *
27806552 556 * @param int $userid Backpack user ID.
2d3c0fae 557 * @param boolean $refresh Refresh badges collection in cache.
27806552
YB
558 * @return null|object Returns null is there is no backpack or object with backpack settings.
559 */
2d3c0fae 560function get_backpack_settings($userid, $refresh = false) {
27806552 561 global $DB;
27806552 562
2d3c0fae
YB
563 // Try to get badges from cache first.
564 $badgescache = cache::make('core', 'externalbadges');
565 $out = $badgescache->get($userid);
566 if ($out !== false && !$refresh) {
567 return $out;
568 }
569 // Get badges through curl request to the backpack.
e2805314 570 $record = $DB->get_record('badge_backpack', array('userid' => $userid));
27806552 571 if ($record) {
7444ba74 572 $sitebackpack = badges_get_site_backpack($record->externalbackpackid);
aae219ac 573 $backpack = new \core_badges\backpack_api($sitebackpack, $record);
27806552 574 $out = new stdClass();
aae219ac 575 $out->backpackid = $sitebackpack->id;
e2805314
YB
576
577 if ($collections = $DB->get_records('badge_external', array('backpackid' => $record->id))) {
578 $out->totalcollections = count($collections);
579 $out->totalbadges = 0;
580 $out->badges = array();
581 foreach ($collections as $collection) {
aae219ac
DW
582 $badges = $backpack->get_badges($collection, true);
583 if (!empty($badges)) {
584 $out->badges = array_merge($out->badges, $badges);
585 $out->totalbadges += count($badges);
e2805314
YB
586 } else {
587 $out->badges = array_merge($out->badges, array());
588 }
589 }
590 } else {
591 $out->totalbadges = 0;
592 $out->totalcollections = 0;
593 }
594
2d3c0fae 595 $badgescache->set($userid, $out);
27806552
YB
596 return $out;
597 }
598
599 return null;
600}
601
602/**
603 * Download all user badges in zip archive.
604 *
605 * @param int $userid ID of badge owner.
606 */
607function badges_download($userid) {
608 global $CFG, $DB;
609 $context = context_user::instance($userid);
610 $records = $DB->get_records('badge_issued', array('userid' => $userid));
611
612 // Get list of files to download.
613 $fs = get_file_storage();
614 $filelist = array();
615 foreach ($records as $issued) {
616 $badge = new badge($issued->badgeid);
617 // Need to make image name user-readable and unique using filename safe characters.
618 $name = $badge->name . ' ' . userdate($issued->dateissued, '%d %b %Y') . ' ' . hash('crc32', $badge->id);
619 $name = str_replace(' ', '_', $name);
d77a6026 620 $name = clean_param($name, PARAM_FILE);
27806552
YB
621 if ($file = $fs->get_file($context->id, 'badges', 'userbadge', $issued->badgeid, '/', $issued->uniquehash . '.png')) {
622 $filelist[$name . '.png'] = $file;
623 }
624 }
625
626 // Zip files and sent them to a user.
627 $tempzip = tempnam($CFG->tempdir.'/', 'mybadges');
628 $zipper = new zip_packer();
629 if ($zipper->archive_to_pathname($filelist, $tempzip)) {
630 send_temp_file($tempzip, 'badges.zip');
631 } else {
62fef3cf
YB
632 debugging("Problems with archiving the files.", DEBUG_DEVELOPER);
633 die;
27806552
YB
634 }
635}
636
27806552
YB
637/**
638 * Checks if badges can be pushed to external backpack.
639 *
640 * @return string Code of backpack accessibility status.
641 */
642function badges_check_backpack_accessibility() {
389aad6e
AN
643 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
644 // For behat sites, do not poll the remote badge site.
645 // Behat sites should not be available, but we should pretend as though they are.
646 return 'available';
647 }
648
aae219ac
DW
649 if (badges_open_badges_backpack_api() == OPEN_BADGES_V2) {
650 return 'available';
651 }
652
27806552
YB
653 global $CFG;
654 include_once $CFG->libdir . '/filelib.php';
655
656 // Using fake assertion url to check whether backpack can access the web site.
657 $fakeassertion = new moodle_url('/badges/assertion.php', array('b' => 'abcd1234567890'));
658
343534a8 659 // Curl request to backpack baker.
27806552
YB
660 $curl = new curl();
661 $options = array(
662 'FRESH_CONNECT' => true,
663 'RETURNTRANSFER' => true,
27806552 664 'HEADER' => 0,
dd4a197e 665 'CONNECTTIMEOUT' => 2,
27806552 666 );
7444ba74 667 // BADGE_BACKPACKURL and the "baker" API is deprecated and should never be used in future.
4d0ebdeb 668 $location = BADGE_BACKPACKURL . '/baker';
27806552
YB
669 $out = $curl->get($location, array('assertion' => $fakeassertion->out(false)), $options);
670
671 $data = json_decode($out);
672 if (!empty($curl->error)) {
673 return 'curl-request-timeout';
674 } else {
675 if (isset($data->code) && $data->code == 'http-unreachable') {
676 return 'http-unreachable';
677 } else {
678 return 'available';
679 }
680 }
681
682 return false;
683}
e2805314
YB
684
685/**
686 * Checks if user has external backpack connected.
687 *
688 * @param int $userid ID of a user.
689 * @return bool True|False whether backpack connection exists.
690 */
691function badges_user_has_backpack($userid) {
692 global $DB;
693 return $DB->record_exists('badge_backpack', array('userid' => $userid));
694}
7deff81f
YB
695
696/**
697 * Handles what happens to the course badges when a course is deleted.
698 *
699 * @param int $courseid course ID.
700 * @return void.
701 */
702function badges_handle_course_deletion($courseid) {
703 global $CFG, $DB;
704 include_once $CFG->libdir . '/filelib.php';
705
706 $systemcontext = context_system::instance();
707 $coursecontext = context_course::instance($courseid);
708 $fs = get_file_storage();
709
710 // Move badges images to the system context.
711 $fs->move_area_files_to_new_context($coursecontext->id, $systemcontext->id, 'badges', 'badgeimage');
712
713 // Get all course badges.
714 $badges = $DB->get_records('badge', array('type' => BADGE_TYPE_COURSE, 'courseid' => $courseid));
715 foreach ($badges as $badge) {
716 // Archive badges in this course.
717 $toupdate = new stdClass();
718 $toupdate->id = $badge->id;
719 $toupdate->type = BADGE_TYPE_SITE;
720 $toupdate->courseid = null;
721 $toupdate->status = BADGE_STATUS_ARCHIVED;
722 $DB->update_record('badge', $toupdate);
723 }
724}
2c910861
YB
725
726/**
727 * Loads JS files required for backpack support.
728 *
729 * @uses $CFG, $PAGE
730 * @return void
731 */
732function badges_setup_backpack_js() {
733 global $CFG, $PAGE;
734 if (!empty($CFG->badges_allowexternalbackpack)) {
aae219ac
DW
735 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
736 $PAGE->requires->string_for_js('error:backpackproblem', 'badges');
7444ba74 737 // The issuer.js API is deprecated and should not be used in future.
aae219ac 738 $PAGE->requires->js(new moodle_url(BADGE_BACKPACKURL . '/issuer.js'), true);
7444ba74 739 // The backpack.js file is deprecated and should not be used in future.
aae219ac
DW
740 $PAGE->requires->js('/badges/backpack.js', true);
741 }
2c910861
YB
742 }
743}
43f1c8e2 744
aae219ac
DW
745/**
746 * No js files are required for backpack support.
747 * This only exists to directly support the custom V1 backpack api.
748 *
749 * @param boolean $checksite Call check site function.
750 * @return void
751 */
752function badges_local_backpack_js($checksite = false) {
753 global $CFG, $PAGE;
754 if (!empty($CFG->badges_allowexternalbackpack)) {
755 if (badges_open_badges_backpack_api() == OPEN_BADGES_V1) {
756 $PAGE->requires->js('/badges/backpack.js', true);
757 if ($checksite) {
758 $PAGE->requires->js_init_call('check_site_access', null, false);
759 }
760 }
761 }
762}
763
764/**
765 * Create the backpack with this data.
766 *
767 * @param stdClass $data The new backpack data.
768 * @return boolean
769 */
770function badges_create_site_backpack($data) {
771 global $DB;
772 $context = context_system::instance();
773 require_capability('moodle/badges:manageglobalsettings', $context);
774
775 $count = $DB->count_records('badge_external_backpack');
776
777 $backpack = new stdClass();
778 $backpack->apiversion = $data->apiversion;
779 $backpack->backpackapiurl = $data->backpackapiurl;
780 $backpack->backpackweburl = $data->backpackweburl;
781 $backpack->sortorder = $count;
782 $DB->insert_record('badge_external_backpack', $backpack);
783 return true;
784}
785
786/**
787 * Update the backpack with this id.
788 *
789 * @param integer $id The backpack to edit
790 * @param stdClass $data The new backpack data.
791 * @return boolean
792 */
793function badges_update_site_backpack($id, $data) {
794 global $DB;
795 $context = context_system::instance();
796 require_capability('moodle/badges:manageglobalsettings', $context);
797
798 if ($backpack = badges_get_site_backpack($id)) {
799 $backpack = new stdClass();
800 $backpack->id = $id;
801 $backpack->apiversion = $data->apiversion;
802 $backpack->backpackweburl = $data->backpackweburl;
803 $backpack->backpackapiurl = $data->backpackapiurl;
15a00bea
TT
804 $backpack->password = !empty($data->password) ? $data->password : '';
805 $backpack->oauth2_issuerid = !empty($data->oauth2_issuerid) ? $data->oauth2_issuerid : '';
aae219ac
DW
806 $DB->update_record('badge_external_backpack', $backpack);
807 return true;
808 }
809 return false;
810}
811
a80541ea
SA
812
813/**
814 * Delete the backpack with this id.
815 *
816 * @param integer $id The backpack to delete.
817 * @return boolean
818 */
819function badges_delete_site_backpack($id) {
820 global $DB, $CFG;
821
822 $context = context_system::instance();
823 require_capability('moodle/badges:manageglobalsettings', $context);
824
825 // Only remove site backpack if it's not the default one.
826 if ($CFG->badges_site_backpack != $id && $DB->record_exists('badge_external_backpack', ['id' => $id])) {
827 $transaction = $DB->start_delegated_transaction();
828
829 // Remove connections for users to this backpack.
830 $sql = "SELECT DISTINCT bb.id
831 FROM {badge_backpack} bb
832 WHERE bb.externalbackpackid = :backpackid";
833 $params = ['backpackid' => $id];
834 $userbackpacks = $DB->get_fieldset_sql($sql, $params);
835 if ($userbackpacks) {
836 // Delete user external collections references to this backpack.
837 list($insql, $params) = $DB->get_in_or_equal($userbackpacks);
838 $DB->delete_records_select('badge_external', "backpackid $insql", $params);
839 }
840 $DB->delete_records('badge_backpack', ['externalbackpackid' => $id]);
841
842 // Delete backpack entry.
843 $result = $DB->delete_records('badge_external_backpack', ['id' => $id]);
844
845 $transaction->allow_commit();
846
847 return $result;
848 }
849
850 return false;
851}
852
aae219ac
DW
853/**
854 * Is any backpack enabled that supports open badges V1?
855 * @return boolean
856 */
857function badges_open_badges_backpack_api() {
858 global $CFG;
859
860 $backpack = badges_get_site_backpack($CFG->badges_site_backpack);
aae219ac
DW
861 if (empty($backpack->apiversion)) {
862 return OPEN_BADGES_V2;
863 }
864 return $backpack->apiversion;
865}
866
867/**
868 * Get a site backpacks by id or url.
869 *
870 * @param int $id The backpack id.
aae219ac
DW
871 * @return array(stdClass)
872 */
7444ba74 873function badges_get_site_backpack($id) {
aae219ac
DW
874 global $DB;
875
7444ba74 876 return $DB->get_record('badge_external_backpack', ['id' => $id]);
aae219ac
DW
877}
878
879/**
880 * List the backpacks at site level.
881 *
882 * @return array(stdClass)
883 */
884function badges_get_site_backpacks() {
885 global $DB, $CFG;
886
887 $all = $DB->get_records('badge_external_backpack');
888
889 foreach ($all as $key => $bp) {
890 if ($bp->id == $CFG->badges_site_backpack) {
891 $all[$key]->sitebackpack = true;
892 } else {
893 $all[$key]->sitebackpack = false;
894 }
895 }
896 return $all;
897}
898
899/**
900 * List the supported badges api versions.
901 *
902 * @return array(version)
903 */
904function badges_get_badge_api_versions() {
905 return [
15a00bea
TT
906 (string)OPEN_BADGES_V1 => get_string('openbadgesv1', 'badges'),
907 (string)OPEN_BADGES_V2 => get_string('openbadgesv2', 'badges'),
908 (string)OPEN_BADGES_V2P1 => get_string('openbadgesv2p1', 'badges')
aae219ac
DW
909 ];
910}
911
aae219ac
DW
912/**
913 * Get the default issuer for a badge from this site.
914 *
915 * @return array
916 */
917function badges_get_default_issuer() {
c659b1c5 918 global $CFG, $SITE;
aae219ac
DW
919
920 $issuer = array();
2f45b6f7 921 $issuerurl = new moodle_url('/');
aae219ac 922 $issuer['name'] = $CFG->badges_defaultissuername;
c659b1c5
DW
923 if (empty($issuer['name'])) {
924 $issuer['name'] = $SITE->fullname ? $SITE->fullname : $SITE->shortname;
925 }
7444ba74 926 $issuer['url'] = $issuerurl->out(false);
aae219ac
DW
927 $issuer['email'] = $CFG->badges_defaultissuercontact;
928 $issuer['@context'] = OPEN_BADGES_V2_CONTEXT;
2f45b6f7
SA
929 $issuerid = new moodle_url('/badges/issuer_json.php');
930 $issuer['id'] = $issuerid->out(false);
aae219ac
DW
931 $issuer['type'] = OPEN_BADGES_V2_TYPE_ISSUER;
932 return $issuer;
933}
934
935/**
936 * Disconnect from the user backpack by deleting the user preferences.
937 *
938 * @param integer $userid The user to diconnect.
939 * @return boolean
940 */
941function badges_disconnect_user_backpack($userid) {
942 global $USER;
943
944 // We can only change backpack settings for our own real backpack.
945 if ($USER->id != $userid ||
946 \core\session\manager::is_loggedinas()) {
947
948 return false;
949 }
950
951 unset_user_preference('badges_email_verify_secret');
952 unset_user_preference('badges_email_verify_address');
953 unset_user_preference('badges_email_verify_backpackid');
954 unset_user_preference('badges_email_verify_password');
955
956 return true;
957}
958
959/**
960 * Used to remember which objects we connected with a backpack before.
961 *
962 * @param integer $sitebackpackid The site backpack to connect to.
963 * @param string $type The type of this remote object.
964 * @param string $internalid The id for this object on the Moodle site.
965 * @return mixed The id or false if it doesn't exist.
966 */
967function badges_external_get_mapping($sitebackpackid, $type, $internalid) {
968 global $DB;
969 // Return externalid if it exists.
970 $params = [
971 'sitebackpackid' => $sitebackpackid,
972 'type' => $type,
973 'internalid' => $internalid
974 ];
975
976 $record = $DB->get_record('badge_external_identifier', $params, 'externalid', IGNORE_MISSING);
977 if ($record) {
978 return $record->externalid;
979 }
980 return false;
981}
982
983/**
984 * Save the info about which objects we connected with a backpack before.
985 *
986 * @param integer $sitebackpackid The site backpack to connect to.
987 * @param string $type The type of this remote object.
988 * @param string $internalid The id for this object on the Moodle site.
989 * @param string $externalid The id of this object on the remote site.
990 * @return boolean
991 */
992function badges_external_create_mapping($sitebackpackid, $type, $internalid, $externalid) {
993 global $DB;
994
995 $params = [
996 'sitebackpackid' => $sitebackpackid,
997 'type' => $type,
998 'internalid' => $internalid,
999 'externalid' => $externalid
1000 ];
1001
1002 return $DB->insert_record('badge_external_identifier', $params);
1003}
1004
1005/**
1006 * Delete all external mapping information for a backpack.
1007 *
1008 * @param integer $sitebackpackid The site backpack to connect to.
1009 * @return boolean
1010 */
1011function badges_external_delete_mappings($sitebackpackid) {
1012 global $DB;
1013
1014 $params = ['sitebackpackid' => $sitebackpackid];
1015
1016 return $DB->delete_records('badge_external_identifier', $params);
1017}
1018
1019/**
1020 * Delete a specific external mapping information for a backpack.
1021 *
1022 * @param integer $sitebackpackid The site backpack to connect to.
1023 * @param string $type The type of this remote object.
1024 * @param string $internalid The id for this object on the Moodle site.
1025 * @return boolean
1026 */
1027function badges_external_delete_mapping($sitebackpackid, $type, $internalid) {
1028 global $DB;
1029
1030 $params = [
1031 'sitebackpackid' => $sitebackpackid,
1032 'type' => $type,
1033 'internalid' => $internalid
1034 ];
1035
1036 $DB->delete_record('badge_external_identifier', $params);
1037}
1038
1039/**
1040 * Create and send a verification email to the email address supplied.
1041 *
1042 * Since we're not sending this email to a user, email_to_user can't be used
1043 * but this function borrows largely the code from that process.
1044 *
1045 * @param string $email the email address to send the verification email to.
1046 * @param int $backpackid the id of the backpack to connect to
1837b1d5 1047 * @param string $backpackpassword the user entered password to connect to this backpack
aae219ac
DW
1048 * @return true if the email was sent successfully, false otherwise.
1049 */
1050function badges_send_verification_email($email, $backpackid, $backpackpassword) {
1051 global $DB, $USER;
1052
1053 // Store a user secret (badges_email_verify_secret) and the address (badges_email_verify_address) as users prefs.
1054 // The address will be used by edit_backpack_form for display during verification and to facilitate the resending
1055 // of verification emails to said address.
1056 $secret = random_string(15);
1057 set_user_preference('badges_email_verify_secret', $secret);
1058 set_user_preference('badges_email_verify_address', $email);
1059 set_user_preference('badges_email_verify_backpackid', $backpackid);
1060 set_user_preference('badges_email_verify_password', $backpackpassword);
1061
1062 // To, from.
1063 $tempuser = $DB->get_record('user', array('id' => $USER->id), '*', MUST_EXIST);
1064 $tempuser->email = $email;
1065 $noreplyuser = core_user::get_noreply_user();
1066
1067 // Generate the verification email body.
1068 $verificationurl = '/badges/backpackemailverify.php';
1069 $verificationurl = new moodle_url($verificationurl);
1070 $verificationpath = $verificationurl->out(false);
1071
1072 $site = get_site();
1073 $args = new stdClass();
1074 $args->link = $verificationpath . '?data='. $secret;
1075 $args->sitename = $site->fullname;
1076 $args->admin = generate_email_signoff();
1077
1078 $messagesubject = get_string('backpackemailverifyemailsubject', 'badges', $site->fullname);
1079 $messagetext = get_string('backpackemailverifyemailbody', 'badges', $args);
1080 $messagehtml = text_to_html($messagetext, false, false, true);
1081
1082 return email_to_user($tempuser, $noreplyuser, $messagesubject, $messagetext, $messagehtml);
1083}
1084
43f1c8e2
DW
1085/**
1086 * Return all the enabled criteria types for this site.
1087 *
8aff6f6f 1088 * @param boolean $enabled
43f1c8e2
DW
1089 * @return array
1090 */
1091function badges_list_criteria($enabled = true) {
1092 global $CFG;
1093
1094 $types = array(
1095 BADGE_CRITERIA_TYPE_OVERALL => 'overall',
1096 BADGE_CRITERIA_TYPE_ACTIVITY => 'activity',
1097 BADGE_CRITERIA_TYPE_MANUAL => 'manual',
1098 BADGE_CRITERIA_TYPE_SOCIAL => 'social',
1099 BADGE_CRITERIA_TYPE_COURSE => 'course',
1100 BADGE_CRITERIA_TYPE_COURSESET => 'courseset',
1101 BADGE_CRITERIA_TYPE_PROFILE => 'profile',
1102 BADGE_CRITERIA_TYPE_BADGE => 'badge',
1103 BADGE_CRITERIA_TYPE_COHORT => 'cohort',
1104 BADGE_CRITERIA_TYPE_COMPETENCY => 'competency',
1105 );
1106 if ($enabled) {
1107 foreach ($types as $key => $type) {
1108 $class = 'award_criteria_' . $type;
1109 $file = $CFG->dirroot . '/badges/criteria/' . $class . '.php';
1110 if (file_exists($file)) {
1111 require_once($file);
1112
1113 if (!$class::is_enabled()) {
1114 unset($types[$key]);
1115 }
1116 }
1117 }
1118 }
1119 return $types;
1120}
f44557d0
DW
1121
1122/**
1123 * Check if any badge has records for competencies.
1124 *
1125 * @param array $competencyids Array of competencies ids.
1126 * @return boolean Return true if competencies were found in any badge.
1127 */
1128function badge_award_criteria_competency_has_records_for_competencies($competencyids) {
1129 global $DB;
1130
1131 list($insql, $params) = $DB->get_in_or_equal($competencyids, SQL_PARAMS_NAMED);
1132
1133 $sql = "SELECT DISTINCT bc.badgeid
1134 FROM {badge_criteria} bc
1135 JOIN {badge_criteria_param} bcp ON bc.id = bcp.critid
1136 WHERE bc.criteriatype = :criteriatype AND bcp.value $insql";
1137 $params['criteriatype'] = BADGE_CRITERIA_TYPE_COMPETENCY;
1138
1139 return $DB->record_exists_sql($sql, $params);
1140}
dabc69af 1141
7c36d669
SL
1142/**
1143 * Creates single message for all notification and sends it out
1144 *
1145 * @param object $badge A badge which is notified about.
1146 */
1147function badge_assemble_notification(stdClass $badge) {
1148 global $DB;
1149
1150 $userfrom = core_user::get_noreply_user();
1151 $userfrom->maildisplay = true;
1152
1153 if ($msgs = $DB->get_records_select('badge_issued', 'issuernotified IS NULL AND badgeid = ?', array($badge->id))) {
1154 // Get badge creator.
1155 $creator = $DB->get_record('user', array('id' => $badge->creator), '*', MUST_EXIST);
1156 $creatorsubject = get_string('creatorsubject', 'badges', $badge->name);
1157 $creatormessage = '';
1158
1159 // Put all messages in one digest.
1160 foreach ($msgs as $msg) {
1161 $issuedlink = html_writer::link(new moodle_url('/badges/badge.php', array('hash' => $msg->uniquehash)), $badge->name);
1162 $recipient = $DB->get_record('user', array('id' => $msg->userid), '*', MUST_EXIST);
1163
1164 $a = new stdClass();
1165 $a->user = fullname($recipient);
1166 $a->link = $issuedlink;
1167 $creatormessage .= get_string('creatorbody', 'badges', $a);
1168 $DB->set_field('badge_issued', 'issuernotified', time(), array('badgeid' => $msg->badgeid, 'userid' => $msg->userid));
1169 }
1170
1171 // Create a message object.
1172 $eventdata = new \core\message\message();
1173 $eventdata->courseid = SITEID;
1174 $eventdata->component = 'moodle';
1175 $eventdata->name = 'badgecreatornotice';
1176 $eventdata->userfrom = $userfrom;
1177 $eventdata->userto = $creator;
1178 $eventdata->notification = 1;
1179 $eventdata->subject = $creatorsubject;
1180 $eventdata->fullmessage = format_text_email($creatormessage, FORMAT_HTML);
1181 $eventdata->fullmessageformat = FORMAT_PLAIN;
1182 $eventdata->fullmessagehtml = $creatormessage;
1183 $eventdata->smallmessage = $creatorsubject;
1184
1185 message_send($eventdata);
1186 }
1187}
d48a52dd
DW
1188
1189/**
1190 * Attempt to authenticate with the site backpack credentials and return an error
2fe34536
DW
1191 * if the authentication fails. If external backpacks are not enabled, this will
1192 * not perform any test.
d48a52dd
DW
1193 *
1194 * @return string
1195 */
1196function badges_verify_site_backpack() {
1197 global $OUTPUT, $CFG;
1198
1199 if (empty($CFG->badges_allowexternalbackpack)) {
1200 return '';
1201 }
1202
1203 $backpack = badges_get_site_backpack($CFG->badges_site_backpack);
1204
1205 if (empty($backpack->apiversion) || ($backpack->apiversion == OPEN_BADGES_V2)) {
1206 $backpackapi = new \core_badges\backpack_api($backpack);
1207
2fe34536
DW
1208 // Clear any cached access tokens in the session.
1209 $backpackapi->clear_system_user_session();
1210
1211 // Now attempt a login with these credentials.
d48a52dd 1212 $result = $backpackapi->authenticate();
084a42f9 1213 if (empty($result) || !empty($result->error)) {
d48a52dd
DW
1214 $warning = $backpackapi->get_authentication_error();
1215
1216 $params = ['id' => $backpack->id, 'action' => 'edit'];
1217 $backpackurl = (new moodle_url('/badges/backpacks.php', $params))->out(false);
1218
1219 $message = get_string('sitebackpackwarning', 'badges', ['url' => $backpackurl, 'warning' => $warning]);
1220 $icon = $OUTPUT->pix_icon('i/warning', get_string('warning', 'moodle'));
1221 return $OUTPUT->container($icon . $message, 'text-error');
1222 }
1223 }
1224 return '';
1225}
15a00bea
TT
1226
1227/**
1228 * Get OAuth2 services for the external backpack.
1229 *
1230 * @return array
1231 * @throws coding_exception
1232 */
1233function badges_get_oauth2_service_options() {
1234 global $DB;
1235
1236 $issuers = core\oauth2\api::get_all_issuers();
1237 $options = ['' => 'None'];
1238 foreach ($issuers as $issuer) {
1239 $options[$issuer->get('id')] = $issuer->get('name');
1240 }
1241
1242 return $options;
1243}