MDL-59369 enrol: Introduce data-action attribute for enrol action links
[moodle.git] / enrol / self / lib.php
CommitLineData
df997f84 1<?php
df997f84
PS
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Self enrolment plugin.
19 *
d9669db9 20 * @package enrol_self
c1dfc4a8
PS
21 * @copyright 2010 Petr Skoda {@link http://skodak.org}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df997f84
PS
23 */
24
25/**
26 * Self enrolment plugin implementation.
27 * @author Petr Skoda
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 */
30class enrol_self_plugin extends enrol_plugin {
31
8a486fdb
PS
32 protected $lasternoller = null;
33 protected $lasternollerinstanceid = 0;
34
9a13c5af
PS
35 /**
36 * Returns optional enrolment information icons.
37 *
38 * This is used in course list for quick overview of enrolment options.
39 *
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.
43 *
44 * @param array $instances all enrol instances of this type in one course
45 * @return array of pix_icon
46 */
3ead116a 47 public function get_info_icons(array $instances) {
9a13c5af
PS
48 $key = false;
49 $nokey = false;
50 foreach ($instances as $instance) {
d92e23cf
MG
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.
e1fa177c
PS
56 continue;
57 }
9a13c5af
PS
58 if ($instance->password or $instance->customint1) {
59 $key = true;
60 } else {
61 $nokey = true;
62 }
63 }
64 $icons = array();
65 if ($nokey) {
66 $icons[] = new pix_icon('withoutkey', get_string('pluginname', 'enrol_self'), 'enrol_self');
67 }
68 if ($key) {
69 $icons[] = new pix_icon('withkey', get_string('pluginname', 'enrol_self'), 'enrol_self');
70 }
71 return $icons;
3ead116a
PS
72 }
73
df997f84
PS
74 /**
75 * Returns localised name of enrol instance
76 *
d9669db9 77 * @param stdClass $instance (null is accepted too)
df997f84
PS
78 * @return string
79 */
80 public function get_instance_name($instance) {
81 global $DB;
82
83 if (empty($instance->name)) {
84 if (!empty($instance->roleid) and $role = $DB->get_record('role', array('id'=>$instance->roleid))) {
55bcef29 85 $role = ' (' . role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)) . ')';
df997f84
PS
86 } else {
87 $role = '';
88 }
89 $enrol = $this->get_name();
90 return get_string('pluginname', 'enrol_'.$enrol) . $role;
91 } else {
92 return format_string($instance->name);
93 }
94 }
95
96 public function roles_protected() {
d9669db9 97 // Users may tweak the roles later.
df997f84
PS
98 return false;
99 }
100
101 public function allow_unenrol(stdClass $instance) {
d9669db9 102 // Users with unenrol cap may unenrol other users manually manually.
df997f84
PS
103 return true;
104 }
105
106 public function allow_manage(stdClass $instance) {
d9669db9 107 // Users with manage cap may tweak period and status.
df997f84
PS
108 return true;
109 }
110
217d0397 111 public function show_enrolme_link(stdClass $instance) {
dd6b1f15 112
cc1b5015 113 if (true !== $this->can_self_enrol($instance, false)) {
e1fa177c
PS
114 return false;
115 }
116
dd6b1f15 117 return true;
217d0397
PS
118 }
119
df997f84 120 /**
60010fd6
DW
121 * Return true if we can add a new instance to this course.
122 *
df997f84 123 * @param int $courseid
60010fd6 124 * @return boolean
df997f84 125 */
60010fd6 126 public function can_add_instance($courseid) {
55bcef29 127 $context = context_course::instance($courseid, MUST_EXIST);
c9f9c900 128
c03ae033 129 if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/self:config', $context)) {
60010fd6 130 return false;
df997f84 131 }
60010fd6
DW
132
133 return true;
df997f84
PS
134 }
135
85d1c53a
RT
136 /**
137 * Self enrol user to course
138 *
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
142 */
143 public function enrol_self(stdClass $instance, $data = null) {
735c3a7b 144 global $DB, $USER, $CFG;
85d1c53a
RT
145
146 // Don't enrol user if password is not passed when required.
147 if ($instance->password && !isset($data->enrolpassword)) {
148 return;
149 }
150
151 $timestart = time();
152 if ($instance->enrolperiod) {
153 $timeend = $timestart + $instance->enrolperiod;
154 } else {
155 $timeend = 0;
156 }
157
158 $this->enrol_user($instance, $USER->id, $instance->roleid, $timestart, $timeend);
85d1c53a
RT
159
160 if ($instance->password and $instance->customint1 and $data->enrolpassword !== $instance->password) {
cc1b5015 161 // It must be a group enrolment, let's assign group too.
85d1c53a
RT
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;
166 }
167 if ($group->enrolmentkey === $data->enrolpassword) {
735c3a7b
RT
168 // Add user to group.
169 require_once($CFG->dirroot.'/group/lib.php');
85d1c53a
RT
170 groups_add_member($group->id, $USER->id);
171 break;
172 }
173 }
174 }
175 // Send welcome message.
bbf401be 176 if ($instance->customint4 != ENROL_DO_NOT_SEND_EMAIL) {
85d1c53a
RT
177 $this->email_welcome_message($instance, $USER);
178 }
179 }
180
df997f84
PS
181 /**
182 * Creates course enrol form, checks if form submitted
183 * and enrols user if necessary. It can also redirect.
184 *
185 * @param stdClass $instance
186 * @return string html text, usually a form in a text box
187 */
188 public function enrol_page_hook(stdClass $instance) {
85d1c53a
RT
189 global $CFG, $OUTPUT, $USER;
190
191 require_once("$CFG->dirroot/enrol/self/locallib.php");
192
193 $enrolstatus = $this->can_self_enrol($instance);
194
cc1b5015 195 if (true === $enrolstatus) {
8f338081 196 // This user can self enrol using this instance.
60010fd6 197 $form = new enrol_self_enrol_form(null, $instance);
cc1b5015
RT
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);
202 }
85d1c53a 203 }
cf6d62fc 204 } else {
8f338081
DM
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;
012d14e8
DM
210
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);
cc1b5015 215 }
8f338081
DM
216
217 ob_start();
218 $form->display();
219 $output = ob_get_clean();
220 return $OUTPUT->box($output);
85d1c53a
RT
221 }
222
223 /**
224 * Checks if user can self enrol.
225 *
226 * @param stdClass $instance enrolment instance
cc1b5015
RT
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.
85d1c53a 230 */
cc1b5015 231 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
9c54a0ab 232 global $CFG, $DB, $OUTPUT, $USER;
df997f84 233
cc1b5015
RT
234 if ($checkuserenrolment) {
235 if (isguestuser()) {
236 // Can not enrol guest.
9c54a0ab 237 return get_string('noguestaccess', 'enrol') . $OUTPUT->continue_button(get_login_url());
cc1b5015
RT
238 }
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');
242 }
243 }
244
245 if ($instance->status != ENROL_INSTANCE_ENABLED) {
246 return get_string('canntenrol', 'enrol_self');
df997f84
PS
247 }
248
03531e27 249 if ($instance->enrolstartdate != 0 and $instance->enrolstartdate > time()) {
933f0d96 250 return get_string('canntenrolearly', 'enrol_self', userdate($instance->enrolstartdate));
df997f84
PS
251 }
252
03531e27 253 if ($instance->enrolenddate != 0 and $instance->enrolenddate < time()) {
933f0d96 254 return get_string('canntenrollate', 'enrol_self', userdate($instance->enrolenddate));
df997f84
PS
255 }
256
e1fa177c
PS
257 if (!$instance->customint6) {
258 // New enrols not allowed.
cc1b5015 259 return get_string('canntenrol', 'enrol_self');
85d1c53a
RT
260 }
261
262 if ($DB->record_exists('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
cc1b5015 263 return get_string('canntenrol', 'enrol_self');
85d1c53a
RT
264 }
265
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.
cc1b5015 271 return get_string('maxenrolledreached', 'enrol_self');
85d1c53a 272 }
e1fa177c
PS
273 }
274
dd6b1f15
PS
275 if ($instance->customint5) {
276 require_once("$CFG->dirroot/cohort/lib.php");
277 if (!cohort_is_member($instance->customint5, $USER->id)) {
85d1c53a 278 $cohort = $DB->get_record('cohort', array('id' => $instance->customint5));
dd6b1f15
PS
279 if (!$cohort) {
280 return null;
281 }
85d1c53a 282 $a = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
cc1b5015 283 return markdown_to_html(get_string('cohortnonmemberinfo', 'enrol_self', $a));
dd6b1f15
PS
284 }
285 }
286
85d1c53a
RT
287 return true;
288 }
52d58821 289
85d1c53a
RT
290 /**
291 * Return information for enrolment instance containing list of parameters required
292 * for enrolment, name of enrolment plugin etc.
293 *
294 * @param stdClass $instance enrolment instance
295 * @return stdClass instance info.
296 */
297 public function get_enrol_info(stdClass $instance) {
df997f84 298
85d1c53a
RT
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);
cc1b5015 304 $instanceinfo->status = $this->can_self_enrol($instance);
df997f84 305
85d1c53a
RT
306 if ($instance->password) {
307 $instanceinfo->requiredparam = new stdClass();
308 $instanceinfo->requiredparam->enrolpassword = get_string('password', 'enrol_self');
df997f84
PS
309 }
310
be9bf94e
RT
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';
314 }
85d1c53a 315 return $instanceinfo;
df997f84
PS
316 }
317
df997f84
PS
318 /**
319 * Add new instance of enrol plugin with default settings.
d9669db9 320 * @param stdClass $course
df997f84
PS
321 * @return int id of new instance
322 */
323 public function add_default_instance($course) {
eac37ff4
PS
324 $fields = $this->get_instance_defaults();
325
326 if ($this->get_config('requirepassword')) {
327 $fields['password'] = generate_password(20);
328 }
329
330 return $this->add_instance($course, $fields);
331 }
332
333 /**
334 * Returns defaults for new instances.
335 * @return array
336 */
337 public function get_instance_defaults() {
338 $expirynotify = $this->get_config('expirynotify');
8a486fdb
PS
339 if ($expirynotify == 2) {
340 $expirynotify = 1;
341 $notifyall = 1;
342 } else {
343 $notifyall = 0;
344 }
df997f84 345
eac37ff4
PS
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;
e1fa177c 358 $fields['customint6'] = $this->get_config('newenrols');
eac37ff4
PS
359
360 return $fields;
df997f84
PS
361 }
362
363 /**
d9669db9 364 * Send welcome email to specified user.
df997f84 365 *
d9669db9
PS
366 * @param stdClass $instance
367 * @param stdClass $user user record
df997f84
PS
368 * @return void
369 */
370 protected function email_welcome_message($instance, $user) {
371 global $CFG, $DB;
372
74df2951 373 $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST);
08962926 374 $context = context_course::instance($course->id);
df997f84 375
94b9c2e8 376 $a = new stdClass();
08962926 377 $a->coursename = format_string($course->fullname, true, array('context'=>$context));
6e0b0a39
PS
378 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
379
380 if (trim($instance->customtext1) !== '') {
381 $message = $instance->customtext1;
ab2fa7a7
LPS
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);
08962926
PS
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);
393 }
df997f84 394 } else {
08962926
PS
395 $messagetext = get_string('welcometocoursetext', 'enrol_self', $a);
396 $messagehtml = text_to_html($messagetext, null, false, true);
df997f84
PS
397 }
398
08962926 399 $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context'=>$context)));
df997f84 400
0ab8b337
SL
401 $sendoption = $instance->customint4;
402 $contact = $this->get_welcome_email_contact($sendoption, $context);
df997f84 403
d9669db9 404 // Directly emailing welcome message rather than using messaging.
08962926 405 email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
df997f84 406 }
770ab27f
PS
407
408 /**
d9669db9 409 * Enrol self cron support.
770ab27f
PS
410 * @return void
411 */
412 public function cron() {
5d549ffc
PS
413 $trace = new text_progress_trace();
414 $this->sync($trace, null);
415 $this->send_expiry_notifications($trace);
90bd8965
PS
416 }
417
418 /**
419 * Sync all meta course links.
420 *
5d549ffc 421 * @param progress_trace $trace
90bd8965 422 * @param int $courseid one course, empty mean all
90bd8965
PS
423 * @return int 0 means ok, 1 means error, 2 means plugin disabled
424 */
5d549ffc 425 public function sync(progress_trace $trace, $courseid = null) {
770ab27f
PS
426 global $DB;
427
428 if (!enrol_is_enabled('self')) {
5d549ffc 429 $trace->finished();
90bd8965 430 return 2;
770ab27f
PS
431 }
432
90bd8965 433 // Unfortunately this may take a long time, execution can be interrupted safely here.
3ef7279f 434 core_php_time_limit::raise();
90bd8965
PS
435 raise_memory_limit(MEMORY_HUGE);
436
5d549ffc 437 $trace->output('Verifying self-enrolments...');
770ab27f 438
90bd8965
PS
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;
444 }
770ab27f 445
d9669db9
PS
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).
cc1d9893 448
90bd8965 449 // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
770ab27f
PS
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
90bd8965
PS
454 WHERE :now - u.lastaccess > e.customint2
455 $coursesql";
456 $rs = $DB->get_recordset_sql($sql, $params);
770ab27f
PS
457 foreach ($rs as $instance) {
458 $userid = $instance->userid;
459 unset($instance->userid);
90bd8965 460 $this->unenrol_user($instance, $userid);
5d549ffc
PS
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);
770ab27f
PS
463 }
464 $rs->close();
465
d9669db9 466 // Now unenrol from course user did not visit for a long time.
770ab27f
PS
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)
90bd8965
PS
471 WHERE :now - ul.timeaccess > e.customint2
472 $coursesql";
473 $rs = $DB->get_recordset_sql($sql, $params);
770ab27f
PS
474 foreach ($rs as $instance) {
475 $userid = $instance->userid;
476 unset($instance->userid);
90bd8965 477 $this->unenrol_user($instance, $userid);
90bd8965 478 $days = $instance->customint2 / 60*60*24;
5d549ffc 479 $trace->output("unenrolling user $userid from course $instance->courseid as they have did not access course for at least $days days", 1);
770ab27f
PS
480 }
481 $rs->close();
482
5d549ffc
PS
483 $trace->output('...user self-enrolment updates finished.');
484 $trace->finished();
90bd8965 485
d8f22c49
PS
486 $this->process_expirations($trace, $courseid);
487
90bd8965 488 return 0;
770ab27f 489 }
8c6e0ebe 490
8a486fdb
PS
491 /**
492 * Returns the user who is responsible for self enrolments in given instance.
493 *
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.
497 *
498 * @param int $instanceid enrolment instance id
499 * @return stdClass user record
500 */
501 protected function get_enroller($instanceid) {
502 global $DB;
503
504 if ($this->lasternollerinstanceid == $instanceid and $this->lasternoller) {
505 return $this->lasternoller;
506 }
507
508 $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST);
509 $context = context_course::instance($instance->courseid);
510
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);
517 }
518
519 $this->lasternollerinstanceid = $instanceid;
520
521 return $this->lasternoller;
522 }
523
524 /**
d9669db9 525 * Gets an array of the user enrolment actions.
8c6e0ebe
SH
526 *
527 * @param course_enrolment_manager $manager
528 * @param stdClass $ue A user enrolment object
529 * @return array An array of user_enrolment_actions
530 */
531 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
532 $actions = array();
533 $context = $manager->get_context();
534 $instance = $ue->enrolmentinstance;
535 $params = $manager->get_moodlepage()->url->params();
536 $params['ue'] = $ue->id;
537 if ($this->allow_unenrol($instance) && has_capability("enrol/self:unenrol", $context)) {
282b5cc7 538 $url = new moodle_url('/enrol/unenroluser.php', $params);
fd0a43be
JP
539 $actionparams = array('class' => 'unenrollink', 'rel' => $ue->id, 'data-action' => ENROL_ACTION_UNENROL);
540 $actions[] = new user_enrolment_action(new pix_icon('t/delete', ''), get_string('unenrol', 'enrol'), $url,
541 $actionparams);
8c6e0ebe
SH
542 }
543 if ($this->allow_manage($instance) && has_capability("enrol/self:manage", $context)) {
0aaea0d2 544 $url = new moodle_url('/enrol/editenrolment.php', $params);
fd0a43be
JP
545 $actionparams = array('class' => 'editenrollink', 'rel' => $ue->id, 'data-action' => ENROL_ACTION_EDIT);
546 $actions[] = new user_enrolment_action(new pix_icon('t/edit', ''), get_string('edit'), $url, $actionparams);
8c6e0ebe
SH
547 }
548 return $actions;
549 }
df997f84 550
7a7b8a1f
PS
551 /**
552 * Restore instance and map settings.
553 *
554 * @param restore_enrolments_structure_step $step
555 * @param stdClass $data
556 * @param stdClass $course
557 * @param int $oldid
558 */
559 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
560 global $DB;
561 if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
562 $merge = false;
563 } else {
564 $merge = array(
565 'courseid' => $data->courseid,
566 'enrol' => $this->get_name(),
92253b15 567 'status' => $data->status,
7a7b8a1f
PS
568 'roleid' => $data->roleid,
569 );
570 }
571 if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
572 $instance = reset($instances);
573 $instanceid = $instance->id;
574 } else {
575 if (!empty($data->customint5)) {
576 if ($step->get_task()->is_samesite()) {
577 // Keep cohort restriction unchanged - we are on the same site.
578 } else {
579 // Use some id that can not exist in order to prevent self enrolment,
580 // because we do not know what cohort it is in this site.
581 $data->customint5 = -1;
582 }
583 }
584 $instanceid = $this->add_instance($course, (array)$data);
585 }
586 $step->set_mapping('enrol', $oldid, $instanceid);
587 }
df997f84 588
7a7b8a1f
PS
589 /**
590 * Restore user enrolment.
591 *
592 * @param restore_enrolments_structure_step $step
593 * @param stdClass $data
594 * @param stdClass $instance
595 * @param int $oldinstancestatus
596 * @param int $userid
597 */
598 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
599 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
600 }
601
602 /**
603 * Restore role assignment.
604 *
605 * @param stdClass $instance
606 * @param int $roleid
607 * @param int $userid
608 * @param int $contextid
609 */
610 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
611 // This is necessary only because we may migrate other types to this instance,
612 // we do not use component in manual or self enrol.
613 role_assign($roleid, $userid, $contextid, '', 0);
f2a9be5f 614 }
ee9e079d
DN
615
616 /**
617 * Is it possible to delete enrol instance via standard UI?
618 *
b5a289c4 619 * @param stdClass $instance
ee9e079d
DN
620 * @return bool
621 */
622 public function can_delete_instance($instance) {
623 $context = context_course::instance($instance->courseid);
624 return has_capability('enrol/self:config', $context);
625 }
b5a289c4
DNA
626
627 /**
628 * Is it possible to hide/show enrol instance via standard UI?
629 *
630 * @param stdClass $instance
631 * @return bool
632 */
633 public function can_hide_show_instance($instance) {
634 $context = context_course::instance($instance->courseid);
d950ba1b
MN
635
636 if (!has_capability('enrol/self:config', $context)) {
637 return false;
638 }
639
640 // If the instance is currently disabled, before it can be enabled,
641 // we must check whether the password meets the password policies.
642 if ($instance->status == ENROL_INSTANCE_DISABLED) {
643 if ($this->get_config('requirepassword')) {
644 if (empty($instance->password)) {
645 return false;
646 }
647 }
648 // Only check the password if it is set.
649 if (!empty($instance->password) && $this->get_config('usepasswordpolicy')) {
650 if (!check_password_policy($instance->password, $errmsg)) {
651 return false;
652 }
653 }
654 }
655
656 return true;
b5a289c4 657 }
60010fd6
DW
658
659 /**
660 * Return an array of valid options for the status.
661 *
662 * @return array
663 */
664 protected function get_status_options() {
665 $options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
666 ENROL_INSTANCE_DISABLED => get_string('no'));
667 return $options;
668 }
669
670 /**
671 * Return an array of valid options for the newenrols property.
672 *
673 * @return array
674 */
675 protected function get_newenrols_options() {
676 $options = array(1 => get_string('yes'), 0 => get_string('no'));
677 return $options;
678 }
679
680 /**
681 * Return an array of valid options for the groupkey property.
682 *
683 * @return array
684 */
685 protected function get_groupkey_options() {
686 $options = array(1 => get_string('yes'), 0 => get_string('no'));
687 return $options;
688 }
689
690 /**
691 * Return an array of valid options for the expirynotify property.
692 *
693 * @return array
694 */
695 protected function get_expirynotify_options() {
696 $options = array(0 => get_string('no'),
697 1 => get_string('expirynotifyenroller', 'core_enrol'),
698 2 => get_string('expirynotifyall', 'core_enrol'));
699 return $options;
700 }
701
702 /**
703 * Return an array of valid options for the longtimenosee property.
704 *
705 * @return array
706 */
707 protected function get_longtimenosee_options() {
708 $options = array(0 => get_string('never'),
709 1800 * 3600 * 24 => get_string('numdays', '', 1800),
710 1000 * 3600 * 24 => get_string('numdays', '', 1000),
711 365 * 3600 * 24 => get_string('numdays', '', 365),
712 180 * 3600 * 24 => get_string('numdays', '', 180),
713 150 * 3600 * 24 => get_string('numdays', '', 150),
714 120 * 3600 * 24 => get_string('numdays', '', 120),
715 90 * 3600 * 24 => get_string('numdays', '', 90),
716 60 * 3600 * 24 => get_string('numdays', '', 60),
717 30 * 3600 * 24 => get_string('numdays', '', 30),
718 21 * 3600 * 24 => get_string('numdays', '', 21),
719 14 * 3600 * 24 => get_string('numdays', '', 14),
720 7 * 3600 * 24 => get_string('numdays', '', 7));
721 return $options;
722 }
723
724 /**
725 * Add elements to the edit instance form.
726 *
727 * @param stdClass $instance
728 * @param MoodleQuickForm $mform
729 * @param context $context
730 * @return bool
731 */
732 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
733 global $CFG;
734
735 // Merge these two settings to one value for the single selection element.
736 if ($instance->notifyall and $instance->expirynotify) {
737 $instance->expirynotify = 2;
738 }
739 unset($instance->notifyall);
740
741 $nameattribs = array('size' => '20', 'maxlength' => '255');
742 $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
743 $mform->setType('name', PARAM_TEXT);
744 $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');
745
746 $options = $this->get_status_options();
747 $mform->addElement('select', 'status', get_string('status', 'enrol_self'), $options);
748 $mform->addHelpButton('status', 'status', 'enrol_self');
749
750 $options = $this->get_newenrols_options();
751 $mform->addElement('select', 'customint6', get_string('newenrols', 'enrol_self'), $options);
752 $mform->addHelpButton('customint6', 'newenrols', 'enrol_self');
753 $mform->disabledIf('customint6', 'status', 'eq', ENROL_INSTANCE_DISABLED);
754
755 $passattribs = array('size' => '20', 'maxlength' => '50');
756 $mform->addElement('passwordunmask', 'password', get_string('password', 'enrol_self'), $passattribs);
757 $mform->addHelpButton('password', 'password', 'enrol_self');
758 if (empty($instance->id) and $this->get_config('requirepassword')) {
759 $mform->addRule('password', get_string('required'), 'required', null, 'client');
760 }
761 $mform->addRule('password', get_string('maximumchars', '', 50), 'maxlength', 50, 'server');
762
763 $options = $this->get_groupkey_options();
764 $mform->addElement('select', 'customint1', get_string('groupkey', 'enrol_self'), $options);
765 $mform->addHelpButton('customint1', 'groupkey', 'enrol_self');
766
767 $roles = $this->extend_assignable_roles($context, $instance->roleid);
768 $mform->addElement('select', 'roleid', get_string('role', 'enrol_self'), $roles);
769
770 $options = array('optional' => true, 'defaultunit' => 86400);
771 $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_self'), $options);
772 $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_self');
773
774 $options = $this->get_expirynotify_options();
775 $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
776 $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
777
778 $options = array('optional' => false, 'defaultunit' => 86400);
779 $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
780 $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
781 $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
782
783 $options = array('optional' => true);
784 $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_self'), $options);
785 $mform->setDefault('enrolstartdate', 0);
786 $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_self');
787
788 $options = array('optional' => true);
789 $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_self'), $options);
790 $mform->setDefault('enrolenddate', 0);
791 $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_self');
792
793 $options = $this->get_longtimenosee_options();
794 $mform->addElement('select', 'customint2', get_string('longtimenosee', 'enrol_self'), $options);
795 $mform->addHelpButton('customint2', 'longtimenosee', 'enrol_self');
796
797 $mform->addElement('text', 'customint3', get_string('maxenrolled', 'enrol_self'));
798 $mform->addHelpButton('customint3', 'maxenrolled', 'enrol_self');
799 $mform->setType('customint3', PARAM_INT);
800
801 require_once($CFG->dirroot.'/cohort/lib.php');
802
803 $cohorts = array(0 => get_string('no'));
804 $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
805 if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
806 $c = $DB->get_record('cohort',
807 array('id' => $instance->customint5),
808 'id, name, idnumber, contextid, visible',
809 IGNORE_MISSING);
810 if ($c) {
811 // Current cohort was not found because current user can not see it. Still keep it.
812 $allcohorts[$instance->customint5] = $c;
813 }
814 }
815 foreach ($allcohorts as $c) {
816 $cohorts[$c->id] = format_string($c->name, true, array('context' => context::instance_by_id($c->contextid)));
817 if ($c->idnumber) {
818 $cohorts[$c->id] .= ' ['.s($c->idnumber).']';
819 }
820 }
821 if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
822 // Somebody deleted a cohort, better keep the wrong value so that random ppl can not enrol.
823 $cohorts[$instance->customint5] = get_string('unknowncohort', 'cohort', $instance->customint5);
824 }
825 if (count($cohorts) > 1) {
826 $mform->addElement('select', 'customint5', get_string('cohortonly', 'enrol_self'), $cohorts);
827 $mform->addHelpButton('customint5', 'cohortonly', 'enrol_self');
828 } else {
829 $mform->addElement('hidden', 'customint5');
830 $mform->setType('customint5', PARAM_INT);
831 $mform->setConstant('customint5', 0);
832 }
833
0ab8b337
SL
834 $mform->addElement('select', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_self'),
835 enrol_send_welcome_email_options());
60010fd6
DW
836 $mform->addHelpButton('customint4', 'sendcoursewelcomemessage', 'enrol_self');
837
838 $options = array('cols' => '60', 'rows' => '8');
839 $mform->addElement('textarea', 'customtext1', get_string('customwelcomemessage', 'enrol_self'), $options);
840 $mform->addHelpButton('customtext1', 'customwelcomemessage', 'enrol_self');
841
842 if (enrol_accessing_via_instance($instance)) {
843 $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
844 $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
845 }
846 }
847
848 /**
849 * We are a good plugin and don't invent our own UI/validation code path.
850 *
851 * @return boolean
852 */
853 public function use_standard_editing_ui() {
854 return true;
855 }
856
857 /**
858 * Perform custom validation of the data used to edit the instance.
859 *
860 * @param array $data array of ("fieldname"=>value) of submitted data
861 * @param array $files array of uploaded files "element_name"=>tmp_file_path
862 * @param object $instance The instance loaded from the DB
863 * @param context $context The context of the instance we are editing
864 * @return array of "element_name"=>"error_description" if there are errors,
865 * or an empty array if everything is OK.
866 * @return void
867 */
868 public function edit_instance_validation($data, $files, $instance, $context) {
869 $errors = array();
870
871 $checkpassword = false;
872
873 if ($instance->id) {
874 // Check the password if we are enabling the plugin again.
875 if (($instance->status == ENROL_INSTANCE_DISABLED) && ($data['status'] == ENROL_INSTANCE_ENABLED)) {
876 $checkpassword = true;
877 }
878
879 // Check the password if the instance is enabled and the password has changed.
880 if (($data['status'] == ENROL_INSTANCE_ENABLED) && ($instance->password !== $data['password'])) {
881 $checkpassword = true;
882 }
883 } else {
884 $checkpassword = true;
885 }
886
887 if ($checkpassword) {
888 $require = $this->get_config('requirepassword');
889 $policy = $this->get_config('usepasswordpolicy');
890 if ($require and trim($data['password']) === '') {
891 $errors['password'] = get_string('required');
892 } else if (!empty($data['password']) && $policy) {
893 $errmsg = '';
894 if (!check_password_policy($data['password'], $errmsg)) {
895 $errors['password'] = $errmsg;
896 }
897 }
898 }
899
900 if ($data['status'] == ENROL_INSTANCE_ENABLED) {
901 if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
902 $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_self');
903 }
904 }
905
906 if ($data['expirynotify'] > 0 and $data['expirythreshold'] < 86400) {
907 $errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
908 }
909
910 // Now these ones are checked by quickforms, but we may be called by the upload enrolments tool, or a webservive.
911 if (core_text::strlen($data['name']) > 255) {
912 $errors['name'] = get_string('err_maxlength', 'form', 255);
913 }
914 $validstatus = array_keys($this->get_status_options());
915 $validnewenrols = array_keys($this->get_newenrols_options());
916 if (core_text::strlen($data['password']) > 50) {
917 $errors['name'] = get_string('err_maxlength', 'form', 50);
918 }
919 $validgroupkey = array_keys($this->get_groupkey_options());
920 $context = context_course::instance($instance->courseid);
921 $validroles = array_keys($this->extend_assignable_roles($context, $instance->roleid));
922 $validexpirynotify = array_keys($this->get_expirynotify_options());
923 $validlongtimenosee = array_keys($this->get_longtimenosee_options());
924 $tovalidate = array(
925 'enrolstartdate' => PARAM_INT,
926 'enrolenddate' => PARAM_INT,
927 'name' => PARAM_TEXT,
928 'customint1' => $validgroupkey,
929 'customint2' => $validlongtimenosee,
930 'customint3' => PARAM_INT,
0ab8b337 931 'customint4' => PARAM_INT,
60010fd6
DW
932 'customint5' => PARAM_INT,
933 'customint6' => $validnewenrols,
934 'status' => $validstatus,
935 'enrolperiod' => PARAM_INT,
936 'expirynotify' => $validexpirynotify,
937 'roleid' => $validroles
938 );
939 if ($data['expirynotify'] != 0) {
940 $tovalidate['expirythreshold'] = PARAM_INT;
941 }
942 $typeerrors = $this->validate_param_types($data, $tovalidate);
943 $errors = array_merge($errors, $typeerrors);
944
945 return $errors;
946 }
947
948 /**
949 * Add new instance of enrol plugin.
950 * @param object $course
951 * @param array $fields instance fields
952 * @return int id of new instance, null if can not be created
953 */
954 public function add_instance($course, array $fields = null) {
955 // In the form we are representing 2 db columns with one field.
956 if (!empty($fields) && !empty($fields['expirynotify'])) {
957 if ($fields['expirynotify'] == 2) {
958 $fields['expirynotify'] = 1;
959 $fields['notifyall'] = 1;
960 } else {
961 $fields['notifyall'] = 0;
962 }
963 }
964
965 return parent::add_instance($course, $fields);
966 }
967
968 /**
969 * Update instance of enrol plugin.
970 * @param stdClass $instance
971 * @param stdClass $data modified instance fields
972 * @return boolean
973 */
974 public function update_instance($instance, $data) {
975 // In the form we are representing 2 db columns with one field.
976 if ($data->expirynotify == 2) {
977 $data->expirynotify = 1;
978 $data->notifyall = 1;
979 } else {
980 $data->notifyall = 0;
981 }
982 // Keep previous/default value of disabled expirythreshold option.
983 if (!$data->expirynotify) {
984 $data->expirythreshold = $instance->expirythreshold;
985 }
986 // Add previous value of newenrols if disabled.
987 if (!isset($data->customint6)) {
988 $data->customint6 = $instance->customint6;
989 }
990
991 return parent::update_instance($instance, $data);
992 }
993
994 /**
995 * Gets a list of roles that this user can assign for the course as the default for self-enrolment.
996 *
997 * @param context $context the context.
998 * @param integer $defaultrole the id of the role that is set as the default for self-enrolment
999 * @return array index is the role id, value is the role name
1000 */
1001 public function extend_assignable_roles($context, $defaultrole) {
1002 global $DB;
1003
1004 $roles = get_assignable_roles($context, ROLENAME_BOTH);
1005 if (!isset($roles[$defaultrole])) {
1006 if ($role = $DB->get_record('role', array('id' => $defaultrole))) {
1007 $roles[$defaultrole] = role_get_name($role, $context, ROLENAME_BOTH);
1008 }
1009 }
1010 return $roles;
1011 }
0ab8b337
SL
1012
1013 /**
1014 * Get the "from" contact which the email will be sent from.
1015 *
1016 * @param int $sendoption send email from constant ENROL_SEND_EMAIL_FROM_*
1017 * @param $context context where the user will be fetched
1018 * @return mixed|stdClass the contact user object.
1019 */
1020 public function get_welcome_email_contact($sendoption, $context) {
1021 global $CFG;
1022
1023 $contact = null;
1024 // Send as the first user assigned as the course contact.
1025 if ($sendoption == ENROL_SEND_EMAIL_FROM_COURSE_CONTACT) {
1026 $rusers = array();
1027 if (!empty($CFG->coursecontact)) {
1028 $croles = explode(',', $CFG->coursecontact);
1029 list($sort, $sortparams) = users_order_by_sql('u');
1030 // We only use the first user.
1031 $i = 0;
1032 do {
1033 $rusers = get_role_users($croles[$i], $context, true, '',
1034 'r.sortorder ASC, ' . $sort, null, '', '', '', '', $sortparams);
1035 $i++;
1036 } while (empty($rusers) && !empty($croles[$i]));
1037 }
1038 if ($rusers) {
1039 $contact = array_values($rusers)[0];
1040 }
1041 } else if ($sendoption == ENROL_SEND_EMAIL_FROM_KEY_HOLDER) {
1042 // Send as the first user with enrol/self:holdkey capability assigned in the course.
1043 list($sort) = users_order_by_sql('u');
1044 $keyholders = get_users_by_capability($context, 'enrol/self:holdkey', 'u.*', $sort);
1045 if (!empty($keyholders)) {
1046 $contact = array_values($keyholders)[0];
1047 }
1048 }
1049
1050 // If send welcome email option is set to no reply or if none of the previous options have
1051 // returned a contact send welcome message as noreplyuser.
1052 if ($sendoption == ENROL_SEND_EMAIL_FROM_NOREPLY || empty($contact)) {
1053 $contact = core_user::get_noreply_user();
1054 }
1055
1056 return $contact;
1057 }
f2a9be5f 1058}
2b931458
DW
1059
1060/**
1061 * Get icon mapping for font-awesome.
1062 */
1063function enrol_self_get_fontawesome_icon_map() {
1064 return [
1065 'enrol_self:withkey' => 'fa-key',
ad056aa2 1066 'enrol_self:withoutkey' => 'fa-sign-in',
2b931458
DW
1067 ];
1068}