2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Self enrolment plugin.
21 * @copyright 2010 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 * Self enrolment plugin implementation.
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;
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) {
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.
58 if ($instance->password
or $instance->customint1
) {
66 $icons[] = new pix_icon('withoutkey', get_string('pluginname', 'enrol_self'), 'enrol_self');
69 $icons[] = new pix_icon('withkey', get_string('pluginname', 'enrol_self'), 'enrol_self');
75 * Returns localised name of enrol instance
77 * @param stdClass $instance (null is accepted too)
80 public function get_instance_name($instance) {
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
)) . ')';
89 $enrol = $this->get_name();
90 return get_string('pluginname', 'enrol_'.$enrol) . $role;
92 return format_string($instance->name
);
96 public function roles_protected() {
97 // Users may tweak the roles later.
101 public function allow_unenrol(stdClass
$instance) {
102 // Users with unenrol cap may unenrol other users manually manually.
106 public function allow_manage(stdClass
$instance) {
107 // Users with manage cap may tweak period and status.
111 public function show_enrolme_link(stdClass
$instance) {
113 if (true !== $this->can_self_enrol($instance, false)) {
121 * Return true if we can add a new instance to this course.
123 * @param int $courseid
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)) {
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
)) {
152 if ($instance->enrolperiod
) {
153 $timeend = $timestart +
$instance->enrolperiod
;
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
)) {
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
);
175 // Send welcome message.
176 if ($instance->customint4
) {
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);
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);
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) {
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
));
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));
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.
337 public function get_instance_defaults() {
338 $expirynotify = $this->get_config('expirynotify');
339 if ($expirynotify == 2) {
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');
364 * Send welcome email to specified user.
366 * @param stdClass $instance
367 * @param stdClass $user user record
370 protected function email_welcome_message($instance, $user) {
373 $course = $DB->get_record('course', array('id'=>$instance->courseid
), '*', MUST_EXIST
);
374 $context = context_course
::instance($course->id
);
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) {
387 $messagetext = $message;
388 $messagehtml = text_to_html($messagetext, null, false, true);
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);
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)));
402 if (!empty($CFG->coursecontact
)) {
403 $croles = explode(',', $CFG->coursecontact
);
404 list($sort, $sortparams) = users_order_by_sql('u');
405 // We only use the first user.
408 $rusers = get_role_users($croles[$i], $context, true, '',
409 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
411 } while (empty($rusers) && !empty($croles[$i]));
414 $contact = reset($rusers);
416 $contact = core_user
::get_support_user();
419 // Directly emailing welcome message rather than using messaging.
420 email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
424 * Enrol self cron support.
427 public function cron() {
428 $trace = new text_progress_trace();
429 $this->sync($trace, null);
430 $this->send_expiry_notifications($trace);
434 * Sync all meta course links.
436 * @param progress_trace $trace
437 * @param int $courseid one course, empty mean all
438 * @return int 0 means ok, 1 means error, 2 means plugin disabled
440 public function sync(progress_trace
$trace, $courseid = null) {
443 if (!enrol_is_enabled('self')) {
448 // Unfortunately this may take a long time, execution can be interrupted safely here.
449 core_php_time_limit
::raise();
450 raise_memory_limit(MEMORY_HUGE
);
452 $trace->output('Verifying self-enrolments...');
454 $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE
, 'courselevel'=>CONTEXT_COURSE
);
457 $coursesql = "AND e.courseid = :courseid";
458 $params['courseid'] = $courseid;
461 // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set)
462 // and that user accessed course at least once too (=== user_lastaccess record exists).
464 // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
465 $sql = "SELECT e.*, ue.userid
466 FROM {user_enrolments} ue
467 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
468 JOIN {user} u ON u.id = ue.userid
469 WHERE :now - u.lastaccess > e.customint2
471 $rs = $DB->get_recordset_sql($sql, $params);
472 foreach ($rs as $instance) {
473 $userid = $instance->userid
;
474 unset($instance->userid
);
475 $this->unenrol_user($instance, $userid);
476 $days = $instance->customint2
/ 60*60*24;
477 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not log in for at least $days days", 1);
481 // Now unenrol from course user did not visit for a long time.
482 $sql = "SELECT e.*, ue.userid
483 FROM {user_enrolments} ue
484 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
485 JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)
486 WHERE :now - ul.timeaccess > e.customint2
488 $rs = $DB->get_recordset_sql($sql, $params);
489 foreach ($rs as $instance) {
490 $userid = $instance->userid
;
491 unset($instance->userid
);
492 $this->unenrol_user($instance, $userid);
493 $days = $instance->customint2
/ 60*60*24;
494 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not access course for at least $days days", 1);
498 $trace->output('...user self-enrolment updates finished.');
501 $this->process_expirations($trace, $courseid);
507 * Returns the user who is responsible for self enrolments in given instance.
509 * Usually it is the first editing teacher - the person with "highest authority"
510 * as defined by sort_by_roleassignment_authority() having 'enrol/self:manage'
513 * @param int $instanceid enrolment instance id
514 * @return stdClass user record
516 protected function get_enroller($instanceid) {
519 if ($this->lasternollerinstanceid
== $instanceid and $this->lasternoller
) {
520 return $this->lasternoller
;
523 $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST
);
524 $context = context_course
::instance($instance->courseid
);
526 if ($users = get_enrolled_users($context, 'enrol/self:manage')) {
527 $users = sort_by_roleassignment_authority($users, $context);
528 $this->lasternoller
= reset($users);
531 $this->lasternoller
= parent
::get_enroller($instanceid);
534 $this->lasternollerinstanceid
= $instanceid;
536 return $this->lasternoller
;
540 * Gets an array of the user enrolment actions.
542 * @param course_enrolment_manager $manager
543 * @param stdClass $ue A user enrolment object
544 * @return array An array of user_enrolment_actions
546 public function get_user_enrolment_actions(course_enrolment_manager
$manager, $ue) {
548 $context = $manager->get_context();
549 $instance = $ue->enrolmentinstance
;
550 $params = $manager->get_moodlepage()->url
->params();
551 $params['ue'] = $ue->id
;
552 if ($this->allow_unenrol($instance) && has_capability("enrol/self:unenrol", $context)) {
553 $url = new moodle_url('/enrol/unenroluser.php', $params);
554 $actions[] = new user_enrolment_action(new pix_icon('t/delete', ''), get_string('unenrol', 'enrol'), $url, array('class'=>'unenrollink', 'rel'=>$ue->id
));
556 if ($this->allow_manage($instance) && has_capability("enrol/self:manage", $context)) {
557 $url = new moodle_url('/enrol/editenrolment.php', $params);
558 $actions[] = new user_enrolment_action(new pix_icon('t/edit', ''), get_string('edit'), $url, array('class'=>'editenrollink', 'rel'=>$ue->id
));
564 * Restore instance and map settings.
566 * @param restore_enrolments_structure_step $step
567 * @param stdClass $data
568 * @param stdClass $course
571 public function restore_instance(restore_enrolments_structure_step
$step, stdClass
$data, $course, $oldid) {
573 if ($step->get_task()->get_target() == backup
::TARGET_NEW_COURSE
) {
577 'courseid' => $data->courseid
,
578 'enrol' => $this->get_name(),
579 'roleid' => $data->roleid
,
582 if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
583 $instance = reset($instances);
584 $instanceid = $instance->id
;
586 if (!empty($data->customint5
)) {
587 if ($step->get_task()->is_samesite()) {
588 // Keep cohort restriction unchanged - we are on the same site.
590 // Use some id that can not exist in order to prevent self enrolment,
591 // because we do not know what cohort it is in this site.
592 $data->customint5
= -1;
595 $instanceid = $this->add_instance($course, (array)$data);
597 $step->set_mapping('enrol', $oldid, $instanceid);
601 * Restore user enrolment.
603 * @param restore_enrolments_structure_step $step
604 * @param stdClass $data
605 * @param stdClass $instance
606 * @param int $oldinstancestatus
609 public function restore_user_enrolment(restore_enrolments_structure_step
$step, $data, $instance, $userid, $oldinstancestatus) {
610 $this->enrol_user($instance, $userid, null, $data->timestart
, $data->timeend
, $data->status
);
614 * Restore role assignment.
616 * @param stdClass $instance
619 * @param int $contextid
621 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
622 // This is necessary only because we may migrate other types to this instance,
623 // we do not use component in manual or self enrol.
624 role_assign($roleid, $userid, $contextid, '', 0);
628 * Is it possible to delete enrol instance via standard UI?
630 * @param stdClass $instance
633 public function can_delete_instance($instance) {
634 $context = context_course
::instance($instance->courseid
);
635 return has_capability('enrol/self:config', $context);
639 * Is it possible to hide/show enrol instance via standard UI?
641 * @param stdClass $instance
644 public function can_hide_show_instance($instance) {
645 $context = context_course
::instance($instance->courseid
);
647 if (!has_capability('enrol/self:config', $context)) {
651 // If the instance is currently disabled, before it can be enabled,
652 // we must check whether the password meets the password policies.
653 if ($instance->status
== ENROL_INSTANCE_DISABLED
) {
654 if ($this->get_config('requirepassword')) {
655 if (empty($instance->password
)) {
659 // Only check the password if it is set.
660 if (!empty($instance->password
) && $this->get_config('usepasswordpolicy')) {
661 if (!check_password_policy($instance->password
, $errmsg)) {
671 * Return an array of valid options for the status.
675 protected function get_status_options() {
676 $options = array(ENROL_INSTANCE_ENABLED
=> get_string('yes'),
677 ENROL_INSTANCE_DISABLED
=> get_string('no'));
682 * Return an array of valid options for the newenrols property.
686 protected function get_newenrols_options() {
687 $options = array(1 => get_string('yes'), 0 => get_string('no'));
692 * Return an array of valid options for the groupkey property.
696 protected function get_groupkey_options() {
697 $options = array(1 => get_string('yes'), 0 => get_string('no'));
702 * Return an array of valid options for the expirynotify property.
706 protected function get_expirynotify_options() {
707 $options = array(0 => get_string('no'),
708 1 => get_string('expirynotifyenroller', 'core_enrol'),
709 2 => get_string('expirynotifyall', 'core_enrol'));
714 * Return an array of valid options for the longtimenosee property.
718 protected function get_longtimenosee_options() {
719 $options = array(0 => get_string('never'),
720 1800 * 3600 * 24 => get_string('numdays', '', 1800),
721 1000 * 3600 * 24 => get_string('numdays', '', 1000),
722 365 * 3600 * 24 => get_string('numdays', '', 365),
723 180 * 3600 * 24 => get_string('numdays', '', 180),
724 150 * 3600 * 24 => get_string('numdays', '', 150),
725 120 * 3600 * 24 => get_string('numdays', '', 120),
726 90 * 3600 * 24 => get_string('numdays', '', 90),
727 60 * 3600 * 24 => get_string('numdays', '', 60),
728 30 * 3600 * 24 => get_string('numdays', '', 30),
729 21 * 3600 * 24 => get_string('numdays', '', 21),
730 14 * 3600 * 24 => get_string('numdays', '', 14),
731 7 * 3600 * 24 => get_string('numdays', '', 7));
736 * Add elements to the edit instance form.
738 * @param stdClass $instance
739 * @param MoodleQuickForm $mform
740 * @param context $context
743 public function edit_instance_form($instance, MoodleQuickForm
$mform, $context) {
746 // Merge these two settings to one value for the single selection element.
747 if ($instance->notifyall
and $instance->expirynotify
) {
748 $instance->expirynotify
= 2;
750 unset($instance->notifyall
);
752 $nameattribs = array('size' => '20', 'maxlength' => '255');
753 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
754 $mform->setType('name', PARAM_TEXT
);
755 $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');
757 $options = $this->get_status_options();
758 $mform->addElement('select', 'status', get_string('status', 'enrol_self'), $options);
759 $mform->addHelpButton('status', 'status', 'enrol_self');
761 $options = $this->get_newenrols_options();
762 $mform->addElement('select', 'customint6', get_string('newenrols', 'enrol_self'), $options);
763 $mform->addHelpButton('customint6', 'newenrols', 'enrol_self');
764 $mform->disabledIf('customint6', 'status', 'eq', ENROL_INSTANCE_DISABLED
);
766 $passattribs = array('size' => '20', 'maxlength' => '50');
767 $mform->addElement('passwordunmask', 'password', get_string('password', 'enrol_self'), $passattribs);
768 $mform->addHelpButton('password', 'password', 'enrol_self');
769 if (empty($instance->id
) and $this->get_config('requirepassword')) {
770 $mform->addRule('password', get_string('required'), 'required', null, 'client');
772 $mform->addRule('password', get_string('maximumchars', '', 50), 'maxlength', 50, 'server');
774 $options = $this->get_groupkey_options();
775 $mform->addElement('select', 'customint1', get_string('groupkey', 'enrol_self'), $options);
776 $mform->addHelpButton('customint1', 'groupkey', 'enrol_self');
778 $roles = $this->extend_assignable_roles($context, $instance->roleid
);
779 $mform->addElement('select', 'roleid', get_string('role', 'enrol_self'), $roles);
781 $options = array('optional' => true, 'defaultunit' => 86400);
782 $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_self'), $options);
783 $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_self');
785 $options = $this->get_expirynotify_options();
786 $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
787 $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
789 $options = array('optional' => false, 'defaultunit' => 86400);
790 $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
791 $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
792 $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
794 $options = array('optional' => true);
795 $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_self'), $options);
796 $mform->setDefault('enrolstartdate', 0);
797 $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_self');
799 $options = array('optional' => true);
800 $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_self'), $options);
801 $mform->setDefault('enrolenddate', 0);
802 $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_self');
804 $options = $this->get_longtimenosee_options();
805 $mform->addElement('select', 'customint2', get_string('longtimenosee', 'enrol_self'), $options);
806 $mform->addHelpButton('customint2', 'longtimenosee', 'enrol_self');
808 $mform->addElement('text', 'customint3', get_string('maxenrolled', 'enrol_self'));
809 $mform->addHelpButton('customint3', 'maxenrolled', 'enrol_self');
810 $mform->setType('customint3', PARAM_INT
);
812 require_once($CFG->dirroot
.'/cohort/lib.php');
814 $cohorts = array(0 => get_string('no'));
815 $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
816 if ($instance->customint5
&& !isset($allcohorts[$instance->customint5
])) {
817 $c = $DB->get_record('cohort',
818 array('id' => $instance->customint5
),
819 'id, name, idnumber, contextid, visible',
822 // Current cohort was not found because current user can not see it. Still keep it.
823 $allcohorts[$instance->customint5
] = $c;
826 foreach ($allcohorts as $c) {
827 $cohorts[$c->id
] = format_string($c->name
, true, array('context' => context
::instance_by_id($c->contextid
)));
829 $cohorts[$c->id
] .= ' ['.s($c->idnumber
).']';
832 if ($instance->customint5
&& !isset($allcohorts[$instance->customint5
])) {
833 // Somebody deleted a cohort, better keep the wrong value so that random ppl can not enrol.
834 $cohorts[$instance->customint5
] = get_string('unknowncohort', 'cohort', $instance->customint5
);
836 if (count($cohorts) > 1) {
837 $mform->addElement('select', 'customint5', get_string('cohortonly', 'enrol_self'), $cohorts);
838 $mform->addHelpButton('customint5', 'cohortonly', 'enrol_self');
840 $mform->addElement('hidden', 'customint5');
841 $mform->setType('customint5', PARAM_INT
);
842 $mform->setConstant('customint5', 0);
845 $mform->addElement('advcheckbox', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_self'));
846 $mform->addHelpButton('customint4', 'sendcoursewelcomemessage', 'enrol_self');
848 $options = array('cols' => '60', 'rows' => '8');
849 $mform->addElement('textarea', 'customtext1', get_string('customwelcomemessage', 'enrol_self'), $options);
850 $mform->addHelpButton('customtext1', 'customwelcomemessage', 'enrol_self');
852 if (enrol_accessing_via_instance($instance)) {
853 $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
854 $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
859 * We are a good plugin and don't invent our own UI/validation code path.
863 public function use_standard_editing_ui() {
868 * Perform custom validation of the data used to edit the instance.
870 * @param array $data array of ("fieldname"=>value) of submitted data
871 * @param array $files array of uploaded files "element_name"=>tmp_file_path
872 * @param object $instance The instance loaded from the DB
873 * @param context $context The context of the instance we are editing
874 * @return array of "element_name"=>"error_description" if there are errors,
875 * or an empty array if everything is OK.
878 public function edit_instance_validation($data, $files, $instance, $context) {
881 $checkpassword = false;
884 // Check the password if we are enabling the plugin again.
885 if (($instance->status
== ENROL_INSTANCE_DISABLED
) && ($data['status'] == ENROL_INSTANCE_ENABLED
)) {
886 $checkpassword = true;
889 // Check the password if the instance is enabled and the password has changed.
890 if (($data['status'] == ENROL_INSTANCE_ENABLED
) && ($instance->password
!== $data['password'])) {
891 $checkpassword = true;
894 $checkpassword = true;
897 if ($checkpassword) {
898 $require = $this->get_config('requirepassword');
899 $policy = $this->get_config('usepasswordpolicy');
900 if ($require and trim($data['password']) === '') {
901 $errors['password'] = get_string('required');
902 } else if (!empty($data['password']) && $policy) {
904 if (!check_password_policy($data['password'], $errmsg)) {
905 $errors['password'] = $errmsg;
910 if ($data['status'] == ENROL_INSTANCE_ENABLED
) {
911 if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
912 $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_self');
916 if ($data['expirynotify'] > 0 and $data['expirythreshold'] < 86400) {
917 $errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
920 // Now these ones are checked by quickforms, but we may be called by the upload enrolments tool, or a webservive.
921 if (core_text
::strlen($data['name']) > 255) {
922 $errors['name'] = get_string('err_maxlength', 'form', 255);
924 $validstatus = array_keys($this->get_status_options());
925 $validnewenrols = array_keys($this->get_newenrols_options());
926 if (core_text
::strlen($data['password']) > 50) {
927 $errors['name'] = get_string('err_maxlength', 'form', 50);
929 $validgroupkey = array_keys($this->get_groupkey_options());
930 $context = context_course
::instance($instance->courseid
);
931 $validroles = array_keys($this->extend_assignable_roles($context, $instance->roleid
));
932 $validexpirynotify = array_keys($this->get_expirynotify_options());
933 $validlongtimenosee = array_keys($this->get_longtimenosee_options());
935 'enrolstartdate' => PARAM_INT
,
936 'enrolenddate' => PARAM_INT
,
937 'name' => PARAM_TEXT
,
938 'customint1' => $validgroupkey,
939 'customint2' => $validlongtimenosee,
940 'customint3' => PARAM_INT
,
941 'customint4' => PARAM_BOOL
,
942 'customint5' => PARAM_INT
,
943 'customint6' => $validnewenrols,
944 'status' => $validstatus,
945 'enrolperiod' => PARAM_INT
,
946 'expirynotify' => $validexpirynotify,
947 'roleid' => $validroles
949 if ($data['expirynotify'] != 0) {
950 $tovalidate['expirythreshold'] = PARAM_INT
;
952 $typeerrors = $this->validate_param_types($data, $tovalidate);
953 $errors = array_merge($errors, $typeerrors);
959 * Add new instance of enrol plugin.
960 * @param object $course
961 * @param array $fields instance fields
962 * @return int id of new instance, null if can not be created
964 public function add_instance($course, array $fields = null) {
965 // In the form we are representing 2 db columns with one field.
966 if (!empty($fields) && !empty($fields['expirynotify'])) {
967 if ($fields['expirynotify'] == 2) {
968 $fields['expirynotify'] = 1;
969 $fields['notifyall'] = 1;
971 $fields['notifyall'] = 0;
975 return parent
::add_instance($course, $fields);
979 * Update instance of enrol plugin.
980 * @param stdClass $instance
981 * @param stdClass $data modified instance fields
984 public function update_instance($instance, $data) {
985 // In the form we are representing 2 db columns with one field.
986 if ($data->expirynotify
== 2) {
987 $data->expirynotify
= 1;
988 $data->notifyall
= 1;
990 $data->notifyall
= 0;
992 // Keep previous/default value of disabled expirythreshold option.
993 if (!$data->expirynotify
) {
994 $data->expirythreshold
= $instance->expirythreshold
;
996 // Add previous value of newenrols if disabled.
997 if (!isset($data->customint6
)) {
998 $data->customint6
= $instance->customint6
;
1001 return parent
::update_instance($instance, $data);
1005 * Gets a list of roles that this user can assign for the course as the default for self-enrolment.
1007 * @param context $context the context.
1008 * @param integer $defaultrole the id of the role that is set as the default for self-enrolment
1009 * @return array index is the role id, value is the role name
1011 public function extend_assignable_roles($context, $defaultrole) {
1014 $roles = get_assignable_roles($context, ROLENAME_BOTH
);
1015 if (!isset($roles[$defaultrole])) {
1016 if ($role = $DB->get_record('role', array('id' => $defaultrole))) {
1017 $roles[$defaultrole] = role_get_name($role, $context, ROLENAME_BOTH
);