MDL-51177 core: Ignore built files in stylelint
[moodle.git] / lib / enrollib.php
blob2df4d50d2385f6d6b9df70ba7943cff75328c730
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 * @return array
562 function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false) {
563 global $DB, $USER, $CFG;
565 if ($sort === null) {
566 if (empty($CFG->navsortmycoursessort)) {
567 $sort = 'visible DESC, sortorder ASC';
568 } else {
569 $sort = 'visible DESC, '.$CFG->navsortmycoursessort.' ASC';
573 // Guest account does not have any enrolled courses.
574 if (!$allaccessible && (isguestuser() or !isloggedin())) {
575 return array();
578 $basefields = array('id', 'category', 'sortorder',
579 'shortname', 'fullname', 'idnumber',
580 'startdate', 'visible',
581 'groupmode', 'groupmodeforce', 'cacherev');
583 if (empty($fields)) {
584 $fields = $basefields;
585 } else if (is_string($fields)) {
586 // turn the fields from a string to an array
587 $fields = explode(',', $fields);
588 $fields = array_map('trim', $fields);
589 $fields = array_unique(array_merge($basefields, $fields));
590 } else if (is_array($fields)) {
591 $fields = array_unique(array_merge($basefields, $fields));
592 } else {
593 throw new coding_exception('Invalid $fields parameter in enrol_get_my_courses()');
595 if (in_array('*', $fields)) {
596 $fields = array('*');
599 $orderby = "";
600 $sort = trim($sort);
601 if (!empty($sort)) {
602 $rawsorts = explode(',', $sort);
603 $sorts = array();
604 foreach ($rawsorts as $rawsort) {
605 $rawsort = trim($rawsort);
606 if (strpos($rawsort, 'c.') === 0) {
607 $rawsort = substr($rawsort, 2);
609 $sorts[] = trim($rawsort);
611 $sort = 'c.'.implode(',c.', $sorts);
612 $orderby = "ORDER BY $sort";
615 $wheres = array("c.id <> :siteid");
616 $params = array('siteid'=>SITEID);
618 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
619 // list _only_ this course - anything else is asking for trouble...
620 $wheres[] = "courseid = :loginas";
621 $params['loginas'] = $USER->loginascontext->instanceid;
624 $coursefields = 'c.' .join(',c.', $fields);
625 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
626 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
627 $params['contextlevel'] = CONTEXT_COURSE;
628 $wheres = implode(" AND ", $wheres);
630 if (!empty($courseids)) {
631 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
632 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
633 $params = array_merge($params, $courseidsparams);
636 $courseidsql = "";
637 // Logged-in, non-guest users get their enrolled courses.
638 if (!isguestuser() && isloggedin()) {
639 $courseidsql .= "
640 SELECT DISTINCT e.courseid
641 FROM {enrol} e
642 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
643 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
644 AND (ue.timeend = 0 OR ue.timeend > :now2)";
645 $params['userid'] = $USER->id;
646 $params['active'] = ENROL_USER_ACTIVE;
647 $params['enabled'] = ENROL_INSTANCE_ENABLED;
648 $params['now1'] = round(time(), -2); // Improves db caching.
649 $params['now2'] = $params['now1'];
652 // When including non-enrolled but accessible courses...
653 if ($allaccessible) {
654 if (is_siteadmin()) {
655 // Site admins can access all courses.
656 $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
657 } else {
658 // If we used the enrolment as well, then this will be UNIONed.
659 if ($courseidsql) {
660 $courseidsql .= " UNION ";
663 // Include courses with guest access and no password.
664 $courseidsql .= "
665 SELECT DISTINCT e.courseid
666 FROM {enrol} e
667 WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
668 $params['emptypass'] = '';
669 $params['enabled2'] = ENROL_INSTANCE_ENABLED;
671 // Include courses where the current user is currently using guest access (may include
672 // those which require a password).
673 $courseids = [];
674 $accessdata = get_user_accessdata($USER->id);
675 foreach ($accessdata['ra'] as $contextpath => $roles) {
676 if (array_key_exists($CFG->guestroleid, $roles)) {
677 // Work out the course id from context path.
678 $context = context::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
679 if ($context instanceof context_course) {
680 $courseids[$context->instanceid] = true;
685 // Include courses where the current user has moodle/course:view capability.
686 $courses = get_user_capability_course('moodle/course:view', null, false);
687 if (!$courses) {
688 $courses = [];
690 foreach ($courses as $course) {
691 $courseids[$course->id] = true;
694 // If there are any in either category, list them individually.
695 if ($courseids) {
696 list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
697 array_keys($courseids), SQL_PARAMS_NAMED);
698 $courseidsql .= "
699 UNION
700 SELECT DISTINCT c3.id AS courseid
701 FROM {course} c3
702 WHERE c3.id $allowedsql";
703 $params = array_merge($params, $allowedparams);
708 // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
709 // we have the subselect there.
710 $sql = "SELECT $coursefields $ccselect
711 FROM {course} c
712 JOIN ($courseidsql) en ON (en.courseid = c.id)
713 $ccjoin
714 WHERE $wheres
715 $orderby";
717 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
719 // preload contexts and check visibility
720 foreach ($courses as $id=>$course) {
721 context_helper::preload_from_record($course);
722 if (!$course->visible) {
723 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
724 unset($courses[$id]);
725 continue;
727 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
728 unset($courses[$id]);
729 continue;
732 $courses[$id] = $course;
735 //wow! Is that really all? :-D
737 return $courses;
741 * Returns course enrolment information icons.
743 * @param object $course
744 * @param array $instances enrol instances of this course, improves performance
745 * @return array of pix_icon
747 function enrol_get_course_info_icons($course, array $instances = NULL) {
748 $icons = array();
749 if (is_null($instances)) {
750 $instances = enrol_get_instances($course->id, true);
752 $plugins = enrol_get_plugins(true);
753 foreach ($plugins as $name => $plugin) {
754 $pis = array();
755 foreach ($instances as $instance) {
756 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
757 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
758 continue;
760 if ($instance->enrol == $name) {
761 $pis[$instance->id] = $instance;
764 if ($pis) {
765 $icons = array_merge($icons, $plugin->get_info_icons($pis));
768 return $icons;
772 * Returns course enrolment detailed information.
774 * @param object $course
775 * @return array of html fragments - can be used to construct lists
777 function enrol_get_course_description_texts($course) {
778 $lines = array();
779 $instances = enrol_get_instances($course->id, true);
780 $plugins = enrol_get_plugins(true);
781 foreach ($instances as $instance) {
782 if (!isset($plugins[$instance->enrol])) {
783 //weird
784 continue;
786 $plugin = $plugins[$instance->enrol];
787 $text = $plugin->get_description_text($instance);
788 if ($text !== NULL) {
789 $lines[] = $text;
792 return $lines;
796 * Returns list of courses user is enrolled into.
798 * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
800 * The $fields param is a list of field names to ADD so name just the fields you really need,
801 * which will be added and uniq'd.
803 * @param int $userid User whose courses are returned, defaults to the current user.
804 * @param bool $onlyactive Return only active enrolments in courses user may see.
805 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
806 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
807 * @return array
809 function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
810 global $DB;
812 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
814 // preload contexts and check visibility
815 if ($onlyactive) {
816 foreach ($courses as $id=>$course) {
817 context_helper::preload_from_record($course);
818 if (!$course->visible) {
819 if (!$context = context_course::instance($id)) {
820 unset($courses[$id]);
821 continue;
823 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
824 unset($courses[$id]);
825 continue;
831 return $courses;
836 * Can user access at least one enrolled course?
838 * Cheat if necessary, but find out as fast as possible!
840 * @param int|stdClass $user null means use current user
841 * @return bool
843 function enrol_user_sees_own_courses($user = null) {
844 global $USER;
846 if ($user === null) {
847 $user = $USER;
849 $userid = is_object($user) ? $user->id : $user;
851 // Guest account does not have any courses
852 if (isguestuser($userid) or empty($userid)) {
853 return false;
856 // Let's cheat here if this is the current user,
857 // if user accessed any course recently, then most probably
858 // we do not need to query the database at all.
859 if ($USER->id == $userid) {
860 if (!empty($USER->enrol['enrolled'])) {
861 foreach ($USER->enrol['enrolled'] as $until) {
862 if ($until > time()) {
863 return true;
869 // Now the slow way.
870 $courses = enrol_get_all_users_courses($userid, true);
871 foreach($courses as $course) {
872 if ($course->visible) {
873 return true;
875 context_helper::preload_from_record($course);
876 $context = context_course::instance($course->id);
877 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
878 return true;
882 return false;
886 * Returns list of courses user is enrolled into without performing any capability checks.
888 * The $fields param is a list of field names to ADD so name just the fields you really need,
889 * which will be added and uniq'd.
891 * @param int $userid User whose courses are returned, defaults to the current user.
892 * @param bool $onlyactive Return only active enrolments in courses user may see.
893 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
894 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
895 * @return array
897 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
898 global $CFG, $DB;
900 if ($sort === null) {
901 if (empty($CFG->navsortmycoursessort)) {
902 $sort = 'visible DESC, sortorder ASC';
903 } else {
904 $sort = 'visible DESC, '.$CFG->navsortmycoursessort.' ASC';
908 // Guest account does not have any courses
909 if (isguestuser($userid) or empty($userid)) {
910 return(array());
913 $basefields = array('id', 'category', 'sortorder',
914 'shortname', 'fullname', 'idnumber',
915 'startdate', 'visible',
916 'defaultgroupingid',
917 'groupmode', 'groupmodeforce');
919 if (empty($fields)) {
920 $fields = $basefields;
921 } else if (is_string($fields)) {
922 // turn the fields from a string to an array
923 $fields = explode(',', $fields);
924 $fields = array_map('trim', $fields);
925 $fields = array_unique(array_merge($basefields, $fields));
926 } else if (is_array($fields)) {
927 $fields = array_unique(array_merge($basefields, $fields));
928 } else {
929 throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
931 if (in_array('*', $fields)) {
932 $fields = array('*');
935 $orderby = "";
936 $sort = trim($sort);
937 if (!empty($sort)) {
938 $rawsorts = explode(',', $sort);
939 $sorts = array();
940 foreach ($rawsorts as $rawsort) {
941 $rawsort = trim($rawsort);
942 if (strpos($rawsort, 'c.') === 0) {
943 $rawsort = substr($rawsort, 2);
945 $sorts[] = trim($rawsort);
947 $sort = 'c.'.implode(',c.', $sorts);
948 $orderby = "ORDER BY $sort";
951 $params = array('siteid'=>SITEID);
953 if ($onlyactive) {
954 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
955 $params['now1'] = round(time(), -2); // improves db caching
956 $params['now2'] = $params['now1'];
957 $params['active'] = ENROL_USER_ACTIVE;
958 $params['enabled'] = ENROL_INSTANCE_ENABLED;
959 } else {
960 $subwhere = "";
963 $coursefields = 'c.' .join(',c.', $fields);
964 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
965 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
966 $params['contextlevel'] = CONTEXT_COURSE;
968 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
969 $sql = "SELECT $coursefields $ccselect
970 FROM {course} c
971 JOIN (SELECT DISTINCT e.courseid
972 FROM {enrol} e
973 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
974 $subwhere
975 ) en ON (en.courseid = c.id)
976 $ccjoin
977 WHERE c.id <> :siteid
978 $orderby";
979 $params['userid'] = $userid;
981 $courses = $DB->get_records_sql($sql, $params);
983 return $courses;
989 * Called when user is about to be deleted.
990 * @param object $user
991 * @return void
993 function enrol_user_delete($user) {
994 global $DB;
996 $plugins = enrol_get_plugins(true);
997 foreach ($plugins as $plugin) {
998 $plugin->user_delete($user);
1001 // force cleanup of all broken enrolments
1002 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
1006 * Called when course is about to be deleted.
1007 * @param stdClass $course
1008 * @return void
1010 function enrol_course_delete($course) {
1011 global $DB;
1013 $instances = enrol_get_instances($course->id, false);
1014 $plugins = enrol_get_plugins(true);
1015 foreach ($instances as $instance) {
1016 if (isset($plugins[$instance->enrol])) {
1017 $plugins[$instance->enrol]->delete_instance($instance);
1019 // low level delete in case plugin did not do it
1020 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1021 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
1022 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1023 $DB->delete_records('enrol', array('id'=>$instance->id));
1028 * Try to enrol user via default internal auth plugin.
1030 * For now this is always using the manual enrol plugin...
1032 * @param $courseid
1033 * @param $userid
1034 * @param $roleid
1035 * @param $timestart
1036 * @param $timeend
1037 * @return bool success
1039 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
1040 global $DB;
1042 //note: this is hardcoded to manual plugin for now
1044 if (!enrol_is_enabled('manual')) {
1045 return false;
1048 if (!$enrol = enrol_get_plugin('manual')) {
1049 return false;
1051 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
1052 return false;
1054 $instance = reset($instances);
1056 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
1058 return true;
1062 * Is there a chance users might self enrol
1063 * @param int $courseid
1064 * @return bool
1066 function enrol_selfenrol_available($courseid) {
1067 $result = false;
1069 $plugins = enrol_get_plugins(true);
1070 $enrolinstances = enrol_get_instances($courseid, true);
1071 foreach($enrolinstances as $instance) {
1072 if (!isset($plugins[$instance->enrol])) {
1073 continue;
1075 if ($instance->enrol === 'guest') {
1076 // blacklist known temporary guest plugins
1077 continue;
1079 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
1080 $result = true;
1081 break;
1085 return $result;
1089 * This function returns the end of current active user enrolment.
1091 * It deals correctly with multiple overlapping user enrolments.
1093 * @param int $courseid
1094 * @param int $userid
1095 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
1097 function enrol_get_enrolment_end($courseid, $userid) {
1098 global $DB;
1100 $sql = "SELECT ue.*
1101 FROM {user_enrolments} ue
1102 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1103 JOIN {user} u ON u.id = ue.userid
1104 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1105 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
1107 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1108 return false;
1111 $changes = array();
1113 foreach ($enrolments as $ue) {
1114 $start = (int)$ue->timestart;
1115 $end = (int)$ue->timeend;
1116 if ($end != 0 and $end < $start) {
1117 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
1118 continue;
1120 if (isset($changes[$start])) {
1121 $changes[$start] = $changes[$start] + 1;
1122 } else {
1123 $changes[$start] = 1;
1125 if ($end === 0) {
1126 // no end
1127 } else if (isset($changes[$end])) {
1128 $changes[$end] = $changes[$end] - 1;
1129 } else {
1130 $changes[$end] = -1;
1134 // let's sort then enrolment starts&ends and go through them chronologically,
1135 // looking for current status and the next future end of enrolment
1136 ksort($changes);
1138 $now = time();
1139 $current = 0;
1140 $present = null;
1142 foreach ($changes as $time => $change) {
1143 if ($time > $now) {
1144 if ($present === null) {
1145 // we have just went past current time
1146 $present = $current;
1147 if ($present < 1) {
1148 // no enrolment active
1149 return false;
1152 if ($present !== null) {
1153 // we are already in the future - look for possible end
1154 if ($current + $change < 1) {
1155 return $time;
1159 $current += $change;
1162 if ($current > 0) {
1163 return 0;
1164 } else {
1165 return false;
1170 * Is current user accessing course via this enrolment method?
1172 * This is intended for operations that are going to affect enrol instances.
1174 * @param stdClass $instance enrol instance
1175 * @return bool
1177 function enrol_accessing_via_instance(stdClass $instance) {
1178 global $DB, $USER;
1180 if (empty($instance->id)) {
1181 return false;
1184 if (is_siteadmin()) {
1185 // Admins may go anywhere.
1186 return false;
1189 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
1193 * Returns true if user is enrolled (is participating) in course
1194 * this is intended for students and teachers.
1196 * Since 2.2 the result for active enrolments and current user are cached.
1198 * @param context $context
1199 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1200 * @param string $withcapability extra capability name
1201 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1202 * @return bool
1204 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1205 global $USER, $DB;
1207 // First find the course context.
1208 $coursecontext = $context->get_course_context();
1210 // Make sure there is a real user specified.
1211 if ($user === null) {
1212 $userid = isset($USER->id) ? $USER->id : 0;
1213 } else {
1214 $userid = is_object($user) ? $user->id : $user;
1217 if (empty($userid)) {
1218 // Not-logged-in!
1219 return false;
1220 } else if (isguestuser($userid)) {
1221 // Guest account can not be enrolled anywhere.
1222 return false;
1225 // Note everybody participates on frontpage, so for other contexts...
1226 if ($coursecontext->instanceid != SITEID) {
1227 // Try cached info first - the enrolled flag is set only when active enrolment present.
1228 if ($USER->id == $userid) {
1229 $coursecontext->reload_if_dirty();
1230 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1231 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1232 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1233 return false;
1235 return true;
1240 if ($onlyactive) {
1241 // Look for active enrolments only.
1242 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1244 if ($until === false) {
1245 return false;
1248 if ($USER->id == $userid) {
1249 if ($until == 0) {
1250 $until = ENROL_MAX_TIMESTAMP;
1252 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1253 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1254 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1255 remove_temp_course_roles($coursecontext);
1259 } else {
1260 // Any enrolment is good for us here, even outdated, disabled or inactive.
1261 $sql = "SELECT 'x'
1262 FROM {user_enrolments} ue
1263 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1264 JOIN {user} u ON u.id = ue.userid
1265 WHERE ue.userid = :userid AND u.deleted = 0";
1266 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid);
1267 if (!$DB->record_exists_sql($sql, $params)) {
1268 return false;
1273 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1274 return false;
1277 return true;
1281 * Returns an array of joins, wheres and params that will limit the group of
1282 * users to only those enrolled and with given capability (if specified).
1284 * Note this join will return duplicate rows for users who have been enrolled
1285 * several times (e.g. as manual enrolment, and as self enrolment). You may
1286 * need to use a SELECT DISTINCT in your query (see get_enrolled_sql for example).
1288 * @param context $context
1289 * @param string $prefix optional, a prefix to the user id column
1290 * @param string|array $capability optional, may include a capability name, or array of names.
1291 * If an array is provided then this is the equivalent of a logical 'OR',
1292 * i.e. the user needs to have one of these capabilities.
1293 * @param int $group optional, 0 indicates no current group, otherwise the group id
1294 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1295 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1296 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1297 * @return \core\dml\sql_join Contains joins, wheres, params
1299 function get_enrolled_with_capabilities_join(context $context, $prefix = '', $capability = '', $group = 0,
1300 $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1301 $uid = $prefix . 'u.id';
1302 $joins = array();
1303 $wheres = array();
1305 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended, $enrolid);
1306 $joins[] = $enrolledjoin->joins;
1307 $wheres[] = $enrolledjoin->wheres;
1308 $params = $enrolledjoin->params;
1310 if (!empty($capability)) {
1311 $capjoin = get_with_capability_join($context, $capability, $uid);
1312 $joins[] = $capjoin->joins;
1313 $wheres[] = $capjoin->wheres;
1314 $params = array_merge($params, $capjoin->params);
1317 if ($group) {
1318 $groupjoin = groups_get_members_join($group, $uid);
1319 $joins[] = $groupjoin->joins;
1320 $params = array_merge($params, $groupjoin->params);
1323 $joins = implode("\n", $joins);
1324 $wheres[] = "{$prefix}u.deleted = 0";
1325 $wheres = implode(" AND ", $wheres);
1327 return new \core\dml\sql_join($joins, $wheres, $params);
1331 * Returns array with sql code and parameters returning all ids
1332 * of users enrolled into course.
1334 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1336 * @param context $context
1337 * @param string $withcapability
1338 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1339 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1340 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1341 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1342 * @return array list($sql, $params)
1344 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false,
1345 $enrolid = 0) {
1347 // Use unique prefix just in case somebody makes some SQL magic with the result.
1348 static $i = 0;
1349 $i++;
1350 $prefix = 'eu' . $i . '_';
1352 $capjoin = get_enrolled_with_capabilities_join(
1353 $context, $prefix, $withcapability, $groupid, $onlyactive, $onlysuspended, $enrolid);
1355 $sql = "SELECT DISTINCT {$prefix}u.id
1356 FROM {user} {$prefix}u
1357 $capjoin->joins
1358 WHERE $capjoin->wheres";
1360 return array($sql, $capjoin->params);
1364 * Returns array with sql joins and parameters returning all ids
1365 * of users enrolled into course.
1367 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1369 * @throws coding_exception
1371 * @param context $context
1372 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1373 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1374 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1375 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1376 * @return \core\dml\sql_join Contains joins, wheres, params
1378 function get_enrolled_join(context $context, $useridcolumn, $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1379 // Use unique prefix just in case somebody makes some SQL magic with the result.
1380 static $i = 0;
1381 $i++;
1382 $prefix = 'ej' . $i . '_';
1384 // First find the course context.
1385 $coursecontext = $context->get_course_context();
1387 $isfrontpage = ($coursecontext->instanceid == SITEID);
1389 if ($onlyactive && $onlysuspended) {
1390 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1392 if ($isfrontpage && $onlysuspended) {
1393 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1396 $joins = array();
1397 $wheres = array();
1398 $params = array();
1400 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1402 // Note all users are "enrolled" on the frontpage, but for others...
1403 if (!$isfrontpage) {
1404 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1405 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1407 $enrolconditions = array(
1408 "{$prefix}e.id = {$prefix}ue.enrolid",
1409 "{$prefix}e.courseid = :{$prefix}courseid",
1411 if ($enrolid) {
1412 $enrolconditions[] = "{$prefix}e.id = :{$prefix}enrolid";
1413 $params[$prefix . 'enrolid'] = $enrolid;
1415 $enrolconditionssql = implode(" AND ", $enrolconditions);
1416 $ejoin = "JOIN {enrol} {$prefix}e ON ($enrolconditionssql)";
1418 $params[$prefix.'courseid'] = $coursecontext->instanceid;
1420 if (!$onlysuspended) {
1421 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1422 $joins[] = $ejoin;
1423 if ($onlyactive) {
1424 $wheres[] = "$where1 AND $where2";
1426 } else {
1427 // Suspended only where there is enrolment but ALL are suspended.
1428 // Consider multiple enrols where one is not suspended or plain role_assign.
1429 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1430 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1431 $enrolconditions = array(
1432 "{$prefix}e1.id = {$prefix}ue1.enrolid",
1433 "{$prefix}e1.courseid = :{$prefix}_e1_courseid",
1435 if ($enrolid) {
1436 $enrolconditions[] = "{$prefix}e1.id = :{$prefix}e1_enrolid";
1437 $params[$prefix . 'e1_enrolid'] = $enrolid;
1439 $enrolconditionssql = implode(" AND ", $enrolconditions);
1440 $joins[] = "JOIN {enrol} {$prefix}e1 ON ($enrolconditionssql)";
1441 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
1442 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1445 if ($onlyactive || $onlysuspended) {
1446 $now = round(time(), -2); // Rounding helps caching in DB.
1447 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED,
1448 $prefix . 'active' => ENROL_USER_ACTIVE,
1449 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1453 $joins = implode("\n", $joins);
1454 $wheres = implode(" AND ", $wheres);
1456 return new \core\dml\sql_join($joins, $wheres, $params);
1460 * Returns list of users enrolled into course.
1462 * @param context $context
1463 * @param string $withcapability
1464 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1465 * @param string $userfields requested user record fields
1466 * @param string $orderby
1467 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1468 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1469 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1470 * @return array of user records
1472 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1473 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1474 global $DB;
1476 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1477 $sql = "SELECT $userfields
1478 FROM {user} u
1479 JOIN ($esql) je ON je.id = u.id
1480 WHERE u.deleted = 0";
1482 if ($orderby) {
1483 $sql = "$sql ORDER BY $orderby";
1484 } else {
1485 list($sort, $sortparams) = users_order_by_sql('u');
1486 $sql = "$sql ORDER BY $sort";
1487 $params = array_merge($params, $sortparams);
1490 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1494 * Counts list of users enrolled into course (as per above function)
1496 * @param context $context
1497 * @param string $withcapability
1498 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1499 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1500 * @return array of user records
1502 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1503 global $DB;
1505 $capjoin = get_enrolled_with_capabilities_join(
1506 $context, '', $withcapability, $groupid, $onlyactive);
1508 $sql = "SELECT count(u.id)
1509 FROM {user} u
1510 $capjoin->joins
1511 WHERE $capjoin->wheres AND u.deleted = 0";
1513 return $DB->count_records_sql($sql, $capjoin->params);
1517 * Send welcome email "from" options.
1519 * @return array list of from options
1521 function enrol_send_welcome_email_options() {
1522 return [
1523 ENROL_DO_NOT_SEND_EMAIL => get_string('no'),
1524 ENROL_SEND_EMAIL_FROM_COURSE_CONTACT => get_string('sendfromcoursecontact', 'enrol'),
1525 ENROL_SEND_EMAIL_FROM_KEY_HOLDER => get_string('sendfromkeyholder', 'enrol'),
1526 ENROL_SEND_EMAIL_FROM_NOREPLY => get_string('sendfromnoreply', 'enrol')
1531 * Serve the user enrolment form as a fragment.
1533 * @param array $args List of named arguments for the fragment loader.
1534 * @return string
1536 function enrol_output_fragment_user_enrolment_form($args) {
1537 global $CFG, $DB;
1539 $args = (object) $args;
1540 $context = $args->context;
1541 require_capability('moodle/course:enrolreview', $context);
1543 $ueid = $args->ueid;
1544 $userenrolment = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST);
1545 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid], '*', MUST_EXIST);
1546 $plugin = enrol_get_plugin($instance->enrol);
1547 $customdata = [
1548 'ue' => $userenrolment,
1549 'modal' => true,
1550 'enrolinstancename' => $plugin->get_instance_name($instance)
1553 // Set the data if applicable.
1554 $data = [];
1555 if (isset($args->formdata)) {
1556 $serialiseddata = json_decode($args->formdata);
1557 parse_str($serialiseddata, $data);
1560 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1561 $mform = new \enrol_user_enrolment_form(null, $customdata, 'post', '', null, true, $data);
1563 if (!empty($data)) {
1564 $mform->set_data($data);
1565 $mform->is_validated();
1568 return $mform->render();
1572 * Returns the course where a user enrolment belong to.
1574 * @param int $ueid user_enrolments id
1575 * @return stdClass
1577 function enrol_get_course_by_user_enrolment_id($ueid) {
1578 global $DB;
1579 $sql = "SELECT c.* FROM {user_enrolments} ue
1580 JOIN {enrol} e ON e.id = ue.enrolid
1581 JOIN {course} c ON c.id = e.courseid
1582 WHERE ue.id = :ueid";
1583 return $DB->get_record_sql($sql, array('ueid' => $ueid));
1587 * Return all users enrolled in a course.
1589 * @param int $courseid Course id or false if using $uefilter (user enrolment ids may belong to different courses)
1590 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1591 * @param array $usersfilter Limit the results obtained to this list of user ids. $uefilter compatibility not guaranteed.
1592 * @param array $uefilter Limit the results obtained to this list of user enrolment ids. $usersfilter compatibility not guaranteed.
1593 * @return stdClass[]
1595 function enrol_get_course_users($courseid = false, $onlyactive = false, $usersfilter = array(), $uefilter = array()) {
1596 global $DB;
1598 if (!$courseid && !$usersfilter && !$uefilter) {
1599 throw new \coding_exception('You should specify at least 1 filter: courseid, users or user enrolments');
1602 $sql = "SELECT ue.id AS ueid, ue.status AS uestatus, ue.enrolid AS ueenrolid, ue.timestart AS uetimestart,
1603 ue.timeend AS uetimeend, ue.modifierid AS uemodifierid, ue.timecreated AS uetimecreated,
1604 ue.timemodified AS uetimemodified,
1605 u.* FROM {user_enrolments} ue
1606 JOIN {enrol} e ON e.id = ue.enrolid
1607 JOIN {user} u ON ue.userid = u.id
1608 WHERE ";
1609 $params = array();
1611 if ($courseid) {
1612 $conditions[] = "e.courseid = :courseid";
1613 $params['courseid'] = $courseid;
1616 if ($onlyactive) {
1617 $conditions[] = "ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND " .
1618 "(ue.timeend = 0 OR ue.timeend > :now2)";
1619 // Improves db caching.
1620 $params['now1'] = round(time(), -2);
1621 $params['now2'] = $params['now1'];
1622 $params['active'] = ENROL_USER_ACTIVE;
1623 $params['enabled'] = ENROL_INSTANCE_ENABLED;
1626 if ($usersfilter) {
1627 list($usersql, $userparams) = $DB->get_in_or_equal($usersfilter, SQL_PARAMS_NAMED);
1628 $conditions[] = "ue.userid $usersql";
1629 $params = $params + $userparams;
1632 if ($uefilter) {
1633 list($uesql, $ueparams) = $DB->get_in_or_equal($uefilter, SQL_PARAMS_NAMED);
1634 $conditions[] = "ue.id $uesql";
1635 $params = $params + $ueparams;
1638 return $DB->get_records_sql($sql . ' ' . implode(' AND ', $conditions), $params);
1642 * Enrolment plugins abstract class.
1644 * All enrol plugins should be based on this class,
1645 * this is also the main source of documentation.
1647 * @copyright 2010 Petr Skoda {@link http://skodak.org}
1648 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1650 abstract class enrol_plugin {
1651 protected $config = null;
1654 * Returns name of this enrol plugin
1655 * @return string
1657 public function get_name() {
1658 // second word in class is always enrol name, sorry, no fancy plugin names with _
1659 $words = explode('_', get_class($this));
1660 return $words[1];
1664 * Returns localised name of enrol instance
1666 * @param object $instance (null is accepted too)
1667 * @return string
1669 public function get_instance_name($instance) {
1670 if (empty($instance->name)) {
1671 $enrol = $this->get_name();
1672 return get_string('pluginname', 'enrol_'.$enrol);
1673 } else {
1674 $context = context_course::instance($instance->courseid);
1675 return format_string($instance->name, true, array('context'=>$context));
1680 * Returns optional enrolment information icons.
1682 * This is used in course list for quick overview of enrolment options.
1684 * We are not using single instance parameter because sometimes
1685 * we might want to prevent icon repetition when multiple instances
1686 * of one type exist. One instance may also produce several icons.
1688 * @param array $instances all enrol instances of this type in one course
1689 * @return array of pix_icon
1691 public function get_info_icons(array $instances) {
1692 return array();
1696 * Returns optional enrolment instance description text.
1698 * This is used in detailed course information.
1701 * @param object $instance
1702 * @return string short html text
1704 public function get_description_text($instance) {
1705 return null;
1709 * Makes sure config is loaded and cached.
1710 * @return void
1712 protected function load_config() {
1713 if (!isset($this->config)) {
1714 $name = $this->get_name();
1715 $this->config = get_config("enrol_$name");
1720 * Returns plugin config value
1721 * @param string $name
1722 * @param string $default value if config does not exist yet
1723 * @return string value or default
1725 public function get_config($name, $default = NULL) {
1726 $this->load_config();
1727 return isset($this->config->$name) ? $this->config->$name : $default;
1731 * Sets plugin config value
1732 * @param string $name name of config
1733 * @param string $value string config value, null means delete
1734 * @return string value
1736 public function set_config($name, $value) {
1737 $pluginname = $this->get_name();
1738 $this->load_config();
1739 if ($value === NULL) {
1740 unset($this->config->$name);
1741 } else {
1742 $this->config->$name = $value;
1744 set_config($name, $value, "enrol_$pluginname");
1748 * Does this plugin assign protected roles are can they be manually removed?
1749 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1751 public function roles_protected() {
1752 return true;
1756 * Does this plugin allow manual enrolments?
1758 * @param stdClass $instance course enrol instance
1759 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1761 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1763 public function allow_enrol(stdClass $instance) {
1764 return false;
1768 * Does this plugin allow manual unenrolment of all users?
1769 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1771 * @param stdClass $instance course enrol instance
1772 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1774 public function allow_unenrol(stdClass $instance) {
1775 return false;
1779 * Does this plugin allow manual unenrolment of a specific user?
1780 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1782 * This is useful especially for synchronisation plugins that
1783 * do suspend instead of full unenrolment.
1785 * @param stdClass $instance course enrol instance
1786 * @param stdClass $ue record from user_enrolments table, specifies user
1788 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1790 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1791 return $this->allow_unenrol($instance);
1795 * Does this plugin allow manual changes in user_enrolments table?
1797 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1799 * @param stdClass $instance course enrol instance
1800 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1802 public function allow_manage(stdClass $instance) {
1803 return false;
1807 * Does this plugin support some way to user to self enrol?
1809 * @param stdClass $instance course enrol instance
1811 * @return bool - true means show "Enrol me in this course" link in course UI
1813 public function show_enrolme_link(stdClass $instance) {
1814 return false;
1818 * Attempt to automatically enrol current user in course without any interaction,
1819 * calling code has to make sure the plugin and instance are active.
1821 * This should return either a timestamp in the future or false.
1823 * @param stdClass $instance course enrol instance
1824 * @return bool|int false means not enrolled, integer means timeend
1826 public function try_autoenrol(stdClass $instance) {
1827 global $USER;
1829 return false;
1833 * Attempt to automatically gain temporary guest access to course,
1834 * calling code has to make sure the plugin and instance are active.
1836 * This should return either a timestamp in the future or false.
1838 * @param stdClass $instance course enrol instance
1839 * @return bool|int false means no guest access, integer means timeend
1841 public function try_guestaccess(stdClass $instance) {
1842 global $USER;
1844 return false;
1848 * Enrol user into course via enrol instance.
1850 * @param stdClass $instance
1851 * @param int $userid
1852 * @param int $roleid optional role id
1853 * @param int $timestart 0 means unknown
1854 * @param int $timeend 0 means forever
1855 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1856 * @param bool $recovergrades restore grade history
1857 * @return void
1859 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
1860 global $DB, $USER, $CFG; // CFG necessary!!!
1862 if ($instance->courseid == SITEID) {
1863 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1866 $name = $this->get_name();
1867 $courseid = $instance->courseid;
1869 if ($instance->enrol !== $name) {
1870 throw new coding_exception('invalid enrol instance!');
1872 $context = context_course::instance($instance->courseid, MUST_EXIST);
1873 if (!isset($recovergrades)) {
1874 $recovergrades = $CFG->recovergradesdefault;
1877 $inserted = false;
1878 $updated = false;
1879 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1880 //only update if timestart or timeend or status are different.
1881 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
1882 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
1884 } else {
1885 $ue = new stdClass();
1886 $ue->enrolid = $instance->id;
1887 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
1888 $ue->userid = $userid;
1889 $ue->timestart = $timestart;
1890 $ue->timeend = $timeend;
1891 $ue->modifierid = $USER->id;
1892 $ue->timecreated = time();
1893 $ue->timemodified = $ue->timecreated;
1894 $ue->id = $DB->insert_record('user_enrolments', $ue);
1896 $inserted = true;
1899 if ($inserted) {
1900 // Trigger event.
1901 $event = \core\event\user_enrolment_created::create(
1902 array(
1903 'objectid' => $ue->id,
1904 'courseid' => $courseid,
1905 'context' => $context,
1906 'relateduserid' => $ue->userid,
1907 'other' => array('enrol' => $name)
1910 $event->trigger();
1911 // Check if course contacts cache needs to be cleared.
1912 core_course_category::user_enrolment_changed($courseid, $ue->userid,
1913 $ue->status, $ue->timestart, $ue->timeend);
1916 if ($roleid) {
1917 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
1918 if ($this->roles_protected()) {
1919 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1920 } else {
1921 role_assign($roleid, $userid, $context->id);
1925 // Recover old grades if present.
1926 if ($recovergrades) {
1927 require_once("$CFG->libdir/gradelib.php");
1928 grade_recover_history_grades($userid, $courseid);
1931 // reset current user enrolment caching
1932 if ($userid == $USER->id) {
1933 if (isset($USER->enrol['enrolled'][$courseid])) {
1934 unset($USER->enrol['enrolled'][$courseid]);
1936 if (isset($USER->enrol['tempguest'][$courseid])) {
1937 unset($USER->enrol['tempguest'][$courseid]);
1938 remove_temp_course_roles($context);
1944 * Store user_enrolments changes and trigger event.
1946 * @param stdClass $instance
1947 * @param int $userid
1948 * @param int $status
1949 * @param int $timestart
1950 * @param int $timeend
1951 * @return void
1953 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1954 global $DB, $USER, $CFG;
1956 $name = $this->get_name();
1958 if ($instance->enrol !== $name) {
1959 throw new coding_exception('invalid enrol instance!');
1962 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1963 // weird, user not enrolled
1964 return;
1967 $modified = false;
1968 if (isset($status) and $ue->status != $status) {
1969 $ue->status = $status;
1970 $modified = true;
1972 if (isset($timestart) and $ue->timestart != $timestart) {
1973 $ue->timestart = $timestart;
1974 $modified = true;
1976 if (isset($timeend) and $ue->timeend != $timeend) {
1977 $ue->timeend = $timeend;
1978 $modified = true;
1981 if (!$modified) {
1982 // no change
1983 return;
1986 $ue->modifierid = $USER->id;
1987 $ue->timemodified = time();
1988 $DB->update_record('user_enrolments', $ue);
1989 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches
1991 // Invalidate core_access cache for get_suspended_userids.
1992 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));
1994 // Trigger event.
1995 $event = \core\event\user_enrolment_updated::create(
1996 array(
1997 'objectid' => $ue->id,
1998 'courseid' => $instance->courseid,
1999 'context' => context_course::instance($instance->courseid),
2000 'relateduserid' => $ue->userid,
2001 'other' => array('enrol' => $name)
2004 $event->trigger();
2006 core_course_category::user_enrolment_changed($instance->courseid, $ue->userid,
2007 $ue->status, $ue->timestart, $ue->timeend);
2011 * Unenrol user from course,
2012 * the last unenrolment removes all remaining roles.
2014 * @param stdClass $instance
2015 * @param int $userid
2016 * @return void
2018 public function unenrol_user(stdClass $instance, $userid) {
2019 global $CFG, $USER, $DB;
2020 require_once("$CFG->dirroot/group/lib.php");
2022 $name = $this->get_name();
2023 $courseid = $instance->courseid;
2025 if ($instance->enrol !== $name) {
2026 throw new coding_exception('invalid enrol instance!');
2028 $context = context_course::instance($instance->courseid, MUST_EXIST);
2030 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
2031 // weird, user not enrolled
2032 return;
2035 // Remove all users groups linked to this enrolment instance.
2036 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
2037 foreach ($gms as $gm) {
2038 groups_remove_member($gm->groupid, $gm->userid);
2042 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
2043 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
2045 // add extra info and trigger event
2046 $ue->courseid = $courseid;
2047 $ue->enrol = $name;
2049 $sql = "SELECT 'x'
2050 FROM {user_enrolments} ue
2051 JOIN {enrol} e ON (e.id = ue.enrolid)
2052 WHERE ue.userid = :userid AND e.courseid = :courseid";
2053 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
2054 $ue->lastenrol = false;
2056 } else {
2057 // the big cleanup IS necessary!
2058 require_once("$CFG->libdir/gradelib.php");
2060 // remove all remaining roles
2061 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
2063 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
2064 groups_delete_group_members($courseid, $userid);
2066 grade_user_unenrol($courseid, $userid);
2068 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
2070 $ue->lastenrol = true; // means user not enrolled any more
2072 // Trigger event.
2073 $event = \core\event\user_enrolment_deleted::create(
2074 array(
2075 'courseid' => $courseid,
2076 'context' => $context,
2077 'relateduserid' => $ue->userid,
2078 'objectid' => $ue->id,
2079 'other' => array(
2080 'userenrolment' => (array)$ue,
2081 'enrol' => $name
2085 $event->trigger();
2086 // reset all enrol caches
2087 $context->mark_dirty();
2089 // Check if courrse contacts cache needs to be cleared.
2090 core_course_category::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);
2092 // reset current user enrolment caching
2093 if ($userid == $USER->id) {
2094 if (isset($USER->enrol['enrolled'][$courseid])) {
2095 unset($USER->enrol['enrolled'][$courseid]);
2097 if (isset($USER->enrol['tempguest'][$courseid])) {
2098 unset($USER->enrol['tempguest'][$courseid]);
2099 remove_temp_course_roles($context);
2105 * Forces synchronisation of user enrolments.
2107 * This is important especially for external enrol plugins,
2108 * this function is called for all enabled enrol plugins
2109 * right after every user login.
2111 * @param object $user user record
2112 * @return void
2114 public function sync_user_enrolments($user) {
2115 // override if necessary
2119 * This returns false for backwards compatibility, but it is really recommended.
2121 * @since Moodle 3.1
2122 * @return boolean
2124 public function use_standard_editing_ui() {
2125 return false;
2129 * Return whether or not, given the current state, it is possible to add a new instance
2130 * of this enrolment plugin to the course.
2132 * Default implementation is just for backwards compatibility.
2134 * @param int $courseid
2135 * @return boolean
2137 public function can_add_instance($courseid) {
2138 $link = $this->get_newinstance_link($courseid);
2139 return !empty($link);
2143 * Return whether or not, given the current state, it is possible to edit an instance
2144 * of this enrolment plugin in the course. Used by the standard editing UI
2145 * to generate a link to the edit instance form if editing is allowed.
2147 * @param stdClass $instance
2148 * @return boolean
2150 public function can_edit_instance($instance) {
2151 $context = context_course::instance($instance->courseid);
2153 return has_capability('enrol/' . $instance->enrol . ':config', $context);
2157 * Returns link to page which may be used to add new instance of enrolment plugin in course.
2158 * @param int $courseid
2159 * @return moodle_url page url
2161 public function get_newinstance_link($courseid) {
2162 // override for most plugins, check if instance already exists in cases only one instance is supported
2163 return NULL;
2167 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
2169 public function instance_deleteable($instance) {
2170 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
2171 enrol_plugin::can_delete_instance() instead');
2175 * Is it possible to delete enrol instance via standard UI?
2177 * @param stdClass $instance
2178 * @return bool
2180 public function can_delete_instance($instance) {
2181 return false;
2185 * Is it possible to hide/show enrol instance via standard UI?
2187 * @param stdClass $instance
2188 * @return bool
2190 public function can_hide_show_instance($instance) {
2191 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER);
2192 return true;
2196 * Returns link to manual enrol UI if exists.
2197 * Does the access control tests automatically.
2199 * @param object $instance
2200 * @return moodle_url
2202 public function get_manual_enrol_link($instance) {
2203 return NULL;
2207 * Returns list of unenrol links for all enrol instances in course.
2209 * @param int $instance
2210 * @return moodle_url or NULL if self unenrolment not supported
2212 public function get_unenrolself_link($instance) {
2213 global $USER, $CFG, $DB;
2215 $name = $this->get_name();
2216 if ($instance->enrol !== $name) {
2217 throw new coding_exception('invalid enrol instance!');
2220 if ($instance->courseid == SITEID) {
2221 return NULL;
2224 if (!enrol_is_enabled($name)) {
2225 return NULL;
2228 if ($instance->status != ENROL_INSTANCE_ENABLED) {
2229 return NULL;
2232 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2233 return NULL;
2236 $context = context_course::instance($instance->courseid, MUST_EXIST);
2238 if (!has_capability("enrol/$name:unenrolself", $context)) {
2239 return NULL;
2242 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
2243 return NULL;
2246 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
2250 * Adds enrol instance UI to course edit form
2252 * @param object $instance enrol instance or null if does not exist yet
2253 * @param MoodleQuickForm $mform
2254 * @param object $data
2255 * @param object $context context of existing course or parent category if course does not exist
2256 * @return void
2258 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
2259 // override - usually at least enable/disable switch, has to add own form header
2263 * Adds form elements to add/edit instance form.
2265 * @since Moodle 3.1
2266 * @param object $instance enrol instance or null if does not exist yet
2267 * @param MoodleQuickForm $mform
2268 * @param context $context
2269 * @return void
2271 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
2272 // Do nothing by default.
2276 * Perform custom validation of the data used to edit the instance.
2278 * @since Moodle 3.1
2279 * @param array $data array of ("fieldname"=>value) of submitted data
2280 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2281 * @param object $instance The instance data loaded from the DB.
2282 * @param context $context The context of the instance we are editing
2283 * @return array of "element_name"=>"error_description" if there are errors,
2284 * or an empty array if everything is OK.
2286 public function edit_instance_validation($data, $files, $instance, $context) {
2287 // No errors by default.
2288 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER);
2289 return array();
2293 * Validates course edit form data
2295 * @param object $instance enrol instance or null if does not exist yet
2296 * @param array $data
2297 * @param object $context context of existing course or parent category if course does not exist
2298 * @return array errors array
2300 public function course_edit_validation($instance, array $data, $context) {
2301 return array();
2305 * Called after updating/inserting course.
2307 * @param bool $inserted true if course just inserted
2308 * @param object $course
2309 * @param object $data form data
2310 * @return void
2312 public function course_updated($inserted, $course, $data) {
2313 if ($inserted) {
2314 if ($this->get_config('defaultenrol')) {
2315 $this->add_default_instance($course);
2321 * Add new instance of enrol plugin.
2322 * @param object $course
2323 * @param array instance fields
2324 * @return int id of new instance, null if can not be created
2326 public function add_instance($course, array $fields = NULL) {
2327 global $DB;
2329 if ($course->id == SITEID) {
2330 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2333 $instance = new stdClass();
2334 $instance->enrol = $this->get_name();
2335 $instance->status = ENROL_INSTANCE_ENABLED;
2336 $instance->courseid = $course->id;
2337 $instance->enrolstartdate = 0;
2338 $instance->enrolenddate = 0;
2339 $instance->timemodified = time();
2340 $instance->timecreated = $instance->timemodified;
2341 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
2343 $fields = (array)$fields;
2344 unset($fields['enrol']);
2345 unset($fields['courseid']);
2346 unset($fields['sortorder']);
2347 foreach($fields as $field=>$value) {
2348 $instance->$field = $value;
2351 $instance->id = $DB->insert_record('enrol', $instance);
2353 \core\event\enrol_instance_created::create_from_record($instance)->trigger();
2355 return $instance->id;
2359 * Update instance of enrol plugin.
2361 * @since Moodle 3.1
2362 * @param stdClass $instance
2363 * @param stdClass $data modified instance fields
2364 * @return boolean
2366 public function update_instance($instance, $data) {
2367 global $DB;
2368 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2369 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2370 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2371 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2372 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2373 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2375 foreach ($properties as $key) {
2376 if (isset($data->$key)) {
2377 $instance->$key = $data->$key;
2380 $instance->timemodified = time();
2382 $update = $DB->update_record('enrol', $instance);
2383 if ($update) {
2384 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2386 return $update;
2390 * Add new instance of enrol plugin with default settings,
2391 * called when adding new instance manually or when adding new course.
2393 * Not all plugins support this.
2395 * @param object $course
2396 * @return int id of new instance or null if no default supported
2398 public function add_default_instance($course) {
2399 return null;
2403 * Update instance status
2405 * Override when plugin needs to do some action when enabled or disabled.
2407 * @param stdClass $instance
2408 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2409 * @return void
2411 public function update_status($instance, $newstatus) {
2412 global $DB;
2414 $instance->status = $newstatus;
2415 $DB->update_record('enrol', $instance);
2417 $context = context_course::instance($instance->courseid);
2418 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2420 // Invalidate all enrol caches.
2421 $context->mark_dirty();
2425 * Delete course enrol plugin instance, unenrol all users.
2426 * @param object $instance
2427 * @return void
2429 public function delete_instance($instance) {
2430 global $DB;
2432 $name = $this->get_name();
2433 if ($instance->enrol !== $name) {
2434 throw new coding_exception('invalid enrol instance!');
2437 //first unenrol all users
2438 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
2439 foreach ($participants as $participant) {
2440 $this->unenrol_user($instance, $participant->userid);
2442 $participants->close();
2444 // now clean up all remainders that were not removed correctly
2445 if ($gms = $DB->get_records('groups_members', array('itemid' => $instance->id, 'component' => 'enrol_' . $name))) {
2446 foreach ($gms as $gm) {
2447 groups_remove_member($gm->groupid, $gm->userid);
2450 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
2451 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
2453 // finally drop the enrol row
2454 $DB->delete_records('enrol', array('id'=>$instance->id));
2456 $context = context_course::instance($instance->courseid);
2457 \core\event\enrol_instance_deleted::create_from_record($instance)->trigger();
2459 // Invalidate all enrol caches.
2460 $context->mark_dirty();
2464 * Creates course enrol form, checks if form submitted
2465 * and enrols user if necessary. It can also redirect.
2467 * @param stdClass $instance
2468 * @return string html text, usually a form in a text box
2470 public function enrol_page_hook(stdClass $instance) {
2471 return null;
2475 * Checks if user can self enrol.
2477 * @param stdClass $instance enrolment instance
2478 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2479 * used by navigation to improve performance.
2480 * @return bool|string true if successful, else error message or false
2482 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
2483 return false;
2487 * Return information for enrolment instance containing list of parameters required
2488 * for enrolment, name of enrolment plugin etc.
2490 * @param stdClass $instance enrolment instance
2491 * @return array instance info.
2493 public function get_enrol_info(stdClass $instance) {
2494 return null;
2498 * Adds navigation links into course admin block.
2500 * By defaults looks for manage links only.
2502 * @param navigation_node $instancesnode
2503 * @param stdClass $instance
2504 * @return void
2506 public function add_course_navigation($instancesnode, stdClass $instance) {
2507 if ($this->use_standard_editing_ui()) {
2508 $context = context_course::instance($instance->courseid);
2509 $cap = 'enrol/' . $instance->enrol . ':config';
2510 if (has_capability($cap, $context)) {
2511 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2512 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2513 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
2519 * Returns edit icons for the page with list of instances
2520 * @param stdClass $instance
2521 * @return array
2523 public function get_action_icons(stdClass $instance) {
2524 global $OUTPUT;
2526 $icons = array();
2527 if ($this->use_standard_editing_ui()) {
2528 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2529 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2530 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2531 array('class' => 'iconsmall')));
2533 return $icons;
2537 * Reads version.php and determines if it is necessary
2538 * to execute the cron job now.
2539 * @return bool
2541 public function is_cron_required() {
2542 global $CFG;
2544 $name = $this->get_name();
2545 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2546 $plugin = new stdClass();
2547 include($versionfile);
2548 if (empty($plugin->cron)) {
2549 return false;
2551 $lastexecuted = $this->get_config('lastcron', 0);
2552 if ($lastexecuted + $plugin->cron < time()) {
2553 return true;
2554 } else {
2555 return false;
2560 * Called for all enabled enrol plugins that returned true from is_cron_required().
2561 * @return void
2563 public function cron() {
2567 * Called when user is about to be deleted
2568 * @param object $user
2569 * @return void
2571 public function user_delete($user) {
2572 global $DB;
2574 $sql = "SELECT e.*
2575 FROM {enrol} e
2576 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2577 WHERE e.enrol = :name AND ue.userid = :userid";
2578 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
2580 $rs = $DB->get_recordset_sql($sql, $params);
2581 foreach($rs as $instance) {
2582 $this->unenrol_user($instance, $user->id);
2584 $rs->close();
2588 * Returns an enrol_user_button that takes the user to a page where they are able to
2589 * enrol users into the managers course through this plugin.
2591 * Optional: If the plugin supports manual enrolments it can choose to override this
2592 * otherwise it shouldn't
2594 * @param course_enrolment_manager $manager
2595 * @return enrol_user_button|false
2597 public function get_manual_enrol_button(course_enrolment_manager $manager) {
2598 return false;
2602 * Gets an array of the user enrolment actions
2604 * @param course_enrolment_manager $manager
2605 * @param stdClass $ue
2606 * @return array An array of user_enrolment_actions
2608 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
2609 $actions = [];
2610 $context = $manager->get_context();
2611 $instance = $ue->enrolmentinstance;
2612 $params = $manager->get_moodlepage()->url->params();
2613 $params['ue'] = $ue->id;
2615 // Edit enrolment action.
2616 if ($this->allow_manage($instance) && has_capability("enrol/{$instance->enrol}:manage", $context)) {
2617 $title = get_string('editenrolment', 'enrol');
2618 $icon = new pix_icon('t/edit', $title);
2619 $url = new moodle_url('/enrol/editenrolment.php', $params);
2620 $actionparams = [
2621 'class' => 'editenrollink',
2622 'rel' => $ue->id,
2623 'data-action' => ENROL_ACTION_EDIT
2625 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2628 // Unenrol action.
2629 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/{$instance->enrol}:unenrol", $context)) {
2630 $title = get_string('unenrol', 'enrol');
2631 $icon = new pix_icon('t/delete', $title);
2632 $url = new moodle_url('/enrol/unenroluser.php', $params);
2633 $actionparams = [
2634 'class' => 'unenrollink',
2635 'rel' => $ue->id,
2636 'data-action' => ENROL_ACTION_UNENROL
2638 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2640 return $actions;
2644 * Returns true if the plugin has one or more bulk operations that can be performed on
2645 * user enrolments.
2647 * @param course_enrolment_manager $manager
2648 * @return bool
2650 public function has_bulk_operations(course_enrolment_manager $manager) {
2651 return false;
2655 * Return an array of enrol_bulk_enrolment_operation objects that define
2656 * the bulk actions that can be performed on user enrolments by the plugin.
2658 * @param course_enrolment_manager $manager
2659 * @return array
2661 public function get_bulk_operations(course_enrolment_manager $manager) {
2662 return array();
2666 * Do any enrolments need expiration processing.
2668 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2670 * @param progress_trace $trace
2671 * @param int $courseid one course, empty mean all
2672 * @return bool true if any data processed, false if not
2674 public function process_expirations(progress_trace $trace, $courseid = null) {
2675 global $DB;
2677 $name = $this->get_name();
2678 if (!enrol_is_enabled($name)) {
2679 $trace->finished();
2680 return false;
2683 $processed = false;
2684 $params = array();
2685 $coursesql = "";
2686 if ($courseid) {
2687 $coursesql = "AND e.courseid = :courseid";
2690 // Deal with expired accounts.
2691 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
2693 if ($action == ENROL_EXT_REMOVED_UNENROL) {
2694 $instances = array();
2695 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2696 FROM {user_enrolments} ue
2697 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2698 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2699 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2700 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
2702 $rs = $DB->get_recordset_sql($sql, $params);
2703 foreach ($rs as $ue) {
2704 if (!$processed) {
2705 $trace->output("Starting processing of enrol_$name expirations...");
2706 $processed = true;
2708 if (empty($instances[$ue->enrolid])) {
2709 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2711 $instance = $instances[$ue->enrolid];
2712 if (!$this->roles_protected()) {
2713 // Let's just guess what extra roles are supposed to be removed.
2714 if ($instance->roleid) {
2715 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
2718 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2719 $this->unenrol_user($instance, $ue->userid);
2720 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2722 $rs->close();
2723 unset($instances);
2725 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
2726 $instances = array();
2727 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2728 FROM {user_enrolments} ue
2729 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2730 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2731 WHERE ue.timeend > 0 AND ue.timeend < :now
2732 AND ue.status = :useractive $coursesql";
2733 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
2734 $rs = $DB->get_recordset_sql($sql, $params);
2735 foreach ($rs as $ue) {
2736 if (!$processed) {
2737 $trace->output("Starting processing of enrol_$name expirations...");
2738 $processed = true;
2740 if (empty($instances[$ue->enrolid])) {
2741 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2743 $instance = $instances[$ue->enrolid];
2745 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
2746 if (!$this->roles_protected()) {
2747 // Let's just guess what roles should be removed.
2748 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
2749 if ($count == 1) {
2750 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
2752 } else if ($count > 1 and $instance->roleid) {
2753 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
2756 // In any case remove all roles that belong to this instance and user.
2757 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
2758 // Final cleanup of subcontexts if there are no more course roles.
2759 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
2760 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
2764 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
2765 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2767 $rs->close();
2768 unset($instances);
2770 } else {
2771 // ENROL_EXT_REMOVED_KEEP means no changes.
2774 if ($processed) {
2775 $trace->output("...finished processing of enrol_$name expirations");
2776 } else {
2777 $trace->output("No expired enrol_$name enrolments detected");
2779 $trace->finished();
2781 return $processed;
2785 * Send expiry notifications.
2787 * Plugin that wants to have expiry notification MUST implement following:
2788 * - expirynotifyhour plugin setting,
2789 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2790 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2791 * expirymessageenrolledsubject and expirymessageenrolledbody),
2792 * - expiry_notification provider in db/messages.php,
2793 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2794 * - something that calls this method, such as cron.
2796 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2798 public function send_expiry_notifications($trace) {
2799 global $DB, $CFG;
2801 $name = $this->get_name();
2802 if (!enrol_is_enabled($name)) {
2803 $trace->finished();
2804 return;
2807 // Unfortunately this may take a long time, it should not be interrupted,
2808 // otherwise users get duplicate notification.
2810 core_php_time_limit::raise();
2811 raise_memory_limit(MEMORY_HUGE);
2814 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2815 $expirynotifyhour = $this->get_config('expirynotifyhour');
2816 if (is_null($expirynotifyhour)) {
2817 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
2818 $trace->finished();
2819 return;
2822 if (!($trace instanceof progress_trace)) {
2823 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
2824 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
2827 $timenow = time();
2828 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
2830 if ($expirynotifylast > $notifytime) {
2831 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
2832 $trace->finished();
2833 return;
2835 } else if ($timenow < $notifytime) {
2836 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
2837 $trace->finished();
2838 return;
2841 $trace->output('Processing '.$name.' enrolment expiration notifications...');
2843 // Notify users responsible for enrolment once every day.
2844 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2845 FROM {user_enrolments} ue
2846 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2847 JOIN {course} c ON (c.id = e.courseid)
2848 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2849 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2850 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2851 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2853 $rs = $DB->get_recordset_sql($sql, $params);
2855 $lastenrollid = 0;
2856 $users = array();
2858 foreach($rs as $ue) {
2859 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
2860 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2861 $users = array();
2863 $lastenrollid = $ue->enrolid;
2865 $enroller = $this->get_enroller($ue->enrolid);
2866 $context = context_course::instance($ue->courseid);
2868 $user = $DB->get_record('user', array('id'=>$ue->userid));
2870 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
2872 if (!$ue->notifyall) {
2873 continue;
2876 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
2877 // Notify enrolled users only once at the start of the threshold.
2878 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2879 continue;
2882 $this->notify_expiry_enrolled($user, $ue, $trace);
2884 $rs->close();
2886 if ($lastenrollid and $users) {
2887 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2890 $trace->output('...notification processing finished.');
2891 $trace->finished();
2893 $this->set_config('expirynotifylast', $timenow);
2897 * Returns the user who is responsible for enrolments for given instance.
2899 * Override if plugin knows anybody better than admin.
2901 * @param int $instanceid enrolment instance id
2902 * @return stdClass user record
2904 protected function get_enroller($instanceid) {
2905 return get_admin();
2909 * Notify user about incoming expiration of their enrolment,
2910 * it is called only if notification of enrolled users (aka students) is enabled in course.
2912 * This is executed only once for each expiring enrolment right
2913 * at the start of the expiration threshold.
2915 * @param stdClass $user
2916 * @param stdClass $ue
2917 * @param progress_trace $trace
2919 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
2920 global $CFG;
2922 $name = $this->get_name();
2924 $oldforcelang = force_current_language($user->lang);
2926 $enroller = $this->get_enroller($ue->enrolid);
2927 $context = context_course::instance($ue->courseid);
2929 $a = new stdClass();
2930 $a->course = format_string($ue->fullname, true, array('context'=>$context));
2931 $a->user = fullname($user, true);
2932 $a->timeend = userdate($ue->timeend, '', $user->timezone);
2933 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
2935 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
2936 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
2938 $message = new \core\message\message();
2939 $message->courseid = $ue->courseid;
2940 $message->notification = 1;
2941 $message->component = 'enrol_'.$name;
2942 $message->name = 'expiry_notification';
2943 $message->userfrom = $enroller;
2944 $message->userto = $user;
2945 $message->subject = $subject;
2946 $message->fullmessage = $body;
2947 $message->fullmessageformat = FORMAT_MARKDOWN;
2948 $message->fullmessagehtml = markdown_to_html($body);
2949 $message->smallmessage = $subject;
2950 $message->contexturlname = $a->course;
2951 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
2953 if (message_send($message)) {
2954 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2955 } else {
2956 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2959 force_current_language($oldforcelang);
2963 * Notify person responsible for enrolments that some user enrolments will be expired soon,
2964 * it is called only if notification of enrollers (aka teachers) is enabled in course.
2966 * This is called repeatedly every day for each course if there are any pending expiration
2967 * in the expiration threshold.
2969 * @param int $eid
2970 * @param array $users
2971 * @param progress_trace $trace
2973 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
2974 global $DB;
2976 $name = $this->get_name();
2978 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
2979 $context = context_course::instance($instance->courseid);
2980 $course = $DB->get_record('course', array('id'=>$instance->courseid));
2982 $enroller = $this->get_enroller($instance->id);
2983 $admin = get_admin();
2985 $oldforcelang = force_current_language($enroller->lang);
2987 foreach($users as $key=>$info) {
2988 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
2991 $a = new stdClass();
2992 $a->course = format_string($course->fullname, true, array('context'=>$context));
2993 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
2994 $a->users = implode("\n", $users);
2995 $a->extendurl = (string)new moodle_url('/user/index.php', array('id'=>$instance->courseid));
2997 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
2998 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
3000 $message = new \core\message\message();
3001 $message->courseid = $course->id;
3002 $message->notification = 1;
3003 $message->component = 'enrol_'.$name;
3004 $message->name = 'expiry_notification';
3005 $message->userfrom = $admin;
3006 $message->userto = $enroller;
3007 $message->subject = $subject;
3008 $message->fullmessage = $body;
3009 $message->fullmessageformat = FORMAT_MARKDOWN;
3010 $message->fullmessagehtml = markdown_to_html($body);
3011 $message->smallmessage = $subject;
3012 $message->contexturlname = $a->course;
3013 $message->contexturl = $a->extendurl;
3015 if (message_send($message)) {
3016 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3017 } else {
3018 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3021 force_current_language($oldforcelang);
3025 * Backup execution step hook to annotate custom fields.
3027 * @param backup_enrolments_execution_step $step
3028 * @param stdClass $enrol
3030 public function backup_annotate_custom_fields(backup_enrolments_execution_step $step, stdClass $enrol) {
3031 // Override as necessary to annotate custom fields in the enrol table.
3035 * Automatic enrol sync executed during restore.
3036 * Useful for automatic sync by course->idnumber or course category.
3037 * @param stdClass $course course record
3039 public function restore_sync_course($course) {
3040 // Override if necessary.
3044 * Restore instance and map settings.
3046 * @param restore_enrolments_structure_step $step
3047 * @param stdClass $data
3048 * @param stdClass $course
3049 * @param int $oldid
3051 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
3052 // Do not call this from overridden methods, restore and set new id there.
3053 $step->set_mapping('enrol', $oldid, 0);
3057 * Restore user enrolment.
3059 * @param restore_enrolments_structure_step $step
3060 * @param stdClass $data
3061 * @param stdClass $instance
3062 * @param int $oldinstancestatus
3063 * @param int $userid
3065 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
3066 // Override as necessary if plugin supports restore of enrolments.
3070 * Restore role assignment.
3072 * @param stdClass $instance
3073 * @param int $roleid
3074 * @param int $userid
3075 * @param int $contextid
3077 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
3078 // No role assignment by default, override if necessary.
3082 * Restore user group membership.
3083 * @param stdClass $instance
3084 * @param int $groupid
3085 * @param int $userid
3087 public function restore_group_member($instance, $groupid, $userid) {
3088 // Implement if you want to restore protected group memberships,
3089 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
3093 * Returns defaults for new instances.
3094 * @since Moodle 3.1
3095 * @return array
3097 public function get_instance_defaults() {
3098 return array();
3102 * Validate a list of parameter names and types.
3103 * @since Moodle 3.1
3105 * @param array $data array of ("fieldname"=>value) of submitted data
3106 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
3107 * @return array of "element_name"=>"error_description" if there are errors,
3108 * or an empty array if everything is OK.
3110 public function validate_param_types($data, $rules) {
3111 $errors = array();
3112 $invalidstr = get_string('invaliddata', 'error');
3113 foreach ($rules as $fieldname => $rule) {
3114 if (is_array($rule)) {
3115 if (!in_array($data[$fieldname], $rule)) {
3116 $errors[$fieldname] = $invalidstr;
3118 } else {
3119 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
3120 $errors[$fieldname] = $invalidstr;
3124 return $errors;