MDL-60425 blog: Remove empty line
[moodle.git] / lib / enrollib.php
blobfa20f6535f4f368e2d292e3c17363ab3fd59a4b3
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 * @param int $limit max number of courses
558 * @param array $courseids the list of course ids to filter by
559 * @param bool $allaccessible Include courses user is not enrolled in, but can access
560 * @param int $offset Offset the result set by this number
561 * @return array
563 function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false, $offset = 0) {
564 global $DB, $USER, $CFG;
566 if ($sort === null) {
567 if (empty($CFG->navsortmycoursessort)) {
568 $sort = 'visible DESC, sortorder ASC';
569 } else {
570 $sort = 'visible DESC, '.$CFG->navsortmycoursessort.' ASC';
574 // Guest account does not have any enrolled courses.
575 if (!$allaccessible && (isguestuser() or !isloggedin())) {
576 return array();
579 $basefields = array('id', 'category', 'sortorder',
580 'shortname', 'fullname', 'idnumber',
581 'startdate', 'visible',
582 'groupmode', 'groupmodeforce', 'cacherev');
584 if (empty($fields)) {
585 $fields = $basefields;
586 } else if (is_string($fields)) {
587 // turn the fields from a string to an array
588 $fields = explode(',', $fields);
589 $fields = array_map('trim', $fields);
590 $fields = array_unique(array_merge($basefields, $fields));
591 } else if (is_array($fields)) {
592 $fields = array_unique(array_merge($basefields, $fields));
593 } else {
594 throw new coding_exception('Invalid $fields parameter in enrol_get_my_courses()');
596 if (in_array('*', $fields)) {
597 $fields = array('*');
600 $orderby = "";
601 $sort = trim($sort);
602 if (!empty($sort)) {
603 $rawsorts = explode(',', $sort);
604 $sorts = array();
605 foreach ($rawsorts as $rawsort) {
606 $rawsort = trim($rawsort);
607 if (strpos($rawsort, 'c.') === 0) {
608 $rawsort = substr($rawsort, 2);
610 $sorts[] = trim($rawsort);
612 $sort = 'c.'.implode(',c.', $sorts);
613 $orderby = "ORDER BY $sort";
616 $wheres = array("c.id <> :siteid");
617 $params = array('siteid'=>SITEID);
619 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
620 // list _only_ this course - anything else is asking for trouble...
621 $wheres[] = "courseid = :loginas";
622 $params['loginas'] = $USER->loginascontext->instanceid;
625 $coursefields = 'c.' .join(',c.', $fields);
626 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
627 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
628 $params['contextlevel'] = CONTEXT_COURSE;
629 $wheres = implode(" AND ", $wheres);
631 if (!empty($courseids)) {
632 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
633 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
634 $params = array_merge($params, $courseidsparams);
637 $courseidsql = "";
638 // Logged-in, non-guest users get their enrolled courses.
639 if (!isguestuser() && isloggedin()) {
640 $courseidsql .= "
641 SELECT DISTINCT e.courseid
642 FROM {enrol} e
643 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
644 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
645 AND (ue.timeend = 0 OR ue.timeend > :now2)";
646 $params['userid'] = $USER->id;
647 $params['active'] = ENROL_USER_ACTIVE;
648 $params['enabled'] = ENROL_INSTANCE_ENABLED;
649 $params['now1'] = round(time(), -2); // Improves db caching.
650 $params['now2'] = $params['now1'];
653 // When including non-enrolled but accessible courses...
654 if ($allaccessible) {
655 if (is_siteadmin()) {
656 // Site admins can access all courses.
657 $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
658 } else {
659 // If we used the enrolment as well, then this will be UNIONed.
660 if ($courseidsql) {
661 $courseidsql .= " UNION ";
664 // Include courses with guest access and no password.
665 $courseidsql .= "
666 SELECT DISTINCT e.courseid
667 FROM {enrol} e
668 WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
669 $params['emptypass'] = '';
670 $params['enabled2'] = ENROL_INSTANCE_ENABLED;
672 // Include courses where the current user is currently using guest access (may include
673 // those which require a password).
674 $courseids = [];
675 $accessdata = get_user_accessdata($USER->id);
676 foreach ($accessdata['ra'] as $contextpath => $roles) {
677 if (array_key_exists($CFG->guestroleid, $roles)) {
678 // Work out the course id from context path.
679 $context = context::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
680 if ($context instanceof context_course) {
681 $courseids[$context->instanceid] = true;
686 // Include courses where the current user has moodle/course:view capability.
687 $courses = get_user_capability_course('moodle/course:view', null, false);
688 if (!$courses) {
689 $courses = [];
691 foreach ($courses as $course) {
692 $courseids[$course->id] = true;
695 // If there are any in either category, list them individually.
696 if ($courseids) {
697 list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
698 array_keys($courseids), SQL_PARAMS_NAMED);
699 $courseidsql .= "
700 UNION
701 SELECT DISTINCT c3.id AS courseid
702 FROM {course} c3
703 WHERE c3.id $allowedsql";
704 $params = array_merge($params, $allowedparams);
709 // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
710 // we have the subselect there.
711 $sql = "SELECT $coursefields $ccselect
712 FROM {course} c
713 JOIN ($courseidsql) en ON (en.courseid = c.id)
714 $ccjoin
715 WHERE $wheres
716 $orderby";
718 $courses = $DB->get_records_sql($sql, $params, $offset, $limit);
720 // preload contexts and check visibility
721 foreach ($courses as $id=>$course) {
722 context_helper::preload_from_record($course);
723 if (!$course->visible) {
724 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
725 unset($courses[$id]);
726 continue;
728 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
729 unset($courses[$id]);
730 continue;
733 $courses[$id] = $course;
736 //wow! Is that really all? :-D
738 return $courses;
742 * Returns course enrolment information icons.
744 * @param object $course
745 * @param array $instances enrol instances of this course, improves performance
746 * @return array of pix_icon
748 function enrol_get_course_info_icons($course, array $instances = NULL) {
749 $icons = array();
750 if (is_null($instances)) {
751 $instances = enrol_get_instances($course->id, true);
753 $plugins = enrol_get_plugins(true);
754 foreach ($plugins as $name => $plugin) {
755 $pis = array();
756 foreach ($instances as $instance) {
757 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
758 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
759 continue;
761 if ($instance->enrol == $name) {
762 $pis[$instance->id] = $instance;
765 if ($pis) {
766 $icons = array_merge($icons, $plugin->get_info_icons($pis));
769 return $icons;
773 * Returns course enrolment detailed information.
775 * @param object $course
776 * @return array of html fragments - can be used to construct lists
778 function enrol_get_course_description_texts($course) {
779 $lines = array();
780 $instances = enrol_get_instances($course->id, true);
781 $plugins = enrol_get_plugins(true);
782 foreach ($instances as $instance) {
783 if (!isset($plugins[$instance->enrol])) {
784 //weird
785 continue;
787 $plugin = $plugins[$instance->enrol];
788 $text = $plugin->get_description_text($instance);
789 if ($text !== NULL) {
790 $lines[] = $text;
793 return $lines;
797 * Returns list of courses user is enrolled into.
799 * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
801 * The $fields param is a list of field names to ADD so name just the fields you really need,
802 * which will be added and uniq'd.
804 * @param int $userid User whose courses are returned, defaults to the current user.
805 * @param bool $onlyactive Return only active enrolments in courses user may see.
806 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
807 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
808 * @return array
810 function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
811 global $DB;
813 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
815 // preload contexts and check visibility
816 if ($onlyactive) {
817 foreach ($courses as $id=>$course) {
818 context_helper::preload_from_record($course);
819 if (!$course->visible) {
820 if (!$context = context_course::instance($id)) {
821 unset($courses[$id]);
822 continue;
824 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
825 unset($courses[$id]);
826 continue;
832 return $courses;
837 * Can user access at least one enrolled course?
839 * Cheat if necessary, but find out as fast as possible!
841 * @param int|stdClass $user null means use current user
842 * @return bool
844 function enrol_user_sees_own_courses($user = null) {
845 global $USER;
847 if ($user === null) {
848 $user = $USER;
850 $userid = is_object($user) ? $user->id : $user;
852 // Guest account does not have any courses
853 if (isguestuser($userid) or empty($userid)) {
854 return false;
857 // Let's cheat here if this is the current user,
858 // if user accessed any course recently, then most probably
859 // we do not need to query the database at all.
860 if ($USER->id == $userid) {
861 if (!empty($USER->enrol['enrolled'])) {
862 foreach ($USER->enrol['enrolled'] as $until) {
863 if ($until > time()) {
864 return true;
870 // Now the slow way.
871 $courses = enrol_get_all_users_courses($userid, true);
872 foreach($courses as $course) {
873 if ($course->visible) {
874 return true;
876 context_helper::preload_from_record($course);
877 $context = context_course::instance($course->id);
878 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
879 return true;
883 return false;
887 * Returns list of courses user is enrolled into without performing any capability checks.
889 * The $fields param is a list of field names to ADD so name just the fields you really need,
890 * which will be added and uniq'd.
892 * @param int $userid User whose courses are returned, defaults to the current user.
893 * @param bool $onlyactive Return only active enrolments in courses user may see.
894 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
895 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
896 * @return array
898 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
899 global $CFG, $DB;
901 if ($sort === null) {
902 if (empty($CFG->navsortmycoursessort)) {
903 $sort = 'visible DESC, sortorder ASC';
904 } else {
905 $sort = 'visible DESC, '.$CFG->navsortmycoursessort.' ASC';
909 // Guest account does not have any courses
910 if (isguestuser($userid) or empty($userid)) {
911 return(array());
914 $basefields = array('id', 'category', 'sortorder',
915 'shortname', 'fullname', 'idnumber',
916 'startdate', 'visible',
917 'defaultgroupingid',
918 'groupmode', 'groupmodeforce');
920 if (empty($fields)) {
921 $fields = $basefields;
922 } else if (is_string($fields)) {
923 // turn the fields from a string to an array
924 $fields = explode(',', $fields);
925 $fields = array_map('trim', $fields);
926 $fields = array_unique(array_merge($basefields, $fields));
927 } else if (is_array($fields)) {
928 $fields = array_unique(array_merge($basefields, $fields));
929 } else {
930 throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
932 if (in_array('*', $fields)) {
933 $fields = array('*');
936 $orderby = "";
937 $sort = trim($sort);
938 if (!empty($sort)) {
939 $rawsorts = explode(',', $sort);
940 $sorts = array();
941 foreach ($rawsorts as $rawsort) {
942 $rawsort = trim($rawsort);
943 if (strpos($rawsort, 'c.') === 0) {
944 $rawsort = substr($rawsort, 2);
946 $sorts[] = trim($rawsort);
948 $sort = 'c.'.implode(',c.', $sorts);
949 $orderby = "ORDER BY $sort";
952 $params = array('siteid'=>SITEID);
954 if ($onlyactive) {
955 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
956 $params['now1'] = round(time(), -2); // improves db caching
957 $params['now2'] = $params['now1'];
958 $params['active'] = ENROL_USER_ACTIVE;
959 $params['enabled'] = ENROL_INSTANCE_ENABLED;
960 } else {
961 $subwhere = "";
964 $coursefields = 'c.' .join(',c.', $fields);
965 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
966 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
967 $params['contextlevel'] = CONTEXT_COURSE;
969 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
970 $sql = "SELECT $coursefields $ccselect
971 FROM {course} c
972 JOIN (SELECT DISTINCT e.courseid
973 FROM {enrol} e
974 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
975 $subwhere
976 ) en ON (en.courseid = c.id)
977 $ccjoin
978 WHERE c.id <> :siteid
979 $orderby";
980 $params['userid'] = $userid;
982 $courses = $DB->get_records_sql($sql, $params);
984 return $courses;
990 * Called when user is about to be deleted.
991 * @param object $user
992 * @return void
994 function enrol_user_delete($user) {
995 global $DB;
997 $plugins = enrol_get_plugins(true);
998 foreach ($plugins as $plugin) {
999 $plugin->user_delete($user);
1002 // force cleanup of all broken enrolments
1003 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
1007 * Called when course is about to be deleted.
1008 * @param stdClass $course
1009 * @return void
1011 function enrol_course_delete($course) {
1012 global $DB;
1014 $instances = enrol_get_instances($course->id, false);
1015 $plugins = enrol_get_plugins(true);
1016 foreach ($instances as $instance) {
1017 if (isset($plugins[$instance->enrol])) {
1018 $plugins[$instance->enrol]->delete_instance($instance);
1020 // low level delete in case plugin did not do it
1021 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1022 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
1023 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1024 $DB->delete_records('enrol', array('id'=>$instance->id));
1029 * Try to enrol user via default internal auth plugin.
1031 * For now this is always using the manual enrol plugin...
1033 * @param $courseid
1034 * @param $userid
1035 * @param $roleid
1036 * @param $timestart
1037 * @param $timeend
1038 * @return bool success
1040 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
1041 global $DB;
1043 //note: this is hardcoded to manual plugin for now
1045 if (!enrol_is_enabled('manual')) {
1046 return false;
1049 if (!$enrol = enrol_get_plugin('manual')) {
1050 return false;
1052 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
1053 return false;
1055 $instance = reset($instances);
1057 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
1059 return true;
1063 * Is there a chance users might self enrol
1064 * @param int $courseid
1065 * @return bool
1067 function enrol_selfenrol_available($courseid) {
1068 $result = false;
1070 $plugins = enrol_get_plugins(true);
1071 $enrolinstances = enrol_get_instances($courseid, true);
1072 foreach($enrolinstances as $instance) {
1073 if (!isset($plugins[$instance->enrol])) {
1074 continue;
1076 if ($instance->enrol === 'guest') {
1077 // blacklist known temporary guest plugins
1078 continue;
1080 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
1081 $result = true;
1082 break;
1086 return $result;
1090 * This function returns the end of current active user enrolment.
1092 * It deals correctly with multiple overlapping user enrolments.
1094 * @param int $courseid
1095 * @param int $userid
1096 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
1098 function enrol_get_enrolment_end($courseid, $userid) {
1099 global $DB;
1101 $sql = "SELECT ue.*
1102 FROM {user_enrolments} ue
1103 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1104 JOIN {user} u ON u.id = ue.userid
1105 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1106 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
1108 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1109 return false;
1112 $changes = array();
1114 foreach ($enrolments as $ue) {
1115 $start = (int)$ue->timestart;
1116 $end = (int)$ue->timeend;
1117 if ($end != 0 and $end < $start) {
1118 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
1119 continue;
1121 if (isset($changes[$start])) {
1122 $changes[$start] = $changes[$start] + 1;
1123 } else {
1124 $changes[$start] = 1;
1126 if ($end === 0) {
1127 // no end
1128 } else if (isset($changes[$end])) {
1129 $changes[$end] = $changes[$end] - 1;
1130 } else {
1131 $changes[$end] = -1;
1135 // let's sort then enrolment starts&ends and go through them chronologically,
1136 // looking for current status and the next future end of enrolment
1137 ksort($changes);
1139 $now = time();
1140 $current = 0;
1141 $present = null;
1143 foreach ($changes as $time => $change) {
1144 if ($time > $now) {
1145 if ($present === null) {
1146 // we have just went past current time
1147 $present = $current;
1148 if ($present < 1) {
1149 // no enrolment active
1150 return false;
1153 if ($present !== null) {
1154 // we are already in the future - look for possible end
1155 if ($current + $change < 1) {
1156 return $time;
1160 $current += $change;
1163 if ($current > 0) {
1164 return 0;
1165 } else {
1166 return false;
1171 * Is current user accessing course via this enrolment method?
1173 * This is intended for operations that are going to affect enrol instances.
1175 * @param stdClass $instance enrol instance
1176 * @return bool
1178 function enrol_accessing_via_instance(stdClass $instance) {
1179 global $DB, $USER;
1181 if (empty($instance->id)) {
1182 return false;
1185 if (is_siteadmin()) {
1186 // Admins may go anywhere.
1187 return false;
1190 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
1194 * Returns true if user is enrolled (is participating) in course
1195 * this is intended for students and teachers.
1197 * Since 2.2 the result for active enrolments and current user are cached.
1199 * @param context $context
1200 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1201 * @param string $withcapability extra capability name
1202 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1203 * @return bool
1205 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1206 global $USER, $DB;
1208 // First find the course context.
1209 $coursecontext = $context->get_course_context();
1211 // Make sure there is a real user specified.
1212 if ($user === null) {
1213 $userid = isset($USER->id) ? $USER->id : 0;
1214 } else {
1215 $userid = is_object($user) ? $user->id : $user;
1218 if (empty($userid)) {
1219 // Not-logged-in!
1220 return false;
1221 } else if (isguestuser($userid)) {
1222 // Guest account can not be enrolled anywhere.
1223 return false;
1226 // Note everybody participates on frontpage, so for other contexts...
1227 if ($coursecontext->instanceid != SITEID) {
1228 // Try cached info first - the enrolled flag is set only when active enrolment present.
1229 if ($USER->id == $userid) {
1230 $coursecontext->reload_if_dirty();
1231 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1232 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1233 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1234 return false;
1236 return true;
1241 if ($onlyactive) {
1242 // Look for active enrolments only.
1243 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1245 if ($until === false) {
1246 return false;
1249 if ($USER->id == $userid) {
1250 if ($until == 0) {
1251 $until = ENROL_MAX_TIMESTAMP;
1253 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1254 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1255 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1256 remove_temp_course_roles($coursecontext);
1260 } else {
1261 // Any enrolment is good for us here, even outdated, disabled or inactive.
1262 $sql = "SELECT 'x'
1263 FROM {user_enrolments} ue
1264 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1265 JOIN {user} u ON u.id = ue.userid
1266 WHERE ue.userid = :userid AND u.deleted = 0";
1267 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid);
1268 if (!$DB->record_exists_sql($sql, $params)) {
1269 return false;
1274 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1275 return false;
1278 return true;
1282 * Returns an array of joins, wheres and params that will limit the group of
1283 * users to only those enrolled and with given capability (if specified).
1285 * Note this join will return duplicate rows for users who have been enrolled
1286 * several times (e.g. as manual enrolment, and as self enrolment). You may
1287 * need to use a SELECT DISTINCT in your query (see get_enrolled_sql for example).
1289 * @param context $context
1290 * @param string $prefix optional, a prefix to the user id column
1291 * @param string|array $capability optional, may include a capability name, or array of names.
1292 * If an array is provided then this is the equivalent of a logical 'OR',
1293 * i.e. the user needs to have one of these capabilities.
1294 * @param int $group optional, 0 indicates no current group and USERSWITHOUTGROUP users without any group; otherwise the group id
1295 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1296 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1297 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1298 * @return \core\dml\sql_join Contains joins, wheres, params
1300 function get_enrolled_with_capabilities_join(context $context, $prefix = '', $capability = '', $group = 0,
1301 $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1302 $uid = $prefix . 'u.id';
1303 $joins = array();
1304 $wheres = array();
1306 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended, $enrolid);
1307 $joins[] = $enrolledjoin->joins;
1308 $wheres[] = $enrolledjoin->wheres;
1309 $params = $enrolledjoin->params;
1311 if (!empty($capability)) {
1312 $capjoin = get_with_capability_join($context, $capability, $uid);
1313 $joins[] = $capjoin->joins;
1314 $wheres[] = $capjoin->wheres;
1315 $params = array_merge($params, $capjoin->params);
1318 if ($group) {
1319 $groupjoin = groups_get_members_join($group, $uid, $context);
1320 $joins[] = $groupjoin->joins;
1321 $params = array_merge($params, $groupjoin->params);
1322 if (!empty($groupjoin->wheres)) {
1323 $wheres[] = $groupjoin->wheres;
1327 $joins = implode("\n", $joins);
1328 $wheres[] = "{$prefix}u.deleted = 0";
1329 $wheres = implode(" AND ", $wheres);
1331 return new \core\dml\sql_join($joins, $wheres, $params);
1335 * Returns array with sql code and parameters returning all ids
1336 * of users enrolled into course.
1338 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1340 * @param context $context
1341 * @param string $withcapability
1342 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1343 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1344 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1345 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1346 * @return array list($sql, $params)
1348 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false,
1349 $enrolid = 0) {
1351 // Use unique prefix just in case somebody makes some SQL magic with the result.
1352 static $i = 0;
1353 $i++;
1354 $prefix = 'eu' . $i . '_';
1356 $capjoin = get_enrolled_with_capabilities_join(
1357 $context, $prefix, $withcapability, $groupid, $onlyactive, $onlysuspended, $enrolid);
1359 $sql = "SELECT DISTINCT {$prefix}u.id
1360 FROM {user} {$prefix}u
1361 $capjoin->joins
1362 WHERE $capjoin->wheres";
1364 return array($sql, $capjoin->params);
1368 * Returns array with sql joins and parameters returning all ids
1369 * of users enrolled into course.
1371 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1373 * @throws coding_exception
1375 * @param context $context
1376 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1377 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1378 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1379 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1380 * @return \core\dml\sql_join Contains joins, wheres, params
1382 function get_enrolled_join(context $context, $useridcolumn, $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1383 // Use unique prefix just in case somebody makes some SQL magic with the result.
1384 static $i = 0;
1385 $i++;
1386 $prefix = 'ej' . $i . '_';
1388 // First find the course context.
1389 $coursecontext = $context->get_course_context();
1391 $isfrontpage = ($coursecontext->instanceid == SITEID);
1393 if ($onlyactive && $onlysuspended) {
1394 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1396 if ($isfrontpage && $onlysuspended) {
1397 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1400 $joins = array();
1401 $wheres = array();
1402 $params = array();
1404 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1406 // Note all users are "enrolled" on the frontpage, but for others...
1407 if (!$isfrontpage) {
1408 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1409 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1411 $enrolconditions = array(
1412 "{$prefix}e.id = {$prefix}ue.enrolid",
1413 "{$prefix}e.courseid = :{$prefix}courseid",
1415 if ($enrolid) {
1416 $enrolconditions[] = "{$prefix}e.id = :{$prefix}enrolid";
1417 $params[$prefix . 'enrolid'] = $enrolid;
1419 $enrolconditionssql = implode(" AND ", $enrolconditions);
1420 $ejoin = "JOIN {enrol} {$prefix}e ON ($enrolconditionssql)";
1422 $params[$prefix.'courseid'] = $coursecontext->instanceid;
1424 if (!$onlysuspended) {
1425 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1426 $joins[] = $ejoin;
1427 if ($onlyactive) {
1428 $wheres[] = "$where1 AND $where2";
1430 } else {
1431 // Suspended only where there is enrolment but ALL are suspended.
1432 // Consider multiple enrols where one is not suspended or plain role_assign.
1433 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1434 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1435 $enrolconditions = array(
1436 "{$prefix}e1.id = {$prefix}ue1.enrolid",
1437 "{$prefix}e1.courseid = :{$prefix}_e1_courseid",
1439 if ($enrolid) {
1440 $enrolconditions[] = "{$prefix}e1.id = :{$prefix}e1_enrolid";
1441 $params[$prefix . 'e1_enrolid'] = $enrolid;
1443 $enrolconditionssql = implode(" AND ", $enrolconditions);
1444 $joins[] = "JOIN {enrol} {$prefix}e1 ON ($enrolconditionssql)";
1445 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
1446 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1449 if ($onlyactive || $onlysuspended) {
1450 $now = round(time(), -2); // Rounding helps caching in DB.
1451 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED,
1452 $prefix . 'active' => ENROL_USER_ACTIVE,
1453 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1457 $joins = implode("\n", $joins);
1458 $wheres = implode(" AND ", $wheres);
1460 return new \core\dml\sql_join($joins, $wheres, $params);
1464 * Returns list of users enrolled into course.
1466 * @param context $context
1467 * @param string $withcapability
1468 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1469 * @param string $userfields requested user record fields
1470 * @param string $orderby
1471 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1472 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1473 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1474 * @return array of user records
1476 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1477 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1478 global $DB;
1480 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1481 $sql = "SELECT $userfields
1482 FROM {user} u
1483 JOIN ($esql) je ON je.id = u.id
1484 WHERE u.deleted = 0";
1486 if ($orderby) {
1487 $sql = "$sql ORDER BY $orderby";
1488 } else {
1489 list($sort, $sortparams) = users_order_by_sql('u');
1490 $sql = "$sql ORDER BY $sort";
1491 $params = array_merge($params, $sortparams);
1494 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1498 * Counts list of users enrolled into course (as per above function)
1500 * @param context $context
1501 * @param string $withcapability
1502 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1503 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1504 * @return array of user records
1506 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1507 global $DB;
1509 $capjoin = get_enrolled_with_capabilities_join(
1510 $context, '', $withcapability, $groupid, $onlyactive);
1512 $sql = "SELECT COUNT(DISTINCT u.id)
1513 FROM {user} u
1514 $capjoin->joins
1515 WHERE $capjoin->wheres AND u.deleted = 0";
1517 return $DB->count_records_sql($sql, $capjoin->params);
1521 * Send welcome email "from" options.
1523 * @return array list of from options
1525 function enrol_send_welcome_email_options() {
1526 return [
1527 ENROL_DO_NOT_SEND_EMAIL => get_string('no'),
1528 ENROL_SEND_EMAIL_FROM_COURSE_CONTACT => get_string('sendfromcoursecontact', 'enrol'),
1529 ENROL_SEND_EMAIL_FROM_KEY_HOLDER => get_string('sendfromkeyholder', 'enrol'),
1530 ENROL_SEND_EMAIL_FROM_NOREPLY => get_string('sendfromnoreply', 'enrol')
1535 * Serve the user enrolment form as a fragment.
1537 * @param array $args List of named arguments for the fragment loader.
1538 * @return string
1540 function enrol_output_fragment_user_enrolment_form($args) {
1541 global $CFG, $DB;
1543 $args = (object) $args;
1544 $context = $args->context;
1545 require_capability('moodle/course:enrolreview', $context);
1547 $ueid = $args->ueid;
1548 $userenrolment = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
1549 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid], '*', MUST_EXIST);
1550 $plugin = enrol_get_plugin($instance->enrol);
1551 $customdata = [
1552 'ue' => $userenrolment,
1553 'modal' => true,
1554 'enrolinstancename' => $plugin->get_instance_name($instance)
1557 // Set the data if applicable.
1558 $data = [];
1559 if (isset($args->formdata)) {
1560 $serialiseddata = json_decode($args->formdata);
1561 parse_str($serialiseddata, $data);
1564 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1565 $mform = new \enrol_user_enrolment_form(null, $customdata, 'post', '', null, true, $data);
1567 if (!empty($data)) {
1568 $mform->set_data($data);
1569 $mform->is_validated();
1572 return $mform->render();
1576 * Returns the course where a user enrolment belong to.
1578 * @param int $ueid user_enrolments id
1579 * @return stdClass
1581 function enrol_get_course_by_user_enrolment_id($ueid) {
1582 global $DB;
1583 $sql = "SELECT c.* FROM {user_enrolments} ue
1584 JOIN {enrol} e ON e.id = ue.enrolid
1585 JOIN {course} c ON c.id = e.courseid
1586 WHERE ue.id = :ueid";
1587 return $DB->get_record_sql($sql, array('ueid' => $ueid));
1591 * Return all users enrolled in a course.
1593 * @param int $courseid Course id or false if using $uefilter (user enrolment ids may belong to different courses)
1594 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1595 * @param array $usersfilter Limit the results obtained to this list of user ids. $uefilter compatibility not guaranteed.
1596 * @param array $uefilter Limit the results obtained to this list of user enrolment ids. $usersfilter compatibility not guaranteed.
1597 * @return stdClass[]
1599 function enrol_get_course_users($courseid = false, $onlyactive = false, $usersfilter = array(), $uefilter = array()) {
1600 global $DB;
1602 if (!$courseid && !$usersfilter && !$uefilter) {
1603 throw new \coding_exception('You should specify at least 1 filter: courseid, users or user enrolments');
1606 $sql = "SELECT ue.id AS ueid, ue.status AS uestatus, ue.enrolid AS ueenrolid, ue.timestart AS uetimestart,
1607 ue.timeend AS uetimeend, ue.modifierid AS uemodifierid, ue.timecreated AS uetimecreated,
1608 ue.timemodified AS uetimemodified,
1609 u.* FROM {user_enrolments} ue
1610 JOIN {enrol} e ON e.id = ue.enrolid
1611 JOIN {user} u ON ue.userid = u.id
1612 WHERE ";
1613 $params = array();
1615 if ($courseid) {
1616 $conditions[] = "e.courseid = :courseid";
1617 $params['courseid'] = $courseid;
1620 if ($onlyactive) {
1621 $conditions[] = "ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND " .
1622 "(ue.timeend = 0 OR ue.timeend > :now2)";
1623 // Improves db caching.
1624 $params['now1'] = round(time(), -2);
1625 $params['now2'] = $params['now1'];
1626 $params['active'] = ENROL_USER_ACTIVE;
1627 $params['enabled'] = ENROL_INSTANCE_ENABLED;
1630 if ($usersfilter) {
1631 list($usersql, $userparams) = $DB->get_in_or_equal($usersfilter, SQL_PARAMS_NAMED);
1632 $conditions[] = "ue.userid $usersql";
1633 $params = $params + $userparams;
1636 if ($uefilter) {
1637 list($uesql, $ueparams) = $DB->get_in_or_equal($uefilter, SQL_PARAMS_NAMED);
1638 $conditions[] = "ue.id $uesql";
1639 $params = $params + $ueparams;
1642 return $DB->get_records_sql($sql . ' ' . implode(' AND ', $conditions), $params);
1646 * Enrolment plugins abstract class.
1648 * All enrol plugins should be based on this class,
1649 * this is also the main source of documentation.
1651 * @copyright 2010 Petr Skoda {@link http://skodak.org}
1652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1654 abstract class enrol_plugin {
1655 protected $config = null;
1658 * Returns name of this enrol plugin
1659 * @return string
1661 public function get_name() {
1662 // second word in class is always enrol name, sorry, no fancy plugin names with _
1663 $words = explode('_', get_class($this));
1664 return $words[1];
1668 * Returns localised name of enrol instance
1670 * @param object $instance (null is accepted too)
1671 * @return string
1673 public function get_instance_name($instance) {
1674 if (empty($instance->name)) {
1675 $enrol = $this->get_name();
1676 return get_string('pluginname', 'enrol_'.$enrol);
1677 } else {
1678 $context = context_course::instance($instance->courseid);
1679 return format_string($instance->name, true, array('context'=>$context));
1684 * Returns optional enrolment information icons.
1686 * This is used in course list for quick overview of enrolment options.
1688 * We are not using single instance parameter because sometimes
1689 * we might want to prevent icon repetition when multiple instances
1690 * of one type exist. One instance may also produce several icons.
1692 * @param array $instances all enrol instances of this type in one course
1693 * @return array of pix_icon
1695 public function get_info_icons(array $instances) {
1696 return array();
1700 * Returns optional enrolment instance description text.
1702 * This is used in detailed course information.
1705 * @param object $instance
1706 * @return string short html text
1708 public function get_description_text($instance) {
1709 return null;
1713 * Makes sure config is loaded and cached.
1714 * @return void
1716 protected function load_config() {
1717 if (!isset($this->config)) {
1718 $name = $this->get_name();
1719 $this->config = get_config("enrol_$name");
1724 * Returns plugin config value
1725 * @param string $name
1726 * @param string $default value if config does not exist yet
1727 * @return string value or default
1729 public function get_config($name, $default = NULL) {
1730 $this->load_config();
1731 return isset($this->config->$name) ? $this->config->$name : $default;
1735 * Sets plugin config value
1736 * @param string $name name of config
1737 * @param string $value string config value, null means delete
1738 * @return string value
1740 public function set_config($name, $value) {
1741 $pluginname = $this->get_name();
1742 $this->load_config();
1743 if ($value === NULL) {
1744 unset($this->config->$name);
1745 } else {
1746 $this->config->$name = $value;
1748 set_config($name, $value, "enrol_$pluginname");
1752 * Does this plugin assign protected roles are can they be manually removed?
1753 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1755 public function roles_protected() {
1756 return true;
1760 * Does this plugin allow manual enrolments?
1762 * @param stdClass $instance course enrol instance
1763 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1765 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1767 public function allow_enrol(stdClass $instance) {
1768 return false;
1772 * Does this plugin allow manual unenrolment of all users?
1773 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1775 * @param stdClass $instance course enrol instance
1776 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1778 public function allow_unenrol(stdClass $instance) {
1779 return false;
1783 * Does this plugin allow manual unenrolment of a specific user?
1784 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1786 * This is useful especially for synchronisation plugins that
1787 * do suspend instead of full unenrolment.
1789 * @param stdClass $instance course enrol instance
1790 * @param stdClass $ue record from user_enrolments table, specifies user
1792 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1794 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1795 return $this->allow_unenrol($instance);
1799 * Does this plugin allow manual changes in user_enrolments table?
1801 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1803 * @param stdClass $instance course enrol instance
1804 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1806 public function allow_manage(stdClass $instance) {
1807 return false;
1811 * Does this plugin support some way to user to self enrol?
1813 * @param stdClass $instance course enrol instance
1815 * @return bool - true means show "Enrol me in this course" link in course UI
1817 public function show_enrolme_link(stdClass $instance) {
1818 return false;
1822 * Attempt to automatically enrol current user in course without any interaction,
1823 * calling code has to make sure the plugin and instance are active.
1825 * This should return either a timestamp in the future or false.
1827 * @param stdClass $instance course enrol instance
1828 * @return bool|int false means not enrolled, integer means timeend
1830 public function try_autoenrol(stdClass $instance) {
1831 global $USER;
1833 return false;
1837 * Attempt to automatically gain temporary guest access to course,
1838 * calling code has to make sure the plugin and instance are active.
1840 * This should return either a timestamp in the future or false.
1842 * @param stdClass $instance course enrol instance
1843 * @return bool|int false means no guest access, integer means timeend
1845 public function try_guestaccess(stdClass $instance) {
1846 global $USER;
1848 return false;
1852 * Enrol user into course via enrol instance.
1854 * @param stdClass $instance
1855 * @param int $userid
1856 * @param int $roleid optional role id
1857 * @param int $timestart 0 means unknown
1858 * @param int $timeend 0 means forever
1859 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1860 * @param bool $recovergrades restore grade history
1861 * @return void
1863 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
1864 global $DB, $USER, $CFG; // CFG necessary!!!
1866 if ($instance->courseid == SITEID) {
1867 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1870 $name = $this->get_name();
1871 $courseid = $instance->courseid;
1873 if ($instance->enrol !== $name) {
1874 throw new coding_exception('invalid enrol instance!');
1876 $context = context_course::instance($instance->courseid, MUST_EXIST);
1877 if (!isset($recovergrades)) {
1878 $recovergrades = $CFG->recovergradesdefault;
1881 $inserted = false;
1882 $updated = false;
1883 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1884 //only update if timestart or timeend or status are different.
1885 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
1886 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
1888 } else {
1889 $ue = new stdClass();
1890 $ue->enrolid = $instance->id;
1891 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
1892 $ue->userid = $userid;
1893 $ue->timestart = $timestart;
1894 $ue->timeend = $timeend;
1895 $ue->modifierid = $USER->id;
1896 $ue->timecreated = time();
1897 $ue->timemodified = $ue->timecreated;
1898 $ue->id = $DB->insert_record('user_enrolments', $ue);
1900 $inserted = true;
1903 if ($inserted) {
1904 // Trigger event.
1905 $event = \core\event\user_enrolment_created::create(
1906 array(
1907 'objectid' => $ue->id,
1908 'courseid' => $courseid,
1909 'context' => $context,
1910 'relateduserid' => $ue->userid,
1911 'other' => array('enrol' => $name)
1914 $event->trigger();
1915 // Check if course contacts cache needs to be cleared.
1916 core_course_category::user_enrolment_changed($courseid, $ue->userid,
1917 $ue->status, $ue->timestart, $ue->timeend);
1920 if ($roleid) {
1921 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
1922 if ($this->roles_protected()) {
1923 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1924 } else {
1925 role_assign($roleid, $userid, $context->id);
1929 // Recover old grades if present.
1930 if ($recovergrades) {
1931 require_once("$CFG->libdir/gradelib.php");
1932 grade_recover_history_grades($userid, $courseid);
1935 // reset current user enrolment caching
1936 if ($userid == $USER->id) {
1937 if (isset($USER->enrol['enrolled'][$courseid])) {
1938 unset($USER->enrol['enrolled'][$courseid]);
1940 if (isset($USER->enrol['tempguest'][$courseid])) {
1941 unset($USER->enrol['tempguest'][$courseid]);
1942 remove_temp_course_roles($context);
1948 * Store user_enrolments changes and trigger event.
1950 * @param stdClass $instance
1951 * @param int $userid
1952 * @param int $status
1953 * @param int $timestart
1954 * @param int $timeend
1955 * @return void
1957 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1958 global $DB, $USER, $CFG;
1960 $name = $this->get_name();
1962 if ($instance->enrol !== $name) {
1963 throw new coding_exception('invalid enrol instance!');
1966 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1967 // weird, user not enrolled
1968 return;
1971 $modified = false;
1972 if (isset($status) and $ue->status != $status) {
1973 $ue->status = $status;
1974 $modified = true;
1976 if (isset($timestart) and $ue->timestart != $timestart) {
1977 $ue->timestart = $timestart;
1978 $modified = true;
1980 if (isset($timeend) and $ue->timeend != $timeend) {
1981 $ue->timeend = $timeend;
1982 $modified = true;
1985 if (!$modified) {
1986 // no change
1987 return;
1990 $ue->modifierid = $USER->id;
1991 $ue->timemodified = time();
1992 $DB->update_record('user_enrolments', $ue);
1994 // User enrolments have changed, so mark user as dirty.
1995 mark_user_dirty($userid);
1997 // Invalidate core_access cache for get_suspended_userids.
1998 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));
2000 // Trigger event.
2001 $event = \core\event\user_enrolment_updated::create(
2002 array(
2003 'objectid' => $ue->id,
2004 'courseid' => $instance->courseid,
2005 'context' => context_course::instance($instance->courseid),
2006 'relateduserid' => $ue->userid,
2007 'other' => array('enrol' => $name)
2010 $event->trigger();
2012 core_course_category::user_enrolment_changed($instance->courseid, $ue->userid,
2013 $ue->status, $ue->timestart, $ue->timeend);
2017 * Unenrol user from course,
2018 * the last unenrolment removes all remaining roles.
2020 * @param stdClass $instance
2021 * @param int $userid
2022 * @return void
2024 public function unenrol_user(stdClass $instance, $userid) {
2025 global $CFG, $USER, $DB;
2026 require_once("$CFG->dirroot/group/lib.php");
2028 $name = $this->get_name();
2029 $courseid = $instance->courseid;
2031 if ($instance->enrol !== $name) {
2032 throw new coding_exception('invalid enrol instance!');
2034 $context = context_course::instance($instance->courseid, MUST_EXIST);
2036 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2037 // weird, user not enrolled
2038 return;
2041 // Remove all users groups linked to this enrolment instance.
2042 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
2043 foreach ($gms as $gm) {
2044 groups_remove_member($gm->groupid, $gm->userid);
2048 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
2049 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
2051 // add extra info and trigger event
2052 $ue->courseid = $courseid;
2053 $ue->enrol = $name;
2055 $sql = "SELECT 'x'
2056 FROM {user_enrolments} ue
2057 JOIN {enrol} e ON (e.id = ue.enrolid)
2058 WHERE ue.userid = :userid AND e.courseid = :courseid";
2059 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
2060 $ue->lastenrol = false;
2062 } else {
2063 // the big cleanup IS necessary!
2064 require_once("$CFG->libdir/gradelib.php");
2066 // remove all remaining roles
2067 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
2069 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
2070 groups_delete_group_members($courseid, $userid);
2072 grade_user_unenrol($courseid, $userid);
2074 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
2076 $ue->lastenrol = true; // means user not enrolled any more
2078 // Trigger event.
2079 $event = \core\event\user_enrolment_deleted::create(
2080 array(
2081 'courseid' => $courseid,
2082 'context' => $context,
2083 'relateduserid' => $ue->userid,
2084 'objectid' => $ue->id,
2085 'other' => array(
2086 'userenrolment' => (array)$ue,
2087 'enrol' => $name
2091 $event->trigger();
2093 // User enrolments have changed, so mark user as dirty.
2094 mark_user_dirty($userid);
2096 // Check if courrse contacts cache needs to be cleared.
2097 core_course_category::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);
2099 // reset current user enrolment caching
2100 if ($userid == $USER->id) {
2101 if (isset($USER->enrol['enrolled'][$courseid])) {
2102 unset($USER->enrol['enrolled'][$courseid]);
2104 if (isset($USER->enrol['tempguest'][$courseid])) {
2105 unset($USER->enrol['tempguest'][$courseid]);
2106 remove_temp_course_roles($context);
2112 * Forces synchronisation of user enrolments.
2114 * This is important especially for external enrol plugins,
2115 * this function is called for all enabled enrol plugins
2116 * right after every user login.
2118 * @param object $user user record
2119 * @return void
2121 public function sync_user_enrolments($user) {
2122 // override if necessary
2126 * This returns false for backwards compatibility, but it is really recommended.
2128 * @since Moodle 3.1
2129 * @return boolean
2131 public function use_standard_editing_ui() {
2132 return false;
2136 * Return whether or not, given the current state, it is possible to add a new instance
2137 * of this enrolment plugin to the course.
2139 * Default implementation is just for backwards compatibility.
2141 * @param int $courseid
2142 * @return boolean
2144 public function can_add_instance($courseid) {
2145 $link = $this->get_newinstance_link($courseid);
2146 return !empty($link);
2150 * Return whether or not, given the current state, it is possible to edit an instance
2151 * of this enrolment plugin in the course. Used by the standard editing UI
2152 * to generate a link to the edit instance form if editing is allowed.
2154 * @param stdClass $instance
2155 * @return boolean
2157 public function can_edit_instance($instance) {
2158 $context = context_course::instance($instance->courseid);
2160 return has_capability('enrol/' . $instance->enrol . ':config', $context);
2164 * Returns link to page which may be used to add new instance of enrolment plugin in course.
2165 * @param int $courseid
2166 * @return moodle_url page url
2168 public function get_newinstance_link($courseid) {
2169 // override for most plugins, check if instance already exists in cases only one instance is supported
2170 return NULL;
2174 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
2176 public function instance_deleteable($instance) {
2177 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
2178 enrol_plugin::can_delete_instance() instead');
2182 * Is it possible to delete enrol instance via standard UI?
2184 * @param stdClass $instance
2185 * @return bool
2187 public function can_delete_instance($instance) {
2188 return false;
2192 * Is it possible to hide/show enrol instance via standard UI?
2194 * @param stdClass $instance
2195 * @return bool
2197 public function can_hide_show_instance($instance) {
2198 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER);
2199 return true;
2203 * Returns link to manual enrol UI if exists.
2204 * Does the access control tests automatically.
2206 * @param object $instance
2207 * @return moodle_url
2209 public function get_manual_enrol_link($instance) {
2210 return NULL;
2214 * Returns list of unenrol links for all enrol instances in course.
2216 * @param int $instance
2217 * @return moodle_url or NULL if self unenrolment not supported
2219 public function get_unenrolself_link($instance) {
2220 global $USER, $CFG, $DB;
2222 $name = $this->get_name();
2223 if ($instance->enrol !== $name) {
2224 throw new coding_exception('invalid enrol instance!');
2227 if ($instance->courseid == SITEID) {
2228 return NULL;
2231 if (!enrol_is_enabled($name)) {
2232 return NULL;
2235 if ($instance->status != ENROL_INSTANCE_ENABLED) {
2236 return NULL;
2239 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2240 return NULL;
2243 $context = context_course::instance($instance->courseid, MUST_EXIST);
2245 if (!has_capability("enrol/$name:unenrolself", $context)) {
2246 return NULL;
2249 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
2250 return NULL;
2253 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
2257 * Adds enrol instance UI to course edit form
2259 * @param object $instance enrol instance or null if does not exist yet
2260 * @param MoodleQuickForm $mform
2261 * @param object $data
2262 * @param object $context context of existing course or parent category if course does not exist
2263 * @return void
2265 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
2266 // override - usually at least enable/disable switch, has to add own form header
2270 * Adds form elements to add/edit instance form.
2272 * @since Moodle 3.1
2273 * @param object $instance enrol instance or null if does not exist yet
2274 * @param MoodleQuickForm $mform
2275 * @param context $context
2276 * @return void
2278 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
2279 // Do nothing by default.
2283 * Perform custom validation of the data used to edit the instance.
2285 * @since Moodle 3.1
2286 * @param array $data array of ("fieldname"=>value) of submitted data
2287 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2288 * @param object $instance The instance data loaded from the DB.
2289 * @param context $context The context of the instance we are editing
2290 * @return array of "element_name"=>"error_description" if there are errors,
2291 * or an empty array if everything is OK.
2293 public function edit_instance_validation($data, $files, $instance, $context) {
2294 // No errors by default.
2295 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER);
2296 return array();
2300 * Validates course edit form data
2302 * @param object $instance enrol instance or null if does not exist yet
2303 * @param array $data
2304 * @param object $context context of existing course or parent category if course does not exist
2305 * @return array errors array
2307 public function course_edit_validation($instance, array $data, $context) {
2308 return array();
2312 * Called after updating/inserting course.
2314 * @param bool $inserted true if course just inserted
2315 * @param object $course
2316 * @param object $data form data
2317 * @return void
2319 public function course_updated($inserted, $course, $data) {
2320 if ($inserted) {
2321 if ($this->get_config('defaultenrol')) {
2322 $this->add_default_instance($course);
2328 * Add new instance of enrol plugin.
2329 * @param object $course
2330 * @param array instance fields
2331 * @return int id of new instance, null if can not be created
2333 public function add_instance($course, array $fields = NULL) {
2334 global $DB;
2336 if ($course->id == SITEID) {
2337 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2340 $instance = new stdClass();
2341 $instance->enrol = $this->get_name();
2342 $instance->status = ENROL_INSTANCE_ENABLED;
2343 $instance->courseid = $course->id;
2344 $instance->enrolstartdate = 0;
2345 $instance->enrolenddate = 0;
2346 $instance->timemodified = time();
2347 $instance->timecreated = $instance->timemodified;
2348 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
2350 $fields = (array)$fields;
2351 unset($fields['enrol']);
2352 unset($fields['courseid']);
2353 unset($fields['sortorder']);
2354 foreach($fields as $field=>$value) {
2355 $instance->$field = $value;
2358 $instance->id = $DB->insert_record('enrol', $instance);
2360 \core\event\enrol_instance_created::create_from_record($instance)->trigger();
2362 return $instance->id;
2366 * Update instance of enrol plugin.
2368 * @since Moodle 3.1
2369 * @param stdClass $instance
2370 * @param stdClass $data modified instance fields
2371 * @return boolean
2373 public function update_instance($instance, $data) {
2374 global $DB;
2375 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2376 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2377 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2378 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2379 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2380 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2382 foreach ($properties as $key) {
2383 if (isset($data->$key)) {
2384 $instance->$key = $data->$key;
2387 $instance->timemodified = time();
2389 $update = $DB->update_record('enrol', $instance);
2390 if ($update) {
2391 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2393 return $update;
2397 * Add new instance of enrol plugin with default settings,
2398 * called when adding new instance manually or when adding new course.
2400 * Not all plugins support this.
2402 * @param object $course
2403 * @return int id of new instance or null if no default supported
2405 public function add_default_instance($course) {
2406 return null;
2410 * Update instance status
2412 * Override when plugin needs to do some action when enabled or disabled.
2414 * @param stdClass $instance
2415 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2416 * @return void
2418 public function update_status($instance, $newstatus) {
2419 global $DB;
2421 $instance->status = $newstatus;
2422 $DB->update_record('enrol', $instance);
2424 $context = context_course::instance($instance->courseid);
2425 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2427 // Invalidate all enrol caches.
2428 $context->mark_dirty();
2432 * Delete course enrol plugin instance, unenrol all users.
2433 * @param object $instance
2434 * @return void
2436 public function delete_instance($instance) {
2437 global $DB;
2439 $name = $this->get_name();
2440 if ($instance->enrol !== $name) {
2441 throw new coding_exception('invalid enrol instance!');
2444 //first unenrol all users
2445 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
2446 foreach ($participants as $participant) {
2447 $this->unenrol_user($instance, $participant->userid);
2449 $participants->close();
2451 // now clean up all remainders that were not removed correctly
2452 if ($gms = $DB->get_records('groups_members', array('itemid' => $instance->id, 'component' => 'enrol_' . $name))) {
2453 foreach ($gms as $gm) {
2454 groups_remove_member($gm->groupid, $gm->userid);
2457 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
2458 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
2460 // finally drop the enrol row
2461 $DB->delete_records('enrol', array('id'=>$instance->id));
2463 $context = context_course::instance($instance->courseid);
2464 \core\event\enrol_instance_deleted::create_from_record($instance)->trigger();
2466 // Invalidate all enrol caches.
2467 $context->mark_dirty();
2471 * Creates course enrol form, checks if form submitted
2472 * and enrols user if necessary. It can also redirect.
2474 * @param stdClass $instance
2475 * @return string html text, usually a form in a text box
2477 public function enrol_page_hook(stdClass $instance) {
2478 return null;
2482 * Checks if user can self enrol.
2484 * @param stdClass $instance enrolment instance
2485 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2486 * used by navigation to improve performance.
2487 * @return bool|string true if successful, else error message or false
2489 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
2490 return false;
2494 * Return information for enrolment instance containing list of parameters required
2495 * for enrolment, name of enrolment plugin etc.
2497 * @param stdClass $instance enrolment instance
2498 * @return array instance info.
2500 public function get_enrol_info(stdClass $instance) {
2501 return null;
2505 * Adds navigation links into course admin block.
2507 * By defaults looks for manage links only.
2509 * @param navigation_node $instancesnode
2510 * @param stdClass $instance
2511 * @return void
2513 public function add_course_navigation($instancesnode, stdClass $instance) {
2514 if ($this->use_standard_editing_ui()) {
2515 $context = context_course::instance($instance->courseid);
2516 $cap = 'enrol/' . $instance->enrol . ':config';
2517 if (has_capability($cap, $context)) {
2518 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2519 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2520 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
2526 * Returns edit icons for the page with list of instances
2527 * @param stdClass $instance
2528 * @return array
2530 public function get_action_icons(stdClass $instance) {
2531 global $OUTPUT;
2533 $icons = array();
2534 if ($this->use_standard_editing_ui()) {
2535 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2536 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2537 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2538 array('class' => 'iconsmall')));
2540 return $icons;
2544 * Reads version.php and determines if it is necessary
2545 * to execute the cron job now.
2546 * @return bool
2548 public function is_cron_required() {
2549 global $CFG;
2551 $name = $this->get_name();
2552 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2553 $plugin = new stdClass();
2554 include($versionfile);
2555 if (empty($plugin->cron)) {
2556 return false;
2558 $lastexecuted = $this->get_config('lastcron', 0);
2559 if ($lastexecuted + $plugin->cron < time()) {
2560 return true;
2561 } else {
2562 return false;
2567 * Called for all enabled enrol plugins that returned true from is_cron_required().
2568 * @return void
2570 public function cron() {
2574 * Called when user is about to be deleted
2575 * @param object $user
2576 * @return void
2578 public function user_delete($user) {
2579 global $DB;
2581 $sql = "SELECT e.*
2582 FROM {enrol} e
2583 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2584 WHERE e.enrol = :name AND ue.userid = :userid";
2585 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
2587 $rs = $DB->get_recordset_sql($sql, $params);
2588 foreach($rs as $instance) {
2589 $this->unenrol_user($instance, $user->id);
2591 $rs->close();
2595 * Returns an enrol_user_button that takes the user to a page where they are able to
2596 * enrol users into the managers course through this plugin.
2598 * Optional: If the plugin supports manual enrolments it can choose to override this
2599 * otherwise it shouldn't
2601 * @param course_enrolment_manager $manager
2602 * @return enrol_user_button|false
2604 public function get_manual_enrol_button(course_enrolment_manager $manager) {
2605 return false;
2609 * Gets an array of the user enrolment actions
2611 * @param course_enrolment_manager $manager
2612 * @param stdClass $ue
2613 * @return array An array of user_enrolment_actions
2615 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
2616 $actions = [];
2617 $context = $manager->get_context();
2618 $instance = $ue->enrolmentinstance;
2619 $params = $manager->get_moodlepage()->url->params();
2620 $params['ue'] = $ue->id;
2622 // Edit enrolment action.
2623 if ($this->allow_manage($instance) && has_capability("enrol/{$instance->enrol}:manage", $context)) {
2624 $title = get_string('editenrolment', 'enrol');
2625 $icon = new pix_icon('t/edit', $title);
2626 $url = new moodle_url('/enrol/editenrolment.php', $params);
2627 $actionparams = [
2628 'class' => 'editenrollink',
2629 'rel' => $ue->id,
2630 'data-action' => ENROL_ACTION_EDIT
2632 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2635 // Unenrol action.
2636 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/{$instance->enrol}:unenrol", $context)) {
2637 $title = get_string('unenrol', 'enrol');
2638 $icon = new pix_icon('t/delete', $title);
2639 $url = new moodle_url('/enrol/unenroluser.php', $params);
2640 $actionparams = [
2641 'class' => 'unenrollink',
2642 'rel' => $ue->id,
2643 'data-action' => ENROL_ACTION_UNENROL
2645 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2647 return $actions;
2651 * Returns true if the plugin has one or more bulk operations that can be performed on
2652 * user enrolments.
2654 * @param course_enrolment_manager $manager
2655 * @return bool
2657 public function has_bulk_operations(course_enrolment_manager $manager) {
2658 return false;
2662 * Return an array of enrol_bulk_enrolment_operation objects that define
2663 * the bulk actions that can be performed on user enrolments by the plugin.
2665 * @param course_enrolment_manager $manager
2666 * @return array
2668 public function get_bulk_operations(course_enrolment_manager $manager) {
2669 return array();
2673 * Do any enrolments need expiration processing.
2675 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2677 * @param progress_trace $trace
2678 * @param int $courseid one course, empty mean all
2679 * @return bool true if any data processed, false if not
2681 public function process_expirations(progress_trace $trace, $courseid = null) {
2682 global $DB;
2684 $name = $this->get_name();
2685 if (!enrol_is_enabled($name)) {
2686 $trace->finished();
2687 return false;
2690 $processed = false;
2691 $params = array();
2692 $coursesql = "";
2693 if ($courseid) {
2694 $coursesql = "AND e.courseid = :courseid";
2697 // Deal with expired accounts.
2698 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
2700 if ($action == ENROL_EXT_REMOVED_UNENROL) {
2701 $instances = array();
2702 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2703 FROM {user_enrolments} ue
2704 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2705 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2706 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2707 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
2709 $rs = $DB->get_recordset_sql($sql, $params);
2710 foreach ($rs as $ue) {
2711 if (!$processed) {
2712 $trace->output("Starting processing of enrol_$name expirations...");
2713 $processed = true;
2715 if (empty($instances[$ue->enrolid])) {
2716 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2718 $instance = $instances[$ue->enrolid];
2719 if (!$this->roles_protected()) {
2720 // Let's just guess what extra roles are supposed to be removed.
2721 if ($instance->roleid) {
2722 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
2725 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2726 $this->unenrol_user($instance, $ue->userid);
2727 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2729 $rs->close();
2730 unset($instances);
2732 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
2733 $instances = array();
2734 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2735 FROM {user_enrolments} ue
2736 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2737 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2738 WHERE ue.timeend > 0 AND ue.timeend < :now
2739 AND ue.status = :useractive $coursesql";
2740 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
2741 $rs = $DB->get_recordset_sql($sql, $params);
2742 foreach ($rs as $ue) {
2743 if (!$processed) {
2744 $trace->output("Starting processing of enrol_$name expirations...");
2745 $processed = true;
2747 if (empty($instances[$ue->enrolid])) {
2748 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2750 $instance = $instances[$ue->enrolid];
2752 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
2753 if (!$this->roles_protected()) {
2754 // Let's just guess what roles should be removed.
2755 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
2756 if ($count == 1) {
2757 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
2759 } else if ($count > 1 and $instance->roleid) {
2760 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
2763 // In any case remove all roles that belong to this instance and user.
2764 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
2765 // Final cleanup of subcontexts if there are no more course roles.
2766 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
2767 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
2771 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
2772 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2774 $rs->close();
2775 unset($instances);
2777 } else {
2778 // ENROL_EXT_REMOVED_KEEP means no changes.
2781 if ($processed) {
2782 $trace->output("...finished processing of enrol_$name expirations");
2783 } else {
2784 $trace->output("No expired enrol_$name enrolments detected");
2786 $trace->finished();
2788 return $processed;
2792 * Send expiry notifications.
2794 * Plugin that wants to have expiry notification MUST implement following:
2795 * - expirynotifyhour plugin setting,
2796 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2797 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2798 * expirymessageenrolledsubject and expirymessageenrolledbody),
2799 * - expiry_notification provider in db/messages.php,
2800 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2801 * - something that calls this method, such as cron.
2803 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2805 public function send_expiry_notifications($trace) {
2806 global $DB, $CFG;
2808 $name = $this->get_name();
2809 if (!enrol_is_enabled($name)) {
2810 $trace->finished();
2811 return;
2814 // Unfortunately this may take a long time, it should not be interrupted,
2815 // otherwise users get duplicate notification.
2817 core_php_time_limit::raise();
2818 raise_memory_limit(MEMORY_HUGE);
2821 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2822 $expirynotifyhour = $this->get_config('expirynotifyhour');
2823 if (is_null($expirynotifyhour)) {
2824 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
2825 $trace->finished();
2826 return;
2829 if (!($trace instanceof progress_trace)) {
2830 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
2831 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
2834 $timenow = time();
2835 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
2837 if ($expirynotifylast > $notifytime) {
2838 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
2839 $trace->finished();
2840 return;
2842 } else if ($timenow < $notifytime) {
2843 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
2844 $trace->finished();
2845 return;
2848 $trace->output('Processing '.$name.' enrolment expiration notifications...');
2850 // Notify users responsible for enrolment once every day.
2851 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2852 FROM {user_enrolments} ue
2853 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2854 JOIN {course} c ON (c.id = e.courseid)
2855 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2856 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2857 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2858 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2860 $rs = $DB->get_recordset_sql($sql, $params);
2862 $lastenrollid = 0;
2863 $users = array();
2865 foreach($rs as $ue) {
2866 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
2867 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2868 $users = array();
2870 $lastenrollid = $ue->enrolid;
2872 $enroller = $this->get_enroller($ue->enrolid);
2873 $context = context_course::instance($ue->courseid);
2875 $user = $DB->get_record('user', array('id'=>$ue->userid));
2877 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
2879 if (!$ue->notifyall) {
2880 continue;
2883 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
2884 // Notify enrolled users only once at the start of the threshold.
2885 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2886 continue;
2889 $this->notify_expiry_enrolled($user, $ue, $trace);
2891 $rs->close();
2893 if ($lastenrollid and $users) {
2894 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2897 $trace->output('...notification processing finished.');
2898 $trace->finished();
2900 $this->set_config('expirynotifylast', $timenow);
2904 * Returns the user who is responsible for enrolments for given instance.
2906 * Override if plugin knows anybody better than admin.
2908 * @param int $instanceid enrolment instance id
2909 * @return stdClass user record
2911 protected function get_enroller($instanceid) {
2912 return get_admin();
2916 * Notify user about incoming expiration of their enrolment,
2917 * it is called only if notification of enrolled users (aka students) is enabled in course.
2919 * This is executed only once for each expiring enrolment right
2920 * at the start of the expiration threshold.
2922 * @param stdClass $user
2923 * @param stdClass $ue
2924 * @param progress_trace $trace
2926 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
2927 global $CFG;
2929 $name = $this->get_name();
2931 $oldforcelang = force_current_language($user->lang);
2933 $enroller = $this->get_enroller($ue->enrolid);
2934 $context = context_course::instance($ue->courseid);
2936 $a = new stdClass();
2937 $a->course = format_string($ue->fullname, true, array('context'=>$context));
2938 $a->user = fullname($user, true);
2939 $a->timeend = userdate($ue->timeend, '', $user->timezone);
2940 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
2942 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
2943 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
2945 $message = new \core\message\message();
2946 $message->courseid = $ue->courseid;
2947 $message->notification = 1;
2948 $message->component = 'enrol_'.$name;
2949 $message->name = 'expiry_notification';
2950 $message->userfrom = $enroller;
2951 $message->userto = $user;
2952 $message->subject = $subject;
2953 $message->fullmessage = $body;
2954 $message->fullmessageformat = FORMAT_MARKDOWN;
2955 $message->fullmessagehtml = markdown_to_html($body);
2956 $message->smallmessage = $subject;
2957 $message->contexturlname = $a->course;
2958 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
2960 if (message_send($message)) {
2961 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2962 } else {
2963 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2966 force_current_language($oldforcelang);
2970 * Notify person responsible for enrolments that some user enrolments will be expired soon,
2971 * it is called only if notification of enrollers (aka teachers) is enabled in course.
2973 * This is called repeatedly every day for each course if there are any pending expiration
2974 * in the expiration threshold.
2976 * @param int $eid
2977 * @param array $users
2978 * @param progress_trace $trace
2980 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
2981 global $DB;
2983 $name = $this->get_name();
2985 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
2986 $context = context_course::instance($instance->courseid);
2987 $course = $DB->get_record('course', array('id'=>$instance->courseid));
2989 $enroller = $this->get_enroller($instance->id);
2990 $admin = get_admin();
2992 $oldforcelang = force_current_language($enroller->lang);
2994 foreach($users as $key=>$info) {
2995 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
2998 $a = new stdClass();
2999 $a->course = format_string($course->fullname, true, array('context'=>$context));
3000 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
3001 $a->users = implode("\n", $users);
3002 $a->extendurl = (string)new moodle_url('/user/index.php', array('id'=>$instance->courseid));
3004 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
3005 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
3007 $message = new \core\message\message();
3008 $message->courseid = $course->id;
3009 $message->notification = 1;
3010 $message->component = 'enrol_'.$name;
3011 $message->name = 'expiry_notification';
3012 $message->userfrom = $admin;
3013 $message->userto = $enroller;
3014 $message->subject = $subject;
3015 $message->fullmessage = $body;
3016 $message->fullmessageformat = FORMAT_MARKDOWN;
3017 $message->fullmessagehtml = markdown_to_html($body);
3018 $message->smallmessage = $subject;
3019 $message->contexturlname = $a->course;
3020 $message->contexturl = $a->extendurl;
3022 if (message_send($message)) {
3023 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3024 } else {
3025 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3028 force_current_language($oldforcelang);
3032 * Backup execution step hook to annotate custom fields.
3034 * @param backup_enrolments_execution_step $step
3035 * @param stdClass $enrol
3037 public function backup_annotate_custom_fields(backup_enrolments_execution_step $step, stdClass $enrol) {
3038 // Override as necessary to annotate custom fields in the enrol table.
3042 * Automatic enrol sync executed during restore.
3043 * Useful for automatic sync by course->idnumber or course category.
3044 * @param stdClass $course course record
3046 public function restore_sync_course($course) {
3047 // Override if necessary.
3051 * Restore instance and map settings.
3053 * @param restore_enrolments_structure_step $step
3054 * @param stdClass $data
3055 * @param stdClass $course
3056 * @param int $oldid
3058 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
3059 // Do not call this from overridden methods, restore and set new id there.
3060 $step->set_mapping('enrol', $oldid, 0);
3064 * Restore user enrolment.
3066 * @param restore_enrolments_structure_step $step
3067 * @param stdClass $data
3068 * @param stdClass $instance
3069 * @param int $oldinstancestatus
3070 * @param int $userid
3072 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
3073 // Override as necessary if plugin supports restore of enrolments.
3077 * Restore role assignment.
3079 * @param stdClass $instance
3080 * @param int $roleid
3081 * @param int $userid
3082 * @param int $contextid
3084 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
3085 // No role assignment by default, override if necessary.
3089 * Restore user group membership.
3090 * @param stdClass $instance
3091 * @param int $groupid
3092 * @param int $userid
3094 public function restore_group_member($instance, $groupid, $userid) {
3095 // Implement if you want to restore protected group memberships,
3096 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
3100 * Returns defaults for new instances.
3101 * @since Moodle 3.1
3102 * @return array
3104 public function get_instance_defaults() {
3105 return array();
3109 * Validate a list of parameter names and types.
3110 * @since Moodle 3.1
3112 * @param array $data array of ("fieldname"=>value) of submitted data
3113 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
3114 * @return array of "element_name"=>"error_description" if there are errors,
3115 * or an empty array if everything is OK.
3117 public function validate_param_types($data, $rules) {
3118 $errors = array();
3119 $invalidstr = get_string('invaliddata', 'error');
3120 foreach ($rules as $fieldname => $rule) {
3121 if (is_array($rule)) {
3122 if (!in_array($data[$fieldname], $rule)) {
3123 $errors[$fieldname] = $invalidstr;
3125 } else {
3126 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
3127 $errors[$fieldname] = $invalidstr;
3131 return $errors;