Merge branch 'MDL-52777-master' of git://github.com/andrewnicols/moodle
[moodle.git] / lib / enrollib.php
blobc8ce48edb4f7ee90ea8d6f353906443d0807569a
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 * Returns instances of enrol plugins
72 * @param bool $enabled return enabled only
73 * @return array of enrol plugins name=>instance
75 function enrol_get_plugins($enabled) {
76 global $CFG;
78 $result = array();
80 if ($enabled) {
81 // sorted by enabled plugin order
82 $enabled = explode(',', $CFG->enrol_plugins_enabled);
83 $plugins = array();
84 foreach ($enabled as $plugin) {
85 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
87 } else {
88 // sorted alphabetically
89 $plugins = core_component::get_plugin_list('enrol');
90 ksort($plugins);
93 foreach ($plugins as $plugin=>$location) {
94 $class = "enrol_{$plugin}_plugin";
95 if (!class_exists($class)) {
96 if (!file_exists("$location/lib.php")) {
97 continue;
99 include_once("$location/lib.php");
100 if (!class_exists($class)) {
101 continue;
105 $result[$plugin] = new $class();
108 return $result;
112 * Returns instance of enrol plugin
113 * @param string $name name of enrol plugin ('manual', 'guest', ...)
114 * @return enrol_plugin
116 function enrol_get_plugin($name) {
117 global $CFG;
119 $name = clean_param($name, PARAM_PLUGIN);
121 if (empty($name)) {
122 // ignore malformed or missing plugin names completely
123 return null;
126 $location = "$CFG->dirroot/enrol/$name";
128 if (!file_exists("$location/lib.php")) {
129 return null;
131 include_once("$location/lib.php");
132 $class = "enrol_{$name}_plugin";
133 if (!class_exists($class)) {
134 return null;
137 return new $class();
141 * Returns enrolment instances in given course.
142 * @param int $courseid
143 * @param bool $enabled
144 * @return array of enrol instances
146 function enrol_get_instances($courseid, $enabled) {
147 global $DB, $CFG;
149 if (!$enabled) {
150 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
153 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
155 $enabled = explode(',', $CFG->enrol_plugins_enabled);
156 foreach ($result as $key=>$instance) {
157 if (!in_array($instance->enrol, $enabled)) {
158 unset($result[$key]);
159 continue;
161 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
162 // broken plugin
163 unset($result[$key]);
164 continue;
168 return $result;
172 * Checks if a given plugin is in the list of enabled enrolment plugins.
174 * @param string $enrol Enrolment plugin name
175 * @return boolean Whether the plugin is enabled
177 function enrol_is_enabled($enrol) {
178 global $CFG;
180 if (empty($CFG->enrol_plugins_enabled)) {
181 return false;
183 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
187 * Check all the login enrolment information for the given user object
188 * by querying the enrolment plugins
190 * This function may be very slow, use only once after log-in or login-as.
192 * @param stdClass $user
193 * @return void
195 function enrol_check_plugins($user) {
196 global $CFG;
198 if (empty($user->id) or isguestuser($user)) {
199 // shortcut - there is no enrolment work for guests and not-logged-in users
200 return;
203 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
204 // which proved it was actually not necessary.
206 static $inprogress = array(); // To prevent this function being called more than once in an invocation
208 if (!empty($inprogress[$user->id])) {
209 return;
212 $inprogress[$user->id] = true; // Set the flag
214 $enabled = enrol_get_plugins(true);
216 foreach($enabled as $enrol) {
217 $enrol->sync_user_enrolments($user);
220 unset($inprogress[$user->id]); // Unset the flag
224 * Do these two students share any course?
226 * The courses has to be visible and enrolments has to be active,
227 * timestart and timeend restrictions are ignored.
229 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
230 * to true.
232 * @param stdClass|int $user1
233 * @param stdClass|int $user2
234 * @return bool
236 function enrol_sharing_course($user1, $user2) {
237 return enrol_get_shared_courses($user1, $user2, false, true);
241 * Returns any courses shared by the two users
243 * The courses has to be visible and enrolments has to be active,
244 * timestart and timeend restrictions are ignored.
246 * @global moodle_database $DB
247 * @param stdClass|int $user1
248 * @param stdClass|int $user2
249 * @param bool $preloadcontexts If set to true contexts for the returned courses
250 * will be preloaded.
251 * @param bool $checkexistsonly If set to true then this function will return true
252 * if the users share any courses and false if not.
253 * @return array|bool An array of courses that both users are enrolled in OR if
254 * $checkexistsonly set returns true if the users share any courses
255 * and false if not.
257 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
258 global $DB, $CFG;
260 $user1 = isset($user1->id) ? $user1->id : $user1;
261 $user2 = isset($user2->id) ? $user2->id : $user2;
263 if (empty($user1) or empty($user2)) {
264 return false;
267 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
268 return false;
271 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
272 $params['enabled'] = ENROL_INSTANCE_ENABLED;
273 $params['active1'] = ENROL_USER_ACTIVE;
274 $params['active2'] = ENROL_USER_ACTIVE;
275 $params['user1'] = $user1;
276 $params['user2'] = $user2;
278 $ctxselect = '';
279 $ctxjoin = '';
280 if ($preloadcontexts) {
281 $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
282 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
283 $params['contextlevel'] = CONTEXT_COURSE;
286 $sql = "SELECT c.* $ctxselect
287 FROM {course} c
288 JOIN (
289 SELECT DISTINCT c.id
290 FROM {enrol} e
291 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
292 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2)
293 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
294 WHERE e.status = :enabled AND e.enrol $plugins
295 ) ec ON ec.id = c.id
296 $ctxjoin";
298 if ($checkexistsonly) {
299 return $DB->record_exists_sql($sql, $params);
300 } else {
301 $courses = $DB->get_records_sql($sql, $params);
302 if ($preloadcontexts) {
303 array_map('context_helper::preload_from_record', $courses);
305 return $courses;
310 * This function adds necessary enrol plugins UI into the course edit form.
312 * @param MoodleQuickForm $mform
313 * @param object $data course edit form data
314 * @param object $context context of existing course or parent category if course does not exist
315 * @return void
317 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
318 $plugins = enrol_get_plugins(true);
319 if (!empty($data->id)) {
320 $instances = enrol_get_instances($data->id, false);
321 foreach ($instances as $instance) {
322 if (!isset($plugins[$instance->enrol])) {
323 continue;
325 $plugin = $plugins[$instance->enrol];
326 $plugin->course_edit_form($instance, $mform, $data, $context);
328 } else {
329 foreach ($plugins as $plugin) {
330 $plugin->course_edit_form(NULL, $mform, $data, $context);
336 * Validate course edit form data
338 * @param array $data raw form data
339 * @param object $context context of existing course or parent category if course does not exist
340 * @return array errors array
342 function enrol_course_edit_validation(array $data, $context) {
343 $errors = array();
344 $plugins = enrol_get_plugins(true);
346 if (!empty($data['id'])) {
347 $instances = enrol_get_instances($data['id'], false);
348 foreach ($instances as $instance) {
349 if (!isset($plugins[$instance->enrol])) {
350 continue;
352 $plugin = $plugins[$instance->enrol];
353 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
355 } else {
356 foreach ($plugins as $plugin) {
357 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
361 return $errors;
365 * Update enrol instances after course edit form submission
366 * @param bool $inserted true means new course added, false course already existed
367 * @param object $course
368 * @param object $data form data
369 * @return void
371 function enrol_course_updated($inserted, $course, $data) {
372 global $DB, $CFG;
374 $plugins = enrol_get_plugins(true);
376 foreach ($plugins as $plugin) {
377 $plugin->course_updated($inserted, $course, $data);
382 * Add navigation nodes
383 * @param navigation_node $coursenode
384 * @param object $course
385 * @return void
387 function enrol_add_course_navigation(navigation_node $coursenode, $course) {
388 global $CFG;
390 $coursecontext = context_course::instance($course->id);
392 $instances = enrol_get_instances($course->id, true);
393 $plugins = enrol_get_plugins(true);
395 // we do not want to break all course pages if there is some borked enrol plugin, right?
396 foreach ($instances as $k=>$instance) {
397 if (!isset($plugins[$instance->enrol])) {
398 unset($instances[$k]);
402 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
404 if ($course->id != SITEID) {
405 // list all participants - allows assigning roles, groups, etc.
406 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
407 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
408 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/enrolusers', ''));
411 // manage enrol plugin instances
412 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
413 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
414 } else {
415 $url = NULL;
417 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
419 // each instance decides how to configure itself or how many other nav items are exposed
420 foreach ($instances as $instance) {
421 if (!isset($plugins[$instance->enrol])) {
422 continue;
424 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
427 if (!$url) {
428 $instancesnode->trim_if_empty();
432 // Manage groups in this course or even frontpage
433 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
434 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
435 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
438 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
439 // Override roles
440 if (has_capability('moodle/role:review', $coursecontext)) {
441 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
442 } else {
443 $url = NULL;
445 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
447 // Add assign or override roles if allowed
448 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
449 if (has_capability('moodle/role:assign', $coursecontext)) {
450 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
451 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
454 // Check role permissions
455 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
456 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
457 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
461 // Deal somehow with users that are not enrolled but still got a role somehow
462 if ($course->id != SITEID) {
463 //TODO, create some new UI for role assignments at course level
464 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
465 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
466 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
470 // just in case nothing was actually added
471 $usersnode->trim_if_empty();
473 if ($course->id != SITEID) {
474 if (isguestuser() or !isloggedin()) {
475 // guest account can not be enrolled - no links for them
476 } else if (is_enrolled($coursecontext)) {
477 // unenrol link if possible
478 foreach ($instances as $instance) {
479 if (!isset($plugins[$instance->enrol])) {
480 continue;
482 $plugin = $plugins[$instance->enrol];
483 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
484 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
485 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
486 break;
487 //TODO. deal with multiple unenrol links - not likely case, but still...
490 } else {
491 // enrol link if possible
492 if (is_viewing($coursecontext)) {
493 // better not show any enrol link, this is intended for managers and inspectors
494 } else {
495 foreach ($instances as $instance) {
496 if (!isset($plugins[$instance->enrol])) {
497 continue;
499 $plugin = $plugins[$instance->enrol];
500 if ($plugin->show_enrolme_link($instance)) {
501 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
502 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
503 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
504 break;
513 * Returns list of courses current $USER is enrolled in and can access
515 * - $fields is an array of field names to ADD
516 * so name the fields you really need, which will
517 * be added and uniq'd
519 * @param string|array $fields
520 * @param string $sort
521 * @param int $limit max number of courses
522 * @return array
524 function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
525 global $DB, $USER;
527 // Guest account does not have any courses
528 if (isguestuser() or !isloggedin()) {
529 return(array());
532 $basefields = array('id', 'category', 'sortorder',
533 'shortname', 'fullname', 'idnumber',
534 'startdate', 'visible',
535 'groupmode', 'groupmodeforce', 'cacherev');
537 if (empty($fields)) {
538 $fields = $basefields;
539 } else if (is_string($fields)) {
540 // turn the fields from a string to an array
541 $fields = explode(',', $fields);
542 $fields = array_map('trim', $fields);
543 $fields = array_unique(array_merge($basefields, $fields));
544 } else if (is_array($fields)) {
545 $fields = array_unique(array_merge($basefields, $fields));
546 } else {
547 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
549 if (in_array('*', $fields)) {
550 $fields = array('*');
553 $orderby = "";
554 $sort = trim($sort);
555 if (!empty($sort)) {
556 $rawsorts = explode(',', $sort);
557 $sorts = array();
558 foreach ($rawsorts as $rawsort) {
559 $rawsort = trim($rawsort);
560 if (strpos($rawsort, 'c.') === 0) {
561 $rawsort = substr($rawsort, 2);
563 $sorts[] = trim($rawsort);
565 $sort = 'c.'.implode(',c.', $sorts);
566 $orderby = "ORDER BY $sort";
569 $wheres = array("c.id <> :siteid");
570 $params = array('siteid'=>SITEID);
572 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
573 // list _only_ this course - anything else is asking for trouble...
574 $wheres[] = "courseid = :loginas";
575 $params['loginas'] = $USER->loginascontext->instanceid;
578 $coursefields = 'c.' .join(',c.', $fields);
579 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
580 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
581 $params['contextlevel'] = CONTEXT_COURSE;
582 $wheres = implode(" AND ", $wheres);
584 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
585 $sql = "SELECT $coursefields $ccselect
586 FROM {course} c
587 JOIN (SELECT DISTINCT e.courseid
588 FROM {enrol} e
589 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
590 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
591 ) en ON (en.courseid = c.id)
592 $ccjoin
593 WHERE $wheres
594 $orderby";
595 $params['userid'] = $USER->id;
596 $params['active'] = ENROL_USER_ACTIVE;
597 $params['enabled'] = ENROL_INSTANCE_ENABLED;
598 $params['now1'] = round(time(), -2); // improves db caching
599 $params['now2'] = $params['now1'];
601 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
603 // preload contexts and check visibility
604 foreach ($courses as $id=>$course) {
605 context_helper::preload_from_record($course);
606 if (!$course->visible) {
607 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
608 unset($courses[$id]);
609 continue;
611 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
612 unset($courses[$id]);
613 continue;
616 $courses[$id] = $course;
619 //wow! Is that really all? :-D
621 return $courses;
625 * Returns course enrolment information icons.
627 * @param object $course
628 * @param array $instances enrol instances of this course, improves performance
629 * @return array of pix_icon
631 function enrol_get_course_info_icons($course, array $instances = NULL) {
632 $icons = array();
633 if (is_null($instances)) {
634 $instances = enrol_get_instances($course->id, true);
636 $plugins = enrol_get_plugins(true);
637 foreach ($plugins as $name => $plugin) {
638 $pis = array();
639 foreach ($instances as $instance) {
640 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
641 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
642 continue;
644 if ($instance->enrol == $name) {
645 $pis[$instance->id] = $instance;
648 if ($pis) {
649 $icons = array_merge($icons, $plugin->get_info_icons($pis));
652 return $icons;
656 * Returns course enrolment detailed information.
658 * @param object $course
659 * @return array of html fragments - can be used to construct lists
661 function enrol_get_course_description_texts($course) {
662 $lines = array();
663 $instances = enrol_get_instances($course->id, true);
664 $plugins = enrol_get_plugins(true);
665 foreach ($instances as $instance) {
666 if (!isset($plugins[$instance->enrol])) {
667 //weird
668 continue;
670 $plugin = $plugins[$instance->enrol];
671 $text = $plugin->get_description_text($instance);
672 if ($text !== NULL) {
673 $lines[] = $text;
676 return $lines;
680 * Returns list of courses user is enrolled into.
681 * (Note: use enrol_get_all_users_courses if you want to use the list wihtout any cap checks )
683 * - $fields is an array of fieldnames to ADD
684 * so name the fields you really need, which will
685 * be added and uniq'd
687 * @param int $userid
688 * @param bool $onlyactive return only active enrolments in courses user may see
689 * @param string|array $fields
690 * @param string $sort
691 * @return array
693 function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
694 global $DB;
696 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
698 // preload contexts and check visibility
699 if ($onlyactive) {
700 foreach ($courses as $id=>$course) {
701 context_helper::preload_from_record($course);
702 if (!$course->visible) {
703 if (!$context = context_course::instance($id)) {
704 unset($courses[$id]);
705 continue;
707 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
708 unset($courses[$id]);
709 continue;
715 return $courses;
720 * Can user access at least one enrolled course?
722 * Cheat if necessary, but find out as fast as possible!
724 * @param int|stdClass $user null means use current user
725 * @return bool
727 function enrol_user_sees_own_courses($user = null) {
728 global $USER;
730 if ($user === null) {
731 $user = $USER;
733 $userid = is_object($user) ? $user->id : $user;
735 // Guest account does not have any courses
736 if (isguestuser($userid) or empty($userid)) {
737 return false;
740 // Let's cheat here if this is the current user,
741 // if user accessed any course recently, then most probably
742 // we do not need to query the database at all.
743 if ($USER->id == $userid) {
744 if (!empty($USER->enrol['enrolled'])) {
745 foreach ($USER->enrol['enrolled'] as $until) {
746 if ($until > time()) {
747 return true;
753 // Now the slow way.
754 $courses = enrol_get_all_users_courses($userid, true);
755 foreach($courses as $course) {
756 if ($course->visible) {
757 return true;
759 context_helper::preload_from_record($course);
760 $context = context_course::instance($course->id);
761 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
762 return true;
766 return false;
770 * Returns list of courses user is enrolled into without any capability checks
771 * - $fields is an array of fieldnames to ADD
772 * so name the fields you really need, which will
773 * be added and uniq'd
775 * @param int $userid
776 * @param bool $onlyactive return only active enrolments in courses user may see
777 * @param string|array $fields
778 * @param string $sort
779 * @return array
781 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
782 global $DB;
784 // Guest account does not have any courses
785 if (isguestuser($userid) or empty($userid)) {
786 return(array());
789 $basefields = array('id', 'category', 'sortorder',
790 'shortname', 'fullname', 'idnumber',
791 'startdate', 'visible',
792 'defaultgroupingid',
793 'groupmode', 'groupmodeforce');
795 if (empty($fields)) {
796 $fields = $basefields;
797 } else if (is_string($fields)) {
798 // turn the fields from a string to an array
799 $fields = explode(',', $fields);
800 $fields = array_map('trim', $fields);
801 $fields = array_unique(array_merge($basefields, $fields));
802 } else if (is_array($fields)) {
803 $fields = array_unique(array_merge($basefields, $fields));
804 } else {
805 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
807 if (in_array('*', $fields)) {
808 $fields = array('*');
811 $orderby = "";
812 $sort = trim($sort);
813 if (!empty($sort)) {
814 $rawsorts = explode(',', $sort);
815 $sorts = array();
816 foreach ($rawsorts as $rawsort) {
817 $rawsort = trim($rawsort);
818 if (strpos($rawsort, 'c.') === 0) {
819 $rawsort = substr($rawsort, 2);
821 $sorts[] = trim($rawsort);
823 $sort = 'c.'.implode(',c.', $sorts);
824 $orderby = "ORDER BY $sort";
827 $params = array('siteid'=>SITEID);
829 if ($onlyactive) {
830 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
831 $params['now1'] = round(time(), -2); // improves db caching
832 $params['now2'] = $params['now1'];
833 $params['active'] = ENROL_USER_ACTIVE;
834 $params['enabled'] = ENROL_INSTANCE_ENABLED;
835 } else {
836 $subwhere = "";
839 $coursefields = 'c.' .join(',c.', $fields);
840 $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
841 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
842 $params['contextlevel'] = CONTEXT_COURSE;
844 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
845 $sql = "SELECT $coursefields $ccselect
846 FROM {course} c
847 JOIN (SELECT DISTINCT e.courseid
848 FROM {enrol} e
849 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
850 $subwhere
851 ) en ON (en.courseid = c.id)
852 $ccjoin
853 WHERE c.id <> :siteid
854 $orderby";
855 $params['userid'] = $userid;
857 $courses = $DB->get_records_sql($sql, $params);
859 return $courses;
865 * Called when user is about to be deleted.
866 * @param object $user
867 * @return void
869 function enrol_user_delete($user) {
870 global $DB;
872 $plugins = enrol_get_plugins(true);
873 foreach ($plugins as $plugin) {
874 $plugin->user_delete($user);
877 // force cleanup of all broken enrolments
878 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
882 * Called when course is about to be deleted.
883 * @param stdClass $course
884 * @return void
886 function enrol_course_delete($course) {
887 global $DB;
889 $instances = enrol_get_instances($course->id, false);
890 $plugins = enrol_get_plugins(true);
891 foreach ($instances as $instance) {
892 if (isset($plugins[$instance->enrol])) {
893 $plugins[$instance->enrol]->delete_instance($instance);
895 // low level delete in case plugin did not do it
896 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
897 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
898 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
899 $DB->delete_records('enrol', array('id'=>$instance->id));
904 * Try to enrol user via default internal auth plugin.
906 * For now this is always using the manual enrol plugin...
908 * @param $courseid
909 * @param $userid
910 * @param $roleid
911 * @param $timestart
912 * @param $timeend
913 * @return bool success
915 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
916 global $DB;
918 //note: this is hardcoded to manual plugin for now
920 if (!enrol_is_enabled('manual')) {
921 return false;
924 if (!$enrol = enrol_get_plugin('manual')) {
925 return false;
927 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
928 return false;
930 $instance = reset($instances);
932 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
934 return true;
938 * Is there a chance users might self enrol
939 * @param int $courseid
940 * @return bool
942 function enrol_selfenrol_available($courseid) {
943 $result = false;
945 $plugins = enrol_get_plugins(true);
946 $enrolinstances = enrol_get_instances($courseid, true);
947 foreach($enrolinstances as $instance) {
948 if (!isset($plugins[$instance->enrol])) {
949 continue;
951 if ($instance->enrol === 'guest') {
952 // blacklist known temporary guest plugins
953 continue;
955 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
956 $result = true;
957 break;
961 return $result;
965 * This function returns the end of current active user enrolment.
967 * It deals correctly with multiple overlapping user enrolments.
969 * @param int $courseid
970 * @param int $userid
971 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
973 function enrol_get_enrolment_end($courseid, $userid) {
974 global $DB;
976 $sql = "SELECT ue.*
977 FROM {user_enrolments} ue
978 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
979 JOIN {user} u ON u.id = ue.userid
980 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
981 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
983 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
984 return false;
987 $changes = array();
989 foreach ($enrolments as $ue) {
990 $start = (int)$ue->timestart;
991 $end = (int)$ue->timeend;
992 if ($end != 0 and $end < $start) {
993 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
994 continue;
996 if (isset($changes[$start])) {
997 $changes[$start] = $changes[$start] + 1;
998 } else {
999 $changes[$start] = 1;
1001 if ($end === 0) {
1002 // no end
1003 } else if (isset($changes[$end])) {
1004 $changes[$end] = $changes[$end] - 1;
1005 } else {
1006 $changes[$end] = -1;
1010 // let's sort then enrolment starts&ends and go through them chronologically,
1011 // looking for current status and the next future end of enrolment
1012 ksort($changes);
1014 $now = time();
1015 $current = 0;
1016 $present = null;
1018 foreach ($changes as $time => $change) {
1019 if ($time > $now) {
1020 if ($present === null) {
1021 // we have just went past current time
1022 $present = $current;
1023 if ($present < 1) {
1024 // no enrolment active
1025 return false;
1028 if ($present !== null) {
1029 // we are already in the future - look for possible end
1030 if ($current + $change < 1) {
1031 return $time;
1035 $current += $change;
1038 if ($current > 0) {
1039 return 0;
1040 } else {
1041 return false;
1046 * Is current user accessing course via this enrolment method?
1048 * This is intended for operations that are going to affect enrol instances.
1050 * @param stdClass $instance enrol instance
1051 * @return bool
1053 function enrol_accessing_via_instance(stdClass $instance) {
1054 global $DB, $USER;
1056 if (empty($instance->id)) {
1057 return false;
1060 if (is_siteadmin()) {
1061 // Admins may go anywhere.
1062 return false;
1065 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
1069 * Returns true if user is enrolled (is participating) in course
1070 * this is intended for students and teachers.
1072 * Since 2.2 the result for active enrolments and current user are cached.
1074 * @param context $context
1075 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1076 * @param string $withcapability extra capability name
1077 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1078 * @return bool
1080 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1081 global $USER, $DB;
1083 // First find the course context.
1084 $coursecontext = $context->get_course_context();
1086 // Make sure there is a real user specified.
1087 if ($user === null) {
1088 $userid = isset($USER->id) ? $USER->id : 0;
1089 } else {
1090 $userid = is_object($user) ? $user->id : $user;
1093 if (empty($userid)) {
1094 // Not-logged-in!
1095 return false;
1096 } else if (isguestuser($userid)) {
1097 // Guest account can not be enrolled anywhere.
1098 return false;
1101 // Note everybody participates on frontpage, so for other contexts...
1102 if ($coursecontext->instanceid != SITEID) {
1103 // Try cached info first - the enrolled flag is set only when active enrolment present.
1104 if ($USER->id == $userid) {
1105 $coursecontext->reload_if_dirty();
1106 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1107 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1108 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1109 return false;
1111 return true;
1116 if ($onlyactive) {
1117 // Look for active enrolments only.
1118 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1120 if ($until === false) {
1121 return false;
1124 if ($USER->id == $userid) {
1125 if ($until == 0) {
1126 $until = ENROL_MAX_TIMESTAMP;
1128 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1129 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1130 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1131 remove_temp_course_roles($coursecontext);
1135 } else {
1136 // Any enrolment is good for us here, even outdated, disabled or inactive.
1137 $sql = "SELECT 'x'
1138 FROM {user_enrolments} ue
1139 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1140 JOIN {user} u ON u.id = ue.userid
1141 WHERE ue.userid = :userid AND u.deleted = 0";
1142 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid);
1143 if (!$DB->record_exists_sql($sql, $params)) {
1144 return false;
1149 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1150 return false;
1153 return true;
1157 * Returns an array of joins, wheres and params that will limit the group of
1158 * users to only those enrolled and with given capability (if specified).
1160 * @param context $context
1161 * @param string $prefix optional, a prefix to the user id column
1162 * @param string|array $capability optional, may include a capability name, or array of names.
1163 * If an array is provided then this is the equivalent of a logical 'OR',
1164 * i.e. the user needs to have one of these capabilities.
1165 * @param int $group optional, 0 indicates no current group, otherwise the group id
1166 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1167 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1168 * @return \core\dml\sql_join Contains joins, wheres, params
1170 function get_enrolled_with_capabilities_join(context $context, $prefix = '', $capability = '', $group = 0,
1171 $onlyactive = false, $onlysuspended = false) {
1172 $uid = $prefix . 'u.id';
1173 $joins = array();
1174 $wheres = array();
1176 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended);
1177 $joins[] = $enrolledjoin->joins;
1178 $wheres[] = $enrolledjoin->wheres;
1179 $params = $enrolledjoin->params;
1181 if (!empty($capability)) {
1182 $capjoin = get_with_capability_join($context, $capability, $uid);
1183 $joins[] = $capjoin->joins;
1184 $wheres[] = $capjoin->wheres;
1185 $params = array_merge($params, $capjoin->params);
1188 if ($group) {
1189 $groupjoin = groups_get_members_join($group, $uid);
1190 $joins[] = $groupjoin->joins;
1191 $params = array_merge($params, $groupjoin->params);
1194 $joins = implode("\n", $joins);
1195 $wheres[] = "{$prefix}u.deleted = 0";
1196 $wheres = implode(" AND ", $wheres);
1198 return new \core\dml\sql_join($joins, $wheres, $params);
1202 * Returns array with sql code and parameters returning all ids
1203 * of users enrolled into course.
1205 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1207 * @param context $context
1208 * @param string $withcapability
1209 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1210 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1211 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1212 * @return array list($sql, $params)
1214 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false) {
1216 // Use unique prefix just in case somebody makes some SQL magic with the result.
1217 static $i = 0;
1218 $i++;
1219 $prefix = 'eu' . $i . '_';
1221 $capjoin = get_enrolled_with_capabilities_join(
1222 $context, $prefix, $withcapability, $groupid, $onlyactive, $onlysuspended);
1224 $sql = "SELECT DISTINCT {$prefix}u.id
1225 FROM {user} {$prefix}u
1226 $capjoin->joins
1227 WHERE $capjoin->wheres";
1229 return array($sql, $capjoin->params);
1233 * Returns array with sql joins and parameters returning all ids
1234 * of users enrolled into course.
1236 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1238 * @throws coding_exception
1240 * @param context $context
1241 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1242 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1243 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1244 * @return \core\dml\sql_join Contains joins, wheres, params
1246 function get_enrolled_join(context $context, $useridcolumn, $onlyactive = false, $onlysuspended = false) {
1247 // Use unique prefix just in case somebody makes some SQL magic with the result.
1248 static $i = 0;
1249 $i++;
1250 $prefix = 'ej' . $i . '_';
1252 // First find the course context.
1253 $coursecontext = $context->get_course_context();
1255 $isfrontpage = ($coursecontext->instanceid == SITEID);
1257 if ($onlyactive && $onlysuspended) {
1258 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1260 if ($isfrontpage && $onlysuspended) {
1261 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1264 $joins = array();
1265 $wheres = array();
1266 $params = array();
1268 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1270 // Note all users are "enrolled" on the frontpage, but for others...
1271 if (!$isfrontpage) {
1272 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1273 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1274 $ejoin = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
1275 $params[$prefix.'courseid'] = $coursecontext->instanceid;
1277 if (!$onlysuspended) {
1278 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1279 $joins[] = $ejoin;
1280 if ($onlyactive) {
1281 $wheres[] = "$where1 AND $where2";
1283 } else {
1284 // Suspended only where there is enrolment but ALL are suspended.
1285 // Consider multiple enrols where one is not suspended or plain role_assign.
1286 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1287 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1288 $joins[] = "JOIN {enrol} {$prefix}e1 ON ({$prefix}e1.id = {$prefix}ue1.enrolid
1289 AND {$prefix}e1.courseid = :{$prefix}_e1_courseid)";
1290 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid;
1291 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1294 if ($onlyactive || $onlysuspended) {
1295 $now = round(time(), -2); // Rounding helps caching in DB.
1296 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED,
1297 $prefix . 'active' => ENROL_USER_ACTIVE,
1298 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1302 $joins = implode("\n", $joins);
1303 $wheres = implode(" AND ", $wheres);
1305 return new \core\dml\sql_join($joins, $wheres, $params);
1309 * Returns list of users enrolled into course.
1311 * @param context $context
1312 * @param string $withcapability
1313 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1314 * @param string $userfields requested user record fields
1315 * @param string $orderby
1316 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1317 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1318 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1319 * @return array of user records
1321 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1322 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1323 global $DB;
1325 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1326 $sql = "SELECT $userfields
1327 FROM {user} u
1328 JOIN ($esql) je ON je.id = u.id
1329 WHERE u.deleted = 0";
1331 if ($orderby) {
1332 $sql = "$sql ORDER BY $orderby";
1333 } else {
1334 list($sort, $sortparams) = users_order_by_sql('u');
1335 $sql = "$sql ORDER BY $sort";
1336 $params = array_merge($params, $sortparams);
1339 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1343 * Counts list of users enrolled into course (as per above function)
1345 * @param context $context
1346 * @param string $withcapability
1347 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1348 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1349 * @return array of user records
1351 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1352 global $DB;
1354 $capjoin = get_enrolled_with_capabilities_join(
1355 $context, '', $withcapability, $groupid, $onlyactive);
1357 $sql = "SELECT count(u.id)
1358 FROM {user} u
1359 $capjoin->joins
1360 WHERE $capjoin->wheres AND u.deleted = 0";
1362 return $DB->count_records_sql($sql, $capjoin->params);
1366 * All enrol plugins should be based on this class,
1367 * this is also the main source of documentation.
1369 abstract class enrol_plugin {
1370 protected $config = null;
1373 * Returns name of this enrol plugin
1374 * @return string
1376 public function get_name() {
1377 // second word in class is always enrol name, sorry, no fancy plugin names with _
1378 $words = explode('_', get_class($this));
1379 return $words[1];
1383 * Returns localised name of enrol instance
1385 * @param object $instance (null is accepted too)
1386 * @return string
1388 public function get_instance_name($instance) {
1389 if (empty($instance->name)) {
1390 $enrol = $this->get_name();
1391 return get_string('pluginname', 'enrol_'.$enrol);
1392 } else {
1393 $context = context_course::instance($instance->courseid);
1394 return format_string($instance->name, true, array('context'=>$context));
1399 * Returns optional enrolment information icons.
1401 * This is used in course list for quick overview of enrolment options.
1403 * We are not using single instance parameter because sometimes
1404 * we might want to prevent icon repetition when multiple instances
1405 * of one type exist. One instance may also produce several icons.
1407 * @param array $instances all enrol instances of this type in one course
1408 * @return array of pix_icon
1410 public function get_info_icons(array $instances) {
1411 return array();
1415 * Returns optional enrolment instance description text.
1417 * This is used in detailed course information.
1420 * @param object $instance
1421 * @return string short html text
1423 public function get_description_text($instance) {
1424 return null;
1428 * Makes sure config is loaded and cached.
1429 * @return void
1431 protected function load_config() {
1432 if (!isset($this->config)) {
1433 $name = $this->get_name();
1434 $this->config = get_config("enrol_$name");
1439 * Returns plugin config value
1440 * @param string $name
1441 * @param string $default value if config does not exist yet
1442 * @return string value or default
1444 public function get_config($name, $default = NULL) {
1445 $this->load_config();
1446 return isset($this->config->$name) ? $this->config->$name : $default;
1450 * Sets plugin config value
1451 * @param string $name name of config
1452 * @param string $value string config value, null means delete
1453 * @return string value
1455 public function set_config($name, $value) {
1456 $pluginname = $this->get_name();
1457 $this->load_config();
1458 if ($value === NULL) {
1459 unset($this->config->$name);
1460 } else {
1461 $this->config->$name = $value;
1463 set_config($name, $value, "enrol_$pluginname");
1467 * Does this plugin assign protected roles are can they be manually removed?
1468 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1470 public function roles_protected() {
1471 return true;
1475 * Does this plugin allow manual enrolments?
1477 * @param stdClass $instance course enrol instance
1478 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1480 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1482 public function allow_enrol(stdClass $instance) {
1483 return false;
1487 * Does this plugin allow manual unenrolment of all users?
1488 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1490 * @param stdClass $instance course enrol instance
1491 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1493 public function allow_unenrol(stdClass $instance) {
1494 return false;
1498 * Does this plugin allow manual unenrolment of a specific user?
1499 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1501 * This is useful especially for synchronisation plugins that
1502 * do suspend instead of full unenrolment.
1504 * @param stdClass $instance course enrol instance
1505 * @param stdClass $ue record from user_enrolments table, specifies user
1507 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1509 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1510 return $this->allow_unenrol($instance);
1514 * Does this plugin allow manual changes in user_enrolments table?
1516 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1518 * @param stdClass $instance course enrol instance
1519 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1521 public function allow_manage(stdClass $instance) {
1522 return false;
1526 * Does this plugin support some way to user to self enrol?
1528 * @param stdClass $instance course enrol instance
1530 * @return bool - true means show "Enrol me in this course" link in course UI
1532 public function show_enrolme_link(stdClass $instance) {
1533 return false;
1537 * Attempt to automatically enrol current user in course without any interaction,
1538 * calling code has to make sure the plugin and instance are active.
1540 * This should return either a timestamp in the future or false.
1542 * @param stdClass $instance course enrol instance
1543 * @return bool|int false means not enrolled, integer means timeend
1545 public function try_autoenrol(stdClass $instance) {
1546 global $USER;
1548 return false;
1552 * Attempt to automatically gain temporary guest access to course,
1553 * calling code has to make sure the plugin and instance are active.
1555 * This should return either a timestamp in the future or false.
1557 * @param stdClass $instance course enrol instance
1558 * @return bool|int false means no guest access, integer means timeend
1560 public function try_guestaccess(stdClass $instance) {
1561 global $USER;
1563 return false;
1567 * Enrol user into course via enrol instance.
1569 * @param stdClass $instance
1570 * @param int $userid
1571 * @param int $roleid optional role id
1572 * @param int $timestart 0 means unknown
1573 * @param int $timeend 0 means forever
1574 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1575 * @param bool $recovergrades restore grade history
1576 * @return void
1578 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
1579 global $DB, $USER, $CFG; // CFG necessary!!!
1581 if ($instance->courseid == SITEID) {
1582 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1585 $name = $this->get_name();
1586 $courseid = $instance->courseid;
1588 if ($instance->enrol !== $name) {
1589 throw new coding_exception('invalid enrol instance!');
1591 $context = context_course::instance($instance->courseid, MUST_EXIST);
1592 if (!isset($recovergrades)) {
1593 $recovergrades = $CFG->recovergradesdefault;
1596 $inserted = false;
1597 $updated = false;
1598 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1599 //only update if timestart or timeend or status are different.
1600 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
1601 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
1603 } else {
1604 $ue = new stdClass();
1605 $ue->enrolid = $instance->id;
1606 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
1607 $ue->userid = $userid;
1608 $ue->timestart = $timestart;
1609 $ue->timeend = $timeend;
1610 $ue->modifierid = $USER->id;
1611 $ue->timecreated = time();
1612 $ue->timemodified = $ue->timecreated;
1613 $ue->id = $DB->insert_record('user_enrolments', $ue);
1615 $inserted = true;
1618 if ($inserted) {
1619 // Trigger event.
1620 $event = \core\event\user_enrolment_created::create(
1621 array(
1622 'objectid' => $ue->id,
1623 'courseid' => $courseid,
1624 'context' => $context,
1625 'relateduserid' => $ue->userid,
1626 'other' => array('enrol' => $name)
1629 $event->trigger();
1630 // Check if course contacts cache needs to be cleared.
1631 require_once($CFG->libdir . '/coursecatlib.php');
1632 coursecat::user_enrolment_changed($courseid, $ue->userid,
1633 $ue->status, $ue->timestart, $ue->timeend);
1636 if ($roleid) {
1637 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
1638 if ($this->roles_protected()) {
1639 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1640 } else {
1641 role_assign($roleid, $userid, $context->id);
1645 // Recover old grades if present.
1646 if ($recovergrades) {
1647 require_once("$CFG->libdir/gradelib.php");
1648 grade_recover_history_grades($userid, $courseid);
1651 // reset current user enrolment caching
1652 if ($userid == $USER->id) {
1653 if (isset($USER->enrol['enrolled'][$courseid])) {
1654 unset($USER->enrol['enrolled'][$courseid]);
1656 if (isset($USER->enrol['tempguest'][$courseid])) {
1657 unset($USER->enrol['tempguest'][$courseid]);
1658 remove_temp_course_roles($context);
1664 * Store user_enrolments changes and trigger event.
1666 * @param stdClass $instance
1667 * @param int $userid
1668 * @param int $status
1669 * @param int $timestart
1670 * @param int $timeend
1671 * @return void
1673 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1674 global $DB, $USER, $CFG;
1676 $name = $this->get_name();
1678 if ($instance->enrol !== $name) {
1679 throw new coding_exception('invalid enrol instance!');
1682 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1683 // weird, user not enrolled
1684 return;
1687 $modified = false;
1688 if (isset($status) and $ue->status != $status) {
1689 $ue->status = $status;
1690 $modified = true;
1692 if (isset($timestart) and $ue->timestart != $timestart) {
1693 $ue->timestart = $timestart;
1694 $modified = true;
1696 if (isset($timeend) and $ue->timeend != $timeend) {
1697 $ue->timeend = $timeend;
1698 $modified = true;
1701 if (!$modified) {
1702 // no change
1703 return;
1706 $ue->modifierid = $USER->id;
1707 $DB->update_record('user_enrolments', $ue);
1708 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches
1710 // Invalidate core_access cache for get_suspended_userids.
1711 cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));
1713 // Trigger event.
1714 $event = \core\event\user_enrolment_updated::create(
1715 array(
1716 'objectid' => $ue->id,
1717 'courseid' => $instance->courseid,
1718 'context' => context_course::instance($instance->courseid),
1719 'relateduserid' => $ue->userid,
1720 'other' => array('enrol' => $name)
1723 $event->trigger();
1725 require_once($CFG->libdir . '/coursecatlib.php');
1726 coursecat::user_enrolment_changed($instance->courseid, $ue->userid,
1727 $ue->status, $ue->timestart, $ue->timeend);
1731 * Unenrol user from course,
1732 * the last unenrolment removes all remaining roles.
1734 * @param stdClass $instance
1735 * @param int $userid
1736 * @return void
1738 public function unenrol_user(stdClass $instance, $userid) {
1739 global $CFG, $USER, $DB;
1740 require_once("$CFG->dirroot/group/lib.php");
1742 $name = $this->get_name();
1743 $courseid = $instance->courseid;
1745 if ($instance->enrol !== $name) {
1746 throw new coding_exception('invalid enrol instance!');
1748 $context = context_course::instance($instance->courseid, MUST_EXIST);
1750 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1751 // weird, user not enrolled
1752 return;
1755 // Remove all users groups linked to this enrolment instance.
1756 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
1757 foreach ($gms as $gm) {
1758 groups_remove_member($gm->groupid, $gm->userid);
1762 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1763 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1765 // add extra info and trigger event
1766 $ue->courseid = $courseid;
1767 $ue->enrol = $name;
1769 $sql = "SELECT 'x'
1770 FROM {user_enrolments} ue
1771 JOIN {enrol} e ON (e.id = ue.enrolid)
1772 WHERE ue.userid = :userid AND e.courseid = :courseid";
1773 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1774 $ue->lastenrol = false;
1776 } else {
1777 // the big cleanup IS necessary!
1778 require_once("$CFG->libdir/gradelib.php");
1780 // remove all remaining roles
1781 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1783 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1784 groups_delete_group_members($courseid, $userid);
1786 grade_user_unenrol($courseid, $userid);
1788 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1790 $ue->lastenrol = true; // means user not enrolled any more
1792 // Trigger event.
1793 $event = \core\event\user_enrolment_deleted::create(
1794 array(
1795 'courseid' => $courseid,
1796 'context' => $context,
1797 'relateduserid' => $ue->userid,
1798 'objectid' => $ue->id,
1799 'other' => array(
1800 'userenrolment' => (array)$ue,
1801 'enrol' => $name
1805 $event->trigger();
1806 // reset all enrol caches
1807 $context->mark_dirty();
1809 // Check if courrse contacts cache needs to be cleared.
1810 require_once($CFG->libdir . '/coursecatlib.php');
1811 coursecat::user_enrolment_changed($courseid, $ue->userid, ENROL_USER_SUSPENDED);
1813 // reset current user enrolment caching
1814 if ($userid == $USER->id) {
1815 if (isset($USER->enrol['enrolled'][$courseid])) {
1816 unset($USER->enrol['enrolled'][$courseid]);
1818 if (isset($USER->enrol['tempguest'][$courseid])) {
1819 unset($USER->enrol['tempguest'][$courseid]);
1820 remove_temp_course_roles($context);
1826 * Forces synchronisation of user enrolments.
1828 * This is important especially for external enrol plugins,
1829 * this function is called for all enabled enrol plugins
1830 * right after every user login.
1832 * @param object $user user record
1833 * @return void
1835 public function sync_user_enrolments($user) {
1836 // override if necessary
1840 * This returns false for backwards compatibility, but it is really recommended.
1842 * @since Moodle 3.1
1843 * @return boolean
1845 public function use_standard_editing_ui() {
1846 return false;
1850 * Return whether or not, given the current state, it is possible to add a new instance
1851 * of this enrolment plugin to the course.
1853 * Default implementation is just for backwards compatibility.
1855 * @param int $courseid
1856 * @return boolean
1858 public function can_add_instance($courseid) {
1859 $link = $this->get_newinstance_link($courseid);
1860 return !empty($link);
1864 * Return whether or not, given the current state, it is possible to edit an instance
1865 * of this enrolment plugin in the course. Used by the standard editing UI
1866 * to generate a link to the edit instance form if editing is allowed.
1868 * @param stdClass $instance
1869 * @return boolean
1871 public function can_edit_instance($instance) {
1872 $context = context_course::instance($instance->courseid);
1874 return has_capability('enrol/' . $instance->enrol . ':config', $context);
1878 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1879 * @param int $courseid
1880 * @return moodle_url page url
1882 public function get_newinstance_link($courseid) {
1883 // override for most plugins, check if instance already exists in cases only one instance is supported
1884 return NULL;
1888 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
1890 public function instance_deleteable($instance) {
1891 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
1892 enrol_plugin::can_delete_instance() instead');
1896 * Is it possible to delete enrol instance via standard UI?
1898 * @param stdClass $instance
1899 * @return bool
1901 public function can_delete_instance($instance) {
1902 return false;
1906 * Is it possible to hide/show enrol instance via standard UI?
1908 * @param stdClass $instance
1909 * @return bool
1911 public function can_hide_show_instance($instance) {
1912 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER);
1913 return true;
1917 * Returns link to manual enrol UI if exists.
1918 * Does the access control tests automatically.
1920 * @param object $instance
1921 * @return moodle_url
1923 public function get_manual_enrol_link($instance) {
1924 return NULL;
1928 * Returns list of unenrol links for all enrol instances in course.
1930 * @param int $instance
1931 * @return moodle_url or NULL if self unenrolment not supported
1933 public function get_unenrolself_link($instance) {
1934 global $USER, $CFG, $DB;
1936 $name = $this->get_name();
1937 if ($instance->enrol !== $name) {
1938 throw new coding_exception('invalid enrol instance!');
1941 if ($instance->courseid == SITEID) {
1942 return NULL;
1945 if (!enrol_is_enabled($name)) {
1946 return NULL;
1949 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1950 return NULL;
1953 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1954 return NULL;
1957 $context = context_course::instance($instance->courseid, MUST_EXIST);
1959 if (!has_capability("enrol/$name:unenrolself", $context)) {
1960 return NULL;
1963 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1964 return NULL;
1967 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
1971 * Adds enrol instance UI to course edit form
1973 * @param object $instance enrol instance or null if does not exist yet
1974 * @param MoodleQuickForm $mform
1975 * @param object $data
1976 * @param object $context context of existing course or parent category if course does not exist
1977 * @return void
1979 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1980 // override - usually at least enable/disable switch, has to add own form header
1984 * Adds form elements to add/edit instance form.
1986 * @since Moodle 3.1
1987 * @param object $instance enrol instance or null if does not exist yet
1988 * @param MoodleQuickForm $mform
1989 * @param context $context
1990 * @return void
1992 public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
1993 // Do nothing by default.
1997 * Perform custom validation of the data used to edit the instance.
1999 * @since Moodle 3.1
2000 * @param array $data array of ("fieldname"=>value) of submitted data
2001 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2002 * @param object $instance The instance data loaded from the DB.
2003 * @param context $context The context of the instance we are editing
2004 * @return array of "element_name"=>"error_description" if there are errors,
2005 * or an empty array if everything is OK.
2007 public function edit_instance_validation($data, $files, $instance, $context) {
2008 // No errors by default.
2009 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER);
2010 return array();
2014 * Validates course edit form data
2016 * @param object $instance enrol instance or null if does not exist yet
2017 * @param array $data
2018 * @param object $context context of existing course or parent category if course does not exist
2019 * @return array errors array
2021 public function course_edit_validation($instance, array $data, $context) {
2022 return array();
2026 * Called after updating/inserting course.
2028 * @param bool $inserted true if course just inserted
2029 * @param object $course
2030 * @param object $data form data
2031 * @return void
2033 public function course_updated($inserted, $course, $data) {
2034 if ($inserted) {
2035 if ($this->get_config('defaultenrol')) {
2036 $this->add_default_instance($course);
2042 * Add new instance of enrol plugin.
2043 * @param object $course
2044 * @param array instance fields
2045 * @return int id of new instance, null if can not be created
2047 public function add_instance($course, array $fields = NULL) {
2048 global $DB;
2050 if ($course->id == SITEID) {
2051 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2054 $instance = new stdClass();
2055 $instance->enrol = $this->get_name();
2056 $instance->status = ENROL_INSTANCE_ENABLED;
2057 $instance->courseid = $course->id;
2058 $instance->enrolstartdate = 0;
2059 $instance->enrolenddate = 0;
2060 $instance->timemodified = time();
2061 $instance->timecreated = $instance->timemodified;
2062 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
2064 $fields = (array)$fields;
2065 unset($fields['enrol']);
2066 unset($fields['courseid']);
2067 unset($fields['sortorder']);
2068 foreach($fields as $field=>$value) {
2069 $instance->$field = $value;
2072 $instance->id = $DB->insert_record('enrol', $instance);
2074 \core\event\enrol_instance_created::create_from_record($instance)->trigger();
2076 return $instance->id;
2080 * Update instance of enrol plugin.
2082 * @since Moodle 3.1
2083 * @param stdClass $instance
2084 * @param stdClass $data modified instance fields
2085 * @return boolean
2087 public function update_instance($instance, $data) {
2088 global $DB;
2089 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2090 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2091 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2092 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2093 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2094 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2096 foreach ($properties as $key) {
2097 if (isset($data->$key)) {
2098 $instance->$key = $data->$key;
2101 $instance->timemodified = time();
2103 $update = $DB->update_record('enrol', $instance);
2104 if ($update) {
2105 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2107 return $update;
2111 * Add new instance of enrol plugin with default settings,
2112 * called when adding new instance manually or when adding new course.
2114 * Not all plugins support this.
2116 * @param object $course
2117 * @return int id of new instance or null if no default supported
2119 public function add_default_instance($course) {
2120 return null;
2124 * Update instance status
2126 * Override when plugin needs to do some action when enabled or disabled.
2128 * @param stdClass $instance
2129 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2130 * @return void
2132 public function update_status($instance, $newstatus) {
2133 global $DB;
2135 $instance->status = $newstatus;
2136 $DB->update_record('enrol', $instance);
2138 $context = context_course::instance($instance->courseid);
2139 \core\event\enrol_instance_updated::create_from_record($instance)->trigger();
2141 // Invalidate all enrol caches.
2142 $context->mark_dirty();
2146 * Delete course enrol plugin instance, unenrol all users.
2147 * @param object $instance
2148 * @return void
2150 public function delete_instance($instance) {
2151 global $DB;
2153 $name = $this->get_name();
2154 if ($instance->enrol !== $name) {
2155 throw new coding_exception('invalid enrol instance!');
2158 //first unenrol all users
2159 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
2160 foreach ($participants as $participant) {
2161 $this->unenrol_user($instance, $participant->userid);
2163 $participants->close();
2165 // now clean up all remainders that were not removed correctly
2166 $DB->delete_records('groups_members', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
2167 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
2168 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
2170 // finally drop the enrol row
2171 $DB->delete_records('enrol', array('id'=>$instance->id));
2173 $context = context_course::instance($instance->courseid);
2174 \core\event\enrol_instance_deleted::create_from_record($instance)->trigger();
2176 // Invalidate all enrol caches.
2177 $context->mark_dirty();
2181 * Creates course enrol form, checks if form submitted
2182 * and enrols user if necessary. It can also redirect.
2184 * @param stdClass $instance
2185 * @return string html text, usually a form in a text box
2187 public function enrol_page_hook(stdClass $instance) {
2188 return null;
2192 * Checks if user can self enrol.
2194 * @param stdClass $instance enrolment instance
2195 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2196 * used by navigation to improve performance.
2197 * @return bool|string true if successful, else error message or false
2199 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
2200 return false;
2204 * Return information for enrolment instance containing list of parameters required
2205 * for enrolment, name of enrolment plugin etc.
2207 * @param stdClass $instance enrolment instance
2208 * @return array instance info.
2210 public function get_enrol_info(stdClass $instance) {
2211 return null;
2215 * Adds navigation links into course admin block.
2217 * By defaults looks for manage links only.
2219 * @param navigation_node $instancesnode
2220 * @param stdClass $instance
2221 * @return void
2223 public function add_course_navigation($instancesnode, stdClass $instance) {
2224 if ($this->use_standard_editing_ui()) {
2225 $context = context_course::instance($instance->courseid);
2226 $cap = 'enrol/' . $instance->enrol . ':config';
2227 if (has_capability($cap, $context)) {
2228 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2229 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2230 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node::TYPE_SETTING);
2236 * Returns edit icons for the page with list of instances
2237 * @param stdClass $instance
2238 * @return array
2240 public function get_action_icons(stdClass $instance) {
2241 global $OUTPUT;
2243 $icons = array();
2244 if ($this->use_standard_editing_ui()) {
2245 $linkparams = array('courseid' => $instance->courseid, 'id' => $instance->id, 'type' => $instance->enrol);
2246 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2247 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2248 array('class' => 'iconsmall')));
2250 return $icons;
2254 * Reads version.php and determines if it is necessary
2255 * to execute the cron job now.
2256 * @return bool
2258 public function is_cron_required() {
2259 global $CFG;
2261 $name = $this->get_name();
2262 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2263 $plugin = new stdClass();
2264 include($versionfile);
2265 if (empty($plugin->cron)) {
2266 return false;
2268 $lastexecuted = $this->get_config('lastcron', 0);
2269 if ($lastexecuted + $plugin->cron < time()) {
2270 return true;
2271 } else {
2272 return false;
2277 * Called for all enabled enrol plugins that returned true from is_cron_required().
2278 * @return void
2280 public function cron() {
2284 * Called when user is about to be deleted
2285 * @param object $user
2286 * @return void
2288 public function user_delete($user) {
2289 global $DB;
2291 $sql = "SELECT e.*
2292 FROM {enrol} e
2293 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2294 WHERE e.enrol = :name AND ue.userid = :userid";
2295 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
2297 $rs = $DB->get_recordset_sql($sql, $params);
2298 foreach($rs as $instance) {
2299 $this->unenrol_user($instance, $user->id);
2301 $rs->close();
2305 * Returns an enrol_user_button that takes the user to a page where they are able to
2306 * enrol users into the managers course through this plugin.
2308 * Optional: If the plugin supports manual enrolments it can choose to override this
2309 * otherwise it shouldn't
2311 * @param course_enrolment_manager $manager
2312 * @return enrol_user_button|false
2314 public function get_manual_enrol_button(course_enrolment_manager $manager) {
2315 return false;
2319 * Gets an array of the user enrolment actions
2321 * @param course_enrolment_manager $manager
2322 * @param stdClass $ue
2323 * @return array An array of user_enrolment_actions
2325 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
2326 return array();
2330 * Returns true if the plugin has one or more bulk operations that can be performed on
2331 * user enrolments.
2333 * @param course_enrolment_manager $manager
2334 * @return bool
2336 public function has_bulk_operations(course_enrolment_manager $manager) {
2337 return false;
2341 * Return an array of enrol_bulk_enrolment_operation objects that define
2342 * the bulk actions that can be performed on user enrolments by the plugin.
2344 * @param course_enrolment_manager $manager
2345 * @return array
2347 public function get_bulk_operations(course_enrolment_manager $manager) {
2348 return array();
2352 * Do any enrolments need expiration processing.
2354 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2356 * @param progress_trace $trace
2357 * @param int $courseid one course, empty mean all
2358 * @return bool true if any data processed, false if not
2360 public function process_expirations(progress_trace $trace, $courseid = null) {
2361 global $DB;
2363 $name = $this->get_name();
2364 if (!enrol_is_enabled($name)) {
2365 $trace->finished();
2366 return false;
2369 $processed = false;
2370 $params = array();
2371 $coursesql = "";
2372 if ($courseid) {
2373 $coursesql = "AND e.courseid = :courseid";
2376 // Deal with expired accounts.
2377 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
2379 if ($action == ENROL_EXT_REMOVED_UNENROL) {
2380 $instances = array();
2381 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2382 FROM {user_enrolments} ue
2383 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2384 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2385 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2386 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
2388 $rs = $DB->get_recordset_sql($sql, $params);
2389 foreach ($rs as $ue) {
2390 if (!$processed) {
2391 $trace->output("Starting processing of enrol_$name expirations...");
2392 $processed = true;
2394 if (empty($instances[$ue->enrolid])) {
2395 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2397 $instance = $instances[$ue->enrolid];
2398 if (!$this->roles_protected()) {
2399 // Let's just guess what extra roles are supposed to be removed.
2400 if ($instance->roleid) {
2401 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
2404 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2405 $this->unenrol_user($instance, $ue->userid);
2406 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2408 $rs->close();
2409 unset($instances);
2411 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
2412 $instances = array();
2413 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2414 FROM {user_enrolments} ue
2415 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2416 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2417 WHERE ue.timeend > 0 AND ue.timeend < :now
2418 AND ue.status = :useractive $coursesql";
2419 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
2420 $rs = $DB->get_recordset_sql($sql, $params);
2421 foreach ($rs as $ue) {
2422 if (!$processed) {
2423 $trace->output("Starting processing of enrol_$name expirations...");
2424 $processed = true;
2426 if (empty($instances[$ue->enrolid])) {
2427 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
2429 $instance = $instances[$ue->enrolid];
2431 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
2432 if (!$this->roles_protected()) {
2433 // Let's just guess what roles should be removed.
2434 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
2435 if ($count == 1) {
2436 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
2438 } else if ($count > 1 and $instance->roleid) {
2439 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
2442 // In any case remove all roles that belong to this instance and user.
2443 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
2444 // Final cleanup of subcontexts if there are no more course roles.
2445 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
2446 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
2450 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
2451 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2453 $rs->close();
2454 unset($instances);
2456 } else {
2457 // ENROL_EXT_REMOVED_KEEP means no changes.
2460 if ($processed) {
2461 $trace->output("...finished processing of enrol_$name expirations");
2462 } else {
2463 $trace->output("No expired enrol_$name enrolments detected");
2465 $trace->finished();
2467 return $processed;
2471 * Send expiry notifications.
2473 * Plugin that wants to have expiry notification MUST implement following:
2474 * - expirynotifyhour plugin setting,
2475 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2476 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2477 * expirymessageenrolledsubject and expirymessageenrolledbody),
2478 * - expiry_notification provider in db/messages.php,
2479 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2480 * - something that calls this method, such as cron.
2482 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2484 public function send_expiry_notifications($trace) {
2485 global $DB, $CFG;
2487 $name = $this->get_name();
2488 if (!enrol_is_enabled($name)) {
2489 $trace->finished();
2490 return;
2493 // Unfortunately this may take a long time, it should not be interrupted,
2494 // otherwise users get duplicate notification.
2496 core_php_time_limit::raise();
2497 raise_memory_limit(MEMORY_HUGE);
2500 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2501 $expirynotifyhour = $this->get_config('expirynotifyhour');
2502 if (is_null($expirynotifyhour)) {
2503 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
2504 $trace->finished();
2505 return;
2508 if (!($trace instanceof progress_trace)) {
2509 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
2510 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
2513 $timenow = time();
2514 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
2516 if ($expirynotifylast > $notifytime) {
2517 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
2518 $trace->finished();
2519 return;
2521 } else if ($timenow < $notifytime) {
2522 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
2523 $trace->finished();
2524 return;
2527 $trace->output('Processing '.$name.' enrolment expiration notifications...');
2529 // Notify users responsible for enrolment once every day.
2530 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2531 FROM {user_enrolments} ue
2532 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2533 JOIN {course} c ON (c.id = e.courseid)
2534 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2535 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2536 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2537 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2539 $rs = $DB->get_recordset_sql($sql, $params);
2541 $lastenrollid = 0;
2542 $users = array();
2544 foreach($rs as $ue) {
2545 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
2546 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2547 $users = array();
2549 $lastenrollid = $ue->enrolid;
2551 $enroller = $this->get_enroller($ue->enrolid);
2552 $context = context_course::instance($ue->courseid);
2554 $user = $DB->get_record('user', array('id'=>$ue->userid));
2556 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
2558 if (!$ue->notifyall) {
2559 continue;
2562 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
2563 // Notify enrolled users only once at the start of the threshold.
2564 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2565 continue;
2568 $this->notify_expiry_enrolled($user, $ue, $trace);
2570 $rs->close();
2572 if ($lastenrollid and $users) {
2573 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2576 $trace->output('...notification processing finished.');
2577 $trace->finished();
2579 $this->set_config('expirynotifylast', $timenow);
2583 * Returns the user who is responsible for enrolments for given instance.
2585 * Override if plugin knows anybody better than admin.
2587 * @param int $instanceid enrolment instance id
2588 * @return stdClass user record
2590 protected function get_enroller($instanceid) {
2591 return get_admin();
2595 * Notify user about incoming expiration of their enrolment,
2596 * it is called only if notification of enrolled users (aka students) is enabled in course.
2598 * This is executed only once for each expiring enrolment right
2599 * at the start of the expiration threshold.
2601 * @param stdClass $user
2602 * @param stdClass $ue
2603 * @param progress_trace $trace
2605 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
2606 global $CFG;
2608 $name = $this->get_name();
2610 $oldforcelang = force_current_language($user->lang);
2612 $enroller = $this->get_enroller($ue->enrolid);
2613 $context = context_course::instance($ue->courseid);
2615 $a = new stdClass();
2616 $a->course = format_string($ue->fullname, true, array('context'=>$context));
2617 $a->user = fullname($user, true);
2618 $a->timeend = userdate($ue->timeend, '', $user->timezone);
2619 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
2621 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
2622 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
2624 $message = new stdClass();
2625 $message->notification = 1;
2626 $message->component = 'enrol_'.$name;
2627 $message->name = 'expiry_notification';
2628 $message->userfrom = $enroller;
2629 $message->userto = $user;
2630 $message->subject = $subject;
2631 $message->fullmessage = $body;
2632 $message->fullmessageformat = FORMAT_MARKDOWN;
2633 $message->fullmessagehtml = markdown_to_html($body);
2634 $message->smallmessage = $subject;
2635 $message->contexturlname = $a->course;
2636 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
2638 if (message_send($message)) {
2639 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2640 } else {
2641 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2644 force_current_language($oldforcelang);
2648 * Notify person responsible for enrolments that some user enrolments will be expired soon,
2649 * it is called only if notification of enrollers (aka teachers) is enabled in course.
2651 * This is called repeatedly every day for each course if there are any pending expiration
2652 * in the expiration threshold.
2654 * @param int $eid
2655 * @param array $users
2656 * @param progress_trace $trace
2658 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
2659 global $DB;
2661 $name = $this->get_name();
2663 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
2664 $context = context_course::instance($instance->courseid);
2665 $course = $DB->get_record('course', array('id'=>$instance->courseid));
2667 $enroller = $this->get_enroller($instance->id);
2668 $admin = get_admin();
2670 $oldforcelang = force_current_language($enroller->lang);
2672 foreach($users as $key=>$info) {
2673 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
2676 $a = new stdClass();
2677 $a->course = format_string($course->fullname, true, array('context'=>$context));
2678 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
2679 $a->users = implode("\n", $users);
2680 $a->extendurl = (string)new moodle_url('/enrol/users.php', array('id'=>$instance->courseid));
2682 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
2683 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
2685 $message = new stdClass();
2686 $message->notification = 1;
2687 $message->component = 'enrol_'.$name;
2688 $message->name = 'expiry_notification';
2689 $message->userfrom = $admin;
2690 $message->userto = $enroller;
2691 $message->subject = $subject;
2692 $message->fullmessage = $body;
2693 $message->fullmessageformat = FORMAT_MARKDOWN;
2694 $message->fullmessagehtml = markdown_to_html($body);
2695 $message->smallmessage = $subject;
2696 $message->contexturlname = $a->course;
2697 $message->contexturl = $a->extendurl;
2699 if (message_send($message)) {
2700 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
2701 } else {
2702 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
2705 force_current_language($oldforcelang);
2709 * Backup execution step hook to annotate custom fields.
2711 * @param backup_enrolments_execution_step $step
2712 * @param stdClass $enrol
2714 public function backup_annotate_custom_fields(backup_enrolments_execution_step $step, stdClass $enrol) {
2715 // Override as necessary to annotate custom fields in the enrol table.
2719 * Automatic enrol sync executed during restore.
2720 * Useful for automatic sync by course->idnumber or course category.
2721 * @param stdClass $course course record
2723 public function restore_sync_course($course) {
2724 // Override if necessary.
2728 * Restore instance and map settings.
2730 * @param restore_enrolments_structure_step $step
2731 * @param stdClass $data
2732 * @param stdClass $course
2733 * @param int $oldid
2735 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
2736 // Do not call this from overridden methods, restore and set new id there.
2737 $step->set_mapping('enrol', $oldid, 0);
2741 * Restore user enrolment.
2743 * @param restore_enrolments_structure_step $step
2744 * @param stdClass $data
2745 * @param stdClass $instance
2746 * @param int $oldinstancestatus
2747 * @param int $userid
2749 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
2750 // Override as necessary if plugin supports restore of enrolments.
2754 * Restore role assignment.
2756 * @param stdClass $instance
2757 * @param int $roleid
2758 * @param int $userid
2759 * @param int $contextid
2761 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
2762 // No role assignment by default, override if necessary.
2766 * Restore user group membership.
2767 * @param stdClass $instance
2768 * @param int $groupid
2769 * @param int $userid
2771 public function restore_group_member($instance, $groupid, $userid) {
2772 // Implement if you want to restore protected group memberships,
2773 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
2777 * Returns defaults for new instances.
2778 * @since Moodle 3.1
2779 * @return array
2781 public function get_instance_defaults() {
2782 return array();
2786 * Validate a list of parameter names and types.
2787 * @since Moodle 3.1
2789 * @param array $data array of ("fieldname"=>value) of submitted data
2790 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
2791 * @return array of "element_name"=>"error_description" if there are errors,
2792 * or an empty array if everything is OK.
2794 public function validate_param_types($data, $rules) {
2795 $errors = array();
2796 $invalidstr = get_string('invaliddata', 'error');
2797 foreach ($rules as $fieldname => $rule) {
2798 if (is_array($rule)) {
2799 if (!in_array($data[$fieldname], $rule)) {
2800 $errors[$fieldname] = $invalidstr;
2802 } else {
2803 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
2804 $errors[$fieldname] = $invalidstr;
2808 return $errors;