MDL-50332 enrol_self: Setting form url for guests
[moodle.git] / enrol / self / lib.php
blob6c1364b4a3b78baf67eb8a282417262753075096
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 * Sets up navigation entries.
123 * @param stdClass $instancesnode
124 * @param stdClass $instance
125 * @return void
127 public function add_course_navigation($instancesnode, stdClass $instance) {
128 if ($instance->enrol !== 'self') {
129 throw new coding_exception('Invalid enrol instance type!');
132 $context = context_course::instance($instance->courseid);
133 if (has_capability('enrol/self:config', $context)) {
134 $managelink = new moodle_url('/enrol/self/edit.php', array('courseid'=>$instance->courseid, 'id'=>$instance->id));
135 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
140 * Returns edit icons for the page with list of instances
141 * @param stdClass $instance
142 * @return array
144 public function get_action_icons(stdClass $instance) {
145 global $OUTPUT;
147 if ($instance->enrol !== 'self') {
148 throw new coding_exception('invalid enrol instance!');
150 $context = context_course::instance($instance->courseid);
152 $icons = array();
154 if (has_capability('enrol/self:config', $context)) {
155 $editlink = new moodle_url("/enrol/self/edit.php", array('courseid'=>$instance->courseid, 'id'=>$instance->id));
156 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
157 array('class' => 'iconsmall')));
160 return $icons;
164 * Returns link to page which may be used to add new instance of enrolment plugin in course.
165 * @param int $courseid
166 * @return moodle_url page url
168 public function get_newinstance_link($courseid) {
169 $context = context_course::instance($courseid, MUST_EXIST);
171 if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/self:config', $context)) {
172 return NULL;
174 // Multiple instances supported - different roles with different password.
175 return new moodle_url('/enrol/self/edit.php', array('courseid'=>$courseid));
179 * Self enrol user to course
181 * @param stdClass $instance enrolment instance
182 * @param stdClass $data data needed for enrolment.
183 * @return bool|array true if enroled else eddor code and messege
185 public function enrol_self(stdClass $instance, $data = null) {
186 global $DB, $USER, $CFG;
188 // Don't enrol user if password is not passed when required.
189 if ($instance->password && !isset($data->enrolpassword)) {
190 return;
193 $timestart = time();
194 if ($instance->enrolperiod) {
195 $timeend = $timestart + $instance->enrolperiod;
196 } else {
197 $timeend = 0;
200 $this->enrol_user($instance, $USER->id, $instance->roleid, $timestart, $timeend);
202 if ($instance->password and $instance->customint1 and $data->enrolpassword !== $instance->password) {
203 // It must be a group enrolment, let's assign group too.
204 $groups = $DB->get_records('groups', array('courseid'=>$instance->courseid), 'id', 'id, enrolmentkey');
205 foreach ($groups as $group) {
206 if (empty($group->enrolmentkey)) {
207 continue;
209 if ($group->enrolmentkey === $data->enrolpassword) {
210 // Add user to group.
211 require_once($CFG->dirroot.'/group/lib.php');
212 groups_add_member($group->id, $USER->id);
213 break;
217 // Send welcome message.
218 if ($instance->customint4) {
219 $this->email_welcome_message($instance, $USER);
224 * Creates course enrol form, checks if form submitted
225 * and enrols user if necessary. It can also redirect.
227 * @param stdClass $instance
228 * @return string html text, usually a form in a text box
230 public function enrol_page_hook(stdClass $instance) {
231 global $CFG, $OUTPUT, $USER;
233 require_once("$CFG->dirroot/enrol/self/locallib.php");
235 $enrolstatus = $this->can_self_enrol($instance);
237 if (true === $enrolstatus) {
238 // This user can self enrol using this instance.
239 $form = new enrol_self_enrol_form(NULL, $instance);
240 $instanceid = optional_param('instance', 0, PARAM_INT);
241 if ($instance->id == $instanceid) {
242 if ($data = $form->get_data()) {
243 $this->enrol_self($instance, $data);
246 } else {
247 // This user can not self enrol using this instance. Using an empty form to keep
248 // the UI consistent with other enrolment plugins that returns a form.
249 $data = new stdClass();
250 $data->header = $this->get_instance_name($instance);
251 $data->info = $enrolstatus;
253 // The can_self_enrol call returns a button to the login page if the user is a
254 // guest, setting the login url to the form if that is the case.
255 $url = isguestuser() ? get_login_url() : null;
256 $form = new enrol_self_empty_form($url, $data);
259 ob_start();
260 $form->display();
261 $output = ob_get_clean();
262 return $OUTPUT->box($output);
266 * Checks if user can self enrol.
268 * @param stdClass $instance enrolment instance
269 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
270 * used by navigation to improve performance.
271 * @return bool|string true if successful, else error message or false.
273 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
274 global $CFG, $DB, $OUTPUT, $USER;
276 if ($checkuserenrolment) {
277 if (isguestuser()) {
278 // Can not enrol guest.
279 return get_string('noguestaccess', 'enrol') . $OUTPUT->continue_button(get_login_url());
281 // Check if user is already enroled.
282 if ($DB->get_record('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
283 return get_string('canntenrol', 'enrol_self');
287 if ($instance->status != ENROL_INSTANCE_ENABLED) {
288 return get_string('canntenrol', 'enrol_self');
291 if ($instance->enrolstartdate != 0 and $instance->enrolstartdate > time()) {
292 return get_string('canntenrol', 'enrol_self');
295 if ($instance->enrolenddate != 0 and $instance->enrolenddate < time()) {
296 return get_string('canntenrol', 'enrol_self');
299 if (!$instance->customint6) {
300 // New enrols not allowed.
301 return get_string('canntenrol', 'enrol_self');
304 if ($DB->record_exists('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
305 return get_string('canntenrol', 'enrol_self');
308 if ($instance->customint3 > 0) {
309 // Max enrol limit specified.
310 $count = $DB->count_records('user_enrolments', array('enrolid' => $instance->id));
311 if ($count >= $instance->customint3) {
312 // Bad luck, no more self enrolments here.
313 return get_string('maxenrolledreached', 'enrol_self');
317 if ($instance->customint5) {
318 require_once("$CFG->dirroot/cohort/lib.php");
319 if (!cohort_is_member($instance->customint5, $USER->id)) {
320 $cohort = $DB->get_record('cohort', array('id' => $instance->customint5));
321 if (!$cohort) {
322 return null;
324 $a = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
325 return markdown_to_html(get_string('cohortnonmemberinfo', 'enrol_self', $a));
329 return true;
333 * Return information for enrolment instance containing list of parameters required
334 * for enrolment, name of enrolment plugin etc.
336 * @param stdClass $instance enrolment instance
337 * @return stdClass instance info.
339 public function get_enrol_info(stdClass $instance) {
341 $instanceinfo = new stdClass();
342 $instanceinfo->id = $instance->id;
343 $instanceinfo->courseid = $instance->courseid;
344 $instanceinfo->type = $this->get_name();
345 $instanceinfo->name = $this->get_instance_name($instance);
346 $instanceinfo->status = $this->can_self_enrol($instance);
348 if ($instance->password) {
349 $instanceinfo->requiredparam = new stdClass();
350 $instanceinfo->requiredparam->enrolpassword = get_string('password', 'enrol_self');
353 // If enrolment is possible and password is required then return ws function name to get more information.
354 if ((true === $instanceinfo->status) && $instance->password) {
355 $instanceinfo->wsfunction = 'enrol_self_get_instance_info';
357 return $instanceinfo;
361 * Add new instance of enrol plugin with default settings.
362 * @param stdClass $course
363 * @return int id of new instance
365 public function add_default_instance($course) {
366 $fields = $this->get_instance_defaults();
368 if ($this->get_config('requirepassword')) {
369 $fields['password'] = generate_password(20);
372 return $this->add_instance($course, $fields);
376 * Returns defaults for new instances.
377 * @return array
379 public function get_instance_defaults() {
380 $expirynotify = $this->get_config('expirynotify');
381 if ($expirynotify == 2) {
382 $expirynotify = 1;
383 $notifyall = 1;
384 } else {
385 $notifyall = 0;
388 $fields = array();
389 $fields['status'] = $this->get_config('status');
390 $fields['roleid'] = $this->get_config('roleid');
391 $fields['enrolperiod'] = $this->get_config('enrolperiod');
392 $fields['expirynotify'] = $expirynotify;
393 $fields['notifyall'] = $notifyall;
394 $fields['expirythreshold'] = $this->get_config('expirythreshold');
395 $fields['customint1'] = $this->get_config('groupkey');
396 $fields['customint2'] = $this->get_config('longtimenosee');
397 $fields['customint3'] = $this->get_config('maxenrolled');
398 $fields['customint4'] = $this->get_config('sendcoursewelcomemessage');
399 $fields['customint5'] = 0;
400 $fields['customint6'] = $this->get_config('newenrols');
402 return $fields;
406 * Send welcome email to specified user.
408 * @param stdClass $instance
409 * @param stdClass $user user record
410 * @return void
412 protected function email_welcome_message($instance, $user) {
413 global $CFG, $DB;
415 $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST);
416 $context = context_course::instance($course->id);
418 $a = new stdClass();
419 $a->coursename = format_string($course->fullname, true, array('context'=>$context));
420 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
422 if (trim($instance->customtext1) !== '') {
423 $message = $instance->customtext1;
424 $key = array('{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}');
425 $value = array($a->coursename, $a->profileurl, fullname($user), $user->email);
426 $message = str_replace($key, $value, $message);
427 if (strpos($message, '<') === false) {
428 // Plain text only.
429 $messagetext = $message;
430 $messagehtml = text_to_html($messagetext, null, false, true);
431 } else {
432 // This is most probably the tag/newline soup known as FORMAT_MOODLE.
433 $messagehtml = format_text($message, FORMAT_MOODLE, array('context'=>$context, 'para'=>false, 'newlines'=>true, 'filter'=>true));
434 $messagetext = html_to_text($messagehtml);
436 } else {
437 $messagetext = get_string('welcometocoursetext', 'enrol_self', $a);
438 $messagehtml = text_to_html($messagetext, null, false, true);
441 $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context'=>$context)));
443 $rusers = array();
444 if (!empty($CFG->coursecontact)) {
445 $croles = explode(',', $CFG->coursecontact);
446 list($sort, $sortparams) = users_order_by_sql('u');
447 // We only use the first user.
448 $i = 0;
449 do {
450 $rusers = get_role_users($croles[$i], $context, true, '',
451 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
452 $i++;
453 } while (empty($rusers) && !empty($croles[$i]));
455 if ($rusers) {
456 $contact = reset($rusers);
457 } else {
458 $contact = core_user::get_support_user();
461 // Directly emailing welcome message rather than using messaging.
462 email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
466 * Enrol self cron support.
467 * @return void
469 public function cron() {
470 $trace = new text_progress_trace();
471 $this->sync($trace, null);
472 $this->send_expiry_notifications($trace);
476 * Sync all meta course links.
478 * @param progress_trace $trace
479 * @param int $courseid one course, empty mean all
480 * @return int 0 means ok, 1 means error, 2 means plugin disabled
482 public function sync(progress_trace $trace, $courseid = null) {
483 global $DB;
485 if (!enrol_is_enabled('self')) {
486 $trace->finished();
487 return 2;
490 // Unfortunately this may take a long time, execution can be interrupted safely here.
491 core_php_time_limit::raise();
492 raise_memory_limit(MEMORY_HUGE);
494 $trace->output('Verifying self-enrolments...');
496 $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE, 'courselevel'=>CONTEXT_COURSE);
497 $coursesql = "";
498 if ($courseid) {
499 $coursesql = "AND e.courseid = :courseid";
500 $params['courseid'] = $courseid;
503 // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set)
504 // and that user accessed course at least once too (=== user_lastaccess record exists).
506 // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
507 $sql = "SELECT e.*, ue.userid
508 FROM {user_enrolments} ue
509 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
510 JOIN {user} u ON u.id = ue.userid
511 WHERE :now - u.lastaccess > e.customint2
512 $coursesql";
513 $rs = $DB->get_recordset_sql($sql, $params);
514 foreach ($rs as $instance) {
515 $userid = $instance->userid;
516 unset($instance->userid);
517 $this->unenrol_user($instance, $userid);
518 $days = $instance->customint2 / 60*60*24;
519 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not log in for at least $days days", 1);
521 $rs->close();
523 // Now unenrol from course user did not visit for a long time.
524 $sql = "SELECT e.*, ue.userid
525 FROM {user_enrolments} ue
526 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
527 JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)
528 WHERE :now - ul.timeaccess > e.customint2
529 $coursesql";
530 $rs = $DB->get_recordset_sql($sql, $params);
531 foreach ($rs as $instance) {
532 $userid = $instance->userid;
533 unset($instance->userid);
534 $this->unenrol_user($instance, $userid);
535 $days = $instance->customint2 / 60*60*24;
536 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not access course for at least $days days", 1);
538 $rs->close();
540 $trace->output('...user self-enrolment updates finished.');
541 $trace->finished();
543 $this->process_expirations($trace, $courseid);
545 return 0;
549 * Returns the user who is responsible for self enrolments in given instance.
551 * Usually it is the first editing teacher - the person with "highest authority"
552 * as defined by sort_by_roleassignment_authority() having 'enrol/self:manage'
553 * capability.
555 * @param int $instanceid enrolment instance id
556 * @return stdClass user record
558 protected function get_enroller($instanceid) {
559 global $DB;
561 if ($this->lasternollerinstanceid == $instanceid and $this->lasternoller) {
562 return $this->lasternoller;
565 $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST);
566 $context = context_course::instance($instance->courseid);
568 if ($users = get_enrolled_users($context, 'enrol/self:manage')) {
569 $users = sort_by_roleassignment_authority($users, $context);
570 $this->lasternoller = reset($users);
571 unset($users);
572 } else {
573 $this->lasternoller = parent::get_enroller($instanceid);
576 $this->lasternollerinstanceid = $instanceid;
578 return $this->lasternoller;
582 * Gets an array of the user enrolment actions.
584 * @param course_enrolment_manager $manager
585 * @param stdClass $ue A user enrolment object
586 * @return array An array of user_enrolment_actions
588 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
589 $actions = array();
590 $context = $manager->get_context();
591 $instance = $ue->enrolmentinstance;
592 $params = $manager->get_moodlepage()->url->params();
593 $params['ue'] = $ue->id;
594 if ($this->allow_unenrol($instance) && has_capability("enrol/self:unenrol", $context)) {
595 $url = new moodle_url('/enrol/unenroluser.php', $params);
596 $actions[] = new user_enrolment_action(new pix_icon('t/delete', ''), get_string('unenrol', 'enrol'), $url, array('class'=>'unenrollink', 'rel'=>$ue->id));
598 if ($this->allow_manage($instance) && has_capability("enrol/self:manage", $context)) {
599 $url = new moodle_url('/enrol/editenrolment.php', $params);
600 $actions[] = new user_enrolment_action(new pix_icon('t/edit', ''), get_string('edit'), $url, array('class'=>'editenrollink', 'rel'=>$ue->id));
602 return $actions;
606 * Restore instance and map settings.
608 * @param restore_enrolments_structure_step $step
609 * @param stdClass $data
610 * @param stdClass $course
611 * @param int $oldid
613 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
614 global $DB;
615 if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
616 $merge = false;
617 } else {
618 $merge = array(
619 'courseid' => $data->courseid,
620 'enrol' => $this->get_name(),
621 'roleid' => $data->roleid,
624 if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
625 $instance = reset($instances);
626 $instanceid = $instance->id;
627 } else {
628 if (!empty($data->customint5)) {
629 if ($step->get_task()->is_samesite()) {
630 // Keep cohort restriction unchanged - we are on the same site.
631 } else {
632 // Use some id that can not exist in order to prevent self enrolment,
633 // because we do not know what cohort it is in this site.
634 $data->customint5 = -1;
637 $instanceid = $this->add_instance($course, (array)$data);
639 $step->set_mapping('enrol', $oldid, $instanceid);
643 * Restore user enrolment.
645 * @param restore_enrolments_structure_step $step
646 * @param stdClass $data
647 * @param stdClass $instance
648 * @param int $oldinstancestatus
649 * @param int $userid
651 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
652 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
656 * Restore role assignment.
658 * @param stdClass $instance
659 * @param int $roleid
660 * @param int $userid
661 * @param int $contextid
663 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
664 // This is necessary only because we may migrate other types to this instance,
665 // we do not use component in manual or self enrol.
666 role_assign($roleid, $userid, $contextid, '', 0);
670 * Is it possible to delete enrol instance via standard UI?
672 * @param stdClass $instance
673 * @return bool
675 public function can_delete_instance($instance) {
676 $context = context_course::instance($instance->courseid);
677 return has_capability('enrol/self:config', $context);
681 * Is it possible to hide/show enrol instance via standard UI?
683 * @param stdClass $instance
684 * @return bool
686 public function can_hide_show_instance($instance) {
687 $context = context_course::instance($instance->courseid);
688 return has_capability('enrol/self:config', $context);