Merge branch 'MDL-38487_23' of git://github.com/timhunt/moodle into MOODLE_23_STABLE
[moodle.git] / lib / enrollib.php
blobbb609fc7c7f6c6bb210f93909f1a4a25c0e60c7e
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 /** enrol plugin feature describing requested restore type */
55 define('ENROL_RESTORE_TYPE', 'enrolrestore');
56 /** User custom backup/restore class stored in backup/moodle2/ subdirectory */
57 define('ENROL_RESTORE_CLASS', 'class');
58 /** Restore all custom fields from enrol table without any changes and all user_enrolments records */
59 define('ENROL_RESTORE_EXACT', 'exact');
60 /** Restore enrol record like ENROL_RESTORE_EXACT, but no user enrolments */
61 define('ENROL_RESTORE_NOUSERS', 'nousers');
63 /**
64 * When user disappears from external source, user enrolment is suspended, roles are kept as is.
65 * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook,
66 * assignments, etc.
68 define('ENROL_EXT_REMOVED_SUSPEND', 2);
70 /**
71 * When user disappears from external source, the enrolment is suspended and roles assigned
72 * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas.
73 * */
74 define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
76 /**
77 * Returns instances of enrol plugins
78 * @param bool $enabled return enabled only
79 * @return array of enrol plugins name=>instance
81 function enrol_get_plugins($enabled) {
82 global $CFG;
84 $result = array();
86 if ($enabled) {
87 // sorted by enabled plugin order
88 $enabled = explode(',', $CFG->enrol_plugins_enabled);
89 $plugins = array();
90 foreach ($enabled as $plugin) {
91 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
93 } else {
94 // sorted alphabetically
95 $plugins = get_plugin_list('enrol');
96 ksort($plugins);
99 foreach ($plugins as $plugin=>$location) {
100 if (!file_exists("$location/lib.php")) {
101 continue;
103 include_once("$location/lib.php");
104 $class = "enrol_{$plugin}_plugin";
105 if (!class_exists($class)) {
106 continue;
109 $result[$plugin] = new $class();
112 return $result;
116 * Returns instance of enrol plugin
117 * @param string $name name of enrol plugin ('manual', 'guest', ...)
118 * @return enrol_plugin
120 function enrol_get_plugin($name) {
121 global $CFG;
123 $name = clean_param($name, PARAM_PLUGIN);
125 if (empty($name)) {
126 // ignore malformed or missing plugin names completely
127 return null;
130 $location = "$CFG->dirroot/enrol/$name";
132 if (!file_exists("$location/lib.php")) {
133 return null;
135 include_once("$location/lib.php");
136 $class = "enrol_{$name}_plugin";
137 if (!class_exists($class)) {
138 return null;
141 return new $class();
145 * Returns enrolment instances in given course.
146 * @param int $courseid
147 * @param bool $enabled
148 * @return array of enrol instances
150 function enrol_get_instances($courseid, $enabled) {
151 global $DB, $CFG;
153 if (!$enabled) {
154 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
157 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
159 $enabled = explode(',', $CFG->enrol_plugins_enabled);
160 foreach ($result as $key=>$instance) {
161 if (!in_array($instance->enrol, $enabled)) {
162 unset($result[$key]);
163 continue;
165 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
166 // broken plugin
167 unset($result[$key]);
168 continue;
172 return $result;
176 * Checks if a given plugin is in the list of enabled enrolment plugins.
178 * @param string $enrol Enrolment plugin name
179 * @return boolean Whether the plugin is enabled
181 function enrol_is_enabled($enrol) {
182 global $CFG;
184 if (empty($CFG->enrol_plugins_enabled)) {
185 return false;
187 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
191 * Check all the login enrolment information for the given user object
192 * by querying the enrolment plugins
194 * This function may be very slow, use only once after log-in or login-as.
196 * @param stdClass $user
197 * @return void
199 function enrol_check_plugins($user) {
200 global $CFG;
202 if (empty($user->id) or isguestuser($user)) {
203 // shortcut - there is no enrolment work for guests and not-logged-in users
204 return;
207 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
208 // which proved it was actually not necessary.
210 static $inprogress = array(); // To prevent this function being called more than once in an invocation
212 if (!empty($inprogress[$user->id])) {
213 return;
216 $inprogress[$user->id] = true; // Set the flag
218 $enabled = enrol_get_plugins(true);
220 foreach($enabled as $enrol) {
221 $enrol->sync_user_enrolments($user);
224 unset($inprogress[$user->id]); // Unset the flag
228 * Do these two students share any course?
230 * The courses has to be visible and enrolments has to be active,
231 * timestart and timeend restrictions are ignored.
233 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
234 * to true.
236 * @param stdClass|int $user1
237 * @param stdClass|int $user2
238 * @return bool
240 function enrol_sharing_course($user1, $user2) {
241 return enrol_get_shared_courses($user1, $user2, false, true);
245 * Returns any courses shared by the two users
247 * The courses has to be visible and enrolments has to be active,
248 * timestart and timeend restrictions are ignored.
250 * @global moodle_database $DB
251 * @param stdClass|int $user1
252 * @param stdClass|int $user2
253 * @param bool $preloadcontexts If set to true contexts for the returned courses
254 * will be preloaded.
255 * @param bool $checkexistsonly If set to true then this function will return true
256 * if the users share any courses and false if not.
257 * @return array|bool An array of courses that both users are enrolled in OR if
258 * $checkexistsonly set returns true if the users share any courses
259 * and false if not.
261 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
262 global $DB, $CFG;
264 $user1 = isset($user1->id) ? $user1->id : $user1;
265 $user2 = isset($user2->id) ? $user2->id : $user2;
267 if (empty($user1) or empty($user2)) {
268 return false;
271 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
272 return false;
275 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
276 $params['enabled'] = ENROL_INSTANCE_ENABLED;
277 $params['active1'] = ENROL_USER_ACTIVE;
278 $params['active2'] = ENROL_USER_ACTIVE;
279 $params['user1'] = $user1;
280 $params['user2'] = $user2;
282 $ctxselect = '';
283 $ctxjoin = '';
284 if ($preloadcontexts) {
285 list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
288 $sql = "SELECT c.* $ctxselect
289 FROM {course} c
290 JOIN (
291 SELECT DISTINCT c.id
292 FROM {enrol} e
293 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
294 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2)
295 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
296 WHERE e.status = :enabled AND e.enrol $plugins
297 ) ec ON ec.id = c.id
298 $ctxjoin";
300 if ($checkexistsonly) {
301 return $DB->record_exists_sql($sql, $params);
302 } else {
303 $courses = $DB->get_records_sql($sql, $params);
304 if ($preloadcontexts) {
305 array_map('context_instance_preload', $courses);
307 return $courses;
312 * This function adds necessary enrol plugins UI into the course edit form.
314 * @param MoodleQuickForm $mform
315 * @param object $data course edit form data
316 * @param object $context context of existing course or parent category if course does not exist
317 * @return void
319 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
320 $plugins = enrol_get_plugins(true);
321 if (!empty($data->id)) {
322 $instances = enrol_get_instances($data->id, false);
323 foreach ($instances as $instance) {
324 if (!isset($plugins[$instance->enrol])) {
325 continue;
327 $plugin = $plugins[$instance->enrol];
328 $plugin->course_edit_form($instance, $mform, $data, $context);
330 } else {
331 foreach ($plugins as $plugin) {
332 $plugin->course_edit_form(NULL, $mform, $data, $context);
338 * Validate course edit form data
340 * @param array $data raw form data
341 * @param object $context context of existing course or parent category if course does not exist
342 * @return array errors array
344 function enrol_course_edit_validation(array $data, $context) {
345 $errors = array();
346 $plugins = enrol_get_plugins(true);
348 if (!empty($data['id'])) {
349 $instances = enrol_get_instances($data['id'], false);
350 foreach ($instances as $instance) {
351 if (!isset($plugins[$instance->enrol])) {
352 continue;
354 $plugin = $plugins[$instance->enrol];
355 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
357 } else {
358 foreach ($plugins as $plugin) {
359 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
363 return $errors;
367 * Update enrol instances after course edit form submission
368 * @param bool $inserted true means new course added, false course already existed
369 * @param object $course
370 * @param object $data form data
371 * @return void
373 function enrol_course_updated($inserted, $course, $data) {
374 global $DB, $CFG;
376 $plugins = enrol_get_plugins(true);
378 foreach ($plugins as $plugin) {
379 $plugin->course_updated($inserted, $course, $data);
384 * Add navigation nodes
385 * @param navigation_node $coursenode
386 * @param object $course
387 * @return void
389 function enrol_add_course_navigation(navigation_node $coursenode, $course) {
390 global $CFG;
392 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
394 $instances = enrol_get_instances($course->id, true);
395 $plugins = enrol_get_plugins(true);
397 // we do not want to break all course pages if there is some borked enrol plugin, right?
398 foreach ($instances as $k=>$instance) {
399 if (!isset($plugins[$instance->enrol])) {
400 unset($instances[$k]);
404 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
406 if ($course->id != SITEID) {
407 // list all participants - allows assigning roles, groups, etc.
408 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
409 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
410 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/users', ''));
413 // manage enrol plugin instances
414 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
415 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
416 } else {
417 $url = NULL;
419 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
421 // each instance decides how to configure itself or how many other nav items are exposed
422 foreach ($instances as $instance) {
423 if (!isset($plugins[$instance->enrol])) {
424 continue;
426 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
429 if (!$url) {
430 $instancesnode->trim_if_empty();
434 // Manage groups in this course or even frontpage
435 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
436 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
437 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
440 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
441 // Override roles
442 if (has_capability('moodle/role:review', $coursecontext)) {
443 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
444 } else {
445 $url = NULL;
447 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
449 // Add assign or override roles if allowed
450 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
451 if (has_capability('moodle/role:assign', $coursecontext)) {
452 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
453 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
456 // Check role permissions
457 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
458 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
459 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
463 // Deal somehow with users that are not enrolled but still got a role somehow
464 if ($course->id != SITEID) {
465 //TODO, create some new UI for role assignments at course level
466 if (has_capability('moodle/role:assign', $coursecontext)) {
467 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
468 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/roles', ''));
472 // just in case nothing was actually added
473 $usersnode->trim_if_empty();
475 if ($course->id != SITEID) {
476 if (isguestuser() or !isloggedin()) {
477 // guest account can not be enrolled - no links for them
478 } else if (is_enrolled($coursecontext)) {
479 // unenrol link if possible
480 foreach ($instances as $instance) {
481 if (!isset($plugins[$instance->enrol])) {
482 continue;
484 $plugin = $plugins[$instance->enrol];
485 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
486 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
487 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
488 break;
489 //TODO. deal with multiple unenrol links - not likely case, but still...
492 } else {
493 // enrol link if possible
494 if (is_viewing($coursecontext)) {
495 // better not show any enrol link, this is intended for managers and inspectors
496 } else {
497 foreach ($instances as $instance) {
498 if (!isset($plugins[$instance->enrol])) {
499 continue;
501 $plugin = $plugins[$instance->enrol];
502 if ($plugin->show_enrolme_link($instance)) {
503 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
504 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
505 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
506 break;
515 * Returns list of courses current $USER is enrolled in and can access
517 * - $fields is an array of field names to ADD
518 * so name the fields you really need, which will
519 * be added and uniq'd
521 * @param string|array $fields
522 * @param string $sort
523 * @param int $limit max number of courses
524 * @return array
526 function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
527 global $DB, $USER;
529 // Guest account does not have any courses
530 if (isguestuser() or !isloggedin()) {
531 return(array());
534 $basefields = array('id', 'category', 'sortorder',
535 'shortname', 'fullname', 'idnumber',
536 'startdate', 'visible',
537 'groupmode', 'groupmodeforce');
539 if (empty($fields)) {
540 $fields = $basefields;
541 } else if (is_string($fields)) {
542 // turn the fields from a string to an array
543 $fields = explode(',', $fields);
544 $fields = array_map('trim', $fields);
545 $fields = array_unique(array_merge($basefields, $fields));
546 } else if (is_array($fields)) {
547 $fields = array_unique(array_merge($basefields, $fields));
548 } else {
549 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
551 if (in_array('*', $fields)) {
552 $fields = array('*');
555 $orderby = "";
556 $sort = trim($sort);
557 if (!empty($sort)) {
558 $rawsorts = explode(',', $sort);
559 $sorts = array();
560 foreach ($rawsorts as $rawsort) {
561 $rawsort = trim($rawsort);
562 if (strpos($rawsort, 'c.') === 0) {
563 $rawsort = substr($rawsort, 2);
565 $sorts[] = trim($rawsort);
567 $sort = 'c.'.implode(',c.', $sorts);
568 $orderby = "ORDER BY $sort";
571 $wheres = array("c.id <> :siteid");
572 $params = array('siteid'=>SITEID);
574 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
575 // list _only_ this course - anything else is asking for trouble...
576 $wheres[] = "courseid = :loginas";
577 $params['loginas'] = $USER->loginascontext->instanceid;
580 $coursefields = 'c.' .join(',c.', $fields);
581 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
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_instance_preload($course);
606 if (!$course->visible) {
607 if (!$context = get_context_instance(CONTEXT_COURSE, $id)) {
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_instance_preload($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 * Returns list of courses user is enrolled into without any capability checks
721 * - $fields is an array of fieldnames to ADD
722 * so name the fields you really need, which will
723 * be added and uniq'd
725 * @param int $userid
726 * @param bool $onlyactive return only active enrolments in courses user may see
727 * @param string|array $fields
728 * @param string $sort
729 * @return array
731 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
732 global $DB;
734 // Guest account does not have any courses
735 if (isguestuser($userid) or empty($userid)) {
736 return(array());
739 $basefields = array('id', 'category', 'sortorder',
740 'shortname', 'fullname', 'idnumber',
741 'startdate', 'visible',
742 'groupmode', 'groupmodeforce');
744 if (empty($fields)) {
745 $fields = $basefields;
746 } else if (is_string($fields)) {
747 // turn the fields from a string to an array
748 $fields = explode(',', $fields);
749 $fields = array_map('trim', $fields);
750 $fields = array_unique(array_merge($basefields, $fields));
751 } else if (is_array($fields)) {
752 $fields = array_unique(array_merge($basefields, $fields));
753 } else {
754 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
756 if (in_array('*', $fields)) {
757 $fields = array('*');
760 $orderby = "";
761 $sort = trim($sort);
762 if (!empty($sort)) {
763 $rawsorts = explode(',', $sort);
764 $sorts = array();
765 foreach ($rawsorts as $rawsort) {
766 $rawsort = trim($rawsort);
767 if (strpos($rawsort, 'c.') === 0) {
768 $rawsort = substr($rawsort, 2);
770 $sorts[] = trim($rawsort);
772 $sort = 'c.'.implode(',c.', $sorts);
773 $orderby = "ORDER BY $sort";
776 $params = array('siteid'=>SITEID);
778 if ($onlyactive) {
779 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
780 $params['now1'] = round(time(), -2); // improves db caching
781 $params['now2'] = $params['now1'];
782 $params['active'] = ENROL_USER_ACTIVE;
783 $params['enabled'] = ENROL_INSTANCE_ENABLED;
784 } else {
785 $subwhere = "";
788 $coursefields = 'c.' .join(',c.', $fields);
789 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
791 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
792 $sql = "SELECT $coursefields $ccselect
793 FROM {course} c
794 JOIN (SELECT DISTINCT e.courseid
795 FROM {enrol} e
796 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
797 $subwhere
798 ) en ON (en.courseid = c.id)
799 $ccjoin
800 WHERE c.id <> :siteid
801 $orderby";
802 $params['userid'] = $userid;
804 $courses = $DB->get_records_sql($sql, $params);
806 return $courses;
812 * Called when user is about to be deleted.
813 * @param object $user
814 * @return void
816 function enrol_user_delete($user) {
817 global $DB;
819 $plugins = enrol_get_plugins(true);
820 foreach ($plugins as $plugin) {
821 $plugin->user_delete($user);
824 // force cleanup of all broken enrolments
825 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
829 * Called when course is about to be deleted.
830 * @param stdClass $course
831 * @return void
833 function enrol_course_delete($course) {
834 global $DB;
836 $instances = enrol_get_instances($course->id, false);
837 $plugins = enrol_get_plugins(true);
838 foreach ($instances as $instance) {
839 if (isset($plugins[$instance->enrol])) {
840 $plugins[$instance->enrol]->delete_instance($instance);
842 // low level delete in case plugin did not do it
843 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
844 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
845 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
846 $DB->delete_records('enrol', array('id'=>$instance->id));
851 * Try to enrol user via default internal auth plugin.
853 * For now this is always using the manual enrol plugin...
855 * @param $courseid
856 * @param $userid
857 * @param $roleid
858 * @param $timestart
859 * @param $timeend
860 * @return bool success
862 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
863 global $DB;
865 //note: this is hardcoded to manual plugin for now
867 if (!enrol_is_enabled('manual')) {
868 return false;
871 if (!$enrol = enrol_get_plugin('manual')) {
872 return false;
874 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
875 return false;
877 $instance = reset($instances);
879 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
881 return true;
885 * Is there a chance users might self enrol
886 * @param int $courseid
887 * @return bool
889 function enrol_selfenrol_available($courseid) {
890 $result = false;
892 $plugins = enrol_get_plugins(true);
893 $enrolinstances = enrol_get_instances($courseid, true);
894 foreach($enrolinstances as $instance) {
895 if (!isset($plugins[$instance->enrol])) {
896 continue;
898 if ($instance->enrol === 'guest') {
899 // blacklist known temporary guest plugins
900 continue;
902 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
903 $result = true;
904 break;
908 return $result;
912 * This function returns the end of current active user enrolment.
914 * It deals correctly with multiple overlapping user enrolments.
916 * @param int $courseid
917 * @param int $userid
918 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
920 function enrol_get_enrolment_end($courseid, $userid) {
921 global $DB;
923 $sql = "SELECT ue.*
924 FROM {user_enrolments} ue
925 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
926 JOIN {user} u ON u.id = ue.userid
927 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
928 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
930 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
931 return false;
934 $changes = array();
936 foreach ($enrolments as $ue) {
937 $start = (int)$ue->timestart;
938 $end = (int)$ue->timeend;
939 if ($end != 0 and $end < $start) {
940 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
941 continue;
943 if (isset($changes[$start])) {
944 $changes[$start] = $changes[$start] + 1;
945 } else {
946 $changes[$start] = 1;
948 if ($end === 0) {
949 // no end
950 } else if (isset($changes[$end])) {
951 $changes[$end] = $changes[$end] - 1;
952 } else {
953 $changes[$end] = -1;
957 // let's sort then enrolment starts&ends and go through them chronologically,
958 // looking for current status and the next future end of enrolment
959 ksort($changes);
961 $now = time();
962 $current = 0;
963 $present = null;
965 foreach ($changes as $time => $change) {
966 if ($time > $now) {
967 if ($present === null) {
968 // we have just went past current time
969 $present = $current;
970 if ($present < 1) {
971 // no enrolment active
972 return false;
975 if ($present !== null) {
976 // we are already in the future - look for possible end
977 if ($current + $change < 1) {
978 return $time;
982 $current += $change;
985 if ($current > 0) {
986 return 0;
987 } else {
988 return false;
994 * All enrol plugins should be based on this class,
995 * this is also the main source of documentation.
997 abstract class enrol_plugin {
998 protected $config = null;
1001 * Returns name of this enrol plugin
1002 * @return string
1004 public function get_name() {
1005 // second word in class is always enrol name, sorry, no fancy plugin names with _
1006 $words = explode('_', get_class($this));
1007 return $words[1];
1011 * Returns localised name of enrol instance
1013 * @param object $instance (null is accepted too)
1014 * @return string
1016 public function get_instance_name($instance) {
1017 if (empty($instance->name)) {
1018 $enrol = $this->get_name();
1019 return get_string('pluginname', 'enrol_'.$enrol);
1020 } else {
1021 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid);
1022 return format_string($instance->name, true, array('context'=>$context));
1027 * Returns optional enrolment information icons.
1029 * This is used in course list for quick overview of enrolment options.
1031 * We are not using single instance parameter because sometimes
1032 * we might want to prevent icon repetition when multiple instances
1033 * of one type exist. One instance may also produce several icons.
1035 * @param array $instances all enrol instances of this type in one course
1036 * @return array of pix_icon
1038 public function get_info_icons(array $instances) {
1039 return array();
1043 * Returns optional enrolment instance description text.
1045 * This is used in detailed course information.
1048 * @param object $instance
1049 * @return string short html text
1051 public function get_description_text($instance) {
1052 return null;
1056 * Makes sure config is loaded and cached.
1057 * @return void
1059 protected function load_config() {
1060 if (!isset($this->config)) {
1061 $name = $this->get_name();
1062 $this->config = get_config("enrol_$name");
1067 * Returns plugin config value
1068 * @param string $name
1069 * @param string $default value if config does not exist yet
1070 * @return string value or default
1072 public function get_config($name, $default = NULL) {
1073 $this->load_config();
1074 return isset($this->config->$name) ? $this->config->$name : $default;
1078 * Sets plugin config value
1079 * @param string $name name of config
1080 * @param string $value string config value, null means delete
1081 * @return string value
1083 public function set_config($name, $value) {
1084 $pluginname = $this->get_name();
1085 $this->load_config();
1086 if ($value === NULL) {
1087 unset($this->config->$name);
1088 } else {
1089 $this->config->$name = $value;
1091 set_config($name, $value, "enrol_$pluginname");
1095 * Does this plugin assign protected roles are can they be manually removed?
1096 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1098 public function roles_protected() {
1099 return true;
1103 * Does this plugin allow manual enrolments?
1105 * @param stdClass $instance course enrol instance
1106 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1108 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1110 public function allow_enrol(stdClass $instance) {
1111 return false;
1115 * Does this plugin allow manual unenrolment of all users?
1116 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1118 * @param stdClass $instance course enrol instance
1119 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1121 public function allow_unenrol(stdClass $instance) {
1122 return false;
1126 * Does this plugin allow manual unenrolment of a specific user?
1127 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1129 * This is useful especially for synchronisation plugins that
1130 * do suspend instead of full unenrolment.
1132 * @param stdClass $instance course enrol instance
1133 * @param stdClass $ue record from user_enrolments table, specifies user
1135 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1137 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1138 return $this->allow_unenrol($instance);
1142 * Does this plugin allow manual changes in user_enrolments table?
1144 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1146 * @param stdClass $instance course enrol instance
1147 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1149 public function allow_manage(stdClass $instance) {
1150 return false;
1154 * Does this plugin support some way to user to self enrol?
1156 * @param stdClass $instance course enrol instance
1158 * @return bool - true means show "Enrol me in this course" link in course UI
1160 public function show_enrolme_link(stdClass $instance) {
1161 return false;
1165 * Attempt to automatically enrol current user in course without any interaction,
1166 * calling code has to make sure the plugin and instance are active.
1168 * This should return either a timestamp in the future or false.
1170 * @param stdClass $instance course enrol instance
1171 * @return bool|int false means not enrolled, integer means timeend
1173 public function try_autoenrol(stdClass $instance) {
1174 global $USER;
1176 return false;
1180 * Attempt to automatically gain temporary guest access to course,
1181 * calling code has to make sure the plugin and instance are active.
1183 * This should return either a timestamp in the future or false.
1185 * @param stdClass $instance course enrol instance
1186 * @return bool|int false means no guest access, integer means timeend
1188 public function try_guestaccess(stdClass $instance) {
1189 global $USER;
1191 return false;
1195 * Enrol user into course via enrol instance.
1197 * @param stdClass $instance
1198 * @param int $userid
1199 * @param int $roleid optional role id
1200 * @param int $timestart 0 means unknown
1201 * @param int $timeend 0 means forever
1202 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1203 * @return void
1205 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
1206 global $DB, $USER, $CFG; // CFG necessary!!!
1208 if ($instance->courseid == SITEID) {
1209 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1212 $name = $this->get_name();
1213 $courseid = $instance->courseid;
1215 if ($instance->enrol !== $name) {
1216 throw new coding_exception('invalid enrol instance!');
1218 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1220 $inserted = false;
1221 $updated = false;
1222 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1223 //only update if timestart or timeend or status are different.
1224 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
1225 $ue->timestart = $timestart;
1226 $ue->timeend = $timeend;
1227 if (!is_null($status)) {
1228 $ue->status = $status;
1230 $ue->modifierid = $USER->id;
1231 $ue->timemodified = time();
1232 $DB->update_record('user_enrolments', $ue);
1234 $updated = true;
1236 } else {
1237 $ue = new stdClass();
1238 $ue->enrolid = $instance->id;
1239 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
1240 $ue->userid = $userid;
1241 $ue->timestart = $timestart;
1242 $ue->timeend = $timeend;
1243 $ue->modifierid = $USER->id;
1244 $ue->timecreated = time();
1245 $ue->timemodified = $ue->timecreated;
1246 $ue->id = $DB->insert_record('user_enrolments', $ue);
1248 $inserted = true;
1251 if ($inserted) {
1252 // add extra info and trigger event
1253 $ue->courseid = $courseid;
1254 $ue->enrol = $name;
1255 events_trigger('user_enrolled', $ue);
1256 } else if ($updated) {
1257 $ue->courseid = $courseid;
1258 $ue->enrol = $name;
1259 events_trigger('user_enrol_modified', $ue);
1260 // resets current enrolment caches
1261 $context->mark_dirty();
1264 if ($roleid) {
1265 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
1266 if ($this->roles_protected()) {
1267 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1268 } else {
1269 role_assign($roleid, $userid, $context->id);
1273 // reset current user enrolment caching
1274 if ($userid == $USER->id) {
1275 if (isset($USER->enrol['enrolled'][$courseid])) {
1276 unset($USER->enrol['enrolled'][$courseid]);
1278 if (isset($USER->enrol['tempguest'][$courseid])) {
1279 unset($USER->enrol['tempguest'][$courseid]);
1280 remove_temp_course_roles($context);
1286 * Store user_enrolments changes and trigger event.
1288 * @param stdClass $instance
1289 * @param int $userid
1290 * @param int $status
1291 * @param int $timestart
1292 * @param int $timeend
1293 * @return void
1295 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1296 global $DB, $USER;
1298 $name = $this->get_name();
1300 if ($instance->enrol !== $name) {
1301 throw new coding_exception('invalid enrol instance!');
1304 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1305 // weird, user not enrolled
1306 return;
1309 $modified = false;
1310 if (isset($status) and $ue->status != $status) {
1311 $ue->status = $status;
1312 $modified = true;
1314 if (isset($timestart) and $ue->timestart != $timestart) {
1315 $ue->timestart = $timestart;
1316 $modified = true;
1318 if (isset($timeend) and $ue->timeend != $timeend) {
1319 $ue->timeend = $timeend;
1320 $modified = true;
1323 if (!$modified) {
1324 // no change
1325 return;
1328 $ue->modifierid = $USER->id;
1329 $DB->update_record('user_enrolments', $ue);
1330 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches
1332 // trigger event
1333 $ue->courseid = $instance->courseid;
1334 $ue->enrol = $instance->name;
1335 events_trigger('user_enrol_modified', $ue);
1339 * Unenrol user from course,
1340 * the last unenrolment removes all remaining roles.
1342 * @param stdClass $instance
1343 * @param int $userid
1344 * @return void
1346 public function unenrol_user(stdClass $instance, $userid) {
1347 global $CFG, $USER, $DB;
1349 $name = $this->get_name();
1350 $courseid = $instance->courseid;
1352 if ($instance->enrol !== $name) {
1353 throw new coding_exception('invalid enrol instance!');
1355 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1357 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1358 // weird, user not enrolled
1359 return;
1362 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1363 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1365 // add extra info and trigger event
1366 $ue->courseid = $courseid;
1367 $ue->enrol = $name;
1369 $sql = "SELECT 'x'
1370 FROM {user_enrolments} ue
1371 JOIN {enrol} e ON (e.id = ue.enrolid)
1372 WHERE ue.userid = :userid AND e.courseid = :courseid";
1373 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1374 $ue->lastenrol = false;
1375 events_trigger('user_unenrolled', $ue);
1376 // user still has some enrolments, no big cleanup yet
1377 } else {
1378 // the big cleanup IS necessary!
1380 require_once("$CFG->dirroot/group/lib.php");
1381 require_once("$CFG->libdir/gradelib.php");
1383 // remove all remaining roles
1384 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1386 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1387 groups_delete_group_members($courseid, $userid);
1389 grade_user_unenrol($courseid, $userid);
1391 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1393 $ue->lastenrol = true; // means user not enrolled any more
1394 events_trigger('user_unenrolled', $ue);
1397 // reset all enrol caches
1398 $context->mark_dirty();
1400 // reset current user enrolment caching
1401 if ($userid == $USER->id) {
1402 if (isset($USER->enrol['enrolled'][$courseid])) {
1403 unset($USER->enrol['enrolled'][$courseid]);
1405 if (isset($USER->enrol['tempguest'][$courseid])) {
1406 unset($USER->enrol['tempguest'][$courseid]);
1407 remove_temp_course_roles($context);
1413 * Forces synchronisation of user enrolments.
1415 * This is important especially for external enrol plugins,
1416 * this function is called for all enabled enrol plugins
1417 * right after every user login.
1419 * @param object $user user record
1420 * @return void
1422 public function sync_user_enrolments($user) {
1423 // override if necessary
1427 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1428 * @param int $courseid
1429 * @return moodle_url page url
1431 public function get_newinstance_link($courseid) {
1432 // override for most plugins, check if instance already exists in cases only one instance is supported
1433 return NULL;
1437 * Is it possible to delete enrol instance via standard UI?
1439 * @param object $instance
1440 * @return bool
1442 public function instance_deleteable($instance) {
1443 return true;
1447 * Returns link to manual enrol UI if exists.
1448 * Does the access control tests automatically.
1450 * @param object $instance
1451 * @return moodle_url
1453 public function get_manual_enrol_link($instance) {
1454 return NULL;
1458 * Returns list of unenrol links for all enrol instances in course.
1460 * @param int $instance
1461 * @return moodle_url or NULL if self unenrolment not supported
1463 public function get_unenrolself_link($instance) {
1464 global $USER, $CFG, $DB;
1466 $name = $this->get_name();
1467 if ($instance->enrol !== $name) {
1468 throw new coding_exception('invalid enrol instance!');
1471 if ($instance->courseid == SITEID) {
1472 return NULL;
1475 if (!enrol_is_enabled($name)) {
1476 return NULL;
1479 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1480 return NULL;
1483 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1484 return NULL;
1487 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1489 if (!has_capability("enrol/$name:unenrolself", $context)) {
1490 return NULL;
1493 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1494 return NULL;
1497 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1501 * Adds enrol instance UI to course edit form
1503 * @param object $instance enrol instance or null if does not exist yet
1504 * @param MoodleQuickForm $mform
1505 * @param object $data
1506 * @param object $context context of existing course or parent category if course does not exist
1507 * @return void
1509 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1510 // override - usually at least enable/disable switch, has to add own form header
1514 * Validates course edit form data
1516 * @param object $instance enrol instance or null if does not exist yet
1517 * @param array $data
1518 * @param object $context context of existing course or parent category if course does not exist
1519 * @return array errors array
1521 public function course_edit_validation($instance, array $data, $context) {
1522 return array();
1526 * Called after updating/inserting course.
1528 * @param bool $inserted true if course just inserted
1529 * @param object $course
1530 * @param object $data form data
1531 * @return void
1533 public function course_updated($inserted, $course, $data) {
1534 if ($inserted) {
1535 if ($this->get_config('defaultenrol')) {
1536 $this->add_default_instance($course);
1542 * Add new instance of enrol plugin.
1543 * @param object $course
1544 * @param array instance fields
1545 * @return int id of new instance, null if can not be created
1547 public function add_instance($course, array $fields = NULL) {
1548 global $DB;
1550 if ($course->id == SITEID) {
1551 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1554 $instance = new stdClass();
1555 $instance->enrol = $this->get_name();
1556 $instance->status = ENROL_INSTANCE_ENABLED;
1557 $instance->courseid = $course->id;
1558 $instance->enrolstartdate = 0;
1559 $instance->enrolenddate = 0;
1560 $instance->timemodified = time();
1561 $instance->timecreated = $instance->timemodified;
1562 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1564 $fields = (array)$fields;
1565 unset($fields['enrol']);
1566 unset($fields['courseid']);
1567 unset($fields['sortorder']);
1568 foreach($fields as $field=>$value) {
1569 $instance->$field = $value;
1572 return $DB->insert_record('enrol', $instance);
1576 * Add new instance of enrol plugin with default settings,
1577 * called when adding new instance manually or when adding new course.
1579 * Not all plugins support this.
1581 * @param object $course
1582 * @return int id of new instance or null if no default supported
1584 public function add_default_instance($course) {
1585 return null;
1589 * Update instance status
1591 * Override when plugin needs to do some action when enabled or disabled.
1593 * @param stdClass $instance
1594 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
1595 * @return void
1597 public function update_status($instance, $newstatus) {
1598 global $DB;
1600 $instance->status = $newstatus;
1601 $DB->update_record('enrol', $instance);
1603 // invalidate all enrol caches
1604 $context = context_course::instance($instance->courseid);
1605 $context->mark_dirty();
1609 * Delete course enrol plugin instance, unenrol all users.
1610 * @param object $instance
1611 * @return void
1613 public function delete_instance($instance) {
1614 global $DB;
1616 $name = $this->get_name();
1617 if ($instance->enrol !== $name) {
1618 throw new coding_exception('invalid enrol instance!');
1621 //first unenrol all users
1622 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1623 foreach ($participants as $participant) {
1624 $this->unenrol_user($instance, $participant->userid);
1626 $participants->close();
1628 // now clean up all remainders that were not removed correctly
1629 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
1630 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1632 // finally drop the enrol row
1633 $DB->delete_records('enrol', array('id'=>$instance->id));
1635 // invalidate all enrol caches
1636 $context = context_course::instance($instance->courseid);
1637 $context->mark_dirty();
1641 * Creates course enrol form, checks if form submitted
1642 * and enrols user if necessary. It can also redirect.
1644 * @param stdClass $instance
1645 * @return string html text, usually a form in a text box
1647 public function enrol_page_hook(stdClass $instance) {
1648 return null;
1652 * Adds navigation links into course admin block.
1654 * By defaults looks for manage links only.
1656 * @param navigation_node $instancesnode
1657 * @param stdClass $instance
1658 * @return void
1660 public function add_course_navigation($instancesnode, stdClass $instance) {
1661 // usually adds manage users
1665 * Returns edit icons for the page with list of instances
1666 * @param stdClass $instance
1667 * @return array
1669 public function get_action_icons(stdClass $instance) {
1670 return array();
1674 * Reads version.php and determines if it is necessary
1675 * to execute the cron job now.
1676 * @return bool
1678 public function is_cron_required() {
1679 global $CFG;
1681 $name = $this->get_name();
1682 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
1683 $plugin = new stdClass();
1684 include($versionfile);
1685 if (empty($plugin->cron)) {
1686 return false;
1688 $lastexecuted = $this->get_config('lastcron', 0);
1689 if ($lastexecuted + $plugin->cron < time()) {
1690 return true;
1691 } else {
1692 return false;
1697 * Called for all enabled enrol plugins that returned true from is_cron_required().
1698 * @return void
1700 public function cron() {
1704 * Called when user is about to be deleted
1705 * @param object $user
1706 * @return void
1708 public function user_delete($user) {
1709 global $DB;
1711 $sql = "SELECT e.*
1712 FROM {enrol} e
1713 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1714 WHERE e.enrol = :name AND ue.userid = :userid";
1715 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1717 $rs = $DB->get_recordset_sql($sql, $params);
1718 foreach($rs as $instance) {
1719 $this->unenrol_user($instance, $user->id);
1721 $rs->close();
1725 * Returns an enrol_user_button that takes the user to a page where they are able to
1726 * enrol users into the managers course through this plugin.
1728 * Optional: If the plugin supports manual enrolments it can choose to override this
1729 * otherwise it shouldn't
1731 * @param course_enrolment_manager $manager
1732 * @return enrol_user_button|false
1734 public function get_manual_enrol_button(course_enrolment_manager $manager) {
1735 return false;
1739 * Gets an array of the user enrolment actions
1741 * @param course_enrolment_manager $manager
1742 * @param stdClass $ue
1743 * @return array An array of user_enrolment_actions
1745 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
1746 return array();
1750 * Returns true if the plugin has one or more bulk operations that can be performed on
1751 * user enrolments.
1753 * @param course_enrolment_manager $manager
1754 * @return bool
1756 public function has_bulk_operations(course_enrolment_manager $manager) {
1757 return false;
1761 * Return an array of enrol_bulk_enrolment_operation objects that define
1762 * the bulk actions that can be performed on user enrolments by the plugin.
1764 * @param course_enrolment_manager $manager
1765 * @return array
1767 public function get_bulk_operations(course_enrolment_manager $manager) {
1768 return array();