MDL-78962 core/loadingicon: remove jQuery requirement in the API
[moodle.git] / lib / enrollib.php
blobf6de9ee76f42e7a8f42d7a591cd254fa41c779af
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();
480 if (has_capability('moodle/course:renameroles', $coursecontext)) {
481 $url = new moodle_url('/enrol/renameroles.php', array('id' => $course->id));
482 $instancesnode->add(
483 get_string('rolerenaming'),
484 $url,
485 navigation_node::TYPE_SETTING,
486 null,
487 'renameroles'
492 // Manage groups in this course or even frontpage
493 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
494 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
495 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
498 if (has_any_capability(
499 [ 'moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:review'],
500 $coursecontext
501 )) {
502 // Override roles
503 if (has_capability('moodle/role:review', $coursecontext)) {
504 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
505 } else {
506 $url = NULL;
508 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
510 // Add assign or override roles if allowed
511 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
512 if (has_capability('moodle/role:assign', $coursecontext)) {
513 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
514 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
517 // Check role permissions
518 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
519 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
520 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
524 // Deal somehow with users that are not enrolled but still got a role somehow
525 if ($course->id != SITEID) {
526 //TODO, create some new UI for role assignments at course level
527 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
528 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
529 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
533 // just in case nothing was actually added
534 $usersnode->trim_if_empty();
536 if ($course->id != SITEID) {
537 if (isguestuser() or !isloggedin()) {
538 // guest account can not be enrolled - no links for them
539 } else if (is_enrolled($coursecontext)) {
540 // unenrol link if possible
541 foreach ($instances as $instance) {
542 if (!isset($plugins[$instance->enrol])) {
543 continue;
545 $plugin = $plugins[$instance->enrol];
546 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
547 $coursenode->add(get_string('unenrolme', 'core_enrol'), $unenrollink,
548 navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
549 $coursenode->get('unenrolself')->set_force_into_more_menu(true);
550 break;
551 //TODO. deal with multiple unenrol links - not likely case, but still...
554 } else {
555 // enrol link if possible
556 if (is_viewing($coursecontext)) {
557 // better not show any enrol link, this is intended for managers and inspectors
558 } else {
559 foreach ($instances as $instance) {
560 if (!isset($plugins[$instance->enrol])) {
561 continue;
563 $plugin = $plugins[$instance->enrol];
564 if ($plugin->show_enrolme_link($instance)) {
565 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
566 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
567 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
568 break;
577 * Returns list of courses current $USER is enrolled in and can access
579 * The $fields param is a list of field names to ADD so name just the fields you really need,
580 * which will be added and uniq'd.
582 * If $allaccessible is true, this will additionally return courses that the current user is not
583 * enrolled in, but can access because they are open to the user for other reasons (course view
584 * permission, currently viewing course as a guest, or course allows guest access without
585 * password).
587 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
588 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
589 * Allowed prefixes for sort fields are: "ul" for the user_lastaccess table, "c" for the courses table,
590 * "ue" for the user_enrolments table.
591 * @param int $limit max number of courses
592 * @param array $courseids the list of course ids to filter by
593 * @param bool $allaccessible Include courses user is not enrolled in, but can access
594 * @param int $offset Offset the result set by this number
595 * @param array $excludecourses IDs of hidden courses to exclude from search
596 * @return array
598 function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false,
599 $offset = 0, $excludecourses = []) {
600 global $DB, $USER, $CFG;
602 // Allowed prefixes and field names.
603 $allowedprefixesandfields = ['c' => array_keys($DB->get_columns('course')),
604 'ul' => array_keys($DB->get_columns('user_lastaccess')),
605 'ue' => array_keys($DB->get_columns('user_enrolments'))];
607 // Re-Arrange the course sorting according to the admin settings.
608 $sort = enrol_get_courses_sortingsql($sort);
610 // Guest account does not have any enrolled courses.
611 if (!$allaccessible && (isguestuser() or !isloggedin())) {
612 return array();
615 $basefields = [
616 'id', 'category', 'sortorder',
617 'shortname', 'fullname', 'idnumber',
618 'startdate', 'visible',
619 'groupmode', 'groupmodeforce', 'cacherev',
620 'showactivitydates', 'showcompletionconditions',
623 if (empty($fields)) {
624 $fields = $basefields;
625 } else if (is_string($fields)) {
626 // turn the fields from a string to an array
627 $fields = explode(',', $fields);
628 $fields = array_map('trim', $fields);
629 $fields = array_unique(array_merge($basefields, $fields));
630 } else if (is_array($fields)) {
631 $fields = array_unique(array_merge($basefields, $fields));
632 } else {
633 throw new coding_exception('Invalid $fields parameter in enrol_get_my_courses()');
635 if (in_array('*', $fields)) {
636 $fields = array('*');
639 $orderby = "";
640 $sort = trim($sort);
641 $sorttimeaccess = false;
642 if (!empty($sort)) {
643 $rawsorts = explode(',', $sort);
644 $sorts = array();
645 foreach ($rawsorts as $rawsort) {
646 $rawsort = trim($rawsort);
647 // Make sure that there are no more white spaces in sortparams after explode.
648 $sortparams = array_values(array_filter(explode(' ', $rawsort)));
649 // If more than 2 values present then throw coding_exception.
650 if (isset($sortparams[2])) {
651 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
653 // Check the sort ordering if present, at the beginning.
654 if (isset($sortparams[1]) && (preg_match("/^(asc|desc)$/i", $sortparams[1]) === 0)) {
655 throw new coding_exception('Invalid sort direction in $sort parameter in enrol_get_my_courses()');
658 $sortfield = $sortparams[0];
659 $sortdirection = $sortparams[1] ?? 'asc';
660 if (strpos($sortfield, '.') !== false) {
661 $sortfieldparams = explode('.', $sortfield);
662 // Check if more than one dots present in the prefix field.
663 if (isset($sortfieldparams[2])) {
664 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
666 list($prefix, $fieldname) = [$sortfieldparams[0], $sortfieldparams[1]];
667 // Check if the field name matches with the allowed prefix.
668 if (array_key_exists($prefix, $allowedprefixesandfields) &&
669 (in_array($fieldname, $allowedprefixesandfields[$prefix]))) {
670 if ($prefix === 'ul') {
671 $sorts[] = "COALESCE({$prefix}.{$fieldname}, 0) {$sortdirection}";
672 $sorttimeaccess = true;
673 } else {
674 // Check if the field name that matches with the prefix and just append to sorts.
675 $sorts[] = $rawsort;
677 } else {
678 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
680 } else {
681 // Check if the field name matches with $allowedprefixesandfields.
682 $found = false;
683 foreach (array_keys($allowedprefixesandfields) as $prefix) {
684 if (in_array($sortfield, $allowedprefixesandfields[$prefix])) {
685 if ($prefix === 'ul') {
686 $sorts[] = "COALESCE({$prefix}.{$sortfield}, 0) {$sortdirection}";
687 $sorttimeaccess = true;
688 } else {
689 $sorts[] = "{$prefix}.{$sortfield} {$sortdirection}";
691 $found = true;
692 break;
695 if (!$found) {
696 // The param is not found in $allowedprefixesandfields.
697 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
701 $sort = implode(',', $sorts);
702 $orderby = "ORDER BY $sort";
705 $wheres = ['c.id <> ' . SITEID];
706 $params = [];
708 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
709 // list _only_ this course - anything else is asking for trouble...
710 $wheres[] = "courseid = :loginas";
711 $params['loginas'] = $USER->loginascontext->instanceid;
714 $coursefields = 'c.' .join(',c.', $fields);
715 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
716 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
717 $params['contextlevel'] = CONTEXT_COURSE;
718 $wheres = implode(" AND ", $wheres);
720 $timeaccessselect = "";
721 $timeaccessjoin = "";
723 if (!empty($courseids)) {
724 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
725 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
726 $params = array_merge($params, $courseidsparams);
729 if (!empty($excludecourses)) {
730 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($excludecourses, SQL_PARAMS_NAMED, 'param', false);
731 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
732 $params = array_merge($params, $courseidsparams);
735 $courseidsql = "";
736 // Logged-in, non-guest users get their enrolled courses.
737 if (!isguestuser() && isloggedin()) {
738 $courseidsql .= "
739 SELECT DISTINCT e.courseid
740 FROM {enrol} e
741 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid1)
742 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart <= :now1
743 AND (ue.timeend = 0 OR ue.timeend > :now2)";
744 $params['userid1'] = $USER->id;
745 $params['active'] = ENROL_USER_ACTIVE;
746 $params['enabled'] = ENROL_INSTANCE_ENABLED;
747 $params['now1'] = $params['now2'] = time();
749 if ($sorttimeaccess) {
750 $params['userid2'] = $USER->id;
751 $timeaccessselect = ', ul.timeaccess as lastaccessed';
752 $timeaccessjoin = "LEFT JOIN {user_lastaccess} ul ON (ul.courseid = c.id AND ul.userid = :userid2)";
756 // When including non-enrolled but accessible courses...
757 if ($allaccessible) {
758 if (is_siteadmin()) {
759 // Site admins can access all courses.
760 $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
761 } else {
762 // If we used the enrolment as well, then this will be UNIONed.
763 if ($courseidsql) {
764 $courseidsql .= " UNION ";
767 // Include courses with guest access and no password.
768 $courseidsql .= "
769 SELECT DISTINCT e.courseid
770 FROM {enrol} e
771 WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
772 $params['emptypass'] = '';
773 $params['enabled2'] = ENROL_INSTANCE_ENABLED;
775 // Include courses where the current user is currently using guest access (may include
776 // those which require a password).
777 $courseids = [];
778 $accessdata = get_user_accessdata($USER->id);
779 foreach ($accessdata['ra'] as $contextpath => $roles) {
780 if (array_key_exists($CFG->guestroleid, $roles)) {
781 // Work out the course id from context path.
782 $context = context::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
783 if ($context instanceof context_course) {
784 $courseids[$context->instanceid] = true;
789 // Include courses where the current user has moodle/course:view capability.
790 $courses = get_user_capability_course('moodle/course:view', null, false);
791 if (!$courses) {
792 $courses = [];
794 foreach ($courses as $course) {
795 $courseids[$course->id] = true;
798 // If there are any in either category, list them individually.
799 if ($courseids) {
800 list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
801 array_keys($courseids), SQL_PARAMS_NAMED);
802 $courseidsql .= "
803 UNION
804 SELECT DISTINCT c3.id AS courseid
805 FROM {course} c3
806 WHERE c3.id $allowedsql";
807 $params = array_merge($params, $allowedparams);
812 // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
813 // we have the subselect there.
814 $sql = "SELECT $coursefields $ccselect $timeaccessselect
815 FROM {course} c
816 JOIN ($courseidsql) en ON (en.courseid = c.id)
817 $timeaccessjoin
818 $ccjoin
819 WHERE $wheres
820 $orderby";
822 $courses = $DB->get_records_sql($sql, $params, $offset, $limit);
824 // preload contexts and check visibility
825 foreach ($courses as $id=>$course) {
826 context_helper::preload_from_record($course);
827 if (!$course->visible) {
828 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
829 unset($courses[$id]);
830 continue;
832 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
833 unset($courses[$id]);
834 continue;
837 $courses[$id] = $course;
840 //wow! Is that really all? :-D
842 return $courses;
846 * Returns course enrolment information icons.
848 * @param object $course
849 * @param array $instances enrol instances of this course, improves performance
850 * @return array of pix_icon
852 function enrol_get_course_info_icons($course, array $instances = NULL) {
853 $icons = array();
854 if (is_null($instances)) {
855 $instances = enrol_get_instances($course->id, true);
857 $plugins = enrol_get_plugins(true);
858 foreach ($plugins as $name => $plugin) {
859 $pis = array();
860 foreach ($instances as $instance) {
861 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
862 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
863 continue;
865 if ($instance->enrol == $name) {
866 $pis[$instance->id] = $instance;
869 if ($pis) {
870 $icons = array_merge($icons, $plugin->get_info_icons($pis));
873 return $icons;
877 * Returns SQL ORDER arguments which reflect the admin settings to sort my courses.
879 * @param string|null $sort SQL ORDER arguments which were originally requested (optionally).
880 * @return string SQL ORDER arguments.
882 function enrol_get_courses_sortingsql($sort = null) {
883 global $CFG;
885 // Prepare the visible SQL fragment as empty.
886 $visible = '';
887 // Only create a visible SQL fragment if the caller didn't already pass a sort order which contains the visible field.
888 if ($sort === null || strpos($sort, 'visible') === false) {
889 // If the admin did not explicitly want to have shown and hidden courses sorted as one list, we will sort hidden
890 // courses to the end of the course list.
891 if (!isset($CFG->navsortmycourseshiddenlast) || $CFG->navsortmycourseshiddenlast == true) {
892 $visible = 'visible DESC, ';
896 // Only create a sortorder SQL fragment if the caller didn't already pass one.
897 if ($sort === null) {
898 // If the admin has configured a course sort order, we will use this.
899 if (!empty($CFG->navsortmycoursessort)) {
900 $sort = $CFG->navsortmycoursessort . ' ASC';
902 // Otherwise we will fall back to the sortorder sorting.
903 } else {
904 $sort = 'sortorder ASC';
908 return $visible . $sort;
912 * Returns course enrolment detailed information.
914 * @param object $course
915 * @return array of html fragments - can be used to construct lists
917 function enrol_get_course_description_texts($course) {
918 $lines = array();
919 $instances = enrol_get_instances($course->id, true);
920 $plugins = enrol_get_plugins(true);
921 foreach ($instances as $instance) {
922 if (!isset($plugins[$instance->enrol])) {
923 //weird
924 continue;
926 $plugin = $plugins[$instance->enrol];
927 $text = $plugin->get_description_text($instance);
928 if ($text !== NULL) {
929 $lines[] = $text;
932 return $lines;
936 * Returns list of courses user is enrolled into.
938 * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
940 * The $fields param is a list of field names to ADD so name just the fields you really need,
941 * which will be added and uniq'd.
943 * @param int $userid User whose courses are returned, defaults to the current user.
944 * @param bool $onlyactive Return only active enrolments in courses user may see.
945 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
946 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
947 * @return array
949 function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
950 global $DB;
952 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
954 // preload contexts and check visibility
955 if ($onlyactive) {
956 foreach ($courses as $id=>$course) {
957 context_helper::preload_from_record($course);
958 if (!$course->visible) {
959 if (!$context = context_course::instance($id)) {
960 unset($courses[$id]);
961 continue;
963 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
964 unset($courses[$id]);
965 continue;
971 return $courses;
975 * Returns list of roles per users into course.
977 * @param int $courseid Course id.
978 * @return array Array[$userid][$roleid] = role_assignment.
980 function enrol_get_course_users_roles(int $courseid) : array {
981 global $DB;
983 $context = context_course::instance($courseid);
985 $roles = array();
987 $records = $DB->get_recordset('role_assignments', array('contextid' => $context->id));
988 foreach ($records as $record) {
989 if (isset($roles[$record->userid]) === false) {
990 $roles[$record->userid] = array();
992 $roles[$record->userid][$record->roleid] = $record;
994 $records->close();
996 return $roles;
1000 * Can user access at least one enrolled course?
1002 * Cheat if necessary, but find out as fast as possible!
1004 * @param int|stdClass $user null means use current user
1005 * @return bool
1007 function enrol_user_sees_own_courses($user = null) {
1008 global $USER;
1010 if ($user === null) {
1011 $user = $USER;
1013 $userid = is_object($user) ? $user->id : $user;
1015 // Guest account does not have any courses
1016 if (isguestuser($userid) or empty($userid)) {
1017 return false;
1020 // Let's cheat here if this is the current user,
1021 // if user accessed any course recently, then most probably
1022 // we do not need to query the database at all.
1023 if ($USER->id == $userid) {
1024 if (!empty($USER->enrol['enrolled'])) {
1025 foreach ($USER->enrol['enrolled'] as $until) {
1026 if ($until > time()) {
1027 return true;
1033 // Now the slow way.
1034 $courses = enrol_get_all_users_courses($userid, true);
1035 foreach($courses as $course) {
1036 if ($course->visible) {
1037 return true;
1039 context_helper::preload_from_record($course);
1040 $context = context_course::instance($course->id);
1041 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
1042 return true;
1046 return false;
1050 * Returns list of courses user is enrolled into without performing any capability checks.
1052 * The $fields param is a list of field names to ADD so name just the fields you really need,
1053 * which will be added and uniq'd.
1055 * @param int $userid User whose courses are returned, defaults to the current user.
1056 * @param bool $onlyactive Return only active enrolments in courses user may see.
1057 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
1058 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
1059 * @return array
1061 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
1062 global $DB;
1064 // Re-Arrange the course sorting according to the admin settings.
1065 $sort = enrol_get_courses_sortingsql($sort);
1067 // Guest account does not have any courses
1068 if (isguestuser($userid) or empty($userid)) {
1069 return(array());
1072 $basefields = array('id', 'category', 'sortorder',
1073 'shortname', 'fullname', 'idnumber',
1074 'startdate', 'visible',
1075 'defaultgroupingid',
1076 'groupmode', 'groupmodeforce');
1078 if (empty($fields)) {
1079 $fields = $basefields;
1080 } else if (is_string($fields)) {
1081 // turn the fields from a string to an array
1082 $fields = explode(',', $fields);
1083 $fields = array_map('trim', $fields);
1084 $fields = array_unique(array_merge($basefields, $fields));
1085 } else if (is_array($fields)) {
1086 $fields = array_unique(array_merge($basefields, $fields));
1087 } else {
1088 throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
1090 if (in_array('*', $fields)) {
1091 $fields = array('*');
1094 $orderby = "";
1095 $sort = trim($sort);
1096 if (!empty($sort)) {
1097 $rawsorts = explode(',', $sort);
1098 $sorts = array();
1099 foreach ($rawsorts as $rawsort) {
1100 $rawsort = trim($rawsort);
1101 if (strpos($rawsort, 'c.') === 0) {
1102 $rawsort = substr($rawsort, 2);
1104 $sorts[] = trim($rawsort);
1106 $sort = 'c.'.implode(',c.', $sorts);
1107 $orderby = "ORDER BY $sort";
1110 $params = [];
1112 if ($onlyactive) {
1113 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
1114 $params['now1'] = round(time(), -2); // improves db caching
1115 $params['now2'] = $params['now1'];
1116 $params['active'] = ENROL_USER_ACTIVE;
1117 $params['enabled'] = ENROL_INSTANCE_ENABLED;
1118 } else {
1119 $subwhere = "";
1122 $coursefields = 'c.' .join(',c.', $fields);
1123 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1124 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1125 $params['contextlevel'] = CONTEXT_COURSE;
1127 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
1128 $sql = "SELECT $coursefields $ccselect
1129 FROM {course} c
1130 JOIN (SELECT DISTINCT e.courseid
1131 FROM {enrol} e
1132 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
1133 $subwhere
1134 ) en ON (en.courseid = c.id)
1135 $ccjoin
1136 WHERE c.id <> " . SITEID . "
1137 $orderby";
1138 $params['userid'] = $userid;
1140 $courses = $DB->get_records_sql($sql, $params);
1142 return $courses;
1148 * Called when user is about to be deleted.
1149 * @param object $user
1150 * @return void
1152 function enrol_user_delete($user) {
1153 global $DB;
1155 $plugins = enrol_get_plugins(true);
1156 foreach ($plugins as $plugin) {
1157 $plugin->user_delete($user);
1160 // force cleanup of all broken enrolments
1161 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
1165 * Called when course is about to be deleted.
1166 * If a user id is passed, only enrolments that the user has permission to un-enrol will be removed,
1167 * otherwise all enrolments in the course will be removed.
1169 * @param stdClass $course
1170 * @param int|null $userid
1171 * @return void
1173 function enrol_course_delete($course, $userid = null) {
1174 global $DB;
1176 $context = context_course::instance($course->id);
1177 $instances = enrol_get_instances($course->id, false);
1178 $plugins = enrol_get_plugins(true);
1180 if ($userid) {
1181 // If the user id is present, include only course enrolment instances which allow manual unenrolment and
1182 // the given user have a capability to perform unenrolment.
1183 $instances = array_filter($instances, function($instance) use ($userid, $plugins, $context) {
1184 $unenrolcap = "enrol/{$instance->enrol}:unenrol";
1185 return $plugins[$instance->enrol]->allow_unenrol($instance) &&
1186 has_capability($unenrolcap, $context, $userid);
1190 foreach ($instances as $instance) {
1191 if (isset($plugins[$instance->enrol])) {
1192 $plugins[$instance->enrol]->delete_instance($instance);
1194 // low level delete in case plugin did not do it
1195 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
1196 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1197 $DB->delete_records('enrol', array('id'=>$instance->id));
1202 * Try to enrol user via default internal auth plugin.
1204 * For now this is always using the manual enrol plugin...
1206 * @param $courseid
1207 * @param $userid
1208 * @param $roleid
1209 * @param $timestart
1210 * @param $timeend
1211 * @return bool success
1213 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
1214 global $DB;
1216 //note: this is hardcoded to manual plugin for now
1218 if (!enrol_is_enabled('manual')) {
1219 return false;
1222 if (!$enrol = enrol_get_plugin('manual')) {
1223 return false;
1225 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
1226 return false;
1229 if ($roleid && !$DB->record_exists('role', ['id' => $roleid])) {
1230 return false;
1233 $instance = reset($instances);
1234 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
1236 return true;
1240 * Is there a chance users might self enrol
1241 * @param int $courseid
1242 * @return bool
1244 function enrol_selfenrol_available($courseid) {
1245 $result = false;
1247 $plugins = enrol_get_plugins(true);
1248 $enrolinstances = enrol_get_instances($courseid, true);
1249 foreach($enrolinstances as $instance) {
1250 if (!isset($plugins[$instance->enrol])) {
1251 continue;
1253 if ($instance->enrol === 'guest') {
1254 continue;
1256 if ((isguestuser() || !isloggedin()) &&
1257 ($plugins[$instance->enrol]->is_self_enrol_available($instance) === true)) {
1258 $result = true;
1259 break;
1261 if ($plugins[$instance->enrol]->show_enrolme_link($instance) === true) {
1262 $result = true;
1263 break;
1267 return $result;
1271 * This function returns the end of current active user enrolment.
1273 * It deals correctly with multiple overlapping user enrolments.
1275 * @param int $courseid
1276 * @param int $userid
1277 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
1279 function enrol_get_enrolment_end($courseid, $userid) {
1280 global $DB;
1282 $sql = "SELECT ue.*
1283 FROM {user_enrolments} ue
1284 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1285 JOIN {user} u ON u.id = ue.userid
1286 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1287 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
1289 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1290 return false;
1293 $changes = array();
1295 foreach ($enrolments as $ue) {
1296 $start = (int)$ue->timestart;
1297 $end = (int)$ue->timeend;
1298 if ($end != 0 and $end < $start) {
1299 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
1300 continue;
1302 if (isset($changes[$start])) {
1303 $changes[$start] = $changes[$start] + 1;
1304 } else {
1305 $changes[$start] = 1;
1307 if ($end === 0) {
1308 // no end
1309 } else if (isset($changes[$end])) {
1310 $changes[$end] = $changes[$end] - 1;
1311 } else {
1312 $changes[$end] = -1;
1316 // let's sort then enrolment starts&ends and go through them chronologically,
1317 // looking for current status and the next future end of enrolment
1318 ksort($changes);
1320 $now = time();
1321 $current = 0;
1322 $present = null;
1324 foreach ($changes as $time => $change) {
1325 if ($time > $now) {
1326 if ($present === null) {
1327 // we have just went past current time
1328 $present = $current;
1329 if ($present < 1) {
1330 // no enrolment active
1331 return false;
1334 if ($present !== null) {
1335 // we are already in the future - look for possible end
1336 if ($current + $change < 1) {
1337 return $time;
1341 $current += $change;
1344 if ($current > 0) {
1345 return 0;
1346 } else {
1347 return false;
1352 * Is current user accessing course via this enrolment method?
1354 * This is intended for operations that are going to affect enrol instances.
1356 * @param stdClass $instance enrol instance
1357 * @return bool
1359 function enrol_accessing_via_instance(stdClass $instance) {
1360 global $DB, $USER;
1362 if (empty($instance->id)) {
1363 return false;
1366 if (is_siteadmin()) {
1367 // Admins may go anywhere.
1368 return false;
1371 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
1375 * Returns true if user is enrolled (is participating) in course
1376 * this is intended for students and teachers.
1378 * Since 2.2 the result for active enrolments and current user are cached.
1380 * @param context $context
1381 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1382 * @param string $withcapability extra capability name
1383 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1384 * @return bool
1386 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1387 global $USER, $DB;
1389 // First find the course context.
1390 $coursecontext = $context->get_course_context();
1392 // Make sure there is a real user specified.
1393 if ($user === null) {
1394 $userid = isset($USER->id) ? $USER->id : 0;
1395 } else {
1396 $userid = is_object($user) ? $user->id : $user;
1399 if (empty($userid)) {
1400 // Not-logged-in!
1401 return false;
1402 } else if (isguestuser($userid)) {
1403 // Guest account can not be enrolled anywhere.
1404 return false;
1407 // Note everybody participates on frontpage, so for other contexts...
1408 if ($coursecontext->instanceid != SITEID) {
1409 // Try cached info first - the enrolled flag is set only when active enrolment present.
1410 if ($USER->id == $userid) {
1411 $coursecontext->reload_if_dirty();
1412 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1413 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1414 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1415 return false;
1417 return true;
1422 if ($onlyactive) {
1423 // Look for active enrolments only.
1424 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1426 if ($until === false) {
1427 return false;
1430 if ($USER->id == $userid) {
1431 if ($until == 0) {
1432 $until = ENROL_MAX_TIMESTAMP;
1434 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1435 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1436 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1437 remove_temp_course_roles($coursecontext);
1441 } else {
1442 // Any enrolment is good for us here, even outdated, disabled or inactive.
1443 $sql = "SELECT 'x'
1444 FROM {user_enrolments} ue
1445 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1446 JOIN {user} u ON u.id = ue.userid
1447 WHERE ue.userid = :userid AND u.deleted = 0";
1448 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid);
1449 if (!$DB->record_exists_sql($sql, $params)) {
1450 return false;
1455 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1456 return false;
1459 return true;
1463 * Returns an array of joins, wheres and params that will limit the group of
1464 * users to only those enrolled and with given capability (if specified).
1466 * Note this join will return duplicate rows for users who have been enrolled
1467 * several times (e.g. as manual enrolment, and as self enrolment). You may
1468 * need to use a SELECT DISTINCT in your query (see get_enrolled_sql for example).
1470 * In case is guaranteed some of the joins never match any rows, the resulting
1471 * join_sql->cannotmatchanyrows will be true. This happens when the capability
1472 * is prohibited.
1474 * @param context $context
1475 * @param string $prefix optional, a prefix to the user id column
1476 * @param string|array $capability optional, may include a capability name, or array of names.
1477 * If an array is provided then this is the equivalent of a logical 'OR',
1478 * i.e. the user needs to have one of these capabilities.
1479 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1480 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1481 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1482 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1483 * @return \core\dml\sql_join Contains joins, wheres, params and cannotmatchanyrows
1485 function get_enrolled_with_capabilities_join(context $context, $prefix = '', $capability = '', $groupids = 0,
1486 $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1487 $uid = $prefix . 'u.id';
1488 $joins = array();
1489 $wheres = array();
1490 $cannotmatchanyrows = false;
1492 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended, $enrolid);
1493 $joins[] = $enrolledjoin->joins;
1494 $wheres[] = $enrolledjoin->wheres;
1495 $params = $enrolledjoin->params;
1496 $cannotmatchanyrows = $cannotmatchanyrows || $enrolledjoin->cannotmatchanyrows;
1498 if (!empty($capability)) {
1499 $capjoin = get_with_capability_join($context, $capability, $uid);
1500 $joins[] = $capjoin->joins;
1501 $wheres[] = $capjoin->wheres;
1502 $params = array_merge($params, $capjoin->params);
1503 $cannotmatchanyrows = $cannotmatchanyrows || $capjoin->cannotmatchanyrows;
1506 if ($groupids) {
1507 $groupjoin = groups_get_members_join($groupids, $uid, $context);
1508 $joins[] = $groupjoin->joins;
1509 $params = array_merge($params, $groupjoin->params);
1510 if (!empty($groupjoin->wheres)) {
1511 $wheres[] = $groupjoin->wheres;
1513 $cannotmatchanyrows = $cannotmatchanyrows || $groupjoin->cannotmatchanyrows;
1516 $joins = implode("\n", $joins);
1517 $wheres[] = "{$prefix}u.deleted = 0";
1518 $wheres = implode(" AND ", $wheres);
1520 return new \core\dml\sql_join($joins, $wheres, $params, $cannotmatchanyrows);
1524 * Returns array with sql code and parameters returning all ids
1525 * of users enrolled into course.
1527 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1529 * @param context $context
1530 * @param string $withcapability
1531 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1532 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1533 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1534 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1535 * @return array list($sql, $params)
1537 function get_enrolled_sql(context $context, $withcapability = '', $groupids = 0, $onlyactive = false, $onlysuspended = false,
1538 $enrolid = 0) {
1540 // Use unique prefix just in case somebody makes some SQL magic with the result.
1541 static $i = 0;
1542 $i++;
1543 $prefix = 'eu' . $i . '_';
1545 $capjoin = get_enrolled_with_capabilities_join(
1546 $context, $prefix, $withcapability, $groupids, $onlyactive, $onlysuspended, $enrolid);
1548 $sql = "SELECT DISTINCT {$prefix}u.id
1549 FROM {user} {$prefix}u
1550 $capjoin->joins
1551 WHERE $capjoin->wheres";
1553 return array($sql, $capjoin->params);
1557 * Returns array with sql joins and parameters returning all ids
1558 * of users enrolled into course.
1560 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1562 * @throws coding_exception
1564 * @param context $context
1565 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1566 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1567 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1568 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1569 * @return \core\dml\sql_join Contains joins, wheres, params
1571 function get_enrolled_join(context $context, $useridcolumn, $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1572 // Use unique prefix just in case somebody makes some SQL magic with the result.
1573 static $i = 0;
1574 $i++;
1575 $prefix = 'ej' . $i . '_';
1577 // First find the course context.
1578 $coursecontext = $context->get_course_context();
1580 $isfrontpage = ($coursecontext->instanceid == SITEID);
1582 if ($onlyactive && $onlysuspended) {
1583 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1585 if ($isfrontpage && $onlysuspended) {
1586 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1589 $joins = array();
1590 $wheres = array();
1591 $params = array();
1593 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1595 // Note all users are "enrolled" on the frontpage, but for others...
1596 if (!$isfrontpage) {
1597 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1598 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1600 $enrolconditions = array(
1601 "{$prefix}e.id = {$prefix}ue.enrolid",
1602 "{$prefix}e.courseid = :{$prefix}courseid",
1604 if ($enrolid) {
1605 $enrolconditions[] = "{$prefix}e.id = :{$prefix}enrolid";
1606 $params[$prefix . 'enrolid'] = $enrolid;
1608 $enrolconditionssql = implode(" AND ", $enrolconditions);
1609 $ejoin = "JOIN {enrol} {$prefix}e ON ($enrolconditionssql)";
1611 $params[$prefix.'courseid'] = $coursecontext->instanceid;
1613 if (!$onlysuspended) {
1614 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1615 $joins[] = $ejoin;
1616 if ($onlyactive) {
1617 $wheres[] = "$where1 AND $where2";
1619 } else {
1620 // Suspended only where there is enrolment but ALL are suspended.
1621 // Consider multiple enrols where one is not suspended or plain role_assign.
1622 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1623 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1624 $enrolconditions = array(
1625 "{$prefix}e1.id = {$prefix}ue1.enrolid",
1626 "{$prefix}e1.courseid = :{$prefix}_e1_courseid",
1628 if ($enrolid) {
1629 $enrolconditions[] = "{$prefix}e1.id = :{$prefix}e1_enrolid";
1630 $params[$prefix . 'e1_enrolid'] = $enrolid;
1632 $enrolconditionssql = implode(" AND ", $enrolconditions);
1633 $joins[] = "JOIN {enrol} {$prefix}e1 ON ($enrolconditionssql)";
1634 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
1635 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1638 if ($onlyactive || $onlysuspended) {
1639 $now = round(time(), -2); // Rounding helps caching in DB.
1640 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED,
1641 $prefix . 'active' => ENROL_USER_ACTIVE,
1642 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1646 $joins = implode("\n", $joins);
1647 $wheres = implode(" AND ", $wheres);
1649 return new \core\dml\sql_join($joins, $wheres, $params);
1653 * Returns list of users enrolled into course.
1655 * @param context $context
1656 * @param string $withcapability
1657 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1658 * @param string $userfields requested user record fields
1659 * @param string $orderby
1660 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1661 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1662 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1663 * @return array of user records
1665 function get_enrolled_users(context $context, $withcapability = '', $groupids = 0, $userfields = 'u.*', $orderby = null,
1666 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1667 global $DB;
1669 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupids, $onlyactive);
1670 $sql = "SELECT $userfields
1671 FROM {user} u
1672 JOIN ($esql) je ON je.id = u.id
1673 WHERE u.deleted = 0";
1675 if ($orderby) {
1676 $sql = "$sql ORDER BY $orderby";
1677 } else {
1678 list($sort, $sortparams) = users_order_by_sql('u');
1679 $sql = "$sql ORDER BY $sort";
1680 $params = array_merge($params, $sortparams);
1683 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1687 * Counts list of users enrolled into course (as per above function)
1689 * @param context $context
1690 * @param string $withcapability
1691 * @param int|array $groupids The groupids, 0 or [] means all groups and USERSWITHOUTGROUP no group
1692 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1693 * @return int number of users enrolled into course
1695 function count_enrolled_users(context $context, $withcapability = '', $groupids = 0, $onlyactive = false) {
1696 global $DB;
1698 $capjoin = get_enrolled_with_capabilities_join(
1699 $context, '', $withcapability, $groupids, $onlyactive);
1701 $sql = "SELECT COUNT(DISTINCT u.id)
1702 FROM {user} u
1703 $capjoin->joins
1704 WHERE $capjoin->wheres AND u.deleted = 0";
1706 return $DB->count_records_sql($sql, $capjoin->params);
1710 * Send welcome email "from" options.
1712 * @return array list of from options
1714 function enrol_send_welcome_email_options() {
1715 return [
1716 ENROL_DO_NOT_SEND_EMAIL => get_string('no'),
1717 ENROL_SEND_EMAIL_FROM_COURSE_CONTACT => get_string('sendfromcoursecontact', 'enrol'),
1718 ENROL_SEND_EMAIL_FROM_KEY_HOLDER => get_string('sendfromkeyholder', 'enrol'),
1719 ENROL_SEND_EMAIL_FROM_NOREPLY => get_string('sendfromnoreply', 'enrol')
1724 * Serve the user enrolment form as a fragment.
1726 * @param array $args List of named arguments for the fragment loader.
1727 * @return string
1729 function enrol_output_fragment_user_enrolment_form($args) {
1730 global $CFG, $DB;
1732 $args = (object) $args;
1733 $context = $args->context;
1734 require_capability('moodle/course:enrolreview', $context);
1736 $ueid = $args->ueid;
1737 $userenrolment = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
1738 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid], '*', MUST_EXIST);
1739 $plugin = enrol_get_plugin($instance->enrol);
1740 $customdata = [
1741 'ue' => $userenrolment,
1742 'modal' => true,
1743 'enrolinstancename' => $plugin->get_instance_name($instance)
1746 // Set the data if applicable.
1747 $data = [];
1748 if (isset($args->formdata)) {
1749 $serialiseddata = json_decode($args->formdata);
1750 parse_str($serialiseddata, $data);
1753 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1754 $mform = new \enrol_user_enrolment_form(null, $customdata, 'post', '', null, true, $data);
1756 if (!empty($data)) {
1757 $mform->set_data($data);
1758 $mform->is_validated();
1761 return $mform->render();
1765 * Returns the course where a user enrolment belong to.
1767 * @param int $ueid user_enrolments id
1768 * @return stdClass
1770 function enrol_get_course_by_user_enrolment_id($ueid) {
1771 global $DB;
1772 $sql = "SELECT c.* FROM {user_enrolments} ue
1773 JOIN {enrol} e ON e.id = ue.enrolid
1774 JOIN {course} c ON c.id = e.courseid
1775 WHERE ue.id = :ueid";
1776 return $DB->get_record_sql($sql, array('ueid' => $ueid));
1780 * Return all users enrolled in a course.
1782 * @param int $courseid Course id or false if using $uefilter (user enrolment ids may belong to different courses)
1783 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1784 * @param array $usersfilter Limit the results obtained to this list of user ids. $uefilter compatibility not guaranteed.
1785 * @param array $uefilter Limit the results obtained to this list of user enrolment ids. $usersfilter compatibility not guaranteed.
1786 * @return stdClass[]
1788 function enrol_get_course_users($courseid = false, $onlyactive = false, $usersfilter = array(), $uefilter = array()) {
1789 global $DB;
1791 if (!$courseid && !$usersfilter && !$uefilter) {
1792 throw new \coding_exception('You should specify at least 1 filter: courseid, users or user enrolments');
1795 $sql = "SELECT ue.id AS ueid, ue.status AS uestatus, ue.enrolid AS ueenrolid, ue.timestart AS uetimestart,
1796 ue.timeend AS uetimeend, ue.modifierid AS uemodifierid, ue.timecreated AS uetimecreated,
1797 ue.timemodified AS uetimemodified, e.status AS estatus,
1798 u.* FROM {user_enrolments} ue
1799 JOIN {enrol} e ON e.id = ue.enrolid
1800 JOIN {user} u ON ue.userid = u.id
1801 WHERE ";
1802 $params = array();
1804 if ($courseid) {
1805 $conditions[] = "e.courseid = :courseid";
1806 $params['courseid'] = $courseid;
1809 if ($onlyactive) {
1810 $conditions[] = "ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND " .
1811 "(ue.timeend = 0 OR ue.timeend > :now2)";
1812 // Improves db caching.
1813 $params['now1'] = round(time(), -2);
1814 $params['now2'] = $params['now1'];
1815 $params['active'] = ENROL_USER_ACTIVE;
1816 $params['enabled'] = ENROL_INSTANCE_ENABLED;
1819 if ($usersfilter) {
1820 list($usersql, $userparams) = $DB->get_in_or_equal($usersfilter, SQL_PARAMS_NAMED);
1821 $conditions[] = "ue.userid $usersql";
1822 $params = $params + $userparams;
1825 if ($uefilter) {
1826 list($uesql, $ueparams) = $DB->get_in_or_equal($uefilter, SQL_PARAMS_NAMED);
1827 $conditions[] = "ue.id $uesql";
1828 $params = $params + $ueparams;
1831 return $DB->get_records_sql($sql . ' ' . implode(' AND ', $conditions), $params);
1835 * Get the list of options for the enrolment period dropdown
1837 * @return array List of options for the enrolment period dropdown
1839 function enrol_get_period_list() {
1840 $periodmenu = [];
1841 $periodmenu[''] = get_string('unlimited');
1842 for ($i = 1; $i <= 365; $i++) {
1843 $seconds = $i * DAYSECS;
1844 $periodmenu[$seconds] = get_string('numdays', '', $i);
1846 return $periodmenu;
1850 * Calculate duration base on start time and end time
1852 * @param int $timestart Time start
1853 * @param int $timeend Time end
1854 * @return float|int Calculated duration
1856 function enrol_calculate_duration($timestart, $timeend) {
1857 $duration = floor(($timeend - $timestart) / DAYSECS) * DAYSECS;
1858 return $duration;
1862 * Enrolment plugins abstract class.
1864 * All enrol plugins should be based on this class,
1865 * this is also the main source of documentation.
1867 * @copyright 2010 Petr Skoda {@link http://skodak.org}
1868 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1870 abstract class enrol_plugin {
1871 protected $config = null;
1874 * Returns name of this enrol plugin
1875 * @return string
1877 public function get_name() {
1878 // second word in class is always enrol name, sorry, no fancy plugin names with _
1879 $words = explode('_', get_class($this));
1880 return $words[1];
1884 * Returns localised name of enrol instance
1886 * @param object $instance (null is accepted too)
1887 * @return string
1889 public function get_instance_name($instance) {
1890 if (empty($instance->name)) {
1891 $enrol = $this->get_name();
1892 return get_string('pluginname', 'enrol_'.$enrol);
1893 } else {
1894 $context = context_course::instance($instance->courseid);
1895 return format_string($instance->name, true, array('context'=>$context));
1900 * Returns optional enrolment information icons.
1902 * This is used in course list for quick overview of enrolment options.
1904 * We are not using single instance parameter because sometimes
1905 * we might want to prevent icon repetition when multiple instances
1906 * of one type exist. One instance may also produce several icons.
1908 * @param array $instances all enrol instances of this type in one course
1909 * @return array of pix_icon
1911 public function get_info_icons(array $instances) {
1912 return array();
1916 * Returns optional enrolment instance description text.
1918 * This is used in detailed course information.
1921 * @param object $instance
1922 * @return string short html text
1924 public function get_description_text($instance) {
1925 return null;
1929 * Makes sure config is loaded and cached.
1930 * @return void
1932 protected function load_config() {
1933 if (!isset($this->config)) {
1934 $name = $this->get_name();
1935 $this->config = get_config("enrol_$name");
1940 * Returns plugin config value
1941 * @param string $name
1942 * @param string $default value if config does not exist yet
1943 * @return string value or default
1945 public function get_config($name, $default = NULL) {
1946 $this->load_config();
1947 return isset($this->config->$name) ? $this->config->$name : $default;
1951 * Sets plugin config value
1952 * @param string $name name of config
1953 * @param string $value string config value, null means delete
1954 * @return string value
1956 public function set_config($name, $value) {
1957 $pluginname = $this->get_name();
1958 $this->load_config();
1959 if ($value === NULL) {
1960 unset($this->config->$name);
1961 } else {
1962 $this->config->$name = $value;
1964 set_config($name, $value, "enrol_$pluginname");
1968 * Does this plugin assign protected roles are can they be manually removed?
1969 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1971 public function roles_protected() {
1972 return true;
1976 * Does this plugin allow manual enrolments?
1978 * @param stdClass $instance course enrol instance
1979 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1981 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1983 public function allow_enrol(stdClass $instance) {
1984 return false;
1988 * Does this plugin allow manual unenrolment of all users?
1989 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1991 * @param stdClass $instance course enrol instance
1992 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1994 public function allow_unenrol(stdClass $instance) {
1995 return false;
1999 * Does this plugin allow manual unenrolment of a specific user?
2000 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
2002 * This is useful especially for synchronisation plugins that
2003 * do suspend instead of full unenrolment.
2005 * @param stdClass $instance course enrol instance
2006 * @param stdClass $ue record from user_enrolments table, specifies user
2008 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
2010 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
2011 return $this->allow_unenrol($instance);
2015 * Does this plugin allow manual changes in user_enrolments table?
2017 * All plugins allowing this must implement 'enrol/xxx:manage' capability
2019 * @param stdClass $instance course enrol instance
2020 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
2022 public function allow_manage(stdClass $instance) {
2023 return false;
2027 * Does this plugin support some way to user to self enrol?
2029 * @param stdClass $instance course enrol instance
2031 * @return bool - true means show "Enrol me in this course" link in course UI
2033 public function show_enrolme_link(stdClass $instance) {
2034 return false;
2038 * Does this plugin support some way to self enrol?
2039 * This function doesn't check user capabilities. Use can_self_enrol to check capabilities.
2041 * @param stdClass $instance enrolment instance
2042 * @return bool - true means "Enrol me in this course" link could be available.
2044 public function is_self_enrol_available(stdClass $instance) {
2045 return false;
2049 * Attempt to automatically enrol current user in course without any interaction,
2050 * calling code has to make sure the plugin and instance are active.
2052 * This should return either a timestamp in the future or false.
2054 * @param stdClass $instance course enrol instance
2055 * @return bool|int false means not enrolled, integer means timeend
2057 public function try_autoenrol(stdClass $instance) {
2058 global $USER;
2060 return false;
2064 * Attempt to automatically gain temporary guest access to course,
2065 * calling code has to make sure the plugin and instance are active.
2067 * This should return either a timestamp in the future or false.
2069 * @param stdClass $instance course enrol instance
2070 * @return bool|int false means no guest access, integer means timeend
2072 public function try_guestaccess(stdClass $instance) {
2073 global $USER;
2075 return false;
2079 * Enrol user into course via enrol instance.
2081 * @param stdClass $instance
2082 * @param int $userid
2083 * @param int $roleid optional role id
2084 * @param int $timestart 0 means unknown
2085 * @param int $timeend 0 means forever
2086 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
2087 * @param bool $recovergrades restore grade history
2088 * @return void
2090 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
2091 global $DB, $USER, $CFG; // CFG necessary!!!
2093 if ($instance->courseid == SITEID) {
2094 throw new coding_exception('invalid attempt to enrol into frontpage course!');
2097 $name = $this->get_name();
2098 $courseid = $instance->courseid;
2100 if ($instance->enrol !== $name) {
2101 throw new coding_exception('invalid enrol instance!');
2103 $context = context_course::instance($instance->courseid, MUST_EXIST);
2104 if (!isset($recovergrades)) {
2105 $recovergrades = $CFG->recovergradesdefault;
2108 $inserted = false;
2109 $updated = false;
2110 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2111 //only update if timestart or timeend or status are different.
2112 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
2113 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
2115 } else {
2116 $ue = new stdClass();
2117 $ue->enrolid = $instance->id;
2118 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
2119 $ue->userid = $userid;
2120 $ue->timestart = $timestart;
2121 $ue->timeend = $timeend;
2122 $ue->modifierid = $USER->id;
2123 $ue->timecreated = time();
2124 $ue->timemodified = $ue->timecreated;
2125 $ue->id = $DB->insert_record('user_enrolments', $ue);
2127 $inserted = true;
2130 if ($inserted) {
2131 // Trigger event.
2132 $event = \core\event\user_enrolment_created::create(
2133 array(
2134 'objectid' => $ue->id,
2135 'courseid' => $courseid,
2136 'context' => $context,
2137 'relateduserid' => $ue->userid,
2138 'other' => array('enrol' => $name)
2141 $event->trigger();
2142 // Check if course contacts cache needs to be cleared.
2143 core_course_category::user_enrolment_changed($courseid, $ue->userid,
2144 $ue->status, $ue->timestart, $ue->timeend);
2147 if ($roleid) {
2148 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
2149 if ($this->roles_protected()) {
2150 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
2151 } else {
2152 role_assign($roleid, $userid, $context->id);
2156 // Recover old grades if present.
2157 if ($recovergrades) {
2158 require_once("$CFG->libdir/gradelib.php");
2159 grade_recover_history_grades($userid, $courseid);
2162 // Add users to a communication room.
2163 if (core_communication\api::is_available()) {
2164 $communication = \core_communication\api::load_by_instance(
2165 'core_course',
2166 'coursecommunication',
2167 $courseid
2169 $communication->add_members_to_room([$userid]);
2172 // reset current user enrolment caching
2173 if ($userid == $USER->id) {
2174 if (isset($USER->enrol['enrolled'][$courseid])) {
2175 unset($USER->enrol['enrolled'][$courseid]);
2177 if (isset($USER->enrol['tempguest'][$courseid])) {
2178 unset($USER->enrol['tempguest'][$courseid]);
2179 remove_temp_course_roles($context);
2185 * Store user_enrolments changes and trigger event.
2187 * @param stdClass $instance
2188 * @param int $userid
2189 * @param int $status
2190 * @param int $timestart
2191 * @param int $timeend
2192 * @return void
2194 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
2195 global $DB, $USER, $CFG;
2197 $name = $this->get_name();
2199 if ($instance->enrol !== $name) {
2200 throw new coding_exception('invalid enrol instance!');
2203 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2204 // weird, user not enrolled
2205 return;
2208 $modified = false;
2209 $statusmodified = false;
2210 $timeendmodified = false;
2211 if (isset($status) and $ue->status != $status) {
2212 $ue->status = $status;
2213 $modified = true;
2214 $statusmodified = true;
2216 if (isset($timestart) and $ue->timestart != $timestart) {
2217 $ue->timestart = $timestart;
2218 $modified = true;
2220 if (isset($timeend) and $ue->timeend != $timeend) {
2221 $ue->timeend = $timeend;
2222 $modified = true;
2223 $timeendmodified = true;
2226 if (!$modified) {
2227 // no change
2228 return;
2231 // Add/remove users to/from communication room.
2232 if (core_communication\api::is_available()) {
2233 $course = enrol_get_course_by_user_enrolment_id($ue->id);
2234 $communication = \core_communication\api::load_by_instance(
2235 'core_course',
2236 'coursecommunication',
2237 $course->id
2239 if (($statusmodified && ((int) $ue->status === 1)) ||
2240 ($timeendmodified && $ue->timeend !== 0 && (time() > $ue->timeend))) {
2241 $communication->remove_members_from_room([$userid]);
2242 } else {
2243 $communication->add_members_to_room([$userid]);
2247 $ue->modifierid = $USER->id;
2248 $ue->timemodified = time();
2249 $DB->update_record('user_enrolments', $ue);
2251 // User enrolments have changed, so mark user as dirty.
2252 mark_user_dirty($userid);
2254 // Invalidate core_access cache for get_suspended_userids.
2255 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));
2257 // Trigger event.
2258 $event = \core\event\user_enrolment_updated::create(
2259 array(
2260 'objectid' => $ue->id,
2261 'courseid' => $instance->courseid,
2262 'context' => context_course::instance($instance->courseid),
2263 'relateduserid' => $ue->userid,
2264 'other' => array('enrol' => $name)
2267 $event->trigger();
2269 core_course_category::user_enrolment_changed($instance->courseid, $ue->userid,
2270 $ue->status, $ue->timestart, $ue->timeend);
2274 * Unenrol user from course,
2275 * the last unenrolment removes all remaining roles.
2277 * @param stdClass $instance
2278 * @param int $userid
2279 * @return void
2281 public function unenrol_user(stdClass $instance, $userid) {
2282 global $CFG, $USER, $DB;
2283 require_once("$CFG->dirroot/group/lib.php");
2285 $name = $this->get_name();
2286 $courseid = $instance->courseid;
2288 if ($instance->enrol !== $name) {
2289 throw new coding_exception('invalid enrol instance!');
2291 $context = context_course::instance($instance->courseid, MUST_EXIST);
2293 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2294 // weird, user not enrolled
2295 return;
2298 // Remove all users groups linked to this enrolment instance.
2299 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
2300 foreach ($gms as $gm) {
2301 groups_remove_member($gm->groupid, $gm->userid);
2305 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
2306 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
2308 // add extra info and trigger event
2309 $ue->courseid = $courseid;
2310 $ue->enrol = $name;
2312 $sql = "SELECT 'x'
2313 FROM {user_enrolments} ue
2314 JOIN {enrol} e ON (e.id = ue.enrolid)
2315 WHERE ue.userid = :userid AND e.courseid = :courseid";
2316 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
2317 $ue->lastenrol = false;
2319 } else {
2320 // the big cleanup IS necessary!
2321 require_once("$CFG->libdir/gradelib.php");
2323 // remove all remaining roles
2324 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
2326 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
2327 groups_delete_group_members($courseid, $userid);
2329 grade_user_unenrol($courseid, $userid);
2331 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
2333 $ue->lastenrol = true; // means user not enrolled any more
2335 // Trigger event.
2336 $event = \core\event\user_enrolment_deleted::create(
2337 array(
2338 'courseid' => $courseid,
2339 'context' => $context,
2340 'relateduserid' => $ue->userid,
2341 'objectid' => $ue->id,
2342 'other' => array(
2343 'userenrolment' => (array)$ue,
2344 'enrol' => $name
2348 $event->trigger();
2350 // Remove users from a communication room.
2351 if (core_communication\api::is_available()) {
2352 $communication = \core_communication\api::load_by_instance(
2353 'core_course',
2354 'coursecommunication',
2355 $courseid
2357 $communication->remove_members_from_room([$userid]);
2360 // User enrolments have changed, so mark user as dirty.
2361 mark_user_dirty($userid);
2363 // Check if courrse contacts cache needs to be cleared.
2364 core_course_category::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);
2366 // reset current user enrolment caching
2367 if ($userid == $USER->id) {
2368 if (isset($USER->enrol['enrolled'][$courseid])) {
2369 unset($USER->enrol['enrolled'][$courseid]);
2371 if (isset($USER->enrol['tempguest'][$courseid])) {
2372 unset($USER->enrol['tempguest'][$courseid]);
2373 remove_temp_course_roles($context);
2379 * Forces synchronisation of user enrolments.
2381 * This is important especially for external enrol plugins,
2382 * this function is called for all enabled enrol plugins
2383 * right after every user login.
2385 * @param object $user user record
2386 * @return void
2388 public function sync_user_enrolments($user) {
2389 // override if necessary
2393 * This returns false for backwards compatibility, but it is really recommended.
2395 * @since Moodle 3.1
2396 * @return boolean
2398 public function use_standard_editing_ui() {
2399 return false;
2403 * Return whether or not, given the current state, it is possible to add a new instance
2404 * of this enrolment plugin to the course.
2406 * Default implementation is just for backwards compatibility.
2408 * @param int $courseid
2409 * @return boolean
2411 public function can_add_instance($courseid) {
2412 $link = $this->get_newinstance_link($courseid);
2413 return !empty($link);
2417 * Return whether or not, given the current state, it is possible to edit an instance
2418 * of this enrolment plugin in the course. Used by the standard editing UI
2419 * to generate a link to the edit instance form if editing is allowed.
2421 * @param stdClass $instance
2422 * @return boolean
2424 public function can_edit_instance($instance) {
2425 $context = context_course::instance($instance->courseid);
2427 return has_capability('enrol/' . $instance->enrol . ':config', $context);
2431 * Returns link to page which may be used to add new instance of enrolment plugin in course.
2432 * @param int $courseid
2433 * @return moodle_url page url
2435 public function get_newinstance_link($courseid) {
2436 // override for most plugins, check if instance already exists in cases only one instance is supported
2437 return NULL;
2441 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
2443 public function instance_deleteable($instance) {
2444 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
2445 enrol_plugin::can_delete_instance() instead');
2449 * Is it possible to delete enrol instance via standard UI?
2451 * @param stdClass $instance
2452 * @return bool
2454 public function can_delete_instance($instance) {
2455 return false;
2459 * Is it possible to hide/show enrol instance via standard UI?
2461 * @param stdClass $instance
2462 * @return bool
2464 public function can_hide_show_instance($instance) {
2465 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER);
2466 return true;
2470 * Returns link to manual enrol UI if exists.
2471 * Does the access control tests automatically.
2473 * @param object $instance
2474 * @return moodle_url
2476 public function get_manual_enrol_link($instance) {
2477 return NULL;
2481 * Returns list of unenrol links for all enrol instances in course.
2483 * @param stdClass $instance
2484 * @return moodle_url or NULL if self unenrolment not supported
2486 public function get_unenrolself_link($instance) {
2487 global $USER, $CFG, $DB;
2489 $name = $this->get_name();
2490 if ($instance->enrol !== $name) {
2491 throw new coding_exception('invalid enrol instance!');
2494 if ($instance->courseid == SITEID) {
2495 return NULL;
2498 if (!enrol_is_enabled($name)) {
2499 return NULL;
2502 if ($instance->status != ENROL_INSTANCE_ENABLED) {
2503 return NULL;
2506 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2507 return NULL;
2510 $context = context_course::instance($instance->courseid, MUST_EXIST);
2512 if (!has_capability("enrol/$name:unenrolself", $context)) {
2513 return NULL;
2516 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
2517 return NULL;
2520 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
2524 * Adds enrol instance UI to course edit form
2526 * @param object $instance enrol instance or null if does not exist yet
2527 * @param MoodleQuickForm $mform
2528 * @param object $data
2529 * @param object $context context of existing course or parent category if course does not exist
2530 * @return void
2532 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
2533 // override - usually at least enable/disable switch, has to add own form header
2537 * Adds form elements to add/edit instance form.
2539 * @since Moodle 3.1
2540 * @param object $instance enrol instance or null if does not exist yet
2541 * @param MoodleQuickForm $mform
2542 * @param context $context
2543 * @return void
2545 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
2546 // Do nothing by default.
2550 * Perform custom validation of the data used to edit the instance.
2552 * @since Moodle 3.1
2553 * @param array $data array of ("fieldname"=>value) of submitted data
2554 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2555 * @param object $instance The instance data loaded from the DB.
2556 * @param context $context The context of the instance we are editing
2557 * @return array of "element_name"=>"error_description" if there are errors,
2558 * or an empty array if everything is OK.
2560 public function edit_instance_validation($data, $files, $instance, $context) {
2561 // No errors by default.
2562 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER);
2563 return array();
2567 * Validates course edit form data
2569 * @param object $instance enrol instance or null if does not exist yet
2570 * @param array $data
2571 * @param object $context context of existing course or parent category if course does not exist
2572 * @return array errors array
2574 public function course_edit_validation($instance, array $data, $context) {
2575 return array();
2579 * Called after updating/inserting course.
2581 * @param bool $inserted true if course just inserted
2582 * @param object $course
2583 * @param object $data form data
2584 * @return void
2586 public function course_updated($inserted, $course, $data) {
2587 if ($inserted) {
2588 if ($this->get_config('defaultenrol')) {
2589 $this->add_default_instance($course);
2595 * Add new instance of enrol plugin.
2596 * @param object $course
2597 * @param array instance fields
2598 * @return int id of new instance, null if can not be created
2600 public function add_instance($course, array $fields = NULL) {
2601 global $DB;
2603 if ($course->id == SITEID) {
2604 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2607 $instance = new stdClass();
2608 $instance->enrol = $this->get_name();
2609 $instance->status = ENROL_INSTANCE_ENABLED;
2610 $instance->courseid = $course->id;
2611 $instance->enrolstartdate = 0;
2612 $instance->enrolenddate = 0;
2613 $instance->timemodified = time();
2614 $instance->timecreated = $instance->timemodified;
2615 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
2617 $fields = (array)$fields;
2618 unset($fields['enrol']);
2619 unset($fields['courseid']);
2620 unset($fields['sortorder']);
2621 foreach($fields as $field=>$value) {
2622 $instance->$field = $value;
2625 $instance->id = $DB->insert_record('enrol', $instance);
2627 \core\event\enrol_instance_created::create_from_record($instance)->trigger();
2629 return $instance->id;
2633 * Update instance of enrol plugin.
2635 * @since Moodle 3.1
2636 * @param stdClass $instance
2637 * @param stdClass $data modified instance fields
2638 * @return boolean
2640 public function update_instance($instance, $data) {
2641 global $DB;
2642 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2643 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2644 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2645 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2646 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2647 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2649 foreach ($properties as $key) {
2650 if (isset($data->$key)) {
2651 $instance->$key = $data->$key;
2654 $instance->timemodified = time();
2656 $update = $DB->update_record('enrol', $instance);
2657 if ($update) {
2658 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2660 return $update;
2664 * Add new instance of enrol plugin with default settings,
2665 * called when adding new instance manually or when adding new course.
2667 * Not all plugins support this.
2669 * @param object $course
2670 * @return int id of new instance or null if no default supported
2672 public function add_default_instance($course) {
2673 return null;
2677 * Update instance status
2679 * Override when plugin needs to do some action when enabled or disabled.
2681 * @param stdClass $instance
2682 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2683 * @return void
2685 public function update_status($instance, $newstatus) {
2686 global $DB;
2688 $instance->status = $newstatus;
2689 $DB->update_record('enrol', $instance);
2691 $context = context_course::instance($instance->courseid);
2692 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2694 // Invalidate all enrol caches.
2695 $context->mark_dirty();
2699 * Update instance members.
2701 * Update communication room membership for an instance action being performed.
2703 * @param int $instanceid ID of the enrolment instance
2704 * @param string $action The update action being performed
2705 * @param int $courseid The id of the course
2706 * @return void
2708 public function update_communication(int $instanceid, string $action, int $courseid): void {
2709 global $DB;
2710 // Get enrolled instance users.
2711 $instanceusers = $DB->get_records('user_enrolments', ['enrolid' => $instanceid, 'status' => 0]);
2712 $enrolledusers = [];
2714 foreach ($instanceusers as $user) {
2715 $enrolledusers[] = $user->userid;
2718 $communication = \core_communication\api::load_by_instance(
2719 'core_course',
2720 'coursecommunication',
2721 $courseid
2724 switch ($action) {
2725 case 'add':
2726 $communication->add_members_to_room($enrolledusers);
2727 break;
2729 case 'remove':
2730 $communication->remove_members_from_room($enrolledusers);
2731 break;
2732 default:
2733 throw new \coding_exception('Invalid action');
2738 * Delete course enrol plugin instance, unenrol all users.
2739 * @param object $instance
2740 * @return void
2742 public function delete_instance($instance) {
2743 global $DB;
2745 $name = $this->get_name();
2746 if ($instance->enrol !== $name) {
2747 throw new coding_exception('invalid enrol instance!');
2750 //first unenrol all users
2751 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
2752 foreach ($participants as $participant) {
2753 $this->unenrol_user($instance, $participant->userid);
2755 $participants->close();
2757 // now clean up all remainders that were not removed correctly
2758 if ($gms = $DB->get_records('groups_members', array('itemid' => $instance->id, 'component' => 'enrol_' . $name))) {
2759 foreach ($gms as $gm) {
2760 groups_remove_member($gm->groupid, $gm->userid);
2763 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
2764 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
2766 // finally drop the enrol row
2767 $DB->delete_records('enrol', array('id'=>$instance->id));
2769 $context = context_course::instance($instance->courseid);
2770 \core\event\enrol_instance_deleted::create_from_record($instance)->trigger();
2772 // Invalidate all enrol caches.
2773 $context->mark_dirty();
2777 * Creates course enrol form, checks if form submitted
2778 * and enrols user if necessary. It can also redirect.
2780 * @param stdClass $instance
2781 * @return string html text, usually a form in a text box
2783 public function enrol_page_hook(stdClass $instance) {
2784 return null;
2788 * Checks if user can self enrol.
2790 * @param stdClass $instance enrolment instance
2791 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2792 * used by navigation to improve performance.
2793 * @return bool|string true if successful, else error message or false
2795 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
2796 return false;
2800 * Return information for enrolment instance containing list of parameters required
2801 * for enrolment, name of enrolment plugin etc.
2803 * @param stdClass $instance enrolment instance
2804 * @return stdClass|null instance info.
2806 public function get_enrol_info(stdClass $instance) {
2807 return null;
2811 * Adds navigation links into course admin block.
2813 * By defaults looks for manage links only.
2815 * @param navigation_node $instancesnode
2816 * @param stdClass $instance
2817 * @return void
2819 public function add_course_navigation($instancesnode, stdClass $instance) {
2820 if ($this->use_standard_editing_ui()) {
2821 $context = context_course::instance($instance->courseid);
2822 $cap = 'enrol/' . $instance->enrol . ':config';
2823 if (has_capability($cap, $context)) {
2824 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2825 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2826 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
2832 * Returns edit icons for the page with list of instances
2833 * @param stdClass $instance
2834 * @return array
2836 public function get_action_icons(stdClass $instance) {
2837 global $OUTPUT;
2839 $icons = array();
2840 if ($this->use_standard_editing_ui()) {
2841 $context = context_course::instance($instance->courseid);
2842 $cap = 'enrol/' . $instance->enrol . ':config';
2843 if (has_capability($cap, $context)) {
2844 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2845 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2846 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2847 array('class' => 'iconsmall')));
2850 return $icons;
2854 * Reads version.php and determines if it is necessary
2855 * to execute the cron job now.
2856 * @return bool
2858 public function is_cron_required() {
2859 global $CFG;
2861 $name = $this->get_name();
2862 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2863 $plugin = new stdClass();
2864 include($versionfile);
2865 if (empty($plugin->cron)) {
2866 return false;
2868 $lastexecuted = $this->get_config('lastcron', 0);
2869 if ($lastexecuted + $plugin->cron < time()) {
2870 return true;
2871 } else {
2872 return false;
2877 * Called for all enabled enrol plugins that returned true from is_cron_required().
2878 * @return void
2880 public function cron() {
2884 * Called when user is about to be deleted
2885 * @param object $user
2886 * @return void
2888 public function user_delete($user) {
2889 global $DB;
2891 $sql = "SELECT e.*
2892 FROM {enrol} e
2893 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2894 WHERE e.enrol = :name AND ue.userid = :userid";
2895 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
2897 $rs = $DB->get_recordset_sql($sql, $params);
2898 foreach($rs as $instance) {
2899 $this->unenrol_user($instance, $user->id);
2901 $rs->close();
2905 * Returns an enrol_user_button that takes the user to a page where they are able to
2906 * enrol users into the managers course through this plugin.
2908 * Optional: If the plugin supports manual enrolments it can choose to override this
2909 * otherwise it shouldn't
2911 * @param course_enrolment_manager $manager
2912 * @return enrol_user_button|false
2914 public function get_manual_enrol_button(course_enrolment_manager $manager) {
2915 return false;
2919 * Gets an array of the user enrolment actions
2921 * @param course_enrolment_manager $manager
2922 * @param stdClass $ue
2923 * @return array An array of user_enrolment_actions
2925 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
2926 $actions = [];
2927 $context = $manager->get_context();
2928 $instance = $ue->enrolmentinstance;
2929 $params = $manager->get_moodlepage()->url->params();
2930 $params['ue'] = $ue->id;
2932 // Edit enrolment action.
2933 if ($this->allow_manage($instance) && has_capability("enrol/{$instance->enrol}:manage", $context)) {
2934 $title = get_string('editenrolment', 'enrol');
2935 $icon = new pix_icon('t/edit', $title);
2936 $url = new moodle_url('/enrol/editenrolment.php', $params);
2937 $actionparams = [
2938 'class' => 'editenrollink',
2939 'rel' => $ue->id,
2940 'data-action' => ENROL_ACTION_EDIT
2942 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2945 // Unenrol action.
2946 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/{$instance->enrol}:unenrol", $context)) {
2947 $title = get_string('unenrol', 'enrol');
2948 $icon = new pix_icon('t/delete', $title);
2949 $url = new moodle_url('/enrol/unenroluser.php', $params);
2950 $actionparams = [
2951 'class' => 'unenrollink',
2952 'rel' => $ue->id,
2953 'data-action' => ENROL_ACTION_UNENROL
2955 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2957 return $actions;
2961 * Returns true if the plugin has one or more bulk operations that can be performed on
2962 * user enrolments.
2964 * @param course_enrolment_manager $manager
2965 * @return bool
2967 public function has_bulk_operations(course_enrolment_manager $manager) {
2968 return false;
2972 * Return an array of enrol_bulk_enrolment_operation objects that define
2973 * the bulk actions that can be performed on user enrolments by the plugin.
2975 * @param course_enrolment_manager $manager
2976 * @return array
2978 public function get_bulk_operations(course_enrolment_manager $manager) {
2979 return array();
2983 * Do any enrolments need expiration processing.
2985 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2987 * @param progress_trace $trace
2988 * @param int $courseid one course, empty mean all
2989 * @return bool true if any data processed, false if not
2991 public function process_expirations(progress_trace $trace, $courseid = null) {
2992 global $DB;
2994 $name = $this->get_name();
2995 if (!enrol_is_enabled($name)) {
2996 $trace->finished();
2997 return false;
3000 $processed = false;
3001 $params = array();
3002 $coursesql = "";
3003 if ($courseid) {
3004 $coursesql = "AND e.courseid = :courseid";
3007 // Deal with expired accounts.
3008 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
3010 if ($action == ENROL_EXT_REMOVED_UNENROL) {
3011 $instances = array();
3012 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
3013 FROM {user_enrolments} ue
3014 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
3015 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
3016 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
3017 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
3019 $rs = $DB->get_recordset_sql($sql, $params);
3020 foreach ($rs as $ue) {
3021 if (!$processed) {
3022 $trace->output("Starting processing of enrol_$name expirations...");
3023 $processed = true;
3025 if (empty($instances[$ue->enrolid])) {
3026 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
3028 $instance = $instances[$ue->enrolid];
3029 if (!$this->roles_protected()) {
3030 // Let's just guess what extra roles are supposed to be removed.
3031 if ($instance->roleid) {
3032 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
3035 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
3036 $this->unenrol_user($instance, $ue->userid);
3037 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
3039 $rs->close();
3040 unset($instances);
3042 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
3043 $instances = array();
3044 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
3045 FROM {user_enrolments} ue
3046 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
3047 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
3048 WHERE ue.timeend > 0 AND ue.timeend < :now
3049 AND ue.status = :useractive $coursesql";
3050 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
3051 $rs = $DB->get_recordset_sql($sql, $params);
3052 foreach ($rs as $ue) {
3053 if (!$processed) {
3054 $trace->output("Starting processing of enrol_$name expirations...");
3055 $processed = true;
3057 if (empty($instances[$ue->enrolid])) {
3058 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
3060 $instance = $instances[$ue->enrolid];
3062 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
3063 if (!$this->roles_protected()) {
3064 // Let's just guess what roles should be removed.
3065 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
3066 if ($count == 1) {
3067 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
3069 } else if ($count > 1 and $instance->roleid) {
3070 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
3073 // In any case remove all roles that belong to this instance and user.
3074 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
3075 // Final cleanup of subcontexts if there are no more course roles.
3076 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
3077 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
3081 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
3082 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
3084 $rs->close();
3085 unset($instances);
3087 } else {
3088 // ENROL_EXT_REMOVED_KEEP means no changes.
3091 if ($processed) {
3092 $trace->output("...finished processing of enrol_$name expirations");
3093 } else {
3094 $trace->output("No expired enrol_$name enrolments detected");
3096 $trace->finished();
3098 return $processed;
3102 * Send expiry notifications.
3104 * Plugin that wants to have expiry notification MUST implement following:
3105 * - expirynotifyhour plugin setting,
3106 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
3107 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
3108 * expirymessageenrolledsubject and expirymessageenrolledbody),
3109 * - expiry_notification provider in db/messages.php,
3110 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
3111 * - something that calls this method, such as cron.
3113 * @param progress_trace $trace (accepts bool for backwards compatibility only)
3115 public function send_expiry_notifications($trace) {
3116 global $DB, $CFG;
3118 $name = $this->get_name();
3119 if (!enrol_is_enabled($name)) {
3120 $trace->finished();
3121 return;
3124 // Unfortunately this may take a long time, it should not be interrupted,
3125 // otherwise users get duplicate notification.
3127 core_php_time_limit::raise();
3128 raise_memory_limit(MEMORY_HUGE);
3131 $expirynotifylast = $this->get_config('expirynotifylast', 0);
3132 $expirynotifyhour = $this->get_config('expirynotifyhour');
3133 if (is_null($expirynotifyhour)) {
3134 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
3135 $trace->finished();
3136 return;
3139 if (!($trace instanceof progress_trace)) {
3140 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
3141 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
3144 $timenow = time();
3145 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
3147 if ($expirynotifylast > $notifytime) {
3148 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
3149 $trace->finished();
3150 return;
3152 } else if ($timenow < $notifytime) {
3153 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
3154 $trace->finished();
3155 return;
3158 $trace->output('Processing '.$name.' enrolment expiration notifications...');
3160 // Notify users responsible for enrolment once every day.
3161 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
3162 FROM {user_enrolments} ue
3163 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
3164 JOIN {course} c ON (c.id = e.courseid)
3165 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
3166 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
3167 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
3168 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
3170 $rs = $DB->get_recordset_sql($sql, $params);
3172 $lastenrollid = 0;
3173 $users = array();
3175 foreach($rs as $ue) {
3176 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
3177 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3178 $users = array();
3180 $lastenrollid = $ue->enrolid;
3182 $enroller = $this->get_enroller($ue->enrolid);
3183 $context = context_course::instance($ue->courseid);
3185 $user = $DB->get_record('user', array('id'=>$ue->userid));
3187 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
3189 if (!$ue->notifyall) {
3190 continue;
3193 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
3194 // Notify enrolled users only once at the start of the threshold.
3195 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3196 continue;
3199 $this->notify_expiry_enrolled($user, $ue, $trace);
3201 $rs->close();
3203 if ($lastenrollid and $users) {
3204 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3207 $trace->output('...notification processing finished.');
3208 $trace->finished();
3210 $this->set_config('expirynotifylast', $timenow);
3214 * Returns the user who is responsible for enrolments for given instance.
3216 * Override if plugin knows anybody better than admin.
3218 * @param int $instanceid enrolment instance id
3219 * @return stdClass user record
3221 protected function get_enroller($instanceid) {
3222 return get_admin();
3226 * Notify user about incoming expiration of their enrolment,
3227 * it is called only if notification of enrolled users (aka students) is enabled in course.
3229 * This is executed only once for each expiring enrolment right
3230 * at the start of the expiration threshold.
3232 * @param stdClass $user
3233 * @param stdClass $ue
3234 * @param progress_trace $trace
3236 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
3237 global $CFG;
3239 $name = $this->get_name();
3241 $oldforcelang = force_current_language($user->lang);
3243 $enroller = $this->get_enroller($ue->enrolid);
3244 $context = context_course::instance($ue->courseid);
3246 $a = new stdClass();
3247 $a->course = format_string($ue->fullname, true, array('context'=>$context));
3248 $a->user = fullname($user, true);
3249 $a->timeend = userdate($ue->timeend, '', $user->timezone);
3250 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
3252 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
3253 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
3255 $message = new \core\message\message();
3256 $message->courseid = $ue->courseid;
3257 $message->notification = 1;
3258 $message->component = 'enrol_'.$name;
3259 $message->name = 'expiry_notification';
3260 $message->userfrom = $enroller;
3261 $message->userto = $user;
3262 $message->subject = $subject;
3263 $message->fullmessage = $body;
3264 $message->fullmessageformat = FORMAT_MARKDOWN;
3265 $message->fullmessagehtml = markdown_to_html($body);
3266 $message->smallmessage = $subject;
3267 $message->contexturlname = $a->course;
3268 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
3270 if (message_send($message)) {
3271 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3272 } else {
3273 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3276 force_current_language($oldforcelang);
3280 * Notify person responsible for enrolments that some user enrolments will be expired soon,
3281 * it is called only if notification of enrollers (aka teachers) is enabled in course.
3283 * This is called repeatedly every day for each course if there are any pending expiration
3284 * in the expiration threshold.
3286 * @param int $eid
3287 * @param array $users
3288 * @param progress_trace $trace
3290 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
3291 global $DB;
3293 $name = $this->get_name();
3295 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
3296 $context = context_course::instance($instance->courseid);
3297 $course = $DB->get_record('course', array('id'=>$instance->courseid));
3299 $enroller = $this->get_enroller($instance->id);
3300 $admin = get_admin();
3302 $oldforcelang = force_current_language($enroller->lang);
3304 foreach($users as $key=>$info) {
3305 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
3308 $a = new stdClass();
3309 $a->course = format_string($course->fullname, true, array('context'=>$context));
3310 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
3311 $a->users = implode("\n", $users);
3312 $a->extendurl = (string)new moodle_url('/user/index.php', array('id'=>$instance->courseid));
3314 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
3315 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
3317 $message = new \core\message\message();
3318 $message->courseid = $course->id;
3319 $message->notification = 1;
3320 $message->component = 'enrol_'.$name;
3321 $message->name = 'expiry_notification';
3322 $message->userfrom = $admin;
3323 $message->userto = $enroller;
3324 $message->subject = $subject;
3325 $message->fullmessage = $body;
3326 $message->fullmessageformat = FORMAT_MARKDOWN;
3327 $message->fullmessagehtml = markdown_to_html($body);
3328 $message->smallmessage = $subject;
3329 $message->contexturlname = $a->course;
3330 $message->contexturl = $a->extendurl;
3332 if (message_send($message)) {
3333 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3334 } else {
3335 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3338 force_current_language($oldforcelang);
3342 * Backup execution step hook to annotate custom fields.
3344 * @param backup_enrolments_execution_step $step
3345 * @param stdClass $enrol
3347 public function backup_annotate_custom_fields(backup_enrolments_execution_step $step, stdClass $enrol) {
3348 // Override as necessary to annotate custom fields in the enrol table.
3352 * Automatic enrol sync executed during restore.
3353 * Useful for automatic sync by course->idnumber or course category.
3354 * @param stdClass $course course record
3356 public function restore_sync_course($course) {
3357 // Override if necessary.
3361 * Restore instance and map settings.
3363 * @param restore_enrolments_structure_step $step
3364 * @param stdClass $data
3365 * @param stdClass $course
3366 * @param int $oldid
3368 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
3369 // Do not call this from overridden methods, restore and set new id there.
3370 $step->set_mapping('enrol', $oldid, 0);
3374 * Restore user enrolment.
3376 * @param restore_enrolments_structure_step $step
3377 * @param stdClass $data
3378 * @param stdClass $instance
3379 * @param int $oldinstancestatus
3380 * @param int $userid
3382 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
3383 // Override as necessary if plugin supports restore of enrolments.
3387 * Restore role assignment.
3389 * @param stdClass $instance
3390 * @param int $roleid
3391 * @param int $userid
3392 * @param int $contextid
3394 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
3395 // No role assignment by default, override if necessary.
3399 * Restore user group membership.
3400 * @param stdClass $instance
3401 * @param int $groupid
3402 * @param int $userid
3404 public function restore_group_member($instance, $groupid, $userid) {
3405 // Implement if you want to restore protected group memberships,
3406 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
3410 * Returns defaults for new instances.
3411 * @since Moodle 3.1
3412 * @return array
3414 public function get_instance_defaults() {
3415 return array();
3419 * Validate a list of parameter names and types.
3420 * @since Moodle 3.1
3422 * @param array $data array of ("fieldname"=>value) of submitted data
3423 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
3424 * @return array of "element_name"=>"error_description" if there are errors,
3425 * or an empty array if everything is OK.
3427 public function validate_param_types($data, $rules) {
3428 $errors = array();
3429 $invalidstr = get_string('invaliddata', 'error');
3430 foreach ($rules as $fieldname => $rule) {
3431 if (is_array($rule)) {
3432 if (!in_array($data[$fieldname], $rule)) {
3433 $errors[$fieldname] = $invalidstr;
3435 } else {
3436 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
3437 $errors[$fieldname] = $invalidstr;
3441 return $errors;
3445 * Fill custom fields data for a given enrolment plugin.
3447 * @param array $enrolmentdata enrolment data.
3448 * @param int $courseid Course ID.
3449 * @return array Updated enrolment data with custom fields info.
3451 public function fill_enrol_custom_fields(array $enrolmentdata, int $courseid) : array {
3452 return $enrolmentdata;
3456 * Check if data is valid for a given enrolment plugin
3458 * @param array $enrolmentdata enrolment data to validate.
3459 * @param int|null $courseid Course ID.
3460 * @return array Errors
3462 public function validate_enrol_plugin_data(array $enrolmentdata, ?int $courseid = null) : array {
3463 return [];
3467 * Check if plugin custom data is allowed in relevant context.
3469 * @param array $enrolmentdata enrolment data to validate.
3470 * @param int|null $courseid Course ID.
3471 * @return lang_string|null Error
3473 public function validate_plugin_data_context(array $enrolmentdata, ?int $courseid = null) : ?lang_string {
3474 return null;