MDL-61993 profilefield_checkbox: take rid of oracle reserved word
[moodle.git] / enrol / self / lib.php
blob98e9583558c3cad018c33dd30c444d1d10c79894
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 * Enrol self cron support.
410 * @return void
412 public function cron() {
413 $trace = new text_progress_trace();
414 $this->sync($trace, null);
415 $this->send_expiry_notifications($trace);
419 * Sync all meta course links.
421 * @param progress_trace $trace
422 * @param int $courseid one course, empty mean all
423 * @return int 0 means ok, 1 means error, 2 means plugin disabled
425 public function sync(progress_trace $trace, $courseid = null) {
426 global $DB;
428 if (!enrol_is_enabled('self')) {
429 $trace->finished();
430 return 2;
433 // Unfortunately this may take a long time, execution can be interrupted safely here.
434 core_php_time_limit::raise();
435 raise_memory_limit(MEMORY_HUGE);
437 $trace->output('Verifying self-enrolments...');
439 $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE, 'courselevel'=>CONTEXT_COURSE);
440 $coursesql = "";
441 if ($courseid) {
442 $coursesql = "AND e.courseid = :courseid";
443 $params['courseid'] = $courseid;
446 // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set)
447 // and that user accessed course at least once too (=== user_lastaccess record exists).
449 // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
450 $sql = "SELECT e.*, ue.userid
451 FROM {user_enrolments} ue
452 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
453 JOIN {user} u ON u.id = ue.userid
454 WHERE :now - u.lastaccess > e.customint2
455 $coursesql";
456 $rs = $DB->get_recordset_sql($sql, $params);
457 foreach ($rs as $instance) {
458 $userid = $instance->userid;
459 unset($instance->userid);
460 $this->unenrol_user($instance, $userid);
461 $days = $instance->customint2 / 60*60*24;
462 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not log in for at least $days days", 1);
464 $rs->close();
466 // Now unenrol from course user did not visit for a long time.
467 $sql = "SELECT e.*, ue.userid
468 FROM {user_enrolments} ue
469 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
470 JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)
471 WHERE :now - ul.timeaccess > e.customint2
472 $coursesql";
473 $rs = $DB->get_recordset_sql($sql, $params);
474 foreach ($rs as $instance) {
475 $userid = $instance->userid;
476 unset($instance->userid);
477 $this->unenrol_user($instance, $userid);
478 $days = $instance->customint2 / 60*60*24;
479 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not access course for at least $days days", 1);
481 $rs->close();
483 $trace->output('...user self-enrolment updates finished.');
484 $trace->finished();
486 $this->process_expirations($trace, $courseid);
488 return 0;
492 * Returns the user who is responsible for self enrolments in given instance.
494 * Usually it is the first editing teacher - the person with "highest authority"
495 * as defined by sort_by_roleassignment_authority() having 'enrol/self:manage'
496 * capability.
498 * @param int $instanceid enrolment instance id
499 * @return stdClass user record
501 protected function get_enroller($instanceid) {
502 global $DB;
504 if ($this->lasternollerinstanceid == $instanceid and $this->lasternoller) {
505 return $this->lasternoller;
508 $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST);
509 $context = context_course::instance($instance->courseid);
511 if ($users = get_enrolled_users($context, 'enrol/self:manage')) {
512 $users = sort_by_roleassignment_authority($users, $context);
513 $this->lasternoller = reset($users);
514 unset($users);
515 } else {
516 $this->lasternoller = parent::get_enroller($instanceid);
519 $this->lasternollerinstanceid = $instanceid;
521 return $this->lasternoller;
525 * Restore instance and map settings.
527 * @param restore_enrolments_structure_step $step
528 * @param stdClass $data
529 * @param stdClass $course
530 * @param int $oldid
532 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
533 global $DB;
534 if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
535 $merge = false;
536 } else {
537 $merge = array(
538 'courseid' => $data->courseid,
539 'enrol' => $this->get_name(),
540 'status' => $data->status,
541 'roleid' => $data->roleid,
544 if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
545 $instance = reset($instances);
546 $instanceid = $instance->id;
547 } else {
548 if (!empty($data->customint5)) {
549 if ($step->get_task()->is_samesite()) {
550 // Keep cohort restriction unchanged - we are on the same site.
551 } else {
552 // Use some id that can not exist in order to prevent self enrolment,
553 // because we do not know what cohort it is in this site.
554 $data->customint5 = -1;
557 $instanceid = $this->add_instance($course, (array)$data);
559 $step->set_mapping('enrol', $oldid, $instanceid);
563 * Restore user enrolment.
565 * @param restore_enrolments_structure_step $step
566 * @param stdClass $data
567 * @param stdClass $instance
568 * @param int $oldinstancestatus
569 * @param int $userid
571 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
572 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
576 * Restore role assignment.
578 * @param stdClass $instance
579 * @param int $roleid
580 * @param int $userid
581 * @param int $contextid
583 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
584 // This is necessary only because we may migrate other types to this instance,
585 // we do not use component in manual or self enrol.
586 role_assign($roleid, $userid, $contextid, '', 0);
590 * Is it possible to delete enrol instance via standard UI?
592 * @param stdClass $instance
593 * @return bool
595 public function can_delete_instance($instance) {
596 $context = context_course::instance($instance->courseid);
597 return has_capability('enrol/self:config', $context);
601 * Is it possible to hide/show enrol instance via standard UI?
603 * @param stdClass $instance
604 * @return bool
606 public function can_hide_show_instance($instance) {
607 $context = context_course::instance($instance->courseid);
609 if (!has_capability('enrol/self:config', $context)) {
610 return false;
613 // If the instance is currently disabled, before it can be enabled,
614 // we must check whether the password meets the password policies.
615 if ($instance->status == ENROL_INSTANCE_DISABLED) {
616 if ($this->get_config('requirepassword')) {
617 if (empty($instance->password)) {
618 return false;
621 // Only check the password if it is set.
622 if (!empty($instance->password) && $this->get_config('usepasswordpolicy')) {
623 if (!check_password_policy($instance->password, $errmsg)) {
624 return false;
629 return true;
633 * Return an array of valid options for the status.
635 * @return array
637 protected function get_status_options() {
638 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
639 ENROL_INSTANCE_DISABLED => get_string('no'));
640 return $options;
644 * Return an array of valid options for the newenrols property.
646 * @return array
648 protected function get_newenrols_options() {
649 $options = array(1 => get_string('yes'), 0 => get_string('no'));
650 return $options;
654 * Return an array of valid options for the groupkey property.
656 * @return array
658 protected function get_groupkey_options() {
659 $options = array(1 => get_string('yes'), 0 => get_string('no'));
660 return $options;
664 * Return an array of valid options for the expirynotify property.
666 * @return array
668 protected function get_expirynotify_options() {
669 $options = array(0 => get_string('no'),
670 1 => get_string('expirynotifyenroller', 'core_enrol'),
671 2 => get_string('expirynotifyall', 'core_enrol'));
672 return $options;
676 * Return an array of valid options for the longtimenosee property.
678 * @return array
680 protected function get_longtimenosee_options() {
681 $options = array(0 => get_string('never'),
682 1800 * 3600 * 24 => get_string('numdays', '', 1800),
683 1000 * 3600 * 24 => get_string('numdays', '', 1000),
684 365 * 3600 * 24 => get_string('numdays', '', 365),
685 180 * 3600 * 24 => get_string('numdays', '', 180),
686 150 * 3600 * 24 => get_string('numdays', '', 150),
687 120 * 3600 * 24 => get_string('numdays', '', 120),
688 90 * 3600 * 24 => get_string('numdays', '', 90),
689 60 * 3600 * 24 => get_string('numdays', '', 60),
690 30 * 3600 * 24 => get_string('numdays', '', 30),
691 21 * 3600 * 24 => get_string('numdays', '', 21),
692 14 * 3600 * 24 => get_string('numdays', '', 14),
693 7 * 3600 * 24 => get_string('numdays', '', 7));
694 return $options;
698 * Add elements to the edit instance form.
700 * @param stdClass $instance
701 * @param MoodleQuickForm $mform
702 * @param context $context
703 * @return bool
705 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
706 global $CFG;
708 // Merge these two settings to one value for the single selection element.
709 if ($instance->notifyall and $instance->expirynotify) {
710 $instance->expirynotify = 2;
712 unset($instance->notifyall);
714 $nameattribs = array('size' => '20', 'maxlength' => '255');
715 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
716 $mform->setType('name', PARAM_TEXT);
717 $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');
719 $options = $this->get_status_options();
720 $mform->addElement('select', 'status', get_string('status', 'enrol_self'), $options);
721 $mform->addHelpButton('status', 'status', 'enrol_self');
723 $options = $this->get_newenrols_options();
724 $mform->addElement('select', 'customint6', get_string('newenrols', 'enrol_self'), $options);
725 $mform->addHelpButton('customint6', 'newenrols', 'enrol_self');
726 $mform->disabledIf('customint6', 'status', 'eq', ENROL_INSTANCE_DISABLED);
728 $passattribs = array('size' => '20', 'maxlength' => '50');
729 $mform->addElement('passwordunmask', 'password', get_string('password', 'enrol_self'), $passattribs);
730 $mform->addHelpButton('password', 'password', 'enrol_self');
731 if (empty($instance->id) and $this->get_config('requirepassword')) {
732 $mform->addRule('password', get_string('required'), 'required', null, 'client');
734 $mform->addRule('password', get_string('maximumchars', '', 50), 'maxlength', 50, 'server');
736 $options = $this->get_groupkey_options();
737 $mform->addElement('select', 'customint1', get_string('groupkey', 'enrol_self'), $options);
738 $mform->addHelpButton('customint1', 'groupkey', 'enrol_self');
740 $roles = $this->extend_assignable_roles($context, $instance->roleid);
741 $mform->addElement('select', 'roleid', get_string('role', 'enrol_self'), $roles);
743 $options = array('optional' => true, 'defaultunit' => 86400);
744 $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_self'), $options);
745 $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_self');
747 $options = $this->get_expirynotify_options();
748 $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
749 $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
751 $options = array('optional' => false, 'defaultunit' => 86400);
752 $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
753 $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
754 $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
756 $options = array('optional' => true);
757 $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_self'), $options);
758 $mform->setDefault('enrolstartdate', 0);
759 $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_self');
761 $options = array('optional' => true);
762 $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_self'), $options);
763 $mform->setDefault('enrolenddate', 0);
764 $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_self');
766 $options = $this->get_longtimenosee_options();
767 $mform->addElement('select', 'customint2', get_string('longtimenosee', 'enrol_self'), $options);
768 $mform->addHelpButton('customint2', 'longtimenosee', 'enrol_self');
770 $mform->addElement('text', 'customint3', get_string('maxenrolled', 'enrol_self'));
771 $mform->addHelpButton('customint3', 'maxenrolled', 'enrol_self');
772 $mform->setType('customint3', PARAM_INT);
774 require_once($CFG->dirroot.'/cohort/lib.php');
776 $cohorts = array(0 => get_string('no'));
777 $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
778 if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
779 $c = $DB->get_record('cohort',
780 array('id' => $instance->customint5),
781 'id, name, idnumber, contextid, visible',
782 IGNORE_MISSING);
783 if ($c) {
784 // Current cohort was not found because current user can not see it. Still keep it.
785 $allcohorts[$instance->customint5] = $c;
788 foreach ($allcohorts as $c) {
789 $cohorts[$c->id] = format_string($c->name, true, array('context' => context::instance_by_id($c->contextid)));
790 if ($c->idnumber) {
791 $cohorts[$c->id] .= ' ['.s($c->idnumber).']';
794 if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
795 // Somebody deleted a cohort, better keep the wrong value so that random ppl can not enrol.
796 $cohorts[$instance->customint5] = get_string('unknowncohort', 'cohort', $instance->customint5);
798 if (count($cohorts) > 1) {
799 $mform->addElement('select', 'customint5', get_string('cohortonly', 'enrol_self'), $cohorts);
800 $mform->addHelpButton('customint5', 'cohortonly', 'enrol_self');
801 } else {
802 $mform->addElement('hidden', 'customint5');
803 $mform->setType('customint5', PARAM_INT);
804 $mform->setConstant('customint5', 0);
807 $mform->addElement('select', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_self'),
808 enrol_send_welcome_email_options());
809 $mform->addHelpButton('customint4', 'sendcoursewelcomemessage', 'enrol_self');
811 $options = array('cols' => '60', 'rows' => '8');
812 $mform->addElement('textarea', 'customtext1', get_string('customwelcomemessage', 'enrol_self'), $options);
813 $mform->addHelpButton('customtext1', 'customwelcomemessage', 'enrol_self');
815 if (enrol_accessing_via_instance($instance)) {
816 $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
817 $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
822 * We are a good plugin and don't invent our own UI/validation code path.
824 * @return boolean
826 public function use_standard_editing_ui() {
827 return true;
831 * Perform custom validation of the data used to edit the instance.
833 * @param array $data array of ("fieldname"=>value) of submitted data
834 * @param array $files array of uploaded files "element_name"=>tmp_file_path
835 * @param object $instance The instance loaded from the DB
836 * @param context $context The context of the instance we are editing
837 * @return array of "element_name"=>"error_description" if there are errors,
838 * or an empty array if everything is OK.
839 * @return void
841 public function edit_instance_validation($data, $files, $instance, $context) {
842 $errors = array();
844 $checkpassword = false;
846 if ($instance->id) {
847 // Check the password if we are enabling the plugin again.
848 if (($instance->status == ENROL_INSTANCE_DISABLED) && ($data['status'] == ENROL_INSTANCE_ENABLED)) {
849 $checkpassword = true;
852 // Check the password if the instance is enabled and the password has changed.
853 if (($data['status'] == ENROL_INSTANCE_ENABLED) && ($instance->password !== $data['password'])) {
854 $checkpassword = true;
856 } else {
857 $checkpassword = true;
860 if ($checkpassword) {
861 $require = $this->get_config('requirepassword');
862 $policy = $this->get_config('usepasswordpolicy');
863 if ($require and trim($data['password']) === '') {
864 $errors['password'] = get_string('required');
865 } else if (!empty($data['password']) && $policy) {
866 $errmsg = '';
867 if (!check_password_policy($data['password'], $errmsg)) {
868 $errors['password'] = $errmsg;
873 if ($data['status'] == ENROL_INSTANCE_ENABLED) {
874 if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
875 $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_self');
879 if ($data['expirynotify'] > 0 and $data['expirythreshold'] < 86400) {
880 $errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
883 // Now these ones are checked by quickforms, but we may be called by the upload enrolments tool, or a webservive.
884 if (core_text::strlen($data['name']) > 255) {
885 $errors['name'] = get_string('err_maxlength', 'form', 255);
887 $validstatus = array_keys($this->get_status_options());
888 $validnewenrols = array_keys($this->get_newenrols_options());
889 if (core_text::strlen($data['password']) > 50) {
890 $errors['name'] = get_string('err_maxlength', 'form', 50);
892 $validgroupkey = array_keys($this->get_groupkey_options());
893 $context = context_course::instance($instance->courseid);
894 $validroles = array_keys($this->extend_assignable_roles($context, $instance->roleid));
895 $validexpirynotify = array_keys($this->get_expirynotify_options());
896 $validlongtimenosee = array_keys($this->get_longtimenosee_options());
897 $tovalidate = array(
898 'enrolstartdate' => PARAM_INT,
899 'enrolenddate' => PARAM_INT,
900 'name' => PARAM_TEXT,
901 'customint1' => $validgroupkey,
902 'customint2' => $validlongtimenosee,
903 'customint3' => PARAM_INT,
904 'customint4' => PARAM_INT,
905 'customint5' => PARAM_INT,
906 'customint6' => $validnewenrols,
907 'status' => $validstatus,
908 'enrolperiod' => PARAM_INT,
909 'expirynotify' => $validexpirynotify,
910 'roleid' => $validroles
912 if ($data['expirynotify'] != 0) {
913 $tovalidate['expirythreshold'] = PARAM_INT;
915 $typeerrors = $this->validate_param_types($data, $tovalidate);
916 $errors = array_merge($errors, $typeerrors);
918 return $errors;
922 * Add new instance of enrol plugin.
923 * @param object $course
924 * @param array $fields instance fields
925 * @return int id of new instance, null if can not be created
927 public function add_instance($course, array $fields = null) {
928 // In the form we are representing 2 db columns with one field.
929 if (!empty($fields) && !empty($fields['expirynotify'])) {
930 if ($fields['expirynotify'] == 2) {
931 $fields['expirynotify'] = 1;
932 $fields['notifyall'] = 1;
933 } else {
934 $fields['notifyall'] = 0;
938 return parent::add_instance($course, $fields);
942 * Update instance of enrol plugin.
943 * @param stdClass $instance
944 * @param stdClass $data modified instance fields
945 * @return boolean
947 public function update_instance($instance, $data) {
948 // In the form we are representing 2 db columns with one field.
949 if ($data->expirynotify == 2) {
950 $data->expirynotify = 1;
951 $data->notifyall = 1;
952 } else {
953 $data->notifyall = 0;
955 // Keep previous/default value of disabled expirythreshold option.
956 if (!$data->expirynotify) {
957 $data->expirythreshold = $instance->expirythreshold;
959 // Add previous value of newenrols if disabled.
960 if (!isset($data->customint6)) {
961 $data->customint6 = $instance->customint6;
964 return parent::update_instance($instance, $data);
968 * Gets a list of roles that this user can assign for the course as the default for self-enrolment.
970 * @param context $context the context.
971 * @param integer $defaultrole the id of the role that is set as the default for self-enrolment
972 * @return array index is the role id, value is the role name
974 public function extend_assignable_roles($context, $defaultrole) {
975 global $DB;
977 $roles = get_assignable_roles($context, ROLENAME_BOTH);
978 if (!isset($roles[$defaultrole])) {
979 if ($role = $DB->get_record('role', array('id' => $defaultrole))) {
980 $roles[$defaultrole] = role_get_name($role, $context, ROLENAME_BOTH);
983 return $roles;
987 * Get the "from" contact which the email will be sent from.
989 * @param int $sendoption send email from constant ENROL_SEND_EMAIL_FROM_*
990 * @param $context context where the user will be fetched
991 * @return mixed|stdClass the contact user object.
993 public function get_welcome_email_contact($sendoption, $context) {
994 global $CFG;
996 $contact = null;
997 // Send as the first user assigned as the course contact.
998 if ($sendoption == ENROL_SEND_EMAIL_FROM_COURSE_CONTACT) {
999 $rusers = array();
1000 if (!empty($CFG->coursecontact)) {
1001 $croles = explode(',', $CFG->coursecontact);
1002 list($sort, $sortparams) = users_order_by_sql('u');
1003 // We only use the first user.
1004 $i = 0;
1005 do {
1006 $allnames = get_all_user_name_fields(true, 'u');
1007 $rusers = get_role_users($croles[$i], $context, true, 'u.id, u.confirmed, u.username, '. $allnames . ',
1008 u.email, r.sortorder, ra.id', 'r.sortorder, ra.id ASC, ' . $sort, null, '', '', '', '', $sortparams);
1009 $i++;
1010 } while (empty($rusers) && !empty($croles[$i]));
1012 if ($rusers) {
1013 $contact = array_values($rusers)[0];
1015 } else if ($sendoption == ENROL_SEND_EMAIL_FROM_KEY_HOLDER) {
1016 // Send as the first user with enrol/self:holdkey capability assigned in the course.
1017 list($sort) = users_order_by_sql('u');
1018 $keyholders = get_users_by_capability($context, 'enrol/self:holdkey', 'u.*', $sort);
1019 if (!empty($keyholders)) {
1020 $contact = array_values($keyholders)[0];
1024 // If send welcome email option is set to no reply or if none of the previous options have
1025 // returned a contact send welcome message as noreplyuser.
1026 if ($sendoption == ENROL_SEND_EMAIL_FROM_NOREPLY || empty($contact)) {
1027 $contact = core_user::get_noreply_user();
1030 return $contact;
1035 * Get icon mapping for font-awesome.
1037 function enrol_self_get_fontawesome_icon_map() {
1038 return [
1039 'enrol_self:withkey' => 'fa-key',
1040 'enrol_self:withoutkey' => 'fa-sign-in',