Merge branch 'MDL-70099-311' of git://github.com/paulholden/moodle into MOODLE_311_STABLE
[moodle.git] / lib / enrollib.php
blob286eb63e1699bc46750888536250612fe5e7a897
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
218 * This function may be very slow, use only once after log-in or login-as.
220 * @param stdClass $user
221 * @return void
223 function enrol_check_plugins($user) {
224 global $CFG;
226 if (empty($user->id) or isguestuser($user)) {
227 // shortcut - there is no enrolment work for guests and not-logged-in users
228 return;
231 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
232 // which proved it was actually not necessary.
234 static $inprogress = array(); // To prevent this function being called more than once in an invocation
236 if (!empty($inprogress[$user->id])) {
237 return;
240 $inprogress[$user->id] = true; // Set the flag
242 $enabled = enrol_get_plugins(true);
244 foreach($enabled as $enrol) {
245 $enrol->sync_user_enrolments($user);
248 unset($inprogress[$user->id]); // Unset the flag
252 * Do these two students share any course?
254 * The courses has to be visible and enrolments has to be active,
255 * timestart and timeend restrictions are ignored.
257 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
258 * to true.
260 * @param stdClass|int $user1
261 * @param stdClass|int $user2
262 * @return bool
264 function enrol_sharing_course($user1, $user2) {
265 return enrol_get_shared_courses($user1, $user2, false, true);
269 * Returns any courses shared by the two users
271 * The courses has to be visible and enrolments has to be active,
272 * timestart and timeend restrictions are ignored.
274 * @global moodle_database $DB
275 * @param stdClass|int $user1
276 * @param stdClass|int $user2
277 * @param bool $preloadcontexts If set to true contexts for the returned courses
278 * will be preloaded.
279 * @param bool $checkexistsonly If set to true then this function will return true
280 * if the users share any courses and false if not.
281 * @return array|bool An array of courses that both users are enrolled in OR if
282 * $checkexistsonly set returns true if the users share any courses
283 * and false if not.
285 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
286 global $DB, $CFG;
288 $user1 = isset($user1->id) ? $user1->id : $user1;
289 $user2 = isset($user2->id) ? $user2->id : $user2;
291 if (empty($user1) or empty($user2)) {
292 return false;
295 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
296 return false;
299 list($plugins1, $params1) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee1');
300 list($plugins2, $params2) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee2');
301 $params = array_merge($params1, $params2);
302 $params['enabled1'] = ENROL_INSTANCE_ENABLED;
303 $params['enabled2'] = ENROL_INSTANCE_ENABLED;
304 $params['active1'] = ENROL_USER_ACTIVE;
305 $params['active2'] = ENROL_USER_ACTIVE;
306 $params['user1'] = $user1;
307 $params['user2'] = $user2;
309 $ctxselect = '';
310 $ctxjoin = '';
311 if ($preloadcontexts) {
312 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
313 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
314 $params['contextlevel'] = CONTEXT_COURSE;
317 $sql = "SELECT c.* $ctxselect
318 FROM {course} c
319 JOIN (
320 SELECT DISTINCT c.id
321 FROM {course} c
322 JOIN {enrol} e1 ON (c.id = e1.courseid AND e1.status = :enabled1 AND e1.enrol $plugins1)
323 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e1.id AND ue1.status = :active1 AND ue1.userid = :user1)
324 JOIN {enrol} e2 ON (c.id = e2.courseid AND e2.status = :enabled2 AND e2.enrol $plugins2)
325 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e2.id AND ue2.status = :active2 AND ue2.userid = :user2)
326 WHERE c.visible = 1
327 ) ec ON ec.id = c.id
328 $ctxjoin";
330 if ($checkexistsonly) {
331 return $DB->record_exists_sql($sql, $params);
332 } else {
333 $courses = $DB->get_records_sql($sql, $params);
334 if ($preloadcontexts) {
335 array_map('context_helper::preload_from_record', $courses);
337 return $courses;
342 * This function adds necessary enrol plugins UI into the course edit form.
344 * @param MoodleQuickForm $mform
345 * @param object $data course edit form data
346 * @param object $context context of existing course or parent category if course does not exist
347 * @return void
349 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
350 $plugins = enrol_get_plugins(true);
351 if (!empty($data->id)) {
352 $instances = enrol_get_instances($data->id, false);
353 foreach ($instances as $instance) {
354 if (!isset($plugins[$instance->enrol])) {
355 continue;
357 $plugin = $plugins[$instance->enrol];
358 $plugin->course_edit_form($instance, $mform, $data, $context);
360 } else {
361 foreach ($plugins as $plugin) {
362 $plugin->course_edit_form(NULL, $mform, $data, $context);
368 * Validate course edit form data
370 * @param array $data raw form data
371 * @param object $context context of existing course or parent category if course does not exist
372 * @return array errors array
374 function enrol_course_edit_validation(array $data, $context) {
375 $errors = array();
376 $plugins = enrol_get_plugins(true);
378 if (!empty($data['id'])) {
379 $instances = enrol_get_instances($data['id'], false);
380 foreach ($instances as $instance) {
381 if (!isset($plugins[$instance->enrol])) {
382 continue;
384 $plugin = $plugins[$instance->enrol];
385 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
387 } else {
388 foreach ($plugins as $plugin) {
389 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
393 return $errors;
397 * Update enrol instances after course edit form submission
398 * @param bool $inserted true means new course added, false course already existed
399 * @param object $course
400 * @param object $data form data
401 * @return void
403 function enrol_course_updated($inserted, $course, $data) {
404 global $DB, $CFG;
406 $plugins = enrol_get_plugins(true);
408 foreach ($plugins as $plugin) {
409 $plugin->course_updated($inserted, $course, $data);
414 * Add navigation nodes
415 * @param navigation_node $coursenode
416 * @param object $course
417 * @return void
419 function enrol_add_course_navigation(navigation_node $coursenode, $course) {
420 global $CFG;
422 $coursecontext = context_course::instance($course->id);
424 $instances = enrol_get_instances($course->id, true);
425 $plugins = enrol_get_plugins(true);
427 // we do not want to break all course pages if there is some borked enrol plugin, right?
428 foreach ($instances as $k=>$instance) {
429 if (!isset($plugins[$instance->enrol])) {
430 unset($instances[$k]);
434 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
436 if ($course->id != SITEID) {
437 // list all participants - allows assigning roles, groups, etc.
438 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
439 $url = new moodle_url('/user/index.php', array('id'=>$course->id));
440 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/enrolusers', ''));
443 // manage enrol plugin instances
444 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
445 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
446 } else {
447 $url = NULL;
449 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
451 // each instance decides how to configure itself or how many other nav items are exposed
452 foreach ($instances as $instance) {
453 if (!isset($plugins[$instance->enrol])) {
454 continue;
456 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
459 if (!$url) {
460 $instancesnode->trim_if_empty();
464 // Manage groups in this course or even frontpage
465 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
466 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
467 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
470 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
471 // Override roles
472 if (has_capability('moodle/role:review', $coursecontext)) {
473 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
474 } else {
475 $url = NULL;
477 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
479 // Add assign or override roles if allowed
480 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
481 if (has_capability('moodle/role:assign', $coursecontext)) {
482 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
483 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
486 // Check role permissions
487 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
488 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
489 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
493 // Deal somehow with users that are not enrolled but still got a role somehow
494 if ($course->id != SITEID) {
495 //TODO, create some new UI for role assignments at course level
496 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
497 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
498 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
502 // just in case nothing was actually added
503 $usersnode->trim_if_empty();
505 if ($course->id != SITEID) {
506 if (isguestuser() or !isloggedin()) {
507 // guest account can not be enrolled - no links for them
508 } else if (is_enrolled($coursecontext)) {
509 // unenrol link if possible
510 foreach ($instances as $instance) {
511 if (!isset($plugins[$instance->enrol])) {
512 continue;
514 $plugin = $plugins[$instance->enrol];
515 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
516 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
517 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
518 break;
519 //TODO. deal with multiple unenrol links - not likely case, but still...
522 } else {
523 // enrol link if possible
524 if (is_viewing($coursecontext)) {
525 // better not show any enrol link, this is intended for managers and inspectors
526 } else {
527 foreach ($instances as $instance) {
528 if (!isset($plugins[$instance->enrol])) {
529 continue;
531 $plugin = $plugins[$instance->enrol];
532 if ($plugin->show_enrolme_link($instance)) {
533 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
534 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
535 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
536 break;
545 * Returns list of courses current $USER is enrolled in and can access
547 * The $fields param is a list of field names to ADD so name just the fields you really need,
548 * which will be added and uniq'd.
550 * If $allaccessible is true, this will additionally return courses that the current user is not
551 * enrolled in, but can access because they are open to the user for other reasons (course view
552 * permission, currently viewing course as a guest, or course allows guest access without
553 * password).
555 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
556 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
557 * Allowed prefixes for sort fields are: "ul" for the user_lastaccess table, "c" for the courses table,
558 * "ue" for the user_enrolments table.
559 * @param int $limit max number of courses
560 * @param array $courseids the list of course ids to filter by
561 * @param bool $allaccessible Include courses user is not enrolled in, but can access
562 * @param int $offset Offset the result set by this number
563 * @param array $excludecourses IDs of hidden courses to exclude from search
564 * @return array
566 function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false,
567 $offset = 0, $excludecourses = []) {
568 global $DB, $USER, $CFG;
570 // Re-Arrange the course sorting according to the admin settings.
571 $sort = enrol_get_courses_sortingsql($sort);
573 // Guest account does not have any enrolled courses.
574 if (!$allaccessible && (isguestuser() or !isloggedin())) {
575 return array();
578 $basefields = array('id', 'category', 'sortorder',
579 'shortname', 'fullname', 'idnumber',
580 'startdate', 'visible',
581 'groupmode', 'groupmodeforce', 'cacherev');
583 if (empty($fields)) {
584 $fields = $basefields;
585 } else if (is_string($fields)) {
586 // turn the fields from a string to an array
587 $fields = explode(',', $fields);
588 $fields = array_map('trim', $fields);
589 $fields = array_unique(array_merge($basefields, $fields));
590 } else if (is_array($fields)) {
591 $fields = array_unique(array_merge($basefields, $fields));
592 } else {
593 throw new coding_exception('Invalid $fields parameter in enrol_get_my_courses()');
595 if (in_array('*', $fields)) {
596 $fields = array('*');
599 $orderby = "";
600 $sort = trim($sort);
601 $sorttimeaccess = false;
602 $allowedsortprefixes = array('c', 'ul', 'ue');
603 if (!empty($sort)) {
604 $rawsorts = explode(',', $sort);
605 $sorts = array();
606 foreach ($rawsorts as $rawsort) {
607 $rawsort = trim($rawsort);
608 if (preg_match('/^ul\.(\S*)\s(asc|desc)/i', $rawsort, $matches)) {
609 if (strcasecmp($matches[2], 'asc') == 0) {
610 $sorts[] = 'COALESCE(ul.' . $matches[1] . ', 0) ASC';
611 } else {
612 $sorts[] = 'COALESCE(ul.' . $matches[1] . ', 0) DESC';
614 $sorttimeaccess = true;
615 } else if (strpos($rawsort, '.') !== false) {
616 $prefix = explode('.', $rawsort);
617 if (in_array($prefix[0], $allowedsortprefixes)) {
618 $sorts[] = trim($rawsort);
619 } else {
620 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
622 } else {
623 $sorts[] = 'c.'.trim($rawsort);
626 $sort = implode(',', $sorts);
627 $orderby = "ORDER BY $sort";
630 $wheres = array("c.id <> :siteid");
631 $params = array('siteid'=>SITEID);
633 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
634 // list _only_ this course - anything else is asking for trouble...
635 $wheres[] = "courseid = :loginas";
636 $params['loginas'] = $USER->loginascontext->instanceid;
639 $coursefields = 'c.' .join(',c.', $fields);
640 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
641 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
642 $params['contextlevel'] = CONTEXT_COURSE;
643 $wheres = implode(" AND ", $wheres);
645 $timeaccessselect = "";
646 $timeaccessjoin = "";
648 if (!empty($courseids)) {
649 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
650 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
651 $params = array_merge($params, $courseidsparams);
654 if (!empty($excludecourses)) {
655 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($excludecourses, SQL_PARAMS_NAMED, 'param', false);
656 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
657 $params = array_merge($params, $courseidsparams);
660 $courseidsql = "";
661 // Logged-in, non-guest users get their enrolled courses.
662 if (!isguestuser() && isloggedin()) {
663 $courseidsql .= "
664 SELECT DISTINCT e.courseid
665 FROM {enrol} e
666 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid1)
667 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart <= :now1
668 AND (ue.timeend = 0 OR ue.timeend > :now2)";
669 $params['userid1'] = $USER->id;
670 $params['active'] = ENROL_USER_ACTIVE;
671 $params['enabled'] = ENROL_INSTANCE_ENABLED;
672 $params['now1'] = $params['now2'] = time();
674 if ($sorttimeaccess) {
675 $params['userid2'] = $USER->id;
676 $timeaccessselect = ', ul.timeaccess as lastaccessed';
677 $timeaccessjoin = "LEFT JOIN {user_lastaccess} ul ON (ul.courseid = c.id AND ul.userid = :userid2)";
681 // When including non-enrolled but accessible courses...
682 if ($allaccessible) {
683 if (is_siteadmin()) {
684 // Site admins can access all courses.
685 $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
686 } else {
687 // If we used the enrolment as well, then this will be UNIONed.
688 if ($courseidsql) {
689 $courseidsql .= " UNION ";
692 // Include courses with guest access and no password.
693 $courseidsql .= "
694 SELECT DISTINCT e.courseid
695 FROM {enrol} e
696 WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
697 $params['emptypass'] = '';
698 $params['enabled2'] = ENROL_INSTANCE_ENABLED;
700 // Include courses where the current user is currently using guest access (may include
701 // those which require a password).
702 $courseids = [];
703 $accessdata = get_user_accessdata($USER->id);
704 foreach ($accessdata['ra'] as $contextpath => $roles) {
705 if (array_key_exists($CFG->guestroleid, $roles)) {
706 // Work out the course id from context path.
707 $context = context::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
708 if ($context instanceof context_course) {
709 $courseids[$context->instanceid] = true;
714 // Include courses where the current user has moodle/course:view capability.
715 $courses = get_user_capability_course('moodle/course:view', null, false);
716 if (!$courses) {
717 $courses = [];
719 foreach ($courses as $course) {
720 $courseids[$course->id] = true;
723 // If there are any in either category, list them individually.
724 if ($courseids) {
725 list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
726 array_keys($courseids), SQL_PARAMS_NAMED);
727 $courseidsql .= "
728 UNION
729 SELECT DISTINCT c3.id AS courseid
730 FROM {course} c3
731 WHERE c3.id $allowedsql";
732 $params = array_merge($params, $allowedparams);
737 // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
738 // we have the subselect there.
739 $sql = "SELECT $coursefields $ccselect $timeaccessselect
740 FROM {course} c
741 JOIN ($courseidsql) en ON (en.courseid = c.id)
742 $timeaccessjoin
743 $ccjoin
744 WHERE $wheres
745 $orderby";
747 $courses = $DB->get_records_sql($sql, $params, $offset, $limit);
749 // preload contexts and check visibility
750 foreach ($courses as $id=>$course) {
751 context_helper::preload_from_record($course);
752 if (!$course->visible) {
753 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
754 unset($courses[$id]);
755 continue;
757 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
758 unset($courses[$id]);
759 continue;
762 $courses[$id] = $course;
765 //wow! Is that really all? :-D
767 return $courses;
771 * Returns course enrolment information icons.
773 * @param object $course
774 * @param array $instances enrol instances of this course, improves performance
775 * @return array of pix_icon
777 function enrol_get_course_info_icons($course, array $instances = NULL) {
778 $icons = array();
779 if (is_null($instances)) {
780 $instances = enrol_get_instances($course->id, true);
782 $plugins = enrol_get_plugins(true);
783 foreach ($plugins as $name => $plugin) {
784 $pis = array();
785 foreach ($instances as $instance) {
786 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
787 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
788 continue;
790 if ($instance->enrol == $name) {
791 $pis[$instance->id] = $instance;
794 if ($pis) {
795 $icons = array_merge($icons, $plugin->get_info_icons($pis));
798 return $icons;
802 * Returns SQL ORDER arguments which reflect the admin settings to sort my courses.
804 * @param string|null $sort SQL ORDER arguments which were originally requested (optionally).
805 * @return string SQL ORDER arguments.
807 function enrol_get_courses_sortingsql($sort = null) {
808 global $CFG;
810 // Prepare the visible SQL fragment as empty.
811 $visible = '';
812 // Only create a visible SQL fragment if the caller didn't already pass a sort order which contains the visible field.
813 if ($sort === null || strpos($sort, 'visible') === false) {
814 // If the admin did not explicitly want to have shown and hidden courses sorted as one list, we will sort hidden
815 // courses to the end of the course list.
816 if (!isset($CFG->navsortmycourseshiddenlast) || $CFG->navsortmycourseshiddenlast == true) {
817 $visible = 'visible DESC, ';
821 // Only create a sortorder SQL fragment if the caller didn't already pass one.
822 if ($sort === null) {
823 // If the admin has configured a course sort order, we will use this.
824 if (!empty($CFG->navsortmycoursessort)) {
825 $sort = $CFG->navsortmycoursessort . ' ASC';
827 // Otherwise we will fall back to the sortorder sorting.
828 } else {
829 $sort = 'sortorder ASC';
833 return $visible . $sort;
837 * Returns course enrolment detailed information.
839 * @param object $course
840 * @return array of html fragments - can be used to construct lists
842 function enrol_get_course_description_texts($course) {
843 $lines = array();
844 $instances = enrol_get_instances($course->id, true);
845 $plugins = enrol_get_plugins(true);
846 foreach ($instances as $instance) {
847 if (!isset($plugins[$instance->enrol])) {
848 //weird
849 continue;
851 $plugin = $plugins[$instance->enrol];
852 $text = $plugin->get_description_text($instance);
853 if ($text !== NULL) {
854 $lines[] = $text;
857 return $lines;
861 * Returns list of courses user is enrolled into.
863 * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
865 * The $fields param is a list of field names to ADD so name just the fields you really need,
866 * which will be added and uniq'd.
868 * @param int $userid User whose courses are returned, defaults to the current user.
869 * @param bool $onlyactive Return only active enrolments in courses user may see.
870 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
871 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
872 * @return array
874 function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
875 global $DB;
877 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
879 // preload contexts and check visibility
880 if ($onlyactive) {
881 foreach ($courses as $id=>$course) {
882 context_helper::preload_from_record($course);
883 if (!$course->visible) {
884 if (!$context = context_course::instance($id)) {
885 unset($courses[$id]);
886 continue;
888 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
889 unset($courses[$id]);
890 continue;
896 return $courses;
900 * Returns list of roles per users into course.
902 * @param int $courseid Course id.
903 * @return array Array[$userid][$roleid] = role_assignment.
905 function enrol_get_course_users_roles(int $courseid) : array {
906 global $DB;
908 $context = context_course::instance($courseid);
910 $roles = array();
912 $records = $DB->get_recordset('role_assignments', array('contextid' => $context->id));
913 foreach ($records as $record) {
914 if (isset($roles[$record->userid]) === false) {
915 $roles[$record->userid] = array();
917 $roles[$record->userid][$record->roleid] = $record;
919 $records->close();
921 return $roles;
925 * Can user access at least one enrolled course?
927 * Cheat if necessary, but find out as fast as possible!
929 * @param int|stdClass $user null means use current user
930 * @return bool
932 function enrol_user_sees_own_courses($user = null) {
933 global $USER;
935 if ($user === null) {
936 $user = $USER;
938 $userid = is_object($user) ? $user->id : $user;
940 // Guest account does not have any courses
941 if (isguestuser($userid) or empty($userid)) {
942 return false;
945 // Let's cheat here if this is the current user,
946 // if user accessed any course recently, then most probably
947 // we do not need to query the database at all.
948 if ($USER->id == $userid) {
949 if (!empty($USER->enrol['enrolled'])) {
950 foreach ($USER->enrol['enrolled'] as $until) {
951 if ($until > time()) {
952 return true;
958 // Now the slow way.
959 $courses = enrol_get_all_users_courses($userid, true);
960 foreach($courses as $course) {
961 if ($course->visible) {
962 return true;
964 context_helper::preload_from_record($course);
965 $context = context_course::instance($course->id);
966 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
967 return true;
971 return false;
975 * Returns list of courses user is enrolled into without performing any capability checks.
977 * The $fields param is a list of field names to ADD so name just the fields you really need,
978 * which will be added and uniq'd.
980 * @param int $userid User whose courses are returned, defaults to the current user.
981 * @param bool $onlyactive Return only active enrolments in courses user may see.
982 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
983 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
984 * @return array
986 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
987 global $DB;
989 // Re-Arrange the course sorting according to the admin settings.
990 $sort = enrol_get_courses_sortingsql($sort);
992 // Guest account does not have any courses
993 if (isguestuser($userid) or empty($userid)) {
994 return(array());
997 $basefields = array('id', 'category', 'sortorder',
998 'shortname', 'fullname', 'idnumber',
999 'startdate', 'visible',
1000 'defaultgroupingid',
1001 'groupmode', 'groupmodeforce');
1003 if (empty($fields)) {
1004 $fields = $basefields;
1005 } else if (is_string($fields)) {
1006 // turn the fields from a string to an array
1007 $fields = explode(',', $fields);
1008 $fields = array_map('trim', $fields);
1009 $fields = array_unique(array_merge($basefields, $fields));
1010 } else if (is_array($fields)) {
1011 $fields = array_unique(array_merge($basefields, $fields));
1012 } else {
1013 throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
1015 if (in_array('*', $fields)) {
1016 $fields = array('*');
1019 $orderby = "";
1020 $sort = trim($sort);
1021 if (!empty($sort)) {
1022 $rawsorts = explode(',', $sort);
1023 $sorts = array();
1024 foreach ($rawsorts as $rawsort) {
1025 $rawsort = trim($rawsort);
1026 if (strpos($rawsort, 'c.') === 0) {
1027 $rawsort = substr($rawsort, 2);
1029 $sorts[] = trim($rawsort);
1031 $sort = 'c.'.implode(',c.', $sorts);
1032 $orderby = "ORDER BY $sort";
1035 $params = array('siteid'=>SITEID);
1037 if ($onlyactive) {
1038 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
1039 $params['now1'] = round(time(), -2); // improves db caching
1040 $params['now2'] = $params['now1'];
1041 $params['active'] = ENROL_USER_ACTIVE;
1042 $params['enabled'] = ENROL_INSTANCE_ENABLED;
1043 } else {
1044 $subwhere = "";
1047 $coursefields = 'c.' .join(',c.', $fields);
1048 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1049 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1050 $params['contextlevel'] = CONTEXT_COURSE;
1052 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
1053 $sql = "SELECT $coursefields $ccselect
1054 FROM {course} c
1055 JOIN (SELECT DISTINCT e.courseid
1056 FROM {enrol} e
1057 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
1058 $subwhere
1059 ) en ON (en.courseid = c.id)
1060 $ccjoin
1061 WHERE c.id <> :siteid
1062 $orderby";
1063 $params['userid'] = $userid;
1065 $courses = $DB->get_records_sql($sql, $params);
1067 return $courses;
1073 * Called when user is about to be deleted.
1074 * @param object $user
1075 * @return void
1077 function enrol_user_delete($user) {
1078 global $DB;
1080 $plugins = enrol_get_plugins(true);
1081 foreach ($plugins as $plugin) {
1082 $plugin->user_delete($user);
1085 // force cleanup of all broken enrolments
1086 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
1090 * Called when course is about to be deleted.
1091 * If a user id is passed, only enrolments that the user has permission to un-enrol will be removed,
1092 * otherwise all enrolments in the course will be removed.
1094 * @param stdClass $course
1095 * @param int|null $userid
1096 * @return void
1098 function enrol_course_delete($course, $userid = null) {
1099 global $DB;
1101 $context = context_course::instance($course->id);
1102 $instances = enrol_get_instances($course->id, false);
1103 $plugins = enrol_get_plugins(true);
1105 if ($userid) {
1106 // If the user id is present, include only course enrolment instances which allow manual unenrolment and
1107 // the given user have a capability to perform unenrolment.
1108 $instances = array_filter($instances, function($instance) use ($userid, $plugins, $context) {
1109 $unenrolcap = "enrol/{$instance->enrol}:unenrol";
1110 return $plugins[$instance->enrol]->allow_unenrol($instance) &&
1111 has_capability($unenrolcap, $context, $userid);
1115 foreach ($instances as $instance) {
1116 if (isset($plugins[$instance->enrol])) {
1117 $plugins[$instance->enrol]->delete_instance($instance);
1119 // low level delete in case plugin did not do it
1120 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
1121 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1122 $DB->delete_records('enrol', array('id'=>$instance->id));
1127 * Try to enrol user via default internal auth plugin.
1129 * For now this is always using the manual enrol plugin...
1131 * @param $courseid
1132 * @param $userid
1133 * @param $roleid
1134 * @param $timestart
1135 * @param $timeend
1136 * @return bool success
1138 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
1139 global $DB;
1141 //note: this is hardcoded to manual plugin for now
1143 if (!enrol_is_enabled('manual')) {
1144 return false;
1147 if (!$enrol = enrol_get_plugin('manual')) {
1148 return false;
1150 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
1151 return false;
1153 $instance = reset($instances);
1155 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
1157 return true;
1161 * Is there a chance users might self enrol
1162 * @param int $courseid
1163 * @return bool
1165 function enrol_selfenrol_available($courseid) {
1166 $result = false;
1168 $plugins = enrol_get_plugins(true);
1169 $enrolinstances = enrol_get_instances($courseid, true);
1170 foreach($enrolinstances as $instance) {
1171 if (!isset($plugins[$instance->enrol])) {
1172 continue;
1174 if ($instance->enrol === 'guest') {
1175 continue;
1177 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
1178 $result = true;
1179 break;
1183 return $result;
1187 * This function returns the end of current active user enrolment.
1189 * It deals correctly with multiple overlapping user enrolments.
1191 * @param int $courseid
1192 * @param int $userid
1193 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
1195 function enrol_get_enrolment_end($courseid, $userid) {
1196 global $DB;
1198 $sql = "SELECT ue.*
1199 FROM {user_enrolments} ue
1200 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1201 JOIN {user} u ON u.id = ue.userid
1202 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1203 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
1205 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1206 return false;
1209 $changes = array();
1211 foreach ($enrolments as $ue) {
1212 $start = (int)$ue->timestart;
1213 $end = (int)$ue->timeend;
1214 if ($end != 0 and $end < $start) {
1215 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
1216 continue;
1218 if (isset($changes[$start])) {
1219 $changes[$start] = $changes[$start] + 1;
1220 } else {
1221 $changes[$start] = 1;
1223 if ($end === 0) {
1224 // no end
1225 } else if (isset($changes[$end])) {
1226 $changes[$end] = $changes[$end] - 1;
1227 } else {
1228 $changes[$end] = -1;
1232 // let's sort then enrolment starts&ends and go through them chronologically,
1233 // looking for current status and the next future end of enrolment
1234 ksort($changes);
1236 $now = time();
1237 $current = 0;
1238 $present = null;
1240 foreach ($changes as $time => $change) {
1241 if ($time > $now) {
1242 if ($present === null) {
1243 // we have just went past current time
1244 $present = $current;
1245 if ($present < 1) {
1246 // no enrolment active
1247 return false;
1250 if ($present !== null) {
1251 // we are already in the future - look for possible end
1252 if ($current + $change < 1) {
1253 return $time;
1257 $current += $change;
1260 if ($current > 0) {
1261 return 0;
1262 } else {
1263 return false;
1268 * Is current user accessing course via this enrolment method?
1270 * This is intended for operations that are going to affect enrol instances.
1272 * @param stdClass $instance enrol instance
1273 * @return bool
1275 function enrol_accessing_via_instance(stdClass $instance) {
1276 global $DB, $USER;
1278 if (empty($instance->id)) {
1279 return false;
1282 if (is_siteadmin()) {
1283 // Admins may go anywhere.
1284 return false;
1287 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
1291 * Returns true if user is enrolled (is participating) in course
1292 * this is intended for students and teachers.
1294 * Since 2.2 the result for active enrolments and current user are cached.
1296 * @param context $context
1297 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1298 * @param string $withcapability extra capability name
1299 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1300 * @return bool
1302 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1303 global $USER, $DB;
1305 // First find the course context.
1306 $coursecontext = $context->get_course_context();
1308 // Make sure there is a real user specified.
1309 if ($user === null) {
1310 $userid = isset($USER->id) ? $USER->id : 0;
1311 } else {
1312 $userid = is_object($user) ? $user->id : $user;
1315 if (empty($userid)) {
1316 // Not-logged-in!
1317 return false;
1318 } else if (isguestuser($userid)) {
1319 // Guest account can not be enrolled anywhere.
1320 return false;
1323 // Note everybody participates on frontpage, so for other contexts...
1324 if ($coursecontext->instanceid != SITEID) {
1325 // Try cached info first - the enrolled flag is set only when active enrolment present.
1326 if ($USER->id == $userid) {
1327 $coursecontext->reload_if_dirty();
1328 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1329 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1330 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1331 return false;
1333 return true;
1338 if ($onlyactive) {
1339 // Look for active enrolments only.
1340 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1342 if ($until === false) {
1343 return false;
1346 if ($USER->id == $userid) {
1347 if ($until == 0) {
1348 $until = ENROL_MAX_TIMESTAMP;
1350 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1351 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1352 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1353 remove_temp_course_roles($coursecontext);
1357 } else {
1358 // Any enrolment is good for us here, even outdated, disabled or inactive.
1359 $sql = "SELECT 'x'
1360 FROM {user_enrolments} ue
1361 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1362 JOIN {user} u ON u.id = ue.userid
1363 WHERE ue.userid = :userid AND u.deleted = 0";
1364 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid);
1365 if (!$DB->record_exists_sql($sql, $params)) {
1366 return false;
1371 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1372 return false;
1375 return true;
1379 * Returns an array of joins, wheres and params that will limit the group of
1380 * users to only those enrolled and with given capability (if specified).
1382 * Note this join will return duplicate rows for users who have been enrolled
1383 * several times (e.g. as manual enrolment, and as self enrolment). You may
1384 * need to use a SELECT DISTINCT in your query (see get_enrolled_sql for example).
1386 * @param context $context
1387 * @param string $prefix optional, a prefix to the user id column
1388 * @param string|array $capability optional, may include a capability name, or array of names.
1389 * If an array is provided then this is the equivalent of a logical 'OR',
1390 * i.e. the user needs to have one of these capabilities.
1391 * @param int $group optional, 0 indicates no current group and USERSWITHOUTGROUP users without any group; otherwise the group id
1392 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1393 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1394 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1395 * @return \core\dml\sql_join Contains joins, wheres, params
1397 function get_enrolled_with_capabilities_join(context $context, $prefix = '', $capability = '', $group = 0,
1398 $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1399 $uid = $prefix . 'u.id';
1400 $joins = array();
1401 $wheres = array();
1403 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended, $enrolid);
1404 $joins[] = $enrolledjoin->joins;
1405 $wheres[] = $enrolledjoin->wheres;
1406 $params = $enrolledjoin->params;
1408 if (!empty($capability)) {
1409 $capjoin = get_with_capability_join($context, $capability, $uid);
1410 $joins[] = $capjoin->joins;
1411 $wheres[] = $capjoin->wheres;
1412 $params = array_merge($params, $capjoin->params);
1415 if ($group) {
1416 $groupjoin = groups_get_members_join($group, $uid, $context);
1417 $joins[] = $groupjoin->joins;
1418 $params = array_merge($params, $groupjoin->params);
1419 if (!empty($groupjoin->wheres)) {
1420 $wheres[] = $groupjoin->wheres;
1424 $joins = implode("\n", $joins);
1425 $wheres[] = "{$prefix}u.deleted = 0";
1426 $wheres = implode(" AND ", $wheres);
1428 return new \core\dml\sql_join($joins, $wheres, $params);
1432 * Returns array with sql code and parameters returning all ids
1433 * of users enrolled into course.
1435 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1437 * @param context $context
1438 * @param string $withcapability
1439 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1440 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1441 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1442 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1443 * @return array list($sql, $params)
1445 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false,
1446 $enrolid = 0) {
1448 // Use unique prefix just in case somebody makes some SQL magic with the result.
1449 static $i = 0;
1450 $i++;
1451 $prefix = 'eu' . $i . '_';
1453 $capjoin = get_enrolled_with_capabilities_join(
1454 $context, $prefix, $withcapability, $groupid, $onlyactive, $onlysuspended, $enrolid);
1456 $sql = "SELECT DISTINCT {$prefix}u.id
1457 FROM {user} {$prefix}u
1458 $capjoin->joins
1459 WHERE $capjoin->wheres";
1461 return array($sql, $capjoin->params);
1465 * Returns array with sql joins and parameters returning all ids
1466 * of users enrolled into course.
1468 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1470 * @throws coding_exception
1472 * @param context $context
1473 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1474 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1475 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1476 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1477 * @return \core\dml\sql_join Contains joins, wheres, params
1479 function get_enrolled_join(context $context, $useridcolumn, $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1480 // Use unique prefix just in case somebody makes some SQL magic with the result.
1481 static $i = 0;
1482 $i++;
1483 $prefix = 'ej' . $i . '_';
1485 // First find the course context.
1486 $coursecontext = $context->get_course_context();
1488 $isfrontpage = ($coursecontext->instanceid == SITEID);
1490 if ($onlyactive && $onlysuspended) {
1491 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1493 if ($isfrontpage && $onlysuspended) {
1494 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1497 $joins = array();
1498 $wheres = array();
1499 $params = array();
1501 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1503 // Note all users are "enrolled" on the frontpage, but for others...
1504 if (!$isfrontpage) {
1505 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1506 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1508 $enrolconditions = array(
1509 "{$prefix}e.id = {$prefix}ue.enrolid",
1510 "{$prefix}e.courseid = :{$prefix}courseid",
1512 if ($enrolid) {
1513 $enrolconditions[] = "{$prefix}e.id = :{$prefix}enrolid";
1514 $params[$prefix . 'enrolid'] = $enrolid;
1516 $enrolconditionssql = implode(" AND ", $enrolconditions);
1517 $ejoin = "JOIN {enrol} {$prefix}e ON ($enrolconditionssql)";
1519 $params[$prefix.'courseid'] = $coursecontext->instanceid;
1521 if (!$onlysuspended) {
1522 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1523 $joins[] = $ejoin;
1524 if ($onlyactive) {
1525 $wheres[] = "$where1 AND $where2";
1527 } else {
1528 // Suspended only where there is enrolment but ALL are suspended.
1529 // Consider multiple enrols where one is not suspended or plain role_assign.
1530 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1531 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1532 $enrolconditions = array(
1533 "{$prefix}e1.id = {$prefix}ue1.enrolid",
1534 "{$prefix}e1.courseid = :{$prefix}_e1_courseid",
1536 if ($enrolid) {
1537 $enrolconditions[] = "{$prefix}e1.id = :{$prefix}e1_enrolid";
1538 $params[$prefix . 'e1_enrolid'] = $enrolid;
1540 $enrolconditionssql = implode(" AND ", $enrolconditions);
1541 $joins[] = "JOIN {enrol} {$prefix}e1 ON ($enrolconditionssql)";
1542 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
1543 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1546 if ($onlyactive || $onlysuspended) {
1547 $now = round(time(), -2); // Rounding helps caching in DB.
1548 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED,
1549 $prefix . 'active' => ENROL_USER_ACTIVE,
1550 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1554 $joins = implode("\n", $joins);
1555 $wheres = implode(" AND ", $wheres);
1557 return new \core\dml\sql_join($joins, $wheres, $params);
1561 * Returns list of users enrolled into course.
1563 * @param context $context
1564 * @param string $withcapability
1565 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1566 * @param string $userfields requested user record fields
1567 * @param string $orderby
1568 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1569 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1570 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1571 * @return array of user records
1573 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1574 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1575 global $DB;
1577 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1578 $sql = "SELECT $userfields
1579 FROM {user} u
1580 JOIN ($esql) je ON je.id = u.id
1581 WHERE u.deleted = 0";
1583 if ($orderby) {
1584 $sql = "$sql ORDER BY $orderby";
1585 } else {
1586 list($sort, $sortparams) = users_order_by_sql('u');
1587 $sql = "$sql ORDER BY $sort";
1588 $params = array_merge($params, $sortparams);
1591 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1595 * Counts list of users enrolled into course (as per above function)
1597 * @param context $context
1598 * @param string $withcapability
1599 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1600 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1601 * @return array of user records
1603 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1604 global $DB;
1606 $capjoin = get_enrolled_with_capabilities_join(
1607 $context, '', $withcapability, $groupid, $onlyactive);
1609 $sql = "SELECT COUNT(DISTINCT u.id)
1610 FROM {user} u
1611 $capjoin->joins
1612 WHERE $capjoin->wheres AND u.deleted = 0";
1614 return $DB->count_records_sql($sql, $capjoin->params);
1618 * Send welcome email "from" options.
1620 * @return array list of from options
1622 function enrol_send_welcome_email_options() {
1623 return [
1624 ENROL_DO_NOT_SEND_EMAIL => get_string('no'),
1625 ENROL_SEND_EMAIL_FROM_COURSE_CONTACT => get_string('sendfromcoursecontact', 'enrol'),
1626 ENROL_SEND_EMAIL_FROM_KEY_HOLDER => get_string('sendfromkeyholder', 'enrol'),
1627 ENROL_SEND_EMAIL_FROM_NOREPLY => get_string('sendfromnoreply', 'enrol')
1632 * Serve the user enrolment form as a fragment.
1634 * @param array $args List of named arguments for the fragment loader.
1635 * @return string
1637 function enrol_output_fragment_user_enrolment_form($args) {
1638 global $CFG, $DB;
1640 $args = (object) $args;
1641 $context = $args->context;
1642 require_capability('moodle/course:enrolreview', $context);
1644 $ueid = $args->ueid;
1645 $userenrolment = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
1646 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid], '*', MUST_EXIST);
1647 $plugin = enrol_get_plugin($instance->enrol);
1648 $customdata = [
1649 'ue' => $userenrolment,
1650 'modal' => true,
1651 'enrolinstancename' => $plugin->get_instance_name($instance)
1654 // Set the data if applicable.
1655 $data = [];
1656 if (isset($args->formdata)) {
1657 $serialiseddata = json_decode($args->formdata);
1658 parse_str($serialiseddata, $data);
1661 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1662 $mform = new \enrol_user_enrolment_form(null, $customdata, 'post', '', null, true, $data);
1664 if (!empty($data)) {
1665 $mform->set_data($data);
1666 $mform->is_validated();
1669 return $mform->render();
1673 * Returns the course where a user enrolment belong to.
1675 * @param int $ueid user_enrolments id
1676 * @return stdClass
1678 function enrol_get_course_by_user_enrolment_id($ueid) {
1679 global $DB;
1680 $sql = "SELECT c.* FROM {user_enrolments} ue
1681 JOIN {enrol} e ON e.id = ue.enrolid
1682 JOIN {course} c ON c.id = e.courseid
1683 WHERE ue.id = :ueid";
1684 return $DB->get_record_sql($sql, array('ueid' => $ueid));
1688 * Return all users enrolled in a course.
1690 * @param int $courseid Course id or false if using $uefilter (user enrolment ids may belong to different courses)
1691 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1692 * @param array $usersfilter Limit the results obtained to this list of user ids. $uefilter compatibility not guaranteed.
1693 * @param array $uefilter Limit the results obtained to this list of user enrolment ids. $usersfilter compatibility not guaranteed.
1694 * @return stdClass[]
1696 function enrol_get_course_users($courseid = false, $onlyactive = false, $usersfilter = array(), $uefilter = array()) {
1697 global $DB;
1699 if (!$courseid && !$usersfilter && !$uefilter) {
1700 throw new \coding_exception('You should specify at least 1 filter: courseid, users or user enrolments');
1703 $sql = "SELECT ue.id AS ueid, ue.status AS uestatus, ue.enrolid AS ueenrolid, ue.timestart AS uetimestart,
1704 ue.timeend AS uetimeend, ue.modifierid AS uemodifierid, ue.timecreated AS uetimecreated,
1705 ue.timemodified AS uetimemodified, e.status AS estatus,
1706 u.* FROM {user_enrolments} ue
1707 JOIN {enrol} e ON e.id = ue.enrolid
1708 JOIN {user} u ON ue.userid = u.id
1709 WHERE ";
1710 $params = array();
1712 if ($courseid) {
1713 $conditions[] = "e.courseid = :courseid";
1714 $params['courseid'] = $courseid;
1717 if ($onlyactive) {
1718 $conditions[] = "ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND " .
1719 "(ue.timeend = 0 OR ue.timeend > :now2)";
1720 // Improves db caching.
1721 $params['now1'] = round(time(), -2);
1722 $params['now2'] = $params['now1'];
1723 $params['active'] = ENROL_USER_ACTIVE;
1724 $params['enabled'] = ENROL_INSTANCE_ENABLED;
1727 if ($usersfilter) {
1728 list($usersql, $userparams) = $DB->get_in_or_equal($usersfilter, SQL_PARAMS_NAMED);
1729 $conditions[] = "ue.userid $usersql";
1730 $params = $params + $userparams;
1733 if ($uefilter) {
1734 list($uesql, $ueparams) = $DB->get_in_or_equal($uefilter, SQL_PARAMS_NAMED);
1735 $conditions[] = "ue.id $uesql";
1736 $params = $params + $ueparams;
1739 return $DB->get_records_sql($sql . ' ' . implode(' AND ', $conditions), $params);
1743 * Get the list of options for the enrolment period dropdown
1745 * @return array List of options for the enrolment period dropdown
1747 function enrol_get_period_list() {
1748 $periodmenu = [];
1749 $periodmenu[''] = get_string('unlimited');
1750 for ($i = 1; $i <= 365; $i++) {
1751 $seconds = $i * DAYSECS;
1752 $periodmenu[$seconds] = get_string('numdays', '', $i);
1754 return $periodmenu;
1758 * Calculate duration base on start time and end time
1760 * @param int $timestart Time start
1761 * @param int $timeend Time end
1762 * @return float|int Calculated duration
1764 function enrol_calculate_duration($timestart, $timeend) {
1765 $duration = floor(($timeend - $timestart) / DAYSECS) * DAYSECS;
1766 return $duration;
1770 * Enrolment plugins abstract class.
1772 * All enrol plugins should be based on this class,
1773 * this is also the main source of documentation.
1775 * @copyright 2010 Petr Skoda {@link http://skodak.org}
1776 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1778 abstract class enrol_plugin {
1779 protected $config = null;
1782 * Returns name of this enrol plugin
1783 * @return string
1785 public function get_name() {
1786 // second word in class is always enrol name, sorry, no fancy plugin names with _
1787 $words = explode('_', get_class($this));
1788 return $words[1];
1792 * Returns localised name of enrol instance
1794 * @param object $instance (null is accepted too)
1795 * @return string
1797 public function get_instance_name($instance) {
1798 if (empty($instance->name)) {
1799 $enrol = $this->get_name();
1800 return get_string('pluginname', 'enrol_'.$enrol);
1801 } else {
1802 $context = context_course::instance($instance->courseid);
1803 return format_string($instance->name, true, array('context'=>$context));
1808 * Returns optional enrolment information icons.
1810 * This is used in course list for quick overview of enrolment options.
1812 * We are not using single instance parameter because sometimes
1813 * we might want to prevent icon repetition when multiple instances
1814 * of one type exist. One instance may also produce several icons.
1816 * @param array $instances all enrol instances of this type in one course
1817 * @return array of pix_icon
1819 public function get_info_icons(array $instances) {
1820 return array();
1824 * Returns optional enrolment instance description text.
1826 * This is used in detailed course information.
1829 * @param object $instance
1830 * @return string short html text
1832 public function get_description_text($instance) {
1833 return null;
1837 * Makes sure config is loaded and cached.
1838 * @return void
1840 protected function load_config() {
1841 if (!isset($this->config)) {
1842 $name = $this->get_name();
1843 $this->config = get_config("enrol_$name");
1848 * Returns plugin config value
1849 * @param string $name
1850 * @param string $default value if config does not exist yet
1851 * @return string value or default
1853 public function get_config($name, $default = NULL) {
1854 $this->load_config();
1855 return isset($this->config->$name) ? $this->config->$name : $default;
1859 * Sets plugin config value
1860 * @param string $name name of config
1861 * @param string $value string config value, null means delete
1862 * @return string value
1864 public function set_config($name, $value) {
1865 $pluginname = $this->get_name();
1866 $this->load_config();
1867 if ($value === NULL) {
1868 unset($this->config->$name);
1869 } else {
1870 $this->config->$name = $value;
1872 set_config($name, $value, "enrol_$pluginname");
1876 * Does this plugin assign protected roles are can they be manually removed?
1877 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1879 public function roles_protected() {
1880 return true;
1884 * Does this plugin allow manual enrolments?
1886 * @param stdClass $instance course enrol instance
1887 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1889 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1891 public function allow_enrol(stdClass $instance) {
1892 return false;
1896 * Does this plugin allow manual unenrolment of all users?
1897 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1899 * @param stdClass $instance course enrol instance
1900 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1902 public function allow_unenrol(stdClass $instance) {
1903 return false;
1907 * Does this plugin allow manual unenrolment of a specific user?
1908 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1910 * This is useful especially for synchronisation plugins that
1911 * do suspend instead of full unenrolment.
1913 * @param stdClass $instance course enrol instance
1914 * @param stdClass $ue record from user_enrolments table, specifies user
1916 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1918 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1919 return $this->allow_unenrol($instance);
1923 * Does this plugin allow manual changes in user_enrolments table?
1925 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1927 * @param stdClass $instance course enrol instance
1928 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1930 public function allow_manage(stdClass $instance) {
1931 return false;
1935 * Does this plugin support some way to user to self enrol?
1937 * @param stdClass $instance course enrol instance
1939 * @return bool - true means show "Enrol me in this course" link in course UI
1941 public function show_enrolme_link(stdClass $instance) {
1942 return false;
1946 * Attempt to automatically enrol current user in course without any interaction,
1947 * calling code has to make sure the plugin and instance are active.
1949 * This should return either a timestamp in the future or false.
1951 * @param stdClass $instance course enrol instance
1952 * @return bool|int false means not enrolled, integer means timeend
1954 public function try_autoenrol(stdClass $instance) {
1955 global $USER;
1957 return false;
1961 * Attempt to automatically gain temporary guest access to course,
1962 * calling code has to make sure the plugin and instance are active.
1964 * This should return either a timestamp in the future or false.
1966 * @param stdClass $instance course enrol instance
1967 * @return bool|int false means no guest access, integer means timeend
1969 public function try_guestaccess(stdClass $instance) {
1970 global $USER;
1972 return false;
1976 * Enrol user into course via enrol instance.
1978 * @param stdClass $instance
1979 * @param int $userid
1980 * @param int $roleid optional role id
1981 * @param int $timestart 0 means unknown
1982 * @param int $timeend 0 means forever
1983 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1984 * @param bool $recovergrades restore grade history
1985 * @return void
1987 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
1988 global $DB, $USER, $CFG; // CFG necessary!!!
1990 if ($instance->courseid == SITEID) {
1991 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1994 $name = $this->get_name();
1995 $courseid = $instance->courseid;
1997 if ($instance->enrol !== $name) {
1998 throw new coding_exception('invalid enrol instance!');
2000 $context = context_course::instance($instance->courseid, MUST_EXIST);
2001 if (!isset($recovergrades)) {
2002 $recovergrades = $CFG->recovergradesdefault;
2005 $inserted = false;
2006 $updated = false;
2007 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2008 //only update if timestart or timeend or status are different.
2009 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
2010 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
2012 } else {
2013 $ue = new stdClass();
2014 $ue->enrolid = $instance->id;
2015 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
2016 $ue->userid = $userid;
2017 $ue->timestart = $timestart;
2018 $ue->timeend = $timeend;
2019 $ue->modifierid = $USER->id;
2020 $ue->timecreated = time();
2021 $ue->timemodified = $ue->timecreated;
2022 $ue->id = $DB->insert_record('user_enrolments', $ue);
2024 $inserted = true;
2027 if ($inserted) {
2028 // Trigger event.
2029 $event = \core\event\user_enrolment_created::create(
2030 array(
2031 'objectid' => $ue->id,
2032 'courseid' => $courseid,
2033 'context' => $context,
2034 'relateduserid' => $ue->userid,
2035 'other' => array('enrol' => $name)
2038 $event->trigger();
2039 // Check if course contacts cache needs to be cleared.
2040 core_course_category::user_enrolment_changed($courseid, $ue->userid,
2041 $ue->status, $ue->timestart, $ue->timeend);
2044 if ($roleid) {
2045 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
2046 if ($this->roles_protected()) {
2047 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
2048 } else {
2049 role_assign($roleid, $userid, $context->id);
2053 // Recover old grades if present.
2054 if ($recovergrades) {
2055 require_once("$CFG->libdir/gradelib.php");
2056 grade_recover_history_grades($userid, $courseid);
2059 // reset current user enrolment caching
2060 if ($userid == $USER->id) {
2061 if (isset($USER->enrol['enrolled'][$courseid])) {
2062 unset($USER->enrol['enrolled'][$courseid]);
2064 if (isset($USER->enrol['tempguest'][$courseid])) {
2065 unset($USER->enrol['tempguest'][$courseid]);
2066 remove_temp_course_roles($context);
2072 * Store user_enrolments changes and trigger event.
2074 * @param stdClass $instance
2075 * @param int $userid
2076 * @param int $status
2077 * @param int $timestart
2078 * @param int $timeend
2079 * @return void
2081 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
2082 global $DB, $USER, $CFG;
2084 $name = $this->get_name();
2086 if ($instance->enrol !== $name) {
2087 throw new coding_exception('invalid enrol instance!');
2090 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2091 // weird, user not enrolled
2092 return;
2095 $modified = false;
2096 if (isset($status) and $ue->status != $status) {
2097 $ue->status = $status;
2098 $modified = true;
2100 if (isset($timestart) and $ue->timestart != $timestart) {
2101 $ue->timestart = $timestart;
2102 $modified = true;
2104 if (isset($timeend) and $ue->timeend != $timeend) {
2105 $ue->timeend = $timeend;
2106 $modified = true;
2109 if (!$modified) {
2110 // no change
2111 return;
2114 $ue->modifierid = $USER->id;
2115 $ue->timemodified = time();
2116 $DB->update_record('user_enrolments', $ue);
2118 // User enrolments have changed, so mark user as dirty.
2119 mark_user_dirty($userid);
2121 // Invalidate core_access cache for get_suspended_userids.
2122 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));
2124 // Trigger event.
2125 $event = \core\event\user_enrolment_updated::create(
2126 array(
2127 'objectid' => $ue->id,
2128 'courseid' => $instance->courseid,
2129 'context' => context_course::instance($instance->courseid),
2130 'relateduserid' => $ue->userid,
2131 'other' => array('enrol' => $name)
2134 $event->trigger();
2136 core_course_category::user_enrolment_changed($instance->courseid, $ue->userid,
2137 $ue->status, $ue->timestart, $ue->timeend);
2141 * Unenrol user from course,
2142 * the last unenrolment removes all remaining roles.
2144 * @param stdClass $instance
2145 * @param int $userid
2146 * @return void
2148 public function unenrol_user(stdClass $instance, $userid) {
2149 global $CFG, $USER, $DB;
2150 require_once("$CFG->dirroot/group/lib.php");
2152 $name = $this->get_name();
2153 $courseid = $instance->courseid;
2155 if ($instance->enrol !== $name) {
2156 throw new coding_exception('invalid enrol instance!');
2158 $context = context_course::instance($instance->courseid, MUST_EXIST);
2160 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2161 // weird, user not enrolled
2162 return;
2165 // Remove all users groups linked to this enrolment instance.
2166 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
2167 foreach ($gms as $gm) {
2168 groups_remove_member($gm->groupid, $gm->userid);
2172 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
2173 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
2175 // add extra info and trigger event
2176 $ue->courseid = $courseid;
2177 $ue->enrol = $name;
2179 $sql = "SELECT 'x'
2180 FROM {user_enrolments} ue
2181 JOIN {enrol} e ON (e.id = ue.enrolid)
2182 WHERE ue.userid = :userid AND e.courseid = :courseid";
2183 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
2184 $ue->lastenrol = false;
2186 } else {
2187 // the big cleanup IS necessary!
2188 require_once("$CFG->libdir/gradelib.php");
2190 // remove all remaining roles
2191 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
2193 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
2194 groups_delete_group_members($courseid, $userid);
2196 grade_user_unenrol($courseid, $userid);
2198 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
2200 $ue->lastenrol = true; // means user not enrolled any more
2202 // Trigger event.
2203 $event = \core\event\user_enrolment_deleted::create(
2204 array(
2205 'courseid' => $courseid,
2206 'context' => $context,
2207 'relateduserid' => $ue->userid,
2208 'objectid' => $ue->id,
2209 'other' => array(
2210 'userenrolment' => (array)$ue,
2211 'enrol' => $name
2215 $event->trigger();
2217 // User enrolments have changed, so mark user as dirty.
2218 mark_user_dirty($userid);
2220 // Check if courrse contacts cache needs to be cleared.
2221 core_course_category::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);
2223 // reset current user enrolment caching
2224 if ($userid == $USER->id) {
2225 if (isset($USER->enrol['enrolled'][$courseid])) {
2226 unset($USER->enrol['enrolled'][$courseid]);
2228 if (isset($USER->enrol['tempguest'][$courseid])) {
2229 unset($USER->enrol['tempguest'][$courseid]);
2230 remove_temp_course_roles($context);
2236 * Forces synchronisation of user enrolments.
2238 * This is important especially for external enrol plugins,
2239 * this function is called for all enabled enrol plugins
2240 * right after every user login.
2242 * @param object $user user record
2243 * @return void
2245 public function sync_user_enrolments($user) {
2246 // override if necessary
2250 * This returns false for backwards compatibility, but it is really recommended.
2252 * @since Moodle 3.1
2253 * @return boolean
2255 public function use_standard_editing_ui() {
2256 return false;
2260 * Return whether or not, given the current state, it is possible to add a new instance
2261 * of this enrolment plugin to the course.
2263 * Default implementation is just for backwards compatibility.
2265 * @param int $courseid
2266 * @return boolean
2268 public function can_add_instance($courseid) {
2269 $link = $this->get_newinstance_link($courseid);
2270 return !empty($link);
2274 * Return whether or not, given the current state, it is possible to edit an instance
2275 * of this enrolment plugin in the course. Used by the standard editing UI
2276 * to generate a link to the edit instance form if editing is allowed.
2278 * @param stdClass $instance
2279 * @return boolean
2281 public function can_edit_instance($instance) {
2282 $context = context_course::instance($instance->courseid);
2284 return has_capability('enrol/' . $instance->enrol . ':config', $context);
2288 * Returns link to page which may be used to add new instance of enrolment plugin in course.
2289 * @param int $courseid
2290 * @return moodle_url page url
2292 public function get_newinstance_link($courseid) {
2293 // override for most plugins, check if instance already exists in cases only one instance is supported
2294 return NULL;
2298 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
2300 public function instance_deleteable($instance) {
2301 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
2302 enrol_plugin::can_delete_instance() instead');
2306 * Is it possible to delete enrol instance via standard UI?
2308 * @param stdClass $instance
2309 * @return bool
2311 public function can_delete_instance($instance) {
2312 return false;
2316 * Is it possible to hide/show enrol instance via standard UI?
2318 * @param stdClass $instance
2319 * @return bool
2321 public function can_hide_show_instance($instance) {
2322 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER);
2323 return true;
2327 * Returns link to manual enrol UI if exists.
2328 * Does the access control tests automatically.
2330 * @param object $instance
2331 * @return moodle_url
2333 public function get_manual_enrol_link($instance) {
2334 return NULL;
2338 * Returns list of unenrol links for all enrol instances in course.
2340 * @param int $instance
2341 * @return moodle_url or NULL if self unenrolment not supported
2343 public function get_unenrolself_link($instance) {
2344 global $USER, $CFG, $DB;
2346 $name = $this->get_name();
2347 if ($instance->enrol !== $name) {
2348 throw new coding_exception('invalid enrol instance!');
2351 if ($instance->courseid == SITEID) {
2352 return NULL;
2355 if (!enrol_is_enabled($name)) {
2356 return NULL;
2359 if ($instance->status != ENROL_INSTANCE_ENABLED) {
2360 return NULL;
2363 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2364 return NULL;
2367 $context = context_course::instance($instance->courseid, MUST_EXIST);
2369 if (!has_capability("enrol/$name:unenrolself", $context)) {
2370 return NULL;
2373 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
2374 return NULL;
2377 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
2381 * Adds enrol instance UI to course edit form
2383 * @param object $instance enrol instance or null if does not exist yet
2384 * @param MoodleQuickForm $mform
2385 * @param object $data
2386 * @param object $context context of existing course or parent category if course does not exist
2387 * @return void
2389 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
2390 // override - usually at least enable/disable switch, has to add own form header
2394 * Adds form elements to add/edit instance form.
2396 * @since Moodle 3.1
2397 * @param object $instance enrol instance or null if does not exist yet
2398 * @param MoodleQuickForm $mform
2399 * @param context $context
2400 * @return void
2402 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
2403 // Do nothing by default.
2407 * Perform custom validation of the data used to edit the instance.
2409 * @since Moodle 3.1
2410 * @param array $data array of ("fieldname"=>value) of submitted data
2411 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2412 * @param object $instance The instance data loaded from the DB.
2413 * @param context $context The context of the instance we are editing
2414 * @return array of "element_name"=>"error_description" if there are errors,
2415 * or an empty array if everything is OK.
2417 public function edit_instance_validation($data, $files, $instance, $context) {
2418 // No errors by default.
2419 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER);
2420 return array();
2424 * Validates course edit form data
2426 * @param object $instance enrol instance or null if does not exist yet
2427 * @param array $data
2428 * @param object $context context of existing course or parent category if course does not exist
2429 * @return array errors array
2431 public function course_edit_validation($instance, array $data, $context) {
2432 return array();
2436 * Called after updating/inserting course.
2438 * @param bool $inserted true if course just inserted
2439 * @param object $course
2440 * @param object $data form data
2441 * @return void
2443 public function course_updated($inserted, $course, $data) {
2444 if ($inserted) {
2445 if ($this->get_config('defaultenrol')) {
2446 $this->add_default_instance($course);
2452 * Add new instance of enrol plugin.
2453 * @param object $course
2454 * @param array instance fields
2455 * @return int id of new instance, null if can not be created
2457 public function add_instance($course, array $fields = NULL) {
2458 global $DB;
2460 if ($course->id == SITEID) {
2461 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2464 $instance = new stdClass();
2465 $instance->enrol = $this->get_name();
2466 $instance->status = ENROL_INSTANCE_ENABLED;
2467 $instance->courseid = $course->id;
2468 $instance->enrolstartdate = 0;
2469 $instance->enrolenddate = 0;
2470 $instance->timemodified = time();
2471 $instance->timecreated = $instance->timemodified;
2472 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
2474 $fields = (array)$fields;
2475 unset($fields['enrol']);
2476 unset($fields['courseid']);
2477 unset($fields['sortorder']);
2478 foreach($fields as $field=>$value) {
2479 $instance->$field = $value;
2482 $instance->id = $DB->insert_record('enrol', $instance);
2484 \core\event\enrol_instance_created::create_from_record($instance)->trigger();
2486 return $instance->id;
2490 * Update instance of enrol plugin.
2492 * @since Moodle 3.1
2493 * @param stdClass $instance
2494 * @param stdClass $data modified instance fields
2495 * @return boolean
2497 public function update_instance($instance, $data) {
2498 global $DB;
2499 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2500 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2501 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2502 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2503 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2504 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2506 foreach ($properties as $key) {
2507 if (isset($data->$key)) {
2508 $instance->$key = $data->$key;
2511 $instance->timemodified = time();
2513 $update = $DB->update_record('enrol', $instance);
2514 if ($update) {
2515 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2517 return $update;
2521 * Add new instance of enrol plugin with default settings,
2522 * called when adding new instance manually or when adding new course.
2524 * Not all plugins support this.
2526 * @param object $course
2527 * @return int id of new instance or null if no default supported
2529 public function add_default_instance($course) {
2530 return null;
2534 * Update instance status
2536 * Override when plugin needs to do some action when enabled or disabled.
2538 * @param stdClass $instance
2539 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2540 * @return void
2542 public function update_status($instance, $newstatus) {
2543 global $DB;
2545 $instance->status = $newstatus;
2546 $DB->update_record('enrol', $instance);
2548 $context = context_course::instance($instance->courseid);
2549 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2551 // Invalidate all enrol caches.
2552 $context->mark_dirty();
2556 * Delete course enrol plugin instance, unenrol all users.
2557 * @param object $instance
2558 * @return void
2560 public function delete_instance($instance) {
2561 global $DB;
2563 $name = $this->get_name();
2564 if ($instance->enrol !== $name) {
2565 throw new coding_exception('invalid enrol instance!');
2568 //first unenrol all users
2569 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
2570 foreach ($participants as $participant) {
2571 $this->unenrol_user($instance, $participant->userid);
2573 $participants->close();
2575 // now clean up all remainders that were not removed correctly
2576 if ($gms = $DB->get_records('groups_members', array('itemid' => $instance->id, 'component' => 'enrol_' . $name))) {
2577 foreach ($gms as $gm) {
2578 groups_remove_member($gm->groupid, $gm->userid);
2581 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
2582 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
2584 // finally drop the enrol row
2585 $DB->delete_records('enrol', array('id'=>$instance->id));
2587 $context = context_course::instance($instance->courseid);
2588 \core\event\enrol_instance_deleted::create_from_record($instance)->trigger();
2590 // Invalidate all enrol caches.
2591 $context->mark_dirty();
2595 * Creates course enrol form, checks if form submitted
2596 * and enrols user if necessary. It can also redirect.
2598 * @param stdClass $instance
2599 * @return string html text, usually a form in a text box
2601 public function enrol_page_hook(stdClass $instance) {
2602 return null;
2606 * Checks if user can self enrol.
2608 * @param stdClass $instance enrolment instance
2609 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2610 * used by navigation to improve performance.
2611 * @return bool|string true if successful, else error message or false
2613 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
2614 return false;
2618 * Return information for enrolment instance containing list of parameters required
2619 * for enrolment, name of enrolment plugin etc.
2621 * @param stdClass $instance enrolment instance
2622 * @return array instance info.
2624 public function get_enrol_info(stdClass $instance) {
2625 return null;
2629 * Adds navigation links into course admin block.
2631 * By defaults looks for manage links only.
2633 * @param navigation_node $instancesnode
2634 * @param stdClass $instance
2635 * @return void
2637 public function add_course_navigation($instancesnode, stdClass $instance) {
2638 if ($this->use_standard_editing_ui()) {
2639 $context = context_course::instance($instance->courseid);
2640 $cap = 'enrol/' . $instance->enrol . ':config';
2641 if (has_capability($cap, $context)) {
2642 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2643 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2644 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
2650 * Returns edit icons for the page with list of instances
2651 * @param stdClass $instance
2652 * @return array
2654 public function get_action_icons(stdClass $instance) {
2655 global $OUTPUT;
2657 $icons = array();
2658 if ($this->use_standard_editing_ui()) {
2659 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2660 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2661 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2662 array('class' => 'iconsmall')));
2664 return $icons;
2668 * Reads version.php and determines if it is necessary
2669 * to execute the cron job now.
2670 * @return bool
2672 public function is_cron_required() {
2673 global $CFG;
2675 $name = $this->get_name();
2676 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2677 $plugin = new stdClass();
2678 include($versionfile);
2679 if (empty($plugin->cron)) {
2680 return false;
2682 $lastexecuted = $this->get_config('lastcron', 0);
2683 if ($lastexecuted + $plugin->cron < time()) {
2684 return true;
2685 } else {
2686 return false;
2691 * Called for all enabled enrol plugins that returned true from is_cron_required().
2692 * @return void
2694 public function cron() {
2698 * Called when user is about to be deleted
2699 * @param object $user
2700 * @return void
2702 public function user_delete($user) {
2703 global $DB;
2705 $sql = "SELECT e.*
2706 FROM {enrol} e
2707 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2708 WHERE e.enrol = :name AND ue.userid = :userid";
2709 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
2711 $rs = $DB->get_recordset_sql($sql, $params);
2712 foreach($rs as $instance) {
2713 $this->unenrol_user($instance, $user->id);
2715 $rs->close();
2719 * Returns an enrol_user_button that takes the user to a page where they are able to
2720 * enrol users into the managers course through this plugin.
2722 * Optional: If the plugin supports manual enrolments it can choose to override this
2723 * otherwise it shouldn't
2725 * @param course_enrolment_manager $manager
2726 * @return enrol_user_button|false
2728 public function get_manual_enrol_button(course_enrolment_manager $manager) {
2729 return false;
2733 * Gets an array of the user enrolment actions
2735 * @param course_enrolment_manager $manager
2736 * @param stdClass $ue
2737 * @return array An array of user_enrolment_actions
2739 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
2740 $actions = [];
2741 $context = $manager->get_context();
2742 $instance = $ue->enrolmentinstance;
2743 $params = $manager->get_moodlepage()->url->params();
2744 $params['ue'] = $ue->id;
2746 // Edit enrolment action.
2747 if ($this->allow_manage($instance) && has_capability("enrol/{$instance->enrol}:manage", $context)) {
2748 $title = get_string('editenrolment', 'enrol');
2749 $icon = new pix_icon('t/edit', $title);
2750 $url = new moodle_url('/enrol/editenrolment.php', $params);
2751 $actionparams = [
2752 'class' => 'editenrollink',
2753 'rel' => $ue->id,
2754 'data-action' => ENROL_ACTION_EDIT
2756 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2759 // Unenrol action.
2760 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/{$instance->enrol}:unenrol", $context)) {
2761 $title = get_string('unenrol', 'enrol');
2762 $icon = new pix_icon('t/delete', $title);
2763 $url = new moodle_url('/enrol/unenroluser.php', $params);
2764 $actionparams = [
2765 'class' => 'unenrollink',
2766 'rel' => $ue->id,
2767 'data-action' => ENROL_ACTION_UNENROL
2769 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2771 return $actions;
2775 * Returns true if the plugin has one or more bulk operations that can be performed on
2776 * user enrolments.
2778 * @param course_enrolment_manager $manager
2779 * @return bool
2781 public function has_bulk_operations(course_enrolment_manager $manager) {
2782 return false;
2786 * Return an array of enrol_bulk_enrolment_operation objects that define
2787 * the bulk actions that can be performed on user enrolments by the plugin.
2789 * @param course_enrolment_manager $manager
2790 * @return array
2792 public function get_bulk_operations(course_enrolment_manager $manager) {
2793 return array();
2797 * Do any enrolments need expiration processing.
2799 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2801 * @param progress_trace $trace
2802 * @param int $courseid one course, empty mean all
2803 * @return bool true if any data processed, false if not
2805 public function process_expirations(progress_trace $trace, $courseid = null) {
2806 global $DB;
2808 $name = $this->get_name();
2809 if (!enrol_is_enabled($name)) {
2810 $trace->finished();
2811 return false;
2814 $processed = false;
2815 $params = array();
2816 $coursesql = "";
2817 if ($courseid) {
2818 $coursesql = "AND e.courseid = :courseid";
2821 // Deal with expired accounts.
2822 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
2824 if ($action == ENROL_EXT_REMOVED_UNENROL) {
2825 $instances = array();
2826 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2827 FROM {user_enrolments} ue
2828 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2829 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2830 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2831 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
2833 $rs = $DB->get_recordset_sql($sql, $params);
2834 foreach ($rs as $ue) {
2835 if (!$processed) {
2836 $trace->output("Starting processing of enrol_$name expirations...");
2837 $processed = true;
2839 if (empty($instances[$ue->enrolid])) {
2840 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2842 $instance = $instances[$ue->enrolid];
2843 if (!$this->roles_protected()) {
2844 // Let's just guess what extra roles are supposed to be removed.
2845 if ($instance->roleid) {
2846 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
2849 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2850 $this->unenrol_user($instance, $ue->userid);
2851 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2853 $rs->close();
2854 unset($instances);
2856 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
2857 $instances = array();
2858 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2859 FROM {user_enrolments} ue
2860 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2861 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2862 WHERE ue.timeend > 0 AND ue.timeend < :now
2863 AND ue.status = :useractive $coursesql";
2864 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
2865 $rs = $DB->get_recordset_sql($sql, $params);
2866 foreach ($rs as $ue) {
2867 if (!$processed) {
2868 $trace->output("Starting processing of enrol_$name expirations...");
2869 $processed = true;
2871 if (empty($instances[$ue->enrolid])) {
2872 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2874 $instance = $instances[$ue->enrolid];
2876 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
2877 if (!$this->roles_protected()) {
2878 // Let's just guess what roles should be removed.
2879 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
2880 if ($count == 1) {
2881 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
2883 } else if ($count > 1 and $instance->roleid) {
2884 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
2887 // In any case remove all roles that belong to this instance and user.
2888 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
2889 // Final cleanup of subcontexts if there are no more course roles.
2890 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
2891 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
2895 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
2896 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2898 $rs->close();
2899 unset($instances);
2901 } else {
2902 // ENROL_EXT_REMOVED_KEEP means no changes.
2905 if ($processed) {
2906 $trace->output("...finished processing of enrol_$name expirations");
2907 } else {
2908 $trace->output("No expired enrol_$name enrolments detected");
2910 $trace->finished();
2912 return $processed;
2916 * Send expiry notifications.
2918 * Plugin that wants to have expiry notification MUST implement following:
2919 * - expirynotifyhour plugin setting,
2920 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2921 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2922 * expirymessageenrolledsubject and expirymessageenrolledbody),
2923 * - expiry_notification provider in db/messages.php,
2924 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2925 * - something that calls this method, such as cron.
2927 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2929 public function send_expiry_notifications($trace) {
2930 global $DB, $CFG;
2932 $name = $this->get_name();
2933 if (!enrol_is_enabled($name)) {
2934 $trace->finished();
2935 return;
2938 // Unfortunately this may take a long time, it should not be interrupted,
2939 // otherwise users get duplicate notification.
2941 core_php_time_limit::raise();
2942 raise_memory_limit(MEMORY_HUGE);
2945 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2946 $expirynotifyhour = $this->get_config('expirynotifyhour');
2947 if (is_null($expirynotifyhour)) {
2948 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
2949 $trace->finished();
2950 return;
2953 if (!($trace instanceof progress_trace)) {
2954 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
2955 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
2958 $timenow = time();
2959 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
2961 if ($expirynotifylast > $notifytime) {
2962 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
2963 $trace->finished();
2964 return;
2966 } else if ($timenow < $notifytime) {
2967 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
2968 $trace->finished();
2969 return;
2972 $trace->output('Processing '.$name.' enrolment expiration notifications...');
2974 // Notify users responsible for enrolment once every day.
2975 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2976 FROM {user_enrolments} ue
2977 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2978 JOIN {course} c ON (c.id = e.courseid)
2979 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2980 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2981 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2982 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2984 $rs = $DB->get_recordset_sql($sql, $params);
2986 $lastenrollid = 0;
2987 $users = array();
2989 foreach($rs as $ue) {
2990 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
2991 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2992 $users = array();
2994 $lastenrollid = $ue->enrolid;
2996 $enroller = $this->get_enroller($ue->enrolid);
2997 $context = context_course::instance($ue->courseid);
2999 $user = $DB->get_record('user', array('id'=>$ue->userid));
3001 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
3003 if (!$ue->notifyall) {
3004 continue;
3007 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
3008 // Notify enrolled users only once at the start of the threshold.
3009 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3010 continue;
3013 $this->notify_expiry_enrolled($user, $ue, $trace);
3015 $rs->close();
3017 if ($lastenrollid and $users) {
3018 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3021 $trace->output('...notification processing finished.');
3022 $trace->finished();
3024 $this->set_config('expirynotifylast', $timenow);
3028 * Returns the user who is responsible for enrolments for given instance.
3030 * Override if plugin knows anybody better than admin.
3032 * @param int $instanceid enrolment instance id
3033 * @return stdClass user record
3035 protected function get_enroller($instanceid) {
3036 return get_admin();
3040 * Notify user about incoming expiration of their enrolment,
3041 * it is called only if notification of enrolled users (aka students) is enabled in course.
3043 * This is executed only once for each expiring enrolment right
3044 * at the start of the expiration threshold.
3046 * @param stdClass $user
3047 * @param stdClass $ue
3048 * @param progress_trace $trace
3050 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
3051 global $CFG;
3053 $name = $this->get_name();
3055 $oldforcelang = force_current_language($user->lang);
3057 $enroller = $this->get_enroller($ue->enrolid);
3058 $context = context_course::instance($ue->courseid);
3060 $a = new stdClass();
3061 $a->course = format_string($ue->fullname, true, array('context'=>$context));
3062 $a->user = fullname($user, true);
3063 $a->timeend = userdate($ue->timeend, '', $user->timezone);
3064 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
3066 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
3067 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
3069 $message = new \core\message\message();
3070 $message->courseid = $ue->courseid;
3071 $message->notification = 1;
3072 $message->component = 'enrol_'.$name;
3073 $message->name = 'expiry_notification';
3074 $message->userfrom = $enroller;
3075 $message->userto = $user;
3076 $message->subject = $subject;
3077 $message->fullmessage = $body;
3078 $message->fullmessageformat = FORMAT_MARKDOWN;
3079 $message->fullmessagehtml = markdown_to_html($body);
3080 $message->smallmessage = $subject;
3081 $message->contexturlname = $a->course;
3082 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
3084 if (message_send($message)) {
3085 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3086 } else {
3087 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
3090 force_current_language($oldforcelang);
3094 * Notify person responsible for enrolments that some user enrolments will be expired soon,
3095 * it is called only if notification of enrollers (aka teachers) is enabled in course.
3097 * This is called repeatedly every day for each course if there are any pending expiration
3098 * in the expiration threshold.
3100 * @param int $eid
3101 * @param array $users
3102 * @param progress_trace $trace
3104 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
3105 global $DB;
3107 $name = $this->get_name();
3109 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
3110 $context = context_course::instance($instance->courseid);
3111 $course = $DB->get_record('course', array('id'=>$instance->courseid));
3113 $enroller = $this->get_enroller($instance->id);
3114 $admin = get_admin();
3116 $oldforcelang = force_current_language($enroller->lang);
3118 foreach($users as $key=>$info) {
3119 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
3122 $a = new stdClass();
3123 $a->course = format_string($course->fullname, true, array('context'=>$context));
3124 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
3125 $a->users = implode("\n", $users);
3126 $a->extendurl = (string)new moodle_url('/user/index.php', array('id'=>$instance->courseid));
3128 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
3129 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
3131 $message = new \core\message\message();
3132 $message->courseid = $course->id;
3133 $message->notification = 1;
3134 $message->component = 'enrol_'.$name;
3135 $message->name = 'expiry_notification';
3136 $message->userfrom = $admin;
3137 $message->userto = $enroller;
3138 $message->subject = $subject;
3139 $message->fullmessage = $body;
3140 $message->fullmessageformat = FORMAT_MARKDOWN;
3141 $message->fullmessagehtml = markdown_to_html($body);
3142 $message->smallmessage = $subject;
3143 $message->contexturlname = $a->course;
3144 $message->contexturl = $a->extendurl;
3146 if (message_send($message)) {
3147 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3148 } else {
3149 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3152 force_current_language($oldforcelang);
3156 * Backup execution step hook to annotate custom fields.
3158 * @param backup_enrolments_execution_step $step
3159 * @param stdClass $enrol
3161 public function backup_annotate_custom_fields(backup_enrolments_execution_step $step, stdClass $enrol) {
3162 // Override as necessary to annotate custom fields in the enrol table.
3166 * Automatic enrol sync executed during restore.
3167 * Useful for automatic sync by course->idnumber or course category.
3168 * @param stdClass $course course record
3170 public function restore_sync_course($course) {
3171 // Override if necessary.
3175 * Restore instance and map settings.
3177 * @param restore_enrolments_structure_step $step
3178 * @param stdClass $data
3179 * @param stdClass $course
3180 * @param int $oldid
3182 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
3183 // Do not call this from overridden methods, restore and set new id there.
3184 $step->set_mapping('enrol', $oldid, 0);
3188 * Restore user enrolment.
3190 * @param restore_enrolments_structure_step $step
3191 * @param stdClass $data
3192 * @param stdClass $instance
3193 * @param int $oldinstancestatus
3194 * @param int $userid
3196 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
3197 // Override as necessary if plugin supports restore of enrolments.
3201 * Restore role assignment.
3203 * @param stdClass $instance
3204 * @param int $roleid
3205 * @param int $userid
3206 * @param int $contextid
3208 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
3209 // No role assignment by default, override if necessary.
3213 * Restore user group membership.
3214 * @param stdClass $instance
3215 * @param int $groupid
3216 * @param int $userid
3218 public function restore_group_member($instance, $groupid, $userid) {
3219 // Implement if you want to restore protected group memberships,
3220 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
3224 * Returns defaults for new instances.
3225 * @since Moodle 3.1
3226 * @return array
3228 public function get_instance_defaults() {
3229 return array();
3233 * Validate a list of parameter names and types.
3234 * @since Moodle 3.1
3236 * @param array $data array of ("fieldname"=>value) of submitted data
3237 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
3238 * @return array of "element_name"=>"error_description" if there are errors,
3239 * or an empty array if everything is OK.
3241 public function validate_param_types($data, $rules) {
3242 $errors = array();
3243 $invalidstr = get_string('invaliddata', 'error');
3244 foreach ($rules as $fieldname => $rule) {
3245 if (is_array($rule)) {
3246 if (!in_array($data[$fieldname], $rule)) {
3247 $errors[$fieldname] = $invalidstr;
3249 } else {
3250 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
3251 $errors[$fieldname] = $invalidstr;
3255 return $errors;