Merge branch 'MDL-75941' of https://github.com/paulholden/moodle
[moodle.git] / lib / enrollib.php
blobcaef6930967504b5bd72a37db0e710412b8da79e
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * This library includes the basic parts of enrol api.
20 * It is available on each page.
22 * @package core
23 * @subpackage enrol
24 * @copyright 2010 Petr Skoda {@link http://skodak.org}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 /** Course enrol instance enabled. (used in enrol->status) */
31 define('ENROL_INSTANCE_ENABLED', 0);
33 /** Course enrol instance disabled, user may enter course if other enrol instance enabled. (used in enrol->status)*/
34 define('ENROL_INSTANCE_DISABLED', 1);
36 /** User is active participant (used in user_enrolments->status)*/
37 define('ENROL_USER_ACTIVE', 0);
39 /** User participation in course is suspended (used in user_enrolments->status) */
40 define('ENROL_USER_SUSPENDED', 1);
42 /** @deprecated - enrol caching was reworked, use ENROL_MAX_TIMESTAMP instead */
43 define('ENROL_REQUIRE_LOGIN_CACHE_PERIOD', 1800);
45 /** The timestamp indicating forever */
46 define('ENROL_MAX_TIMESTAMP', 2147483647);
48 /** When user disappears from external source, the enrolment is completely removed */
49 define('ENROL_EXT_REMOVED_UNENROL', 0);
51 /** When user disappears from external source, the enrolment is kept as is - one way sync */
52 define('ENROL_EXT_REMOVED_KEEP', 1);
54 /** @deprecated since 2.4 not used any more, migrate plugin to new restore methods */
55 define('ENROL_RESTORE_TYPE', 'enrolrestore');
57 /**
58 * When user disappears from external source, user enrolment is suspended, roles are kept as is.
59 * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook,
60 * assignments, etc.
62 define('ENROL_EXT_REMOVED_SUSPEND', 2);
64 /**
65 * When user disappears from external source, the enrolment is suspended and roles assigned
66 * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas.
67 * */
68 define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
70 /**
71 * Do not send email.
73 define('ENROL_DO_NOT_SEND_EMAIL', 0);
75 /**
76 * Send email from course contact.
78 define('ENROL_SEND_EMAIL_FROM_COURSE_CONTACT', 1);
80 /**
81 * Send email from enrolment key holder.
83 define('ENROL_SEND_EMAIL_FROM_KEY_HOLDER', 2);
85 /**
86 * Send email from no reply address.
88 define('ENROL_SEND_EMAIL_FROM_NOREPLY', 3);
90 /** Edit enrolment action. */
91 define('ENROL_ACTION_EDIT', 'editenrolment');
93 /** Unenrol action. */
94 define('ENROL_ACTION_UNENROL', 'unenrol');
96 /**
97 * Returns instances of enrol plugins
98 * @param bool $enabled return enabled only
99 * @return array of enrol plugins name=>instance
101 function enrol_get_plugins($enabled) {
102 global $CFG;
104 $result = array();
106 if ($enabled) {
107 // sorted by enabled plugin order
108 $enabled = explode(',', $CFG->enrol_plugins_enabled);
109 $plugins = array();
110 foreach ($enabled as $plugin) {
111 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
113 } else {
114 // sorted alphabetically
115 $plugins = core_component::get_plugin_list('enrol');
116 ksort($plugins);
119 foreach ($plugins as $plugin=>$location) {
120 $class = "enrol_{$plugin}_plugin";
121 if (!class_exists($class)) {
122 if (!file_exists("$location/lib.php")) {
123 continue;
125 include_once("$location/lib.php");
126 if (!class_exists($class)) {
127 continue;
131 $result[$plugin] = new $class();
134 return $result;
138 * Returns instance of enrol plugin
139 * @param string $name name of enrol plugin ('manual', 'guest', ...)
140 * @return enrol_plugin
142 function enrol_get_plugin($name) {
143 global $CFG;
145 $name = clean_param($name, PARAM_PLUGIN);
147 if (empty($name)) {
148 // ignore malformed or missing plugin names completely
149 return null;
152 $location = "$CFG->dirroot/enrol/$name";
154 $class = "enrol_{$name}_plugin";
155 if (!class_exists($class)) {
156 if (!file_exists("$location/lib.php")) {
157 return null;
159 include_once("$location/lib.php");
160 if (!class_exists($class)) {
161 return null;
165 return new $class();
169 * Returns enrolment instances in given course.
170 * @param int $courseid
171 * @param bool $enabled
172 * @return array of enrol instances
174 function enrol_get_instances($courseid, $enabled) {
175 global $DB, $CFG;
177 if (!$enabled) {
178 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
181 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
183 $enabled = explode(',', $CFG->enrol_plugins_enabled);
184 foreach ($result as $key=>$instance) {
185 if (!in_array($instance->enrol, $enabled)) {
186 unset($result[$key]);
187 continue;
189 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
190 // broken plugin
191 unset($result[$key]);
192 continue;
196 return $result;
200 * Checks if a given plugin is in the list of enabled enrolment plugins.
202 * @param string $enrol Enrolment plugin name
203 * @return boolean Whether the plugin is enabled
205 function enrol_is_enabled($enrol) {
206 global $CFG;
208 if (empty($CFG->enrol_plugins_enabled)) {
209 return false;
211 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
215 * Check all the login enrolment information for the given user object
216 * by querying the enrolment plugins
217 * This function may be very slow, use only once after log-in or login-as.
219 * @param stdClass $user User object.
220 * @param bool $ignoreintervalcheck Force to ignore checking configured sync intervals.
222 * @return void
224 function enrol_check_plugins($user, bool $ignoreintervalcheck = true) {
225 global $CFG;
227 if (empty($user->id) or isguestuser($user)) {
228 // shortcut - there is no enrolment work for guests and not-logged-in users
229 return;
232 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
233 // which proved it was actually not necessary.
235 static $inprogress = array(); // To prevent this function being called more than once in an invocation
237 if (!empty($inprogress[$user->id])) {
238 return;
241 $syncinterval = isset($CFG->enrolments_sync_interval) ? (int)$CFG->enrolments_sync_interval : HOURSECS;
242 $needintervalchecking = !$ignoreintervalcheck && !empty($syncinterval);
244 if ($needintervalchecking) {
245 $lastsync = get_user_preferences('last_time_enrolments_synced', 0, $user);
246 if (time() - $lastsync < $syncinterval) {
247 return;
251 $inprogress[$user->id] = true; // Set the flag
253 $enabled = enrol_get_plugins(true);
255 foreach($enabled as $enrol) {
256 $enrol->sync_user_enrolments($user);
259 if ($needintervalchecking) {
260 set_user_preference('last_time_enrolments_synced', time(), $user);
263 unset($inprogress[$user->id]); // Unset the flag
267 * Do these two students share any course?
269 * The courses has to be visible and enrolments has to be active,
270 * timestart and timeend restrictions are ignored.
272 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
273 * to true.
275 * @param stdClass|int $user1
276 * @param stdClass|int $user2
277 * @return bool
279 function enrol_sharing_course($user1, $user2) {
280 return enrol_get_shared_courses($user1, $user2, false, true);
284 * Returns any courses shared by the two users
286 * The courses has to be visible and enrolments has to be active,
287 * timestart and timeend restrictions are ignored.
289 * @global moodle_database $DB
290 * @param stdClass|int $user1
291 * @param stdClass|int $user2
292 * @param bool $preloadcontexts If set to true contexts for the returned courses
293 * will be preloaded.
294 * @param bool $checkexistsonly If set to true then this function will return true
295 * if the users share any courses and false if not.
296 * @return array|bool An array of courses that both users are enrolled in OR if
297 * $checkexistsonly set returns true if the users share any courses
298 * and false if not.
300 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
301 global $DB, $CFG;
303 $user1 = isset($user1->id) ? $user1->id : $user1;
304 $user2 = isset($user2->id) ? $user2->id : $user2;
306 if (empty($user1) or empty($user2)) {
307 return false;
310 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
311 return false;
314 list($plugins1, $params1) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee1');
315 list($plugins2, $params2) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee2');
316 $params = array_merge($params1, $params2);
317 $params['enabled1'] = ENROL_INSTANCE_ENABLED;
318 $params['enabled2'] = ENROL_INSTANCE_ENABLED;
319 $params['active1'] = ENROL_USER_ACTIVE;
320 $params['active2'] = ENROL_USER_ACTIVE;
321 $params['user1'] = $user1;
322 $params['user2'] = $user2;
324 $ctxselect = '';
325 $ctxjoin = '';
326 if ($preloadcontexts) {
327 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
328 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
329 $params['contextlevel'] = CONTEXT_COURSE;
332 $sql = "SELECT c.* $ctxselect
333 FROM {course} c
334 JOIN (
335 SELECT DISTINCT c.id
336 FROM {course} c
337 JOIN {enrol} e1 ON (c.id = e1.courseid AND e1.status = :enabled1 AND e1.enrol $plugins1)
338 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e1.id AND ue1.status = :active1 AND ue1.userid = :user1)
339 JOIN {enrol} e2 ON (c.id = e2.courseid AND e2.status = :enabled2 AND e2.enrol $plugins2)
340 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e2.id AND ue2.status = :active2 AND ue2.userid = :user2)
341 WHERE c.visible = 1
342 ) ec ON ec.id = c.id
343 $ctxjoin";
345 if ($checkexistsonly) {
346 return $DB->record_exists_sql($sql, $params);
347 } else {
348 $courses = $DB->get_records_sql($sql, $params);
349 if ($preloadcontexts) {
350 array_map('context_helper::preload_from_record', $courses);
352 return $courses;
357 * This function adds necessary enrol plugins UI into the course edit form.
359 * @param MoodleQuickForm $mform
360 * @param object $data course edit form data
361 * @param object $context context of existing course or parent category if course does not exist
362 * @return void
364 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
365 $plugins = enrol_get_plugins(true);
366 if (!empty($data->id)) {
367 $instances = enrol_get_instances($data->id, false);
368 foreach ($instances as $instance) {
369 if (!isset($plugins[$instance->enrol])) {
370 continue;
372 $plugin = $plugins[$instance->enrol];
373 $plugin->course_edit_form($instance, $mform, $data, $context);
375 } else {
376 foreach ($plugins as $plugin) {
377 $plugin->course_edit_form(NULL, $mform, $data, $context);
383 * Validate course edit form data
385 * @param array $data raw form data
386 * @param object $context context of existing course or parent category if course does not exist
387 * @return array errors array
389 function enrol_course_edit_validation(array $data, $context) {
390 $errors = array();
391 $plugins = enrol_get_plugins(true);
393 if (!empty($data['id'])) {
394 $instances = enrol_get_instances($data['id'], false);
395 foreach ($instances as $instance) {
396 if (!isset($plugins[$instance->enrol])) {
397 continue;
399 $plugin = $plugins[$instance->enrol];
400 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
402 } else {
403 foreach ($plugins as $plugin) {
404 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
408 return $errors;
412 * Update enrol instances after course edit form submission
413 * @param bool $inserted true means new course added, false course already existed
414 * @param object $course
415 * @param object $data form data
416 * @return void
418 function enrol_course_updated($inserted, $course, $data) {
419 global $DB, $CFG;
421 $plugins = enrol_get_plugins(true);
423 foreach ($plugins as $plugin) {
424 $plugin->course_updated($inserted, $course, $data);
429 * Add navigation nodes
430 * @param navigation_node $coursenode
431 * @param object $course
432 * @return void
434 function enrol_add_course_navigation(navigation_node $coursenode, $course) {
435 global $CFG;
437 $coursecontext = context_course::instance($course->id);
439 $instances = enrol_get_instances($course->id, true);
440 $plugins = enrol_get_plugins(true);
442 // we do not want to break all course pages if there is some borked enrol plugin, right?
443 foreach ($instances as $k=>$instance) {
444 if (!isset($plugins[$instance->enrol])) {
445 unset($instances[$k]);
449 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
451 // List all participants - allows assigning roles, groups, etc.
452 // Have this available even in the site context as the page is still accessible from the frontpage.
453 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
454 $url = new moodle_url('/user/index.php', array('id' => $course->id));
455 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING,
456 null, 'review', new pix_icon('i/enrolusers', ''));
459 if ($course->id != SITEID) {
460 // manage enrol plugin instances
461 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
462 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
463 } else {
464 $url = NULL;
466 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
468 // each instance decides how to configure itself or how many other nav items are exposed
469 foreach ($instances as $instance) {
470 if (!isset($plugins[$instance->enrol])) {
471 continue;
473 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
476 if (!$url) {
477 $instancesnode->trim_if_empty();
481 // Manage groups in this course or even frontpage
482 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
483 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
484 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
487 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
488 // Override roles
489 if (has_capability('moodle/role:review', $coursecontext)) {
490 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
491 } else {
492 $url = NULL;
494 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
496 // Add assign or override roles if allowed
497 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
498 if (has_capability('moodle/role:assign', $coursecontext)) {
499 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
500 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
503 // Check role permissions
504 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
505 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
506 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
510 // Deal somehow with users that are not enrolled but still got a role somehow
511 if ($course->id != SITEID) {
512 //TODO, create some new UI for role assignments at course level
513 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
514 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
515 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
519 // just in case nothing was actually added
520 $usersnode->trim_if_empty();
522 if ($course->id != SITEID) {
523 if (isguestuser() or !isloggedin()) {
524 // guest account can not be enrolled - no links for them
525 } else if (is_enrolled($coursecontext)) {
526 // unenrol link if possible
527 foreach ($instances as $instance) {
528 if (!isset($plugins[$instance->enrol])) {
529 continue;
531 $plugin = $plugins[$instance->enrol];
532 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
533 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
534 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
535 $coursenode->get('unenrolself')->set_force_into_more_menu(true);
536 break;
537 //TODO. deal with multiple unenrol links - not likely case, but still...
540 } else {
541 // enrol link if possible
542 if (is_viewing($coursecontext)) {
543 // better not show any enrol link, this is intended for managers and inspectors
544 } else {
545 foreach ($instances as $instance) {
546 if (!isset($plugins[$instance->enrol])) {
547 continue;
549 $plugin = $plugins[$instance->enrol];
550 if ($plugin->show_enrolme_link($instance)) {
551 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
552 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
553 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
554 break;
563 * Returns list of courses current $USER is enrolled in and can access
565 * The $fields param is a list of field names to ADD so name just the fields you really need,
566 * which will be added and uniq'd.
568 * If $allaccessible is true, this will additionally return courses that the current user is not
569 * enrolled in, but can access because they are open to the user for other reasons (course view
570 * permission, currently viewing course as a guest, or course allows guest access without
571 * password).
573 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
574 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
575 * Allowed prefixes for sort fields are: "ul" for the user_lastaccess table, "c" for the courses table,
576 * "ue" for the user_enrolments table.
577 * @param int $limit max number of courses
578 * @param array $courseids the list of course ids to filter by
579 * @param bool $allaccessible Include courses user is not enrolled in, but can access
580 * @param int $offset Offset the result set by this number
581 * @param array $excludecourses IDs of hidden courses to exclude from search
582 * @return array
584 function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false,
585 $offset = 0, $excludecourses = []) {
586 global $DB, $USER, $CFG;
588 // Allowed prefixes and field names.
589 $allowedprefixesandfields = ['c' => array_keys($DB->get_columns('course')),
590 'ul' => array_keys($DB->get_columns('user_lastaccess')),
591 'ue' => array_keys($DB->get_columns('user_enrolments'))];
593 // Re-Arrange the course sorting according to the admin settings.
594 $sort = enrol_get_courses_sortingsql($sort);
596 // Guest account does not have any enrolled courses.
597 if (!$allaccessible && (isguestuser() or !isloggedin())) {
598 return array();
601 $basefields = [
602 'id', 'category', 'sortorder',
603 'shortname', 'fullname', 'idnumber',
604 'startdate', 'visible',
605 'groupmode', 'groupmodeforce', 'cacherev',
606 'showactivitydates', 'showcompletionconditions',
609 if (empty($fields)) {
610 $fields = $basefields;
611 } else if (is_string($fields)) {
612 // turn the fields from a string to an array
613 $fields = explode(',', $fields);
614 $fields = array_map('trim', $fields);
615 $fields = array_unique(array_merge($basefields, $fields));
616 } else if (is_array($fields)) {
617 $fields = array_unique(array_merge($basefields, $fields));
618 } else {
619 throw new coding_exception('Invalid $fields parameter in enrol_get_my_courses()');
621 if (in_array('*', $fields)) {
622 $fields = array('*');
625 $orderby = "";
626 $sort = trim($sort);
627 $sorttimeaccess = false;
628 if (!empty($sort)) {
629 $rawsorts = explode(',', $sort);
630 $sorts = array();
631 foreach ($rawsorts as $rawsort) {
632 $rawsort = trim($rawsort);
633 // Make sure that there are no more white spaces in sortparams after explode.
634 $sortparams = array_values(array_filter(explode(' ', $rawsort)));
635 // If more than 2 values present then throw coding_exception.
636 if (isset($sortparams[2])) {
637 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
639 // Check the sort ordering if present, at the beginning.
640 if (isset($sortparams[1]) && (preg_match("/^(asc|desc)$/i", $sortparams[1]) === 0)) {
641 throw new coding_exception('Invalid sort direction in $sort parameter in enrol_get_my_courses()');
644 $sortfield = $sortparams[0];
645 $sortdirection = $sortparams[1] ?? 'asc';
646 if (strpos($sortfield, '.') !== false) {
647 $sortfieldparams = explode('.', $sortfield);
648 // Check if more than one dots present in the prefix field.
649 if (isset($sortfieldparams[2])) {
650 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
652 list($prefix, $fieldname) = [$sortfieldparams[0], $sortfieldparams[1]];
653 // Check if the field name matches with the allowed prefix.
654 if (array_key_exists($prefix, $allowedprefixesandfields) &&
655 (in_array($fieldname, $allowedprefixesandfields[$prefix]))) {
656 if ($prefix === 'ul') {
657 $sorts[] = "COALESCE({$prefix}.{$fieldname}, 0) {$sortdirection}";
658 $sorttimeaccess = true;
659 } else {
660 // Check if the field name that matches with the prefix and just append to sorts.
661 $sorts[] = $rawsort;
663 } else {
664 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
666 } else {
667 // Check if the field name matches with $allowedprefixesandfields.
668 $found = false;
669 foreach (array_keys($allowedprefixesandfields) as $prefix) {
670 if (in_array($sortfield, $allowedprefixesandfields[$prefix])) {
671 if ($prefix === 'ul') {
672 $sorts[] = "COALESCE({$prefix}.{$sortfield}, 0) {$sortdirection}";
673 $sorttimeaccess = true;
674 } else {
675 $sorts[] = "{$prefix}.{$sortfield} {$sortdirection}";
677 $found = true;
678 break;
681 if (!$found) {
682 // The param is not found in $allowedprefixesandfields.
683 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
687 $sort = implode(',', $sorts);
688 $orderby = "ORDER BY $sort";
691 $wheres = ['c.id <> ' . SITEID];
692 $params = [];
694 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
695 // list _only_ this course - anything else is asking for trouble...
696 $wheres[] = "courseid = :loginas";
697 $params['loginas'] = $USER->loginascontext->instanceid;
700 $coursefields = 'c.' .join(',c.', $fields);
701 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
702 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
703 $params['contextlevel'] = CONTEXT_COURSE;
704 $wheres = implode(" AND ", $wheres);
706 $timeaccessselect = "";
707 $timeaccessjoin = "";
709 if (!empty($courseids)) {
710 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
711 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
712 $params = array_merge($params, $courseidsparams);
715 if (!empty($excludecourses)) {
716 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($excludecourses, SQL_PARAMS_NAMED, 'param', false);
717 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
718 $params = array_merge($params, $courseidsparams);
721 $courseidsql = "";
722 // Logged-in, non-guest users get their enrolled courses.
723 if (!isguestuser() && isloggedin()) {
724 $courseidsql .= "
725 SELECT DISTINCT e.courseid
726 FROM {enrol} e
727 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid1)
728 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart <= :now1
729 AND (ue.timeend = 0 OR ue.timeend > :now2)";
730 $params['userid1'] = $USER->id;
731 $params['active'] = ENROL_USER_ACTIVE;
732 $params['enabled'] = ENROL_INSTANCE_ENABLED;
733 $params['now1'] = $params['now2'] = time();
735 if ($sorttimeaccess) {
736 $params['userid2'] = $USER->id;
737 $timeaccessselect = ', ul.timeaccess as lastaccessed';
738 $timeaccessjoin = "LEFT JOIN {user_lastaccess} ul ON (ul.courseid = c.id AND ul.userid = :userid2)";
742 // When including non-enrolled but accessible courses...
743 if ($allaccessible) {
744 if (is_siteadmin()) {
745 // Site admins can access all courses.
746 $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
747 } else {
748 // If we used the enrolment as well, then this will be UNIONed.
749 if ($courseidsql) {
750 $courseidsql .= " UNION ";
753 // Include courses with guest access and no password.
754 $courseidsql .= "
755 SELECT DISTINCT e.courseid
756 FROM {enrol} e
757 WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
758 $params['emptypass'] = '';
759 $params['enabled2'] = ENROL_INSTANCE_ENABLED;
761 // Include courses where the current user is currently using guest access (may include
762 // those which require a password).
763 $courseids = [];
764 $accessdata = get_user_accessdata($USER->id);
765 foreach ($accessdata['ra'] as $contextpath => $roles) {
766 if (array_key_exists($CFG->guestroleid, $roles)) {
767 // Work out the course id from context path.
768 $context = context::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
769 if ($context instanceof context_course) {
770 $courseids[$context->instanceid] = true;
775 // Include courses where the current user has moodle/course:view capability.
776 $courses = get_user_capability_course('moodle/course:view', null, false);
777 if (!$courses) {
778 $courses = [];
780 foreach ($courses as $course) {
781 $courseids[$course->id] = true;
784 // If there are any in either category, list them individually.
785 if ($courseids) {
786 list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
787 array_keys($courseids), SQL_PARAMS_NAMED);
788 $courseidsql .= "
789 UNION
790 SELECT DISTINCT c3.id AS courseid
791 FROM {course} c3
792 WHERE c3.id $allowedsql";
793 $params = array_merge($params, $allowedparams);
798 // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
799 // we have the subselect there.
800 $sql = "SELECT $coursefields $ccselect $timeaccessselect
801 FROM {course} c
802 JOIN ($courseidsql) en ON (en.courseid = c.id)
803 $timeaccessjoin
804 $ccjoin
805 WHERE $wheres
806 $orderby";
808 $courses = $DB->get_records_sql($sql, $params, $offset, $limit);
810 // preload contexts and check visibility
811 foreach ($courses as $id=>$course) {
812 context_helper::preload_from_record($course);
813 if (!$course->visible) {
814 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
815 unset($courses[$id]);
816 continue;
818 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
819 unset($courses[$id]);
820 continue;
823 $courses[$id] = $course;
826 //wow! Is that really all? :-D
828 return $courses;
832 * Returns course enrolment information icons.
834 * @param object $course
835 * @param array $instances enrol instances of this course, improves performance
836 * @return array of pix_icon
838 function enrol_get_course_info_icons($course, array $instances = NULL) {
839 $icons = array();
840 if (is_null($instances)) {
841 $instances = enrol_get_instances($course->id, true);
843 $plugins = enrol_get_plugins(true);
844 foreach ($plugins as $name => $plugin) {
845 $pis = array();
846 foreach ($instances as $instance) {
847 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
848 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
849 continue;
851 if ($instance->enrol == $name) {
852 $pis[$instance->id] = $instance;
855 if ($pis) {
856 $icons = array_merge($icons, $plugin->get_info_icons($pis));
859 return $icons;
863 * Returns SQL ORDER arguments which reflect the admin settings to sort my courses.
865 * @param string|null $sort SQL ORDER arguments which were originally requested (optionally).
866 * @return string SQL ORDER arguments.
868 function enrol_get_courses_sortingsql($sort = null) {
869 global $CFG;
871 // Prepare the visible SQL fragment as empty.
872 $visible = '';
873 // Only create a visible SQL fragment if the caller didn't already pass a sort order which contains the visible field.
874 if ($sort === null || strpos($sort, 'visible') === false) {
875 // If the admin did not explicitly want to have shown and hidden courses sorted as one list, we will sort hidden
876 // courses to the end of the course list.
877 if (!isset($CFG->navsortmycourseshiddenlast) || $CFG->navsortmycourseshiddenlast == true) {
878 $visible = 'visible DESC, ';
882 // Only create a sortorder SQL fragment if the caller didn't already pass one.
883 if ($sort === null) {
884 // If the admin has configured a course sort order, we will use this.
885 if (!empty($CFG->navsortmycoursessort)) {
886 $sort = $CFG->navsortmycoursessort . ' ASC';
888 // Otherwise we will fall back to the sortorder sorting.
889 } else {
890 $sort = 'sortorder ASC';
894 return $visible . $sort;
898 * Returns course enrolment detailed information.
900 * @param object $course
901 * @return array of html fragments - can be used to construct lists
903 function enrol_get_course_description_texts($course) {
904 $lines = array();
905 $instances = enrol_get_instances($course->id, true);
906 $plugins = enrol_get_plugins(true);
907 foreach ($instances as $instance) {
908 if (!isset($plugins[$instance->enrol])) {
909 //weird
910 continue;
912 $plugin = $plugins[$instance->enrol];
913 $text = $plugin->get_description_text($instance);
914 if ($text !== NULL) {
915 $lines[] = $text;
918 return $lines;
922 * Returns list of courses user is enrolled into.
924 * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
926 * The $fields param is a list of field names to ADD so name just the fields you really need,
927 * which will be added and uniq'd.
929 * @param int $userid User whose courses are returned, defaults to the current user.
930 * @param bool $onlyactive Return only active enrolments in courses user may see.
931 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
932 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
933 * @return array
935 function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
936 global $DB;
938 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
940 // preload contexts and check visibility
941 if ($onlyactive) {
942 foreach ($courses as $id=>$course) {
943 context_helper::preload_from_record($course);
944 if (!$course->visible) {
945 if (!$context = context_course::instance($id)) {
946 unset($courses[$id]);
947 continue;
949 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
950 unset($courses[$id]);
951 continue;
957 return $courses;
961 * Returns list of roles per users into course.
963 * @param int $courseid Course id.
964 * @return array Array[$userid][$roleid] = role_assignment.
966 function enrol_get_course_users_roles(int $courseid) : array {
967 global $DB;
969 $context = context_course::instance($courseid);
971 $roles = array();
973 $records = $DB->get_recordset('role_assignments', array('contextid' => $context->id));
974 foreach ($records as $record) {
975 if (isset($roles[$record->userid]) === false) {
976 $roles[$record->userid] = array();
978 $roles[$record->userid][$record->roleid] = $record;
980 $records->close();
982 return $roles;
986 * Can user access at least one enrolled course?
988 * Cheat if necessary, but find out as fast as possible!
990 * @param int|stdClass $user null means use current user
991 * @return bool
993 function enrol_user_sees_own_courses($user = null) {
994 global $USER;
996 if ($user === null) {
997 $user = $USER;
999 $userid = is_object($user) ? $user->id : $user;
1001 // Guest account does not have any courses
1002 if (isguestuser($userid) or empty($userid)) {
1003 return false;
1006 // Let's cheat here if this is the current user,
1007 // if user accessed any course recently, then most probably
1008 // we do not need to query the database at all.
1009 if ($USER->id == $userid) {
1010 if (!empty($USER->enrol['enrolled'])) {
1011 foreach ($USER->enrol['enrolled'] as $until) {
1012 if ($until > time()) {
1013 return true;
1019 // Now the slow way.
1020 $courses = enrol_get_all_users_courses($userid, true);
1021 foreach($courses as $course) {
1022 if ($course->visible) {
1023 return true;
1025 context_helper::preload_from_record($course);
1026 $context = context_course::instance($course->id);
1027 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
1028 return true;
1032 return false;
1036 * Returns list of courses user is enrolled into without performing any capability checks.
1038 * The $fields param is a list of field names to ADD so name just the fields you really need,
1039 * which will be added and uniq'd.
1041 * @param int $userid User whose courses are returned, defaults to the current user.
1042 * @param bool $onlyactive Return only active enrolments in courses user may see.
1043 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
1044 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
1045 * @return array
1047 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
1048 global $DB;
1050 // Re-Arrange the course sorting according to the admin settings.
1051 $sort = enrol_get_courses_sortingsql($sort);
1053 // Guest account does not have any courses
1054 if (isguestuser($userid) or empty($userid)) {
1055 return(array());
1058 $basefields = array('id', 'category', 'sortorder',
1059 'shortname', 'fullname', 'idnumber',
1060 'startdate', 'visible',
1061 'defaultgroupingid',
1062 'groupmode', 'groupmodeforce');
1064 if (empty($fields)) {
1065 $fields = $basefields;
1066 } else if (is_string($fields)) {
1067 // turn the fields from a string to an array
1068 $fields = explode(',', $fields);
1069 $fields = array_map('trim', $fields);
1070 $fields = array_unique(array_merge($basefields, $fields));
1071 } else if (is_array($fields)) {
1072 $fields = array_unique(array_merge($basefields, $fields));
1073 } else {
1074 throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
1076 if (in_array('*', $fields)) {
1077 $fields = array('*');
1080 $orderby = "";
1081 $sort = trim($sort);
1082 if (!empty($sort)) {
1083 $rawsorts = explode(',', $sort);
1084 $sorts = array();
1085 foreach ($rawsorts as $rawsort) {
1086 $rawsort = trim($rawsort);
1087 if (strpos($rawsort, 'c.') === 0) {
1088 $rawsort = substr($rawsort, 2);
1090 $sorts[] = trim($rawsort);
1092 $sort = 'c.'.implode(',c.', $sorts);
1093 $orderby = "ORDER BY $sort";
1096 $params = [];
1098 if ($onlyactive) {
1099 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
1100 $params['now1'] = round(time(), -2); // improves db caching
1101 $params['now2'] = $params['now1'];
1102 $params['active'] = ENROL_USER_ACTIVE;
1103 $params['enabled'] = ENROL_INSTANCE_ENABLED;
1104 } else {
1105 $subwhere = "";
1108 $coursefields = 'c.' .join(',c.', $fields);
1109 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1110 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1111 $params['contextlevel'] = CONTEXT_COURSE;
1113 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
1114 $sql = "SELECT $coursefields $ccselect
1115 FROM {course} c
1116 JOIN (SELECT DISTINCT e.courseid
1117 FROM {enrol} e
1118 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
1119 $subwhere
1120 ) en ON (en.courseid = c.id)
1121 $ccjoin
1122 WHERE c.id <> " . SITEID . "
1123 $orderby";
1124 $params['userid'] = $userid;
1126 $courses = $DB->get_records_sql($sql, $params);
1128 return $courses;
1134 * Called when user is about to be deleted.
1135 * @param object $user
1136 * @return void
1138 function enrol_user_delete($user) {
1139 global $DB;
1141 $plugins = enrol_get_plugins(true);
1142 foreach ($plugins as $plugin) {
1143 $plugin->user_delete($user);
1146 // force cleanup of all broken enrolments
1147 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
1151 * Called when course is about to be deleted.
1152 * If a user id is passed, only enrolments that the user has permission to un-enrol will be removed,
1153 * otherwise all enrolments in the course will be removed.
1155 * @param stdClass $course
1156 * @param int|null $userid
1157 * @return void
1159 function enrol_course_delete($course, $userid = null) {
1160 global $DB;
1162 $context = context_course::instance($course->id);
1163 $instances = enrol_get_instances($course->id, false);
1164 $plugins = enrol_get_plugins(true);
1166 if ($userid) {
1167 // If the user id is present, include only course enrolment instances which allow manual unenrolment and
1168 // the given user have a capability to perform unenrolment.
1169 $instances = array_filter($instances, function($instance) use ($userid, $plugins, $context) {
1170 $unenrolcap = "enrol/{$instance->enrol}:unenrol";
1171 return $plugins[$instance->enrol]->allow_unenrol($instance) &&
1172 has_capability($unenrolcap, $context, $userid);
1176 foreach ($instances as $instance) {
1177 if (isset($plugins[$instance->enrol])) {
1178 $plugins[$instance->enrol]->delete_instance($instance);
1180 // low level delete in case plugin did not do it
1181 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
1182 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1183 $DB->delete_records('enrol', array('id'=>$instance->id));
1188 * Try to enrol user via default internal auth plugin.
1190 * For now this is always using the manual enrol plugin...
1192 * @param $courseid
1193 * @param $userid
1194 * @param $roleid
1195 * @param $timestart
1196 * @param $timeend
1197 * @return bool success
1199 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
1200 global $DB;
1202 //note: this is hardcoded to manual plugin for now
1204 if (!enrol_is_enabled('manual')) {
1205 return false;
1208 if (!$enrol = enrol_get_plugin('manual')) {
1209 return false;
1211 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
1212 return false;
1214 $instance = reset($instances);
1216 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
1218 return true;
1222 * Is there a chance users might self enrol
1223 * @param int $courseid
1224 * @return bool
1226 function enrol_selfenrol_available($courseid) {
1227 $result = false;
1229 $plugins = enrol_get_plugins(true);
1230 $enrolinstances = enrol_get_instances($courseid, true);
1231 foreach($enrolinstances as $instance) {
1232 if (!isset($plugins[$instance->enrol])) {
1233 continue;
1235 if ($instance->enrol === 'guest') {
1236 continue;
1238 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
1239 $result = true;
1240 break;
1244 return $result;
1248 * This function returns the end of current active user enrolment.
1250 * It deals correctly with multiple overlapping user enrolments.
1252 * @param int $courseid
1253 * @param int $userid
1254 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
1256 function enrol_get_enrolment_end($courseid, $userid) {
1257 global $DB;
1259 $sql = "SELECT ue.*
1260 FROM {user_enrolments} ue
1261 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1262 JOIN {user} u ON u.id = ue.userid
1263 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1264 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
1266 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1267 return false;
1270 $changes = array();
1272 foreach ($enrolments as $ue) {
1273 $start = (int)$ue->timestart;
1274 $end = (int)$ue->timeend;
1275 if ($end != 0 and $end < $start) {
1276 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
1277 continue;
1279 if (isset($changes[$start])) {
1280 $changes[$start] = $changes[$start] + 1;
1281 } else {
1282 $changes[$start] = 1;
1284 if ($end === 0) {
1285 // no end
1286 } else if (isset($changes[$end])) {
1287 $changes[$end] = $changes[$end] - 1;
1288 } else {
1289 $changes[$end] = -1;
1293 // let's sort then enrolment starts&ends and go through them chronologically,
1294 // looking for current status and the next future end of enrolment
1295 ksort($changes);
1297 $now = time();
1298 $current = 0;
1299 $present = null;
1301 foreach ($changes as $time => $change) {
1302 if ($time > $now) {
1303 if ($present === null) {
1304 // we have just went past current time
1305 $present = $current;
1306 if ($present < 1) {
1307 // no enrolment active
1308 return false;
1311 if ($present !== null) {
1312 // we are already in the future - look for possible end
1313 if ($current + $change < 1) {
1314 return $time;
1318 $current += $change;
1321 if ($current > 0) {
1322 return 0;
1323 } else {
1324 return false;
1329 * Is current user accessing course via this enrolment method?
1331 * This is intended for operations that are going to affect enrol instances.
1333 * @param stdClass $instance enrol instance
1334 * @return bool
1336 function enrol_accessing_via_instance(stdClass $instance) {
1337 global $DB, $USER;
1339 if (empty($instance->id)) {
1340 return false;
1343 if (is_siteadmin()) {
1344 // Admins may go anywhere.
1345 return false;
1348 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
1352 * Returns true if user is enrolled (is participating) in course
1353 * this is intended for students and teachers.
1355 * Since 2.2 the result for active enrolments and current user are cached.
1357 * @param context $context
1358 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1359 * @param string $withcapability extra capability name
1360 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1361 * @return bool
1363 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1364 global $USER, $DB;
1366 // First find the course context.
1367 $coursecontext = $context->get_course_context();
1369 // Make sure there is a real user specified.
1370 if ($user === null) {
1371 $userid = isset($USER->id) ? $USER->id : 0;
1372 } else {
1373 $userid = is_object($user) ? $user->id : $user;
1376 if (empty($userid)) {
1377 // Not-logged-in!
1378 return false;
1379 } else if (isguestuser($userid)) {
1380 // Guest account can not be enrolled anywhere.
1381 return false;
1384 // Note everybody participates on frontpage, so for other contexts...
1385 if ($coursecontext->instanceid != SITEID) {
1386 // Try cached info first - the enrolled flag is set only when active enrolment present.
1387 if ($USER->id == $userid) {
1388 $coursecontext->reload_if_dirty();
1389 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1390 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1391 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1392 return false;
1394 return true;
1399 if ($onlyactive) {
1400 // Look for active enrolments only.
1401 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1403 if ($until === false) {
1404 return false;
1407 if ($USER->id == $userid) {
1408 if ($until == 0) {
1409 $until = ENROL_MAX_TIMESTAMP;
1411 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1412 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1413 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1414 remove_temp_course_roles($coursecontext);
1418 } else {
1419 // Any enrolment is good for us here, even outdated, disabled or inactive.
1420 $sql = "SELECT 'x'
1421 FROM {user_enrolments} ue
1422 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1423 JOIN {user} u ON u.id = ue.userid
1424 WHERE ue.userid = :userid AND u.deleted = 0";
1425 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid);
1426 if (!$DB->record_exists_sql($sql, $params)) {
1427 return false;
1432 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1433 return false;
1436 return true;
1440 * Returns an array of joins, wheres and params that will limit the group of
1441 * users to only those enrolled and with given capability (if specified).
1443 * Note this join will return duplicate rows for users who have been enrolled
1444 * several times (e.g. as manual enrolment, and as self enrolment). You may
1445 * need to use a SELECT DISTINCT in your query (see get_enrolled_sql for example).
1447 * In case is guaranteed some of the joins never match any rows, the resulting
1448 * join_sql->cannotmatchanyrows will be true. This happens when the capability
1449 * is prohibited.
1451 * @param context $context
1452 * @param string $prefix optional, a prefix to the user id column
1453 * @param string|array $capability optional, may include a capability name, or array of names.
1454 * If an array is provided then this is the equivalent of a logical 'OR',
1455 * i.e. the user needs to have one of these capabilities.
1456 * @param int $group optional, 0 indicates no current group and USERSWITHOUTGROUP users without any group; otherwise the group id
1457 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1458 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1459 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1460 * @return \core\dml\sql_join Contains joins, wheres, params and cannotmatchanyrows
1462 function get_enrolled_with_capabilities_join(context $context, $prefix = '', $capability = '', $group = 0,
1463 $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1464 $uid = $prefix . 'u.id';
1465 $joins = array();
1466 $wheres = array();
1467 $cannotmatchanyrows = false;
1469 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended, $enrolid);
1470 $joins[] = $enrolledjoin->joins;
1471 $wheres[] = $enrolledjoin->wheres;
1472 $params = $enrolledjoin->params;
1473 $cannotmatchanyrows = $cannotmatchanyrows || $enrolledjoin->cannotmatchanyrows;
1475 if (!empty($capability)) {
1476 $capjoin = get_with_capability_join($context, $capability, $uid);
1477 $joins[] = $capjoin->joins;
1478 $wheres[] = $capjoin->wheres;
1479 $params = array_merge($params, $capjoin->params);
1480 $cannotmatchanyrows = $cannotmatchanyrows || $capjoin->cannotmatchanyrows;
1483 if ($group) {
1484 $groupjoin = groups_get_members_join($group, $uid, $context);
1485 $joins[] = $groupjoin->joins;
1486 $params = array_merge($params, $groupjoin->params);
1487 if (!empty($groupjoin->wheres)) {
1488 $wheres[] = $groupjoin->wheres;
1490 $cannotmatchanyrows = $cannotmatchanyrows || $groupjoin->cannotmatchanyrows;
1493 $joins = implode("\n", $joins);
1494 $wheres[] = "{$prefix}u.deleted = 0";
1495 $wheres = implode(" AND ", $wheres);
1497 return new \core\dml\sql_join($joins, $wheres, $params, $cannotmatchanyrows);
1501 * Returns array with sql code and parameters returning all ids
1502 * of users enrolled into course.
1504 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1506 * @param context $context
1507 * @param string $withcapability
1508 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1509 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1510 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1511 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1512 * @return array list($sql, $params)
1514 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false,
1515 $enrolid = 0) {
1517 // Use unique prefix just in case somebody makes some SQL magic with the result.
1518 static $i = 0;
1519 $i++;
1520 $prefix = 'eu' . $i . '_';
1522 $capjoin = get_enrolled_with_capabilities_join(
1523 $context, $prefix, $withcapability, $groupid, $onlyactive, $onlysuspended, $enrolid);
1525 $sql = "SELECT DISTINCT {$prefix}u.id
1526 FROM {user} {$prefix}u
1527 $capjoin->joins
1528 WHERE $capjoin->wheres";
1530 return array($sql, $capjoin->params);
1534 * Returns array with sql joins and parameters returning all ids
1535 * of users enrolled into course.
1537 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1539 * @throws coding_exception
1541 * @param context $context
1542 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1543 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1544 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1545 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1546 * @return \core\dml\sql_join Contains joins, wheres, params
1548 function get_enrolled_join(context $context, $useridcolumn, $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1549 // Use unique prefix just in case somebody makes some SQL magic with the result.
1550 static $i = 0;
1551 $i++;
1552 $prefix = 'ej' . $i . '_';
1554 // First find the course context.
1555 $coursecontext = $context->get_course_context();
1557 $isfrontpage = ($coursecontext->instanceid == SITEID);
1559 if ($onlyactive && $onlysuspended) {
1560 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1562 if ($isfrontpage && $onlysuspended) {
1563 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1566 $joins = array();
1567 $wheres = array();
1568 $params = array();
1570 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1572 // Note all users are "enrolled" on the frontpage, but for others...
1573 if (!$isfrontpage) {
1574 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1575 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1577 $enrolconditions = array(
1578 "{$prefix}e.id = {$prefix}ue.enrolid",
1579 "{$prefix}e.courseid = :{$prefix}courseid",
1581 if ($enrolid) {
1582 $enrolconditions[] = "{$prefix}e.id = :{$prefix}enrolid";
1583 $params[$prefix . 'enrolid'] = $enrolid;
1585 $enrolconditionssql = implode(" AND ", $enrolconditions);
1586 $ejoin = "JOIN {enrol} {$prefix}e ON ($enrolconditionssql)";
1588 $params[$prefix.'courseid'] = $coursecontext->instanceid;
1590 if (!$onlysuspended) {
1591 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1592 $joins[] = $ejoin;
1593 if ($onlyactive) {
1594 $wheres[] = "$where1 AND $where2";
1596 } else {
1597 // Suspended only where there is enrolment but ALL are suspended.
1598 // Consider multiple enrols where one is not suspended or plain role_assign.
1599 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1600 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1601 $enrolconditions = array(
1602 "{$prefix}e1.id = {$prefix}ue1.enrolid",
1603 "{$prefix}e1.courseid = :{$prefix}_e1_courseid",
1605 if ($enrolid) {
1606 $enrolconditions[] = "{$prefix}e1.id = :{$prefix}e1_enrolid";
1607 $params[$prefix . 'e1_enrolid'] = $enrolid;
1609 $enrolconditionssql = implode(" AND ", $enrolconditions);
1610 $joins[] = "JOIN {enrol} {$prefix}e1 ON ($enrolconditionssql)";
1611 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
1612 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1615 if ($onlyactive || $onlysuspended) {
1616 $now = round(time(), -2); // Rounding helps caching in DB.
1617 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED,
1618 $prefix . 'active' => ENROL_USER_ACTIVE,
1619 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1623 $joins = implode("\n", $joins);
1624 $wheres = implode(" AND ", $wheres);
1626 return new \core\dml\sql_join($joins, $wheres, $params);
1630 * Returns list of users enrolled into course.
1632 * @param context $context
1633 * @param string $withcapability
1634 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1635 * @param string $userfields requested user record fields
1636 * @param string $orderby
1637 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1638 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1639 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1640 * @return array of user records
1642 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1643 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1644 global $DB;
1646 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1647 $sql = "SELECT $userfields
1648 FROM {user} u
1649 JOIN ($esql) je ON je.id = u.id
1650 WHERE u.deleted = 0";
1652 if ($orderby) {
1653 $sql = "$sql ORDER BY $orderby";
1654 } else {
1655 list($sort, $sortparams) = users_order_by_sql('u');
1656 $sql = "$sql ORDER BY $sort";
1657 $params = array_merge($params, $sortparams);
1660 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1664 * Counts list of users enrolled into course (as per above function)
1666 * @param context $context
1667 * @param string $withcapability
1668 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1669 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1670 * @return int number of users enrolled into course
1672 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1673 global $DB;
1675 $capjoin = get_enrolled_with_capabilities_join(
1676 $context, '', $withcapability, $groupid, $onlyactive);
1678 $sql = "SELECT COUNT(DISTINCT u.id)
1679 FROM {user} u
1680 $capjoin->joins
1681 WHERE $capjoin->wheres AND u.deleted = 0";
1683 return $DB->count_records_sql($sql, $capjoin->params);
1687 * Send welcome email "from" options.
1689 * @return array list of from options
1691 function enrol_send_welcome_email_options() {
1692 return [
1693 ENROL_DO_NOT_SEND_EMAIL => get_string('no'),
1694 ENROL_SEND_EMAIL_FROM_COURSE_CONTACT => get_string('sendfromcoursecontact', 'enrol'),
1695 ENROL_SEND_EMAIL_FROM_KEY_HOLDER => get_string('sendfromkeyholder', 'enrol'),
1696 ENROL_SEND_EMAIL_FROM_NOREPLY => get_string('sendfromnoreply', 'enrol')
1701 * Serve the user enrolment form as a fragment.
1703 * @param array $args List of named arguments for the fragment loader.
1704 * @return string
1706 function enrol_output_fragment_user_enrolment_form($args) {
1707 global $CFG, $DB;
1709 $args = (object) $args;
1710 $context = $args->context;
1711 require_capability('moodle/course:enrolreview', $context);
1713 $ueid = $args->ueid;
1714 $userenrolment = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
1715 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid], '*', MUST_EXIST);
1716 $plugin = enrol_get_plugin($instance->enrol);
1717 $customdata = [
1718 'ue' => $userenrolment,
1719 'modal' => true,
1720 'enrolinstancename' => $plugin->get_instance_name($instance)
1723 // Set the data if applicable.
1724 $data = [];
1725 if (isset($args->formdata)) {
1726 $serialiseddata = json_decode($args->formdata);
1727 parse_str($serialiseddata, $data);
1730 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1731 $mform = new \enrol_user_enrolment_form(null, $customdata, 'post', '', null, true, $data);
1733 if (!empty($data)) {
1734 $mform->set_data($data);
1735 $mform->is_validated();
1738 return $mform->render();
1742 * Returns the course where a user enrolment belong to.
1744 * @param int $ueid user_enrolments id
1745 * @return stdClass
1747 function enrol_get_course_by_user_enrolment_id($ueid) {
1748 global $DB;
1749 $sql = "SELECT c.* FROM {user_enrolments} ue
1750 JOIN {enrol} e ON e.id = ue.enrolid
1751 JOIN {course} c ON c.id = e.courseid
1752 WHERE ue.id = :ueid";
1753 return $DB->get_record_sql($sql, array('ueid' => $ueid));
1757 * Return all users enrolled in a course.
1759 * @param int $courseid Course id or false if using $uefilter (user enrolment ids may belong to different courses)
1760 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1761 * @param array $usersfilter Limit the results obtained to this list of user ids. $uefilter compatibility not guaranteed.
1762 * @param array $uefilter Limit the results obtained to this list of user enrolment ids. $usersfilter compatibility not guaranteed.
1763 * @return stdClass[]
1765 function enrol_get_course_users($courseid = false, $onlyactive = false, $usersfilter = array(), $uefilter = array()) {
1766 global $DB;
1768 if (!$courseid && !$usersfilter && !$uefilter) {
1769 throw new \coding_exception('You should specify at least 1 filter: courseid, users or user enrolments');
1772 $sql = "SELECT ue.id AS ueid, ue.status AS uestatus, ue.enrolid AS ueenrolid, ue.timestart AS uetimestart,
1773 ue.timeend AS uetimeend, ue.modifierid AS uemodifierid, ue.timecreated AS uetimecreated,
1774 ue.timemodified AS uetimemodified, e.status AS estatus,
1775 u.* FROM {user_enrolments} ue
1776 JOIN {enrol} e ON e.id = ue.enrolid
1777 JOIN {user} u ON ue.userid = u.id
1778 WHERE ";
1779 $params = array();
1781 if ($courseid) {
1782 $conditions[] = "e.courseid = :courseid";
1783 $params['courseid'] = $courseid;
1786 if ($onlyactive) {
1787 $conditions[] = "ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND " .
1788 "(ue.timeend = 0 OR ue.timeend > :now2)";
1789 // Improves db caching.
1790 $params['now1'] = round(time(), -2);
1791 $params['now2'] = $params['now1'];
1792 $params['active'] = ENROL_USER_ACTIVE;
1793 $params['enabled'] = ENROL_INSTANCE_ENABLED;
1796 if ($usersfilter) {
1797 list($usersql, $userparams) = $DB->get_in_or_equal($usersfilter, SQL_PARAMS_NAMED);
1798 $conditions[] = "ue.userid $usersql";
1799 $params = $params + $userparams;
1802 if ($uefilter) {
1803 list($uesql, $ueparams) = $DB->get_in_or_equal($uefilter, SQL_PARAMS_NAMED);
1804 $conditions[] = "ue.id $uesql";
1805 $params = $params + $ueparams;
1808 return $DB->get_records_sql($sql . ' ' . implode(' AND ', $conditions), $params);
1812 * Get the list of options for the enrolment period dropdown
1814 * @return array List of options for the enrolment period dropdown
1816 function enrol_get_period_list() {
1817 $periodmenu = [];
1818 $periodmenu[''] = get_string('unlimited');
1819 for ($i = 1; $i <= 365; $i++) {
1820 $seconds = $i * DAYSECS;
1821 $periodmenu[$seconds] = get_string('numdays', '', $i);
1823 return $periodmenu;
1827 * Calculate duration base on start time and end time
1829 * @param int $timestart Time start
1830 * @param int $timeend Time end
1831 * @return float|int Calculated duration
1833 function enrol_calculate_duration($timestart, $timeend) {
1834 $duration = floor(($timeend - $timestart) / DAYSECS) * DAYSECS;
1835 return $duration;
1839 * Enrolment plugins abstract class.
1841 * All enrol plugins should be based on this class,
1842 * this is also the main source of documentation.
1844 * @copyright 2010 Petr Skoda {@link http://skodak.org}
1845 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1847 abstract class enrol_plugin {
1848 protected $config = null;
1851 * Returns name of this enrol plugin
1852 * @return string
1854 public function get_name() {
1855 // second word in class is always enrol name, sorry, no fancy plugin names with _
1856 $words = explode('_', get_class($this));
1857 return $words[1];
1861 * Returns localised name of enrol instance
1863 * @param object $instance (null is accepted too)
1864 * @return string
1866 public function get_instance_name($instance) {
1867 if (empty($instance->name)) {
1868 $enrol = $this->get_name();
1869 return get_string('pluginname', 'enrol_'.$enrol);
1870 } else {
1871 $context = context_course::instance($instance->courseid);
1872 return format_string($instance->name, true, array('context'=>$context));
1877 * Returns optional enrolment information icons.
1879 * This is used in course list for quick overview of enrolment options.
1881 * We are not using single instance parameter because sometimes
1882 * we might want to prevent icon repetition when multiple instances
1883 * of one type exist. One instance may also produce several icons.
1885 * @param array $instances all enrol instances of this type in one course
1886 * @return array of pix_icon
1888 public function get_info_icons(array $instances) {
1889 return array();
1893 * Returns optional enrolment instance description text.
1895 * This is used in detailed course information.
1898 * @param object $instance
1899 * @return string short html text
1901 public function get_description_text($instance) {
1902 return null;
1906 * Makes sure config is loaded and cached.
1907 * @return void
1909 protected function load_config() {
1910 if (!isset($this->config)) {
1911 $name = $this->get_name();
1912 $this->config = get_config("enrol_$name");
1917 * Returns plugin config value
1918 * @param string $name
1919 * @param string $default value if config does not exist yet
1920 * @return string value or default
1922 public function get_config($name, $default = NULL) {
1923 $this->load_config();
1924 return isset($this->config->$name) ? $this->config->$name : $default;
1928 * Sets plugin config value
1929 * @param string $name name of config
1930 * @param string $value string config value, null means delete
1931 * @return string value
1933 public function set_config($name, $value) {
1934 $pluginname = $this->get_name();
1935 $this->load_config();
1936 if ($value === NULL) {
1937 unset($this->config->$name);
1938 } else {
1939 $this->config->$name = $value;
1941 set_config($name, $value, "enrol_$pluginname");
1945 * Does this plugin assign protected roles are can they be manually removed?
1946 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1948 public function roles_protected() {
1949 return true;
1953 * Does this plugin allow manual enrolments?
1955 * @param stdClass $instance course enrol instance
1956 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1958 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1960 public function allow_enrol(stdClass $instance) {
1961 return false;
1965 * Does this plugin allow manual unenrolment of all users?
1966 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1968 * @param stdClass $instance course enrol instance
1969 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1971 public function allow_unenrol(stdClass $instance) {
1972 return false;
1976 * Does this plugin allow manual unenrolment of a specific user?
1977 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1979 * This is useful especially for synchronisation plugins that
1980 * do suspend instead of full unenrolment.
1982 * @param stdClass $instance course enrol instance
1983 * @param stdClass $ue record from user_enrolments table, specifies user
1985 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1987 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1988 return $this->allow_unenrol($instance);
1992 * Does this plugin allow manual changes in user_enrolments table?
1994 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1996 * @param stdClass $instance course enrol instance
1997 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1999 public function allow_manage(stdClass $instance) {
2000 return false;
2004 * Does this plugin support some way to user to self enrol?
2006 * @param stdClass $instance course enrol instance
2008 * @return bool - true means show "Enrol me in this course" link in course UI
2010 public function show_enrolme_link(stdClass $instance) {
2011 return false;
2015 * Attempt to automatically enrol current user in course without any interaction,
2016 * calling code has to make sure the plugin and instance are active.
2018 * This should return either a timestamp in the future or false.
2020 * @param stdClass $instance course enrol instance
2021 * @return bool|int false means not enrolled, integer means timeend
2023 public function try_autoenrol(stdClass $instance) {
2024 global $USER;
2026 return false;
2030 * Attempt to automatically gain temporary guest access to course,
2031 * calling code has to make sure the plugin and instance are active.
2033 * This should return either a timestamp in the future or false.
2035 * @param stdClass $instance course enrol instance
2036 * @return bool|int false means no guest access, integer means timeend
2038 public function try_guestaccess(stdClass $instance) {
2039 global $USER;
2041 return false;
2045 * Enrol user into course via enrol instance.
2047 * @param stdClass $instance
2048 * @param int $userid
2049 * @param int $roleid optional role id
2050 * @param int $timestart 0 means unknown
2051 * @param int $timeend 0 means forever
2052 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
2053 * @param bool $recovergrades restore grade history
2054 * @return void
2056 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
2057 global $DB, $USER, $CFG; // CFG necessary!!!
2059 if ($instance->courseid == SITEID) {
2060 throw new coding_exception('invalid attempt to enrol into frontpage course!');
2063 $name = $this->get_name();
2064 $courseid = $instance->courseid;
2066 if ($instance->enrol !== $name) {
2067 throw new coding_exception('invalid enrol instance!');
2069 $context = context_course::instance($instance->courseid, MUST_EXIST);
2070 if (!isset($recovergrades)) {
2071 $recovergrades = $CFG->recovergradesdefault;
2074 $inserted = false;
2075 $updated = false;
2076 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2077 //only update if timestart or timeend or status are different.
2078 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
2079 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
2081 } else {
2082 $ue = new stdClass();
2083 $ue->enrolid = $instance->id;
2084 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
2085 $ue->userid = $userid;
2086 $ue->timestart = $timestart;
2087 $ue->timeend = $timeend;
2088 $ue->modifierid = $USER->id;
2089 $ue->timecreated = time();
2090 $ue->timemodified = $ue->timecreated;
2091 $ue->id = $DB->insert_record('user_enrolments', $ue);
2093 $inserted = true;
2096 if ($inserted) {
2097 // Trigger event.
2098 $event = \core\event\user_enrolment_created::create(
2099 array(
2100 'objectid' => $ue->id,
2101 'courseid' => $courseid,
2102 'context' => $context,
2103 'relateduserid' => $ue->userid,
2104 'other' => array('enrol' => $name)
2107 $event->trigger();
2108 // Check if course contacts cache needs to be cleared.
2109 core_course_category::user_enrolment_changed($courseid, $ue->userid,
2110 $ue->status, $ue->timestart, $ue->timeend);
2113 if ($roleid) {
2114 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
2115 if ($this->roles_protected()) {
2116 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
2117 } else {
2118 role_assign($roleid, $userid, $context->id);
2122 // Recover old grades if present.
2123 if ($recovergrades) {
2124 require_once("$CFG->libdir/gradelib.php");
2125 grade_recover_history_grades($userid, $courseid);
2128 // reset current user enrolment caching
2129 if ($userid == $USER->id) {
2130 if (isset($USER->enrol['enrolled'][$courseid])) {
2131 unset($USER->enrol['enrolled'][$courseid]);
2133 if (isset($USER->enrol['tempguest'][$courseid])) {
2134 unset($USER->enrol['tempguest'][$courseid]);
2135 remove_temp_course_roles($context);
2141 * Store user_enrolments changes and trigger event.
2143 * @param stdClass $instance
2144 * @param int $userid
2145 * @param int $status
2146 * @param int $timestart
2147 * @param int $timeend
2148 * @return void
2150 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
2151 global $DB, $USER, $CFG;
2153 $name = $this->get_name();
2155 if ($instance->enrol !== $name) {
2156 throw new coding_exception('invalid enrol instance!');
2159 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2160 // weird, user not enrolled
2161 return;
2164 $modified = false;
2165 if (isset($status) and $ue->status != $status) {
2166 $ue->status = $status;
2167 $modified = true;
2169 if (isset($timestart) and $ue->timestart != $timestart) {
2170 $ue->timestart = $timestart;
2171 $modified = true;
2173 if (isset($timeend) and $ue->timeend != $timeend) {
2174 $ue->timeend = $timeend;
2175 $modified = true;
2178 if (!$modified) {
2179 // no change
2180 return;
2183 $ue->modifierid = $USER->id;
2184 $ue->timemodified = time();
2185 $DB->update_record('user_enrolments', $ue);
2187 // User enrolments have changed, so mark user as dirty.
2188 mark_user_dirty($userid);
2190 // Invalidate core_access cache for get_suspended_userids.
2191 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));
2193 // Trigger event.
2194 $event = \core\event\user_enrolment_updated::create(
2195 array(
2196 'objectid' => $ue->id,
2197 'courseid' => $instance->courseid,
2198 'context' => context_course::instance($instance->courseid),
2199 'relateduserid' => $ue->userid,
2200 'other' => array('enrol' => $name)
2203 $event->trigger();
2205 core_course_category::user_enrolment_changed($instance->courseid, $ue->userid,
2206 $ue->status, $ue->timestart, $ue->timeend);
2210 * Unenrol user from course,
2211 * the last unenrolment removes all remaining roles.
2213 * @param stdClass $instance
2214 * @param int $userid
2215 * @return void
2217 public function unenrol_user(stdClass $instance, $userid) {
2218 global $CFG, $USER, $DB;
2219 require_once("$CFG->dirroot/group/lib.php");
2221 $name = $this->get_name();
2222 $courseid = $instance->courseid;
2224 if ($instance->enrol !== $name) {
2225 throw new coding_exception('invalid enrol instance!');
2227 $context = context_course::instance($instance->courseid, MUST_EXIST);
2229 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2230 // weird, user not enrolled
2231 return;
2234 // Remove all users groups linked to this enrolment instance.
2235 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
2236 foreach ($gms as $gm) {
2237 groups_remove_member($gm->groupid, $gm->userid);
2241 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
2242 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
2244 // add extra info and trigger event
2245 $ue->courseid = $courseid;
2246 $ue->enrol = $name;
2248 $sql = "SELECT 'x'
2249 FROM {user_enrolments} ue
2250 JOIN {enrol} e ON (e.id = ue.enrolid)
2251 WHERE ue.userid = :userid AND e.courseid = :courseid";
2252 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
2253 $ue->lastenrol = false;
2255 } else {
2256 // the big cleanup IS necessary!
2257 require_once("$CFG->libdir/gradelib.php");
2259 // remove all remaining roles
2260 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
2262 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
2263 groups_delete_group_members($courseid, $userid);
2265 grade_user_unenrol($courseid, $userid);
2267 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
2269 $ue->lastenrol = true; // means user not enrolled any more
2271 // Trigger event.
2272 $event = \core\event\user_enrolment_deleted::create(
2273 array(
2274 'courseid' => $courseid,
2275 'context' => $context,
2276 'relateduserid' => $ue->userid,
2277 'objectid' => $ue->id,
2278 'other' => array(
2279 'userenrolment' => (array)$ue,
2280 'enrol' => $name
2284 $event->trigger();
2286 // User enrolments have changed, so mark user as dirty.
2287 mark_user_dirty($userid);
2289 // Check if courrse contacts cache needs to be cleared.
2290 core_course_category::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);
2292 // reset current user enrolment caching
2293 if ($userid == $USER->id) {
2294 if (isset($USER->enrol['enrolled'][$courseid])) {
2295 unset($USER->enrol['enrolled'][$courseid]);
2297 if (isset($USER->enrol['tempguest'][$courseid])) {
2298 unset($USER->enrol['tempguest'][$courseid]);
2299 remove_temp_course_roles($context);
2305 * Forces synchronisation of user enrolments.
2307 * This is important especially for external enrol plugins,
2308 * this function is called for all enabled enrol plugins
2309 * right after every user login.
2311 * @param object $user user record
2312 * @return void
2314 public function sync_user_enrolments($user) {
2315 // override if necessary
2319 * This returns false for backwards compatibility, but it is really recommended.
2321 * @since Moodle 3.1
2322 * @return boolean
2324 public function use_standard_editing_ui() {
2325 return false;
2329 * Return whether or not, given the current state, it is possible to add a new instance
2330 * of this enrolment plugin to the course.
2332 * Default implementation is just for backwards compatibility.
2334 * @param int $courseid
2335 * @return boolean
2337 public function can_add_instance($courseid) {
2338 $link = $this->get_newinstance_link($courseid);
2339 return !empty($link);
2343 * Return whether or not, given the current state, it is possible to edit an instance
2344 * of this enrolment plugin in the course. Used by the standard editing UI
2345 * to generate a link to the edit instance form if editing is allowed.
2347 * @param stdClass $instance
2348 * @return boolean
2350 public function can_edit_instance($instance) {
2351 $context = context_course::instance($instance->courseid);
2353 return has_capability('enrol/' . $instance->enrol . ':config', $context);
2357 * Returns link to page which may be used to add new instance of enrolment plugin in course.
2358 * @param int $courseid
2359 * @return moodle_url page url
2361 public function get_newinstance_link($courseid) {
2362 // override for most plugins, check if instance already exists in cases only one instance is supported
2363 return NULL;
2367 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
2369 public function instance_deleteable($instance) {
2370 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
2371 enrol_plugin::can_delete_instance() instead');
2375 * Is it possible to delete enrol instance via standard UI?
2377 * @param stdClass $instance
2378 * @return bool
2380 public function can_delete_instance($instance) {
2381 return false;
2385 * Is it possible to hide/show enrol instance via standard UI?
2387 * @param stdClass $instance
2388 * @return bool
2390 public function can_hide_show_instance($instance) {
2391 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER);
2392 return true;
2396 * Returns link to manual enrol UI if exists.
2397 * Does the access control tests automatically.
2399 * @param object $instance
2400 * @return moodle_url
2402 public function get_manual_enrol_link($instance) {
2403 return NULL;
2407 * Returns list of unenrol links for all enrol instances in course.
2409 * @param int $instance
2410 * @return moodle_url or NULL if self unenrolment not supported
2412 public function get_unenrolself_link($instance) {
2413 global $USER, $CFG, $DB;
2415 $name = $this->get_name();
2416 if ($instance->enrol !== $name) {
2417 throw new coding_exception('invalid enrol instance!');
2420 if ($instance->courseid == SITEID) {
2421 return NULL;
2424 if (!enrol_is_enabled($name)) {
2425 return NULL;
2428 if ($instance->status != ENROL_INSTANCE_ENABLED) {
2429 return NULL;
2432 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2433 return NULL;
2436 $context = context_course::instance($instance->courseid, MUST_EXIST);
2438 if (!has_capability("enrol/$name:unenrolself", $context)) {
2439 return NULL;
2442 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
2443 return NULL;
2446 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
2450 * Adds enrol instance UI to course edit form
2452 * @param object $instance enrol instance or null if does not exist yet
2453 * @param MoodleQuickForm $mform
2454 * @param object $data
2455 * @param object $context context of existing course or parent category if course does not exist
2456 * @return void
2458 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
2459 // override - usually at least enable/disable switch, has to add own form header
2463 * Adds form elements to add/edit instance form.
2465 * @since Moodle 3.1
2466 * @param object $instance enrol instance or null if does not exist yet
2467 * @param MoodleQuickForm $mform
2468 * @param context $context
2469 * @return void
2471 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
2472 // Do nothing by default.
2476 * Perform custom validation of the data used to edit the instance.
2478 * @since Moodle 3.1
2479 * @param array $data array of ("fieldname"=>value) of submitted data
2480 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2481 * @param object $instance The instance data loaded from the DB.
2482 * @param context $context The context of the instance we are editing
2483 * @return array of "element_name"=>"error_description" if there are errors,
2484 * or an empty array if everything is OK.
2486 public function edit_instance_validation($data, $files, $instance, $context) {
2487 // No errors by default.
2488 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER);
2489 return array();
2493 * Validates course edit form data
2495 * @param object $instance enrol instance or null if does not exist yet
2496 * @param array $data
2497 * @param object $context context of existing course or parent category if course does not exist
2498 * @return array errors array
2500 public function course_edit_validation($instance, array $data, $context) {
2501 return array();
2505 * Called after updating/inserting course.
2507 * @param bool $inserted true if course just inserted
2508 * @param object $course
2509 * @param object $data form data
2510 * @return void
2512 public function course_updated($inserted, $course, $data) {
2513 if ($inserted) {
2514 if ($this->get_config('defaultenrol')) {
2515 $this->add_default_instance($course);
2521 * Add new instance of enrol plugin.
2522 * @param object $course
2523 * @param array instance fields
2524 * @return int id of new instance, null if can not be created
2526 public function add_instance($course, array $fields = NULL) {
2527 global $DB;
2529 if ($course->id == SITEID) {
2530 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2533 $instance = new stdClass();
2534 $instance->enrol = $this->get_name();
2535 $instance->status = ENROL_INSTANCE_ENABLED;
2536 $instance->courseid = $course->id;
2537 $instance->enrolstartdate = 0;
2538 $instance->enrolenddate = 0;
2539 $instance->timemodified = time();
2540 $instance->timecreated = $instance->timemodified;
2541 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
2543 $fields = (array)$fields;
2544 unset($fields['enrol']);
2545 unset($fields['courseid']);
2546 unset($fields['sortorder']);
2547 foreach($fields as $field=>$value) {
2548 $instance->$field = $value;
2551 $instance->id = $DB->insert_record('enrol', $instance);
2553 \core\event\enrol_instance_created::create_from_record($instance)->trigger();
2555 return $instance->id;
2559 * Update instance of enrol plugin.
2561 * @since Moodle 3.1
2562 * @param stdClass $instance
2563 * @param stdClass $data modified instance fields
2564 * @return boolean
2566 public function update_instance($instance, $data) {
2567 global $DB;
2568 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2569 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2570 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2571 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2572 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2573 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2575 foreach ($properties as $key) {
2576 if (isset($data->$key)) {
2577 $instance->$key = $data->$key;
2580 $instance->timemodified = time();
2582 $update = $DB->update_record('enrol', $instance);
2583 if ($update) {
2584 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2586 return $update;
2590 * Add new instance of enrol plugin with default settings,
2591 * called when adding new instance manually or when adding new course.
2593 * Not all plugins support this.
2595 * @param object $course
2596 * @return int id of new instance or null if no default supported
2598 public function add_default_instance($course) {
2599 return null;
2603 * Update instance status
2605 * Override when plugin needs to do some action when enabled or disabled.
2607 * @param stdClass $instance
2608 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2609 * @return void
2611 public function update_status($instance, $newstatus) {
2612 global $DB;
2614 $instance->status = $newstatus;
2615 $DB->update_record('enrol', $instance);
2617 $context = context_course::instance($instance->courseid);
2618 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2620 // Invalidate all enrol caches.
2621 $context->mark_dirty();
2625 * Delete course enrol plugin instance, unenrol all users.
2626 * @param object $instance
2627 * @return void
2629 public function delete_instance($instance) {
2630 global $DB;
2632 $name = $this->get_name();
2633 if ($instance->enrol !== $name) {
2634 throw new coding_exception('invalid enrol instance!');
2637 //first unenrol all users
2638 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
2639 foreach ($participants as $participant) {
2640 $this->unenrol_user($instance, $participant->userid);
2642 $participants->close();
2644 // now clean up all remainders that were not removed correctly
2645 if ($gms = $DB->get_records('groups_members', array('itemid' => $instance->id, 'component' => 'enrol_' . $name))) {
2646 foreach ($gms as $gm) {
2647 groups_remove_member($gm->groupid, $gm->userid);
2650 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
2651 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
2653 // finally drop the enrol row
2654 $DB->delete_records('enrol', array('id'=>$instance->id));
2656 $context = context_course::instance($instance->courseid);
2657 \core\event\enrol_instance_deleted::create_from_record($instance)->trigger();
2659 // Invalidate all enrol caches.
2660 $context->mark_dirty();
2664 * Creates course enrol form, checks if form submitted
2665 * and enrols user if necessary. It can also redirect.
2667 * @param stdClass $instance
2668 * @return string html text, usually a form in a text box
2670 public function enrol_page_hook(stdClass $instance) {
2671 return null;
2675 * Checks if user can self enrol.
2677 * @param stdClass $instance enrolment instance
2678 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2679 * used by navigation to improve performance.
2680 * @return bool|string true if successful, else error message or false
2682 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
2683 return false;
2687 * Return information for enrolment instance containing list of parameters required
2688 * for enrolment, name of enrolment plugin etc.
2690 * @param stdClass $instance enrolment instance
2691 * @return array instance info.
2693 public function get_enrol_info(stdClass $instance) {
2694 return null;
2698 * Adds navigation links into course admin block.
2700 * By defaults looks for manage links only.
2702 * @param navigation_node $instancesnode
2703 * @param stdClass $instance
2704 * @return void
2706 public function add_course_navigation($instancesnode, stdClass $instance) {
2707 if ($this->use_standard_editing_ui()) {
2708 $context = context_course::instance($instance->courseid);
2709 $cap = 'enrol/' . $instance->enrol . ':config';
2710 if (has_capability($cap, $context)) {
2711 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2712 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2713 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
2719 * Returns edit icons for the page with list of instances
2720 * @param stdClass $instance
2721 * @return array
2723 public function get_action_icons(stdClass $instance) {
2724 global $OUTPUT;
2726 $icons = array();
2727 if ($this->use_standard_editing_ui()) {
2728 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2729 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2730 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2731 array('class' => 'iconsmall')));
2733 return $icons;
2737 * Reads version.php and determines if it is necessary
2738 * to execute the cron job now.
2739 * @return bool
2741 public function is_cron_required() {
2742 global $CFG;
2744 $name = $this->get_name();
2745 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2746 $plugin = new stdClass();
2747 include($versionfile);
2748 if (empty($plugin->cron)) {
2749 return false;
2751 $lastexecuted = $this->get_config('lastcron', 0);
2752 if ($lastexecuted + $plugin->cron < time()) {
2753 return true;
2754 } else {
2755 return false;
2760 * Called for all enabled enrol plugins that returned true from is_cron_required().
2761 * @return void
2763 public function cron() {
2767 * Called when user is about to be deleted
2768 * @param object $user
2769 * @return void
2771 public function user_delete($user) {
2772 global $DB;
2774 $sql = "SELECT e.*
2775 FROM {enrol} e
2776 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2777 WHERE e.enrol = :name AND ue.userid = :userid";
2778 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
2780 $rs = $DB->get_recordset_sql($sql, $params);
2781 foreach($rs as $instance) {
2782 $this->unenrol_user($instance, $user->id);
2784 $rs->close();
2788 * Returns an enrol_user_button that takes the user to a page where they are able to
2789 * enrol users into the managers course through this plugin.
2791 * Optional: If the plugin supports manual enrolments it can choose to override this
2792 * otherwise it shouldn't
2794 * @param course_enrolment_manager $manager
2795 * @return enrol_user_button|false
2797 public function get_manual_enrol_button(course_enrolment_manager $manager) {
2798 return false;
2802 * Gets an array of the user enrolment actions
2804 * @param course_enrolment_manager $manager
2805 * @param stdClass $ue
2806 * @return array An array of user_enrolment_actions
2808 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
2809 $actions = [];
2810 $context = $manager->get_context();
2811 $instance = $ue->enrolmentinstance;
2812 $params = $manager->get_moodlepage()->url->params();
2813 $params['ue'] = $ue->id;
2815 // Edit enrolment action.
2816 if ($this->allow_manage($instance) && has_capability("enrol/{$instance->enrol}:manage", $context)) {
2817 $title = get_string('editenrolment', 'enrol');
2818 $icon = new pix_icon('t/edit', $title);
2819 $url = new moodle_url('/enrol/editenrolment.php', $params);
2820 $actionparams = [
2821 'class' => 'editenrollink',
2822 'rel' => $ue->id,
2823 'data-action' => ENROL_ACTION_EDIT
2825 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2828 // Unenrol action.
2829 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/{$instance->enrol}:unenrol", $context)) {
2830 $title = get_string('unenrol', 'enrol');
2831 $icon = new pix_icon('t/delete', $title);
2832 $url = new moodle_url('/enrol/unenroluser.php', $params);
2833 $actionparams = [
2834 'class' => 'unenrollink',
2835 'rel' => $ue->id,
2836 'data-action' => ENROL_ACTION_UNENROL
2838 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2840 return $actions;
2844 * Returns true if the plugin has one or more bulk operations that can be performed on
2845 * user enrolments.
2847 * @param course_enrolment_manager $manager
2848 * @return bool
2850 public function has_bulk_operations(course_enrolment_manager $manager) {
2851 return false;
2855 * Return an array of enrol_bulk_enrolment_operation objects that define
2856 * the bulk actions that can be performed on user enrolments by the plugin.
2858 * @param course_enrolment_manager $manager
2859 * @return array
2861 public function get_bulk_operations(course_enrolment_manager $manager) {
2862 return array();
2866 * Do any enrolments need expiration processing.
2868 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2870 * @param progress_trace $trace
2871 * @param int $courseid one course, empty mean all
2872 * @return bool true if any data processed, false if not
2874 public function process_expirations(progress_trace $trace, $courseid = null) {
2875 global $DB;
2877 $name = $this->get_name();
2878 if (!enrol_is_enabled($name)) {
2879 $trace->finished();
2880 return false;
2883 $processed = false;
2884 $params = array();
2885 $coursesql = "";
2886 if ($courseid) {
2887 $coursesql = "AND e.courseid = :courseid";
2890 // Deal with expired accounts.
2891 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
2893 if ($action == ENROL_EXT_REMOVED_UNENROL) {
2894 $instances = array();
2895 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2896 FROM {user_enrolments} ue
2897 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2898 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2899 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2900 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
2902 $rs = $DB->get_recordset_sql($sql, $params);
2903 foreach ($rs as $ue) {
2904 if (!$processed) {
2905 $trace->output("Starting processing of enrol_$name expirations...");
2906 $processed = true;
2908 if (empty($instances[$ue->enrolid])) {
2909 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2911 $instance = $instances[$ue->enrolid];
2912 if (!$this->roles_protected()) {
2913 // Let's just guess what extra roles are supposed to be removed.
2914 if ($instance->roleid) {
2915 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
2918 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2919 $this->unenrol_user($instance, $ue->userid);
2920 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2922 $rs->close();
2923 unset($instances);
2925 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
2926 $instances = array();
2927 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2928 FROM {user_enrolments} ue
2929 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2930 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2931 WHERE ue.timeend > 0 AND ue.timeend < :now
2932 AND ue.status = :useractive $coursesql";
2933 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
2934 $rs = $DB->get_recordset_sql($sql, $params);
2935 foreach ($rs as $ue) {
2936 if (!$processed) {
2937 $trace->output("Starting processing of enrol_$name expirations...");
2938 $processed = true;
2940 if (empty($instances[$ue->enrolid])) {
2941 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2943 $instance = $instances[$ue->enrolid];
2945 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
2946 if (!$this->roles_protected()) {
2947 // Let's just guess what roles should be removed.
2948 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
2949 if ($count == 1) {
2950 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
2952 } else if ($count > 1 and $instance->roleid) {
2953 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
2956 // In any case remove all roles that belong to this instance and user.
2957 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
2958 // Final cleanup of subcontexts if there are no more course roles.
2959 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
2960 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
2964 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
2965 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2967 $rs->close();
2968 unset($instances);
2970 } else {
2971 // ENROL_EXT_REMOVED_KEEP means no changes.
2974 if ($processed) {
2975 $trace->output("...finished processing of enrol_$name expirations");
2976 } else {
2977 $trace->output("No expired enrol_$name enrolments detected");
2979 $trace->finished();
2981 return $processed;
2985 * Send expiry notifications.
2987 * Plugin that wants to have expiry notification MUST implement following:
2988 * - expirynotifyhour plugin setting,
2989 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2990 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2991 * expirymessageenrolledsubject and expirymessageenrolledbody),
2992 * - expiry_notification provider in db/messages.php,
2993 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2994 * - something that calls this method, such as cron.
2996 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2998 public function send_expiry_notifications($trace) {
2999 global $DB, $CFG;
3001 $name = $this->get_name();
3002 if (!enrol_is_enabled($name)) {
3003 $trace->finished();
3004 return;
3007 // Unfortunately this may take a long time, it should not be interrupted,
3008 // otherwise users get duplicate notification.
3010 core_php_time_limit::raise();
3011 raise_memory_limit(MEMORY_HUGE);
3014 $expirynotifylast = $this->get_config('expirynotifylast', 0);
3015 $expirynotifyhour = $this->get_config('expirynotifyhour');
3016 if (is_null($expirynotifyhour)) {
3017 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
3018 $trace->finished();
3019 return;
3022 if (!($trace instanceof progress_trace)) {
3023 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
3024 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
3027 $timenow = time();
3028 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
3030 if ($expirynotifylast > $notifytime) {
3031 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
3032 $trace->finished();
3033 return;
3035 } else if ($timenow < $notifytime) {
3036 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
3037 $trace->finished();
3038 return;
3041 $trace->output('Processing '.$name.' enrolment expiration notifications...');
3043 // Notify users responsible for enrolment once every day.
3044 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
3045 FROM {user_enrolments} ue
3046 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
3047 JOIN {course} c ON (c.id = e.courseid)
3048 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
3049 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
3050 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
3051 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
3053 $rs = $DB->get_recordset_sql($sql, $params);
3055 $lastenrollid = 0;
3056 $users = array();
3058 foreach($rs as $ue) {
3059 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
3060 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3061 $users = array();
3063 $lastenrollid = $ue->enrolid;
3065 $enroller = $this->get_enroller($ue->enrolid);
3066 $context = context_course::instance($ue->courseid);
3068 $user = $DB->get_record('user', array('id'=>$ue->userid));
3070 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
3072 if (!$ue->notifyall) {
3073 continue;
3076 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
3077 // Notify enrolled users only once at the start of the threshold.
3078 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3079 continue;
3082 $this->notify_expiry_enrolled($user, $ue, $trace);
3084 $rs->close();
3086 if ($lastenrollid and $users) {
3087 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3090 $trace->output('...notification processing finished.');
3091 $trace->finished();
3093 $this->set_config('expirynotifylast', $timenow);
3097 * Returns the user who is responsible for enrolments for given instance.
3099 * Override if plugin knows anybody better than admin.
3101 * @param int $instanceid enrolment instance id
3102 * @return stdClass user record
3104 protected function get_enroller($instanceid) {
3105 return get_admin();
3109 * Notify user about incoming expiration of their enrolment,
3110 * it is called only if notification of enrolled users (aka students) is enabled in course.
3112 * This is executed only once for each expiring enrolment right
3113 * at the start of the expiration threshold.
3115 * @param stdClass $user
3116 * @param stdClass $ue
3117 * @param progress_trace $trace
3119 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
3120 global $CFG;
3122 $name = $this->get_name();
3124 $oldforcelang = force_current_language($user->lang);
3126 $enroller = $this->get_enroller($ue->enrolid);
3127 $context = context_course::instance($ue->courseid);
3129 $a = new stdClass();
3130 $a->course = format_string($ue->fullname, true, array('context'=>$context));
3131 $a->user = fullname($user, true);
3132 $a->timeend = userdate($ue->timeend, '', $user->timezone);
3133 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
3135 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
3136 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
3138 $message = new \core\message\message();
3139 $message->courseid = $ue->courseid;
3140 $message->notification = 1;
3141 $message->component = 'enrol_'.$name;
3142 $message->name = 'expiry_notification';
3143 $message->userfrom = $enroller;
3144 $message->userto = $user;
3145 $message->subject = $subject;
3146 $message->fullmessage = $body;
3147 $message->fullmessageformat = FORMAT_MARKDOWN;
3148 $message->fullmessagehtml = markdown_to_html($body);
3149 $message->smallmessage = $subject;
3150 $message->contexturlname = $a->course;
3151 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
3153 if (message_send($message)) {
3154 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3155 } else {
3156 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3159 force_current_language($oldforcelang);
3163 * Notify person responsible for enrolments that some user enrolments will be expired soon,
3164 * it is called only if notification of enrollers (aka teachers) is enabled in course.
3166 * This is called repeatedly every day for each course if there are any pending expiration
3167 * in the expiration threshold.
3169 * @param int $eid
3170 * @param array $users
3171 * @param progress_trace $trace
3173 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
3174 global $DB;
3176 $name = $this->get_name();
3178 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
3179 $context = context_course::instance($instance->courseid);
3180 $course = $DB->get_record('course', array('id'=>$instance->courseid));
3182 $enroller = $this->get_enroller($instance->id);
3183 $admin = get_admin();
3185 $oldforcelang = force_current_language($enroller->lang);
3187 foreach($users as $key=>$info) {
3188 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
3191 $a = new stdClass();
3192 $a->course = format_string($course->fullname, true, array('context'=>$context));
3193 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
3194 $a->users = implode("\n", $users);
3195 $a->extendurl = (string)new moodle_url('/user/index.php', array('id'=>$instance->courseid));
3197 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
3198 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
3200 $message = new \core\message\message();
3201 $message->courseid = $course->id;
3202 $message->notification = 1;
3203 $message->component = 'enrol_'.$name;
3204 $message->name = 'expiry_notification';
3205 $message->userfrom = $admin;
3206 $message->userto = $enroller;
3207 $message->subject = $subject;
3208 $message->fullmessage = $body;
3209 $message->fullmessageformat = FORMAT_MARKDOWN;
3210 $message->fullmessagehtml = markdown_to_html($body);
3211 $message->smallmessage = $subject;
3212 $message->contexturlname = $a->course;
3213 $message->contexturl = $a->extendurl;
3215 if (message_send($message)) {
3216 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3217 } else {
3218 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3221 force_current_language($oldforcelang);
3225 * Backup execution step hook to annotate custom fields.
3227 * @param backup_enrolments_execution_step $step
3228 * @param stdClass $enrol
3230 public function backup_annotate_custom_fields(backup_enrolments_execution_step $step, stdClass $enrol) {
3231 // Override as necessary to annotate custom fields in the enrol table.
3235 * Automatic enrol sync executed during restore.
3236 * Useful for automatic sync by course->idnumber or course category.
3237 * @param stdClass $course course record
3239 public function restore_sync_course($course) {
3240 // Override if necessary.
3244 * Restore instance and map settings.
3246 * @param restore_enrolments_structure_step $step
3247 * @param stdClass $data
3248 * @param stdClass $course
3249 * @param int $oldid
3251 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
3252 // Do not call this from overridden methods, restore and set new id there.
3253 $step->set_mapping('enrol', $oldid, 0);
3257 * Restore user enrolment.
3259 * @param restore_enrolments_structure_step $step
3260 * @param stdClass $data
3261 * @param stdClass $instance
3262 * @param int $oldinstancestatus
3263 * @param int $userid
3265 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
3266 // Override as necessary if plugin supports restore of enrolments.
3270 * Restore role assignment.
3272 * @param stdClass $instance
3273 * @param int $roleid
3274 * @param int $userid
3275 * @param int $contextid
3277 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
3278 // No role assignment by default, override if necessary.
3282 * Restore user group membership.
3283 * @param stdClass $instance
3284 * @param int $groupid
3285 * @param int $userid
3287 public function restore_group_member($instance, $groupid, $userid) {
3288 // Implement if you want to restore protected group memberships,
3289 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
3293 * Returns defaults for new instances.
3294 * @since Moodle 3.1
3295 * @return array
3297 public function get_instance_defaults() {
3298 return array();
3302 * Validate a list of parameter names and types.
3303 * @since Moodle 3.1
3305 * @param array $data array of ("fieldname"=>value) of submitted data
3306 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
3307 * @return array of "element_name"=>"error_description" if there are errors,
3308 * or an empty array if everything is OK.
3310 public function validate_param_types($data, $rules) {
3311 $errors = array();
3312 $invalidstr = get_string('invaliddata', 'error');
3313 foreach ($rules as $fieldname => $rule) {
3314 if (is_array($rule)) {
3315 if (!in_array($data[$fieldname], $rule)) {
3316 $errors[$fieldname] = $invalidstr;
3318 } else {
3319 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
3320 $errors[$fieldname] = $invalidstr;
3324 return $errors;