Merge branch 'MDL-62144-master' of git://github.com/damyon/moodle
[moodle.git] / enrol / self / lib.php
blobbac388754b9309660a0156b2d4712e9b3a4629b6
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Self enrolment plugin.
20 * @package enrol_self
21 * @copyright 2010 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 /**
26 * Self enrolment plugin implementation.
27 * @author Petr Skoda
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 class enrol_self_plugin extends enrol_plugin {
32 protected $lasternoller = null;
33 protected $lasternollerinstanceid = 0;
35 /**
36 * Returns optional enrolment information icons.
38 * This is used in course list for quick overview of enrolment options.
40 * We are not using single instance parameter because sometimes
41 * we might want to prevent icon repetition when multiple instances
42 * of one type exist. One instance may also produce several icons.
44 * @param array $instances all enrol instances of this type in one course
45 * @return array of pix_icon
47 public function get_info_icons(array $instances) {
48 $key = false;
49 $nokey = false;
50 foreach ($instances as $instance) {
51 if ($this->can_self_enrol($instance, false) !== true) {
52 // User can not enrol himself.
53 // Note that we do not check here if user is already enrolled for performance reasons -
54 // such check would execute extra queries for each course in the list of courses and
55 // would hide self-enrolment icons from guests.
56 continue;
58 if ($instance->password or $instance->customint1) {
59 $key = true;
60 } else {
61 $nokey = true;
64 $icons = array();
65 if ($nokey) {
66 $icons[] = new pix_icon('withoutkey', get_string('pluginname', 'enrol_self'), 'enrol_self');
68 if ($key) {
69 $icons[] = new pix_icon('withkey', get_string('pluginname', 'enrol_self'), 'enrol_self');
71 return $icons;
74 /**
75 * Returns localised name of enrol instance
77 * @param stdClass $instance (null is accepted too)
78 * @return string
80 public function get_instance_name($instance) {
81 global $DB;
83 if (empty($instance->name)) {
84 if (!empty($instance->roleid) and $role = $DB->get_record('role', array('id'=>$instance->roleid))) {
85 $role = ' (' . role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)) . ')';
86 } else {
87 $role = '';
89 $enrol = $this->get_name();
90 return get_string('pluginname', 'enrol_'.$enrol) . $role;
91 } else {
92 return format_string($instance->name);
96 public function roles_protected() {
97 // Users may tweak the roles later.
98 return false;
101 public function allow_unenrol(stdClass $instance) {
102 // Users with unenrol cap may unenrol other users manually manually.
103 return true;
106 public function allow_manage(stdClass $instance) {
107 // Users with manage cap may tweak period and status.
108 return true;
111 public function show_enrolme_link(stdClass $instance) {
113 if (true !== $this->can_self_enrol($instance, false)) {
114 return false;
117 return true;
121 * Return true if we can add a new instance to this course.
123 * @param int $courseid
124 * @return boolean
126 public function can_add_instance($courseid) {
127 $context = context_course::instance($courseid, MUST_EXIST);
129 if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/self:config', $context)) {
130 return false;
133 return true;
137 * Self enrol user to course
139 * @param stdClass $instance enrolment instance
140 * @param stdClass $data data needed for enrolment.
141 * @return bool|array true if enroled else eddor code and messege
143 public function enrol_self(stdClass $instance, $data = null) {
144 global $DB, $USER, $CFG;
146 // Don't enrol user if password is not passed when required.
147 if ($instance->password && !isset($data->enrolpassword)) {
148 return;
151 $timestart = time();
152 if ($instance->enrolperiod) {
153 $timeend = $timestart + $instance->enrolperiod;
154 } else {
155 $timeend = 0;
158 $this->enrol_user($instance, $USER->id, $instance->roleid, $timestart, $timeend);
160 if ($instance->password and $instance->customint1 and $data->enrolpassword !== $instance->password) {
161 // It must be a group enrolment, let's assign group too.
162 $groups = $DB->get_records('groups', array('courseid'=>$instance->courseid), 'id', 'id, enrolmentkey');
163 foreach ($groups as $group) {
164 if (empty($group->enrolmentkey)) {
165 continue;
167 if ($group->enrolmentkey === $data->enrolpassword) {
168 // Add user to group.
169 require_once($CFG->dirroot.'/group/lib.php');
170 groups_add_member($group->id, $USER->id);
171 break;
175 // Send welcome message.
176 if ($instance->customint4 != ENROL_DO_NOT_SEND_EMAIL) {
177 $this->email_welcome_message($instance, $USER);
182 * Creates course enrol form, checks if form submitted
183 * and enrols user if necessary. It can also redirect.
185 * @param stdClass $instance
186 * @return string html text, usually a form in a text box
188 public function enrol_page_hook(stdClass $instance) {
189 global $CFG, $OUTPUT, $USER;
191 require_once("$CFG->dirroot/enrol/self/locallib.php");
193 $enrolstatus = $this->can_self_enrol($instance);
195 if (true === $enrolstatus) {
196 // This user can self enrol using this instance.
197 $form = new enrol_self_enrol_form(null, $instance);
198 $instanceid = optional_param('instance', 0, PARAM_INT);
199 if ($instance->id == $instanceid) {
200 if ($data = $form->get_data()) {
201 $this->enrol_self($instance, $data);
204 } else {
205 // This user can not self enrol using this instance. Using an empty form to keep
206 // the UI consistent with other enrolment plugins that returns a form.
207 $data = new stdClass();
208 $data->header = $this->get_instance_name($instance);
209 $data->info = $enrolstatus;
211 // The can_self_enrol call returns a button to the login page if the user is a
212 // guest, setting the login url to the form if that is the case.
213 $url = isguestuser() ? get_login_url() : null;
214 $form = new enrol_self_empty_form($url, $data);
217 ob_start();
218 $form->display();
219 $output = ob_get_clean();
220 return $OUTPUT->box($output);
224 * Checks if user can self enrol.
226 * @param stdClass $instance enrolment instance
227 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
228 * used by navigation to improve performance.
229 * @return bool|string true if successful, else error message or false.
231 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
232 global $CFG, $DB, $OUTPUT, $USER;
234 if ($checkuserenrolment) {
235 if (isguestuser()) {
236 // Can not enrol guest.
237 return get_string('noguestaccess', 'enrol') . $OUTPUT->continue_button(get_login_url());
239 // Check if user is already enroled.
240 if ($DB->get_record('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
241 return get_string('canntenrol', 'enrol_self');
245 if ($instance->status != ENROL_INSTANCE_ENABLED) {
246 return get_string('canntenrol', 'enrol_self');
249 if ($instance->enrolstartdate != 0 and $instance->enrolstartdate > time()) {
250 return get_string('canntenrolearly', 'enrol_self', userdate($instance->enrolstartdate));
253 if ($instance->enrolenddate != 0 and $instance->enrolenddate < time()) {
254 return get_string('canntenrollate', 'enrol_self', userdate($instance->enrolenddate));
257 if (!$instance->customint6) {
258 // New enrols not allowed.
259 return get_string('canntenrol', 'enrol_self');
262 if ($DB->record_exists('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
263 return get_string('canntenrol', 'enrol_self');
266 if ($instance->customint3 > 0) {
267 // Max enrol limit specified.
268 $count = $DB->count_records('user_enrolments', array('enrolid' => $instance->id));
269 if ($count >= $instance->customint3) {
270 // Bad luck, no more self enrolments here.
271 return get_string('maxenrolledreached', 'enrol_self');
275 if ($instance->customint5) {
276 require_once("$CFG->dirroot/cohort/lib.php");
277 if (!cohort_is_member($instance->customint5, $USER->id)) {
278 $cohort = $DB->get_record('cohort', array('id' => $instance->customint5));
279 if (!$cohort) {
280 return null;
282 $a = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
283 return markdown_to_html(get_string('cohortnonmemberinfo', 'enrol_self', $a));
287 return true;
291 * Return information for enrolment instance containing list of parameters required
292 * for enrolment, name of enrolment plugin etc.
294 * @param stdClass $instance enrolment instance
295 * @return stdClass instance info.
297 public function get_enrol_info(stdClass $instance) {
299 $instanceinfo = new stdClass();
300 $instanceinfo->id = $instance->id;
301 $instanceinfo->courseid = $instance->courseid;
302 $instanceinfo->type = $this->get_name();
303 $instanceinfo->name = $this->get_instance_name($instance);
304 $instanceinfo->status = $this->can_self_enrol($instance);
306 if ($instance->password) {
307 $instanceinfo->requiredparam = new stdClass();
308 $instanceinfo->requiredparam->enrolpassword = get_string('password', 'enrol_self');
311 // If enrolment is possible and password is required then return ws function name to get more information.
312 if ((true === $instanceinfo->status) && $instance->password) {
313 $instanceinfo->wsfunction = 'enrol_self_get_instance_info';
315 return $instanceinfo;
319 * Add new instance of enrol plugin with default settings.
320 * @param stdClass $course
321 * @return int id of new instance
323 public function add_default_instance($course) {
324 $fields = $this->get_instance_defaults();
326 if ($this->get_config('requirepassword')) {
327 $fields['password'] = generate_password(20);
330 return $this->add_instance($course, $fields);
334 * Returns defaults for new instances.
335 * @return array
337 public function get_instance_defaults() {
338 $expirynotify = $this->get_config('expirynotify');
339 if ($expirynotify == 2) {
340 $expirynotify = 1;
341 $notifyall = 1;
342 } else {
343 $notifyall = 0;
346 $fields = array();
347 $fields['status'] = $this->get_config('status');
348 $fields['roleid'] = $this->get_config('roleid');
349 $fields['enrolperiod'] = $this->get_config('enrolperiod');
350 $fields['expirynotify'] = $expirynotify;
351 $fields['notifyall'] = $notifyall;
352 $fields['expirythreshold'] = $this->get_config('expirythreshold');
353 $fields['customint1'] = $this->get_config('groupkey');
354 $fields['customint2'] = $this->get_config('longtimenosee');
355 $fields['customint3'] = $this->get_config('maxenrolled');
356 $fields['customint4'] = $this->get_config('sendcoursewelcomemessage');
357 $fields['customint5'] = 0;
358 $fields['customint6'] = $this->get_config('newenrols');
360 return $fields;
364 * Send welcome email to specified user.
366 * @param stdClass $instance
367 * @param stdClass $user user record
368 * @return void
370 protected function email_welcome_message($instance, $user) {
371 global $CFG, $DB;
373 $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST);
374 $context = context_course::instance($course->id);
376 $a = new stdClass();
377 $a->coursename = format_string($course->fullname, true, array('context'=>$context));
378 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
380 if (trim($instance->customtext1) !== '') {
381 $message = $instance->customtext1;
382 $key = array('{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}');
383 $value = array($a->coursename, $a->profileurl, fullname($user), $user->email);
384 $message = str_replace($key, $value, $message);
385 if (strpos($message, '<') === false) {
386 // Plain text only.
387 $messagetext = $message;
388 $messagehtml = text_to_html($messagetext, null, false, true);
389 } else {
390 // This is most probably the tag/newline soup known as FORMAT_MOODLE.
391 $messagehtml = format_text($message, FORMAT_MOODLE, array('context'=>$context, 'para'=>false, 'newlines'=>true, 'filter'=>true));
392 $messagetext = html_to_text($messagehtml);
394 } else {
395 $messagetext = get_string('welcometocoursetext', 'enrol_self', $a);
396 $messagehtml = text_to_html($messagetext, null, false, true);
399 $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context'=>$context)));
401 $sendoption = $instance->customint4;
402 $contact = $this->get_welcome_email_contact($sendoption, $context);
404 // Directly emailing welcome message rather than using messaging.
405 email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
409 * Sync all meta course links.
411 * @param progress_trace $trace
412 * @param int $courseid one course, empty mean all
413 * @return int 0 means ok, 1 means error, 2 means plugin disabled
415 public function sync(progress_trace $trace, $courseid = null) {
416 global $DB;
418 if (!enrol_is_enabled('self')) {
419 $trace->finished();
420 return 2;
423 // Unfortunately this may take a long time, execution can be interrupted safely here.
424 core_php_time_limit::raise();
425 raise_memory_limit(MEMORY_HUGE);
427 $trace->output('Verifying self-enrolments...');
429 $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE, 'courselevel'=>CONTEXT_COURSE);
430 $coursesql = "";
431 if ($courseid) {
432 $coursesql = "AND e.courseid = :courseid";
433 $params['courseid'] = $courseid;
436 // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set)
437 // and that user accessed course at least once too (=== user_lastaccess record exists).
439 // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
440 $sql = "SELECT e.*, ue.userid
441 FROM {user_enrolments} ue
442 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
443 JOIN {user} u ON u.id = ue.userid
444 WHERE :now - u.lastaccess > e.customint2
445 $coursesql";
446 $rs = $DB->get_recordset_sql($sql, $params);
447 foreach ($rs as $instance) {
448 $userid = $instance->userid;
449 unset($instance->userid);
450 $this->unenrol_user($instance, $userid);
451 $days = $instance->customint2 / 60*60*24;
452 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not log in for at least $days days", 1);
454 $rs->close();
456 // Now unenrol from course user did not visit for a long time.
457 $sql = "SELECT e.*, ue.userid
458 FROM {user_enrolments} ue
459 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
460 JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)
461 WHERE :now - ul.timeaccess > e.customint2
462 $coursesql";
463 $rs = $DB->get_recordset_sql($sql, $params);
464 foreach ($rs as $instance) {
465 $userid = $instance->userid;
466 unset($instance->userid);
467 $this->unenrol_user($instance, $userid);
468 $days = $instance->customint2 / 60*60*24;
469 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not access course for at least $days days", 1);
471 $rs->close();
473 $trace->output('...user self-enrolment updates finished.');
474 $trace->finished();
476 $this->process_expirations($trace, $courseid);
478 return 0;
482 * Returns the user who is responsible for self enrolments in given instance.
484 * Usually it is the first editing teacher - the person with "highest authority"
485 * as defined by sort_by_roleassignment_authority() having 'enrol/self:manage'
486 * capability.
488 * @param int $instanceid enrolment instance id
489 * @return stdClass user record
491 protected function get_enroller($instanceid) {
492 global $DB;
494 if ($this->lasternollerinstanceid == $instanceid and $this->lasternoller) {
495 return $this->lasternoller;
498 $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST);
499 $context = context_course::instance($instance->courseid);
501 if ($users = get_enrolled_users($context, 'enrol/self:manage')) {
502 $users = sort_by_roleassignment_authority($users, $context);
503 $this->lasternoller = reset($users);
504 unset($users);
505 } else {
506 $this->lasternoller = parent::get_enroller($instanceid);
509 $this->lasternollerinstanceid = $instanceid;
511 return $this->lasternoller;
515 * Restore instance and map settings.
517 * @param restore_enrolments_structure_step $step
518 * @param stdClass $data
519 * @param stdClass $course
520 * @param int $oldid
522 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
523 global $DB;
524 if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
525 $merge = false;
526 } else {
527 $merge = array(
528 'courseid' => $data->courseid,
529 'enrol' => $this->get_name(),
530 'status' => $data->status,
531 'roleid' => $data->roleid,
534 if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
535 $instance = reset($instances);
536 $instanceid = $instance->id;
537 } else {
538 if (!empty($data->customint5)) {
539 if ($step->get_task()->is_samesite()) {
540 // Keep cohort restriction unchanged - we are on the same site.
541 } else {
542 // Use some id that can not exist in order to prevent self enrolment,
543 // because we do not know what cohort it is in this site.
544 $data->customint5 = -1;
547 $instanceid = $this->add_instance($course, (array)$data);
549 $step->set_mapping('enrol', $oldid, $instanceid);
553 * Restore user enrolment.
555 * @param restore_enrolments_structure_step $step
556 * @param stdClass $data
557 * @param stdClass $instance
558 * @param int $oldinstancestatus
559 * @param int $userid
561 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
562 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
566 * Restore role assignment.
568 * @param stdClass $instance
569 * @param int $roleid
570 * @param int $userid
571 * @param int $contextid
573 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
574 // This is necessary only because we may migrate other types to this instance,
575 // we do not use component in manual or self enrol.
576 role_assign($roleid, $userid, $contextid, '', 0);
580 * Is it possible to delete enrol instance via standard UI?
582 * @param stdClass $instance
583 * @return bool
585 public function can_delete_instance($instance) {
586 $context = context_course::instance($instance->courseid);
587 return has_capability('enrol/self:config', $context);
591 * Is it possible to hide/show enrol instance via standard UI?
593 * @param stdClass $instance
594 * @return bool
596 public function can_hide_show_instance($instance) {
597 $context = context_course::instance($instance->courseid);
599 if (!has_capability('enrol/self:config', $context)) {
600 return false;
603 // If the instance is currently disabled, before it can be enabled,
604 // we must check whether the password meets the password policies.
605 if ($instance->status == ENROL_INSTANCE_DISABLED) {
606 if ($this->get_config('requirepassword')) {
607 if (empty($instance->password)) {
608 return false;
611 // Only check the password if it is set.
612 if (!empty($instance->password) && $this->get_config('usepasswordpolicy')) {
613 if (!check_password_policy($instance->password, $errmsg)) {
614 return false;
619 return true;
623 * Return an array of valid options for the status.
625 * @return array
627 protected function get_status_options() {
628 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
629 ENROL_INSTANCE_DISABLED => get_string('no'));
630 return $options;
634 * Return an array of valid options for the newenrols property.
636 * @return array
638 protected function get_newenrols_options() {
639 $options = array(1 => get_string('yes'), 0 => get_string('no'));
640 return $options;
644 * Return an array of valid options for the groupkey property.
646 * @return array
648 protected function get_groupkey_options() {
649 $options = array(1 => get_string('yes'), 0 => get_string('no'));
650 return $options;
654 * Return an array of valid options for the expirynotify property.
656 * @return array
658 protected function get_expirynotify_options() {
659 $options = array(0 => get_string('no'),
660 1 => get_string('expirynotifyenroller', 'enrol_self'),
661 2 => get_string('expirynotifyall', 'enrol_self'));
662 return $options;
666 * Return an array of valid options for the longtimenosee property.
668 * @return array
670 protected function get_longtimenosee_options() {
671 $options = array(0 => get_string('never'),
672 1800 * 3600 * 24 => get_string('numdays', '', 1800),
673 1000 * 3600 * 24 => get_string('numdays', '', 1000),
674 365 * 3600 * 24 => get_string('numdays', '', 365),
675 180 * 3600 * 24 => get_string('numdays', '', 180),
676 150 * 3600 * 24 => get_string('numdays', '', 150),
677 120 * 3600 * 24 => get_string('numdays', '', 120),
678 90 * 3600 * 24 => get_string('numdays', '', 90),
679 60 * 3600 * 24 => get_string('numdays', '', 60),
680 30 * 3600 * 24 => get_string('numdays', '', 30),
681 21 * 3600 * 24 => get_string('numdays', '', 21),
682 14 * 3600 * 24 => get_string('numdays', '', 14),
683 7 * 3600 * 24 => get_string('numdays', '', 7));
684 return $options;
688 * The self enrollment plugin has several bulk operations that can be performed.
689 * @param course_enrolment_manager $manager
690 * @return array
692 public function get_bulk_operations(course_enrolment_manager $manager) {
693 global $CFG;
694 require_once($CFG->dirroot.'/enrol/self/locallib.php');
695 $context = $manager->get_context();
696 $bulkoperations = array();
697 if (has_capability("enrol/self:manage", $context)) {
698 $bulkoperations['editselectedusers'] = new enrol_self_editselectedusers_operation($manager, $this);
700 if (has_capability("enrol/self:unenrol", $context)) {
701 $bulkoperations['deleteselectedusers'] = new enrol_self_deleteselectedusers_operation($manager, $this);
703 return $bulkoperations;
707 * Add elements to the edit instance form.
709 * @param stdClass $instance
710 * @param MoodleQuickForm $mform
711 * @param context $context
712 * @return bool
714 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
715 global $CFG;
717 // Merge these two settings to one value for the single selection element.
718 if ($instance->notifyall and $instance->expirynotify) {
719 $instance->expirynotify = 2;
721 unset($instance->notifyall);
723 $nameattribs = array('size' => '20', 'maxlength' => '255');
724 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
725 $mform->setType('name', PARAM_TEXT);
726 $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');
728 $options = $this->get_status_options();
729 $mform->addElement('select', 'status', get_string('status', 'enrol_self'), $options);
730 $mform->addHelpButton('status', 'status', 'enrol_self');
732 $options = $this->get_newenrols_options();
733 $mform->addElement('select', 'customint6', get_string('newenrols', 'enrol_self'), $options);
734 $mform->addHelpButton('customint6', 'newenrols', 'enrol_self');
735 $mform->disabledIf('customint6', 'status', 'eq', ENROL_INSTANCE_DISABLED);
737 $passattribs = array('size' => '20', 'maxlength' => '50');
738 $mform->addElement('passwordunmask', 'password', get_string('password', 'enrol_self'), $passattribs);
739 $mform->addHelpButton('password', 'password', 'enrol_self');
740 if (empty($instance->id) and $this->get_config('requirepassword')) {
741 $mform->addRule('password', get_string('required'), 'required', null, 'client');
743 $mform->addRule('password', get_string('maximumchars', '', 50), 'maxlength', 50, 'server');
745 $options = $this->get_groupkey_options();
746 $mform->addElement('select', 'customint1', get_string('groupkey', 'enrol_self'), $options);
747 $mform->addHelpButton('customint1', 'groupkey', 'enrol_self');
749 $roles = $this->extend_assignable_roles($context, $instance->roleid);
750 $mform->addElement('select', 'roleid', get_string('role', 'enrol_self'), $roles);
752 $options = array('optional' => true, 'defaultunit' => 86400);
753 $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_self'), $options);
754 $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_self');
756 $options = $this->get_expirynotify_options();
757 $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
758 $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
760 $options = array('optional' => false, 'defaultunit' => 86400);
761 $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
762 $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
763 $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
765 $options = array('optional' => true);
766 $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_self'), $options);
767 $mform->setDefault('enrolstartdate', 0);
768 $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_self');
770 $options = array('optional' => true);
771 $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_self'), $options);
772 $mform->setDefault('enrolenddate', 0);
773 $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_self');
775 $options = $this->get_longtimenosee_options();
776 $mform->addElement('select', 'customint2', get_string('longtimenosee', 'enrol_self'), $options);
777 $mform->addHelpButton('customint2', 'longtimenosee', 'enrol_self');
779 $mform->addElement('text', 'customint3', get_string('maxenrolled', 'enrol_self'));
780 $mform->addHelpButton('customint3', 'maxenrolled', 'enrol_self');
781 $mform->setType('customint3', PARAM_INT);
783 require_once($CFG->dirroot.'/cohort/lib.php');
785 $cohorts = array(0 => get_string('no'));
786 $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
787 if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
788 $c = $DB->get_record('cohort',
789 array('id' => $instance->customint5),
790 'id, name, idnumber, contextid, visible',
791 IGNORE_MISSING);
792 if ($c) {
793 // Current cohort was not found because current user can not see it. Still keep it.
794 $allcohorts[$instance->customint5] = $c;
797 foreach ($allcohorts as $c) {
798 $cohorts[$c->id] = format_string($c->name, true, array('context' => context::instance_by_id($c->contextid)));
799 if ($c->idnumber) {
800 $cohorts[$c->id] .= ' ['.s($c->idnumber).']';
803 if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
804 // Somebody deleted a cohort, better keep the wrong value so that random ppl can not enrol.
805 $cohorts[$instance->customint5] = get_string('unknowncohort', 'cohort', $instance->customint5);
807 if (count($cohorts) > 1) {
808 $mform->addElement('select', 'customint5', get_string('cohortonly', 'enrol_self'), $cohorts);
809 $mform->addHelpButton('customint5', 'cohortonly', 'enrol_self');
810 } else {
811 $mform->addElement('hidden', 'customint5');
812 $mform->setType('customint5', PARAM_INT);
813 $mform->setConstant('customint5', 0);
816 $mform->addElement('select', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_self'),
817 enrol_send_welcome_email_options());
818 $mform->addHelpButton('customint4', 'sendcoursewelcomemessage', 'enrol_self');
820 $options = array('cols' => '60', 'rows' => '8');
821 $mform->addElement('textarea', 'customtext1', get_string('customwelcomemessage', 'enrol_self'), $options);
822 $mform->addHelpButton('customtext1', 'customwelcomemessage', 'enrol_self');
824 if (enrol_accessing_via_instance($instance)) {
825 $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
826 $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
831 * We are a good plugin and don't invent our own UI/validation code path.
833 * @return boolean
835 public function use_standard_editing_ui() {
836 return true;
840 * Perform custom validation of the data used to edit the instance.
842 * @param array $data array of ("fieldname"=>value) of submitted data
843 * @param array $files array of uploaded files "element_name"=>tmp_file_path
844 * @param object $instance The instance loaded from the DB
845 * @param context $context The context of the instance we are editing
846 * @return array of "element_name"=>"error_description" if there are errors,
847 * or an empty array if everything is OK.
848 * @return void
850 public function edit_instance_validation($data, $files, $instance, $context) {
851 $errors = array();
853 $checkpassword = false;
855 if ($instance->id) {
856 // Check the password if we are enabling the plugin again.
857 if (($instance->status == ENROL_INSTANCE_DISABLED) && ($data['status'] == ENROL_INSTANCE_ENABLED)) {
858 $checkpassword = true;
861 // Check the password if the instance is enabled and the password has changed.
862 if (($data['status'] == ENROL_INSTANCE_ENABLED) && ($instance->password !== $data['password'])) {
863 $checkpassword = true;
865 } else {
866 $checkpassword = true;
869 if ($checkpassword) {
870 $require = $this->get_config('requirepassword');
871 $policy = $this->get_config('usepasswordpolicy');
872 if ($require and trim($data['password']) === '') {
873 $errors['password'] = get_string('required');
874 } else if (!empty($data['password']) && $policy) {
875 $errmsg = '';
876 if (!check_password_policy($data['password'], $errmsg)) {
877 $errors['password'] = $errmsg;
882 if ($data['status'] == ENROL_INSTANCE_ENABLED) {
883 if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
884 $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_self');
888 if ($data['expirynotify'] > 0 and $data['expirythreshold'] < 86400) {
889 $errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
892 // Now these ones are checked by quickforms, but we may be called by the upload enrolments tool, or a webservive.
893 if (core_text::strlen($data['name']) > 255) {
894 $errors['name'] = get_string('err_maxlength', 'form', 255);
896 $validstatus = array_keys($this->get_status_options());
897 $validnewenrols = array_keys($this->get_newenrols_options());
898 if (core_text::strlen($data['password']) > 50) {
899 $errors['name'] = get_string('err_maxlength', 'form', 50);
901 $validgroupkey = array_keys($this->get_groupkey_options());
902 $context = context_course::instance($instance->courseid);
903 $validroles = array_keys($this->extend_assignable_roles($context, $instance->roleid));
904 $validexpirynotify = array_keys($this->get_expirynotify_options());
905 $validlongtimenosee = array_keys($this->get_longtimenosee_options());
906 $tovalidate = array(
907 'enrolstartdate' => PARAM_INT,
908 'enrolenddate' => PARAM_INT,
909 'name' => PARAM_TEXT,
910 'customint1' => $validgroupkey,
911 'customint2' => $validlongtimenosee,
912 'customint3' => PARAM_INT,
913 'customint4' => PARAM_INT,
914 'customint5' => PARAM_INT,
915 'customint6' => $validnewenrols,
916 'status' => $validstatus,
917 'enrolperiod' => PARAM_INT,
918 'expirynotify' => $validexpirynotify,
919 'roleid' => $validroles
921 if ($data['expirynotify'] != 0) {
922 $tovalidate['expirythreshold'] = PARAM_INT;
924 $typeerrors = $this->validate_param_types($data, $tovalidate);
925 $errors = array_merge($errors, $typeerrors);
927 return $errors;
931 * Add new instance of enrol plugin.
932 * @param object $course
933 * @param array $fields instance fields
934 * @return int id of new instance, null if can not be created
936 public function add_instance($course, array $fields = null) {
937 // In the form we are representing 2 db columns with one field.
938 if (!empty($fields) && !empty($fields['expirynotify'])) {
939 if ($fields['expirynotify'] == 2) {
940 $fields['expirynotify'] = 1;
941 $fields['notifyall'] = 1;
942 } else {
943 $fields['notifyall'] = 0;
947 return parent::add_instance($course, $fields);
951 * Update instance of enrol plugin.
952 * @param stdClass $instance
953 * @param stdClass $data modified instance fields
954 * @return boolean
956 public function update_instance($instance, $data) {
957 // In the form we are representing 2 db columns with one field.
958 if ($data->expirynotify == 2) {
959 $data->expirynotify = 1;
960 $data->notifyall = 1;
961 } else {
962 $data->notifyall = 0;
964 // Keep previous/default value of disabled expirythreshold option.
965 if (!$data->expirynotify) {
966 $data->expirythreshold = $instance->expirythreshold;
968 // Add previous value of newenrols if disabled.
969 if (!isset($data->customint6)) {
970 $data->customint6 = $instance->customint6;
973 return parent::update_instance($instance, $data);
977 * Gets a list of roles that this user can assign for the course as the default for self-enrolment.
979 * @param context $context the context.
980 * @param integer $defaultrole the id of the role that is set as the default for self-enrolment
981 * @return array index is the role id, value is the role name
983 public function extend_assignable_roles($context, $defaultrole) {
984 global $DB;
986 $roles = get_assignable_roles($context, ROLENAME_BOTH);
987 if (!isset($roles[$defaultrole])) {
988 if ($role = $DB->get_record('role', array('id' => $defaultrole))) {
989 $roles[$defaultrole] = role_get_name($role, $context, ROLENAME_BOTH);
992 return $roles;
996 * Get the "from" contact which the email will be sent from.
998 * @param int $sendoption send email from constant ENROL_SEND_EMAIL_FROM_*
999 * @param $context context where the user will be fetched
1000 * @return mixed|stdClass the contact user object.
1002 public function get_welcome_email_contact($sendoption, $context) {
1003 global $CFG;
1005 $contact = null;
1006 // Send as the first user assigned as the course contact.
1007 if ($sendoption == ENROL_SEND_EMAIL_FROM_COURSE_CONTACT) {
1008 $rusers = array();
1009 if (!empty($CFG->coursecontact)) {
1010 $croles = explode(',', $CFG->coursecontact);
1011 list($sort, $sortparams) = users_order_by_sql('u');
1012 // We only use the first user.
1013 $i = 0;
1014 do {
1015 $allnames = get_all_user_name_fields(true, 'u');
1016 $rusers = get_role_users($croles[$i], $context, true, 'u.id, u.confirmed, u.username, '. $allnames . ',
1017 u.email, r.sortorder, ra.id', 'r.sortorder, ra.id ASC, ' . $sort, null, '', '', '', '', $sortparams);
1018 $i++;
1019 } while (empty($rusers) && !empty($croles[$i]));
1021 if ($rusers) {
1022 $contact = array_values($rusers)[0];
1024 } else if ($sendoption == ENROL_SEND_EMAIL_FROM_KEY_HOLDER) {
1025 // Send as the first user with enrol/self:holdkey capability assigned in the course.
1026 list($sort) = users_order_by_sql('u');
1027 $keyholders = get_users_by_capability($context, 'enrol/self:holdkey', 'u.*', $sort);
1028 if (!empty($keyholders)) {
1029 $contact = array_values($keyholders)[0];
1033 // If send welcome email option is set to no reply or if none of the previous options have
1034 // returned a contact send welcome message as noreplyuser.
1035 if ($sendoption == ENROL_SEND_EMAIL_FROM_NOREPLY || empty($contact)) {
1036 $contact = core_user::get_noreply_user();
1039 return $contact;
1044 * Get icon mapping for font-awesome.
1046 function enrol_self_get_fontawesome_icon_map() {
1047 return [
1048 'enrol_self:withkey' => 'fa-key',
1049 'enrol_self:withoutkey' => 'fa-sign-in',