MDL-35669 gravatar Provide default image URL to Gravatar
[moodle.git] / lib / enrollib.php
blobca626060b600365db21f982edfaa4971114f63c6
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 = get_plugin_list('enrol');
90 ksort($plugins);
93 foreach ($plugins as $plugin=>$location) {
94 if (!file_exists("$location/lib.php")) {
95 continue;
97 include_once("$location/lib.php");
98 $class = "enrol_{$plugin}_plugin";
99 if (!class_exists($class)) {
100 continue;
103 $result[$plugin] = new $class();
106 return $result;
110 * Returns instance of enrol plugin
111 * @param string $name name of enrol plugin ('manual', 'guest', ...)
112 * @return enrol_plugin
114 function enrol_get_plugin($name) {
115 global $CFG;
117 $name = clean_param($name, PARAM_PLUGIN);
119 if (empty($name)) {
120 // ignore malformed or missing plugin names completely
121 return null;
124 $location = "$CFG->dirroot/enrol/$name";
126 if (!file_exists("$location/lib.php")) {
127 return null;
129 include_once("$location/lib.php");
130 $class = "enrol_{$name}_plugin";
131 if (!class_exists($class)) {
132 return null;
135 return new $class();
139 * Returns enrolment instances in given course.
140 * @param int $courseid
141 * @param bool $enabled
142 * @return array of enrol instances
144 function enrol_get_instances($courseid, $enabled) {
145 global $DB, $CFG;
147 if (!$enabled) {
148 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
151 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
153 $enabled = explode(',', $CFG->enrol_plugins_enabled);
154 foreach ($result as $key=>$instance) {
155 if (!in_array($instance->enrol, $enabled)) {
156 unset($result[$key]);
157 continue;
159 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
160 // broken plugin
161 unset($result[$key]);
162 continue;
166 return $result;
170 * Checks if a given plugin is in the list of enabled enrolment plugins.
172 * @param string $enrol Enrolment plugin name
173 * @return boolean Whether the plugin is enabled
175 function enrol_is_enabled($enrol) {
176 global $CFG;
178 if (empty($CFG->enrol_plugins_enabled)) {
179 return false;
181 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
185 * Check all the login enrolment information for the given user object
186 * by querying the enrolment plugins
188 * This function may be very slow, use only once after log-in or login-as.
190 * @param stdClass $user
191 * @return void
193 function enrol_check_plugins($user) {
194 global $CFG;
196 if (empty($user->id) or isguestuser($user)) {
197 // shortcut - there is no enrolment work for guests and not-logged-in users
198 return;
201 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
202 // which proved it was actually not necessary.
204 static $inprogress = array(); // To prevent this function being called more than once in an invocation
206 if (!empty($inprogress[$user->id])) {
207 return;
210 $inprogress[$user->id] = true; // Set the flag
212 $enabled = enrol_get_plugins(true);
214 foreach($enabled as $enrol) {
215 $enrol->sync_user_enrolments($user);
218 unset($inprogress[$user->id]); // Unset the flag
222 * Do these two students share any course?
224 * The courses has to be visible and enrolments has to be active,
225 * timestart and timeend restrictions are ignored.
227 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
228 * to true.
230 * @param stdClass|int $user1
231 * @param stdClass|int $user2
232 * @return bool
234 function enrol_sharing_course($user1, $user2) {
235 return enrol_get_shared_courses($user1, $user2, false, true);
239 * Returns any courses shared by the two users
241 * The courses has to be visible and enrolments has to be active,
242 * timestart and timeend restrictions are ignored.
244 * @global moodle_database $DB
245 * @param stdClass|int $user1
246 * @param stdClass|int $user2
247 * @param bool $preloadcontexts If set to true contexts for the returned courses
248 * will be preloaded.
249 * @param bool $checkexistsonly If set to true then this function will return true
250 * if the users share any courses and false if not.
251 * @return array|bool An array of courses that both users are enrolled in OR if
252 * $checkexistsonly set returns true if the users share any courses
253 * and false if not.
255 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
256 global $DB, $CFG;
258 $user1 = isset($user1->id) ? $user1->id : $user1;
259 $user2 = isset($user2->id) ? $user2->id : $user2;
261 if (empty($user1) or empty($user2)) {
262 return false;
265 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
266 return false;
269 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
270 $params['enabled'] = ENROL_INSTANCE_ENABLED;
271 $params['active1'] = ENROL_USER_ACTIVE;
272 $params['active2'] = ENROL_USER_ACTIVE;
273 $params['user1'] = $user1;
274 $params['user2'] = $user2;
276 $ctxselect = '';
277 $ctxjoin = '';
278 if ($preloadcontexts) {
279 list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
282 $sql = "SELECT c.* $ctxselect
283 FROM {course} c
284 JOIN (
285 SELECT DISTINCT c.id
286 FROM {enrol} e
287 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
288 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2)
289 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
290 WHERE e.status = :enabled AND e.enrol $plugins
291 ) ec ON ec.id = c.id
292 $ctxjoin";
294 if ($checkexistsonly) {
295 return $DB->record_exists_sql($sql, $params);
296 } else {
297 $courses = $DB->get_records_sql($sql, $params);
298 if ($preloadcontexts) {
299 array_map('context_instance_preload', $courses);
301 return $courses;
306 * This function adds necessary enrol plugins UI into the course edit form.
308 * @param MoodleQuickForm $mform
309 * @param object $data course edit form data
310 * @param object $context context of existing course or parent category if course does not exist
311 * @return void
313 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
314 $plugins = enrol_get_plugins(true);
315 if (!empty($data->id)) {
316 $instances = enrol_get_instances($data->id, false);
317 foreach ($instances as $instance) {
318 if (!isset($plugins[$instance->enrol])) {
319 continue;
321 $plugin = $plugins[$instance->enrol];
322 $plugin->course_edit_form($instance, $mform, $data, $context);
324 } else {
325 foreach ($plugins as $plugin) {
326 $plugin->course_edit_form(NULL, $mform, $data, $context);
332 * Validate course edit form data
334 * @param array $data raw form data
335 * @param object $context context of existing course or parent category if course does not exist
336 * @return array errors array
338 function enrol_course_edit_validation(array $data, $context) {
339 $errors = array();
340 $plugins = enrol_get_plugins(true);
342 if (!empty($data['id'])) {
343 $instances = enrol_get_instances($data['id'], false);
344 foreach ($instances as $instance) {
345 if (!isset($plugins[$instance->enrol])) {
346 continue;
348 $plugin = $plugins[$instance->enrol];
349 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
351 } else {
352 foreach ($plugins as $plugin) {
353 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
357 return $errors;
361 * Update enrol instances after course edit form submission
362 * @param bool $inserted true means new course added, false course already existed
363 * @param object $course
364 * @param object $data form data
365 * @return void
367 function enrol_course_updated($inserted, $course, $data) {
368 global $DB, $CFG;
370 $plugins = enrol_get_plugins(true);
372 foreach ($plugins as $plugin) {
373 $plugin->course_updated($inserted, $course, $data);
378 * Add navigation nodes
379 * @param navigation_node $coursenode
380 * @param object $course
381 * @return void
383 function enrol_add_course_navigation(navigation_node $coursenode, $course) {
384 global $CFG;
386 $coursecontext = context_course::instance($course->id);
388 $instances = enrol_get_instances($course->id, true);
389 $plugins = enrol_get_plugins(true);
391 // we do not want to break all course pages if there is some borked enrol plugin, right?
392 foreach ($instances as $k=>$instance) {
393 if (!isset($plugins[$instance->enrol])) {
394 unset($instances[$k]);
398 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
400 if ($course->id != SITEID) {
401 // list all participants - allows assigning roles, groups, etc.
402 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
403 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
404 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/users', ''));
407 // manage enrol plugin instances
408 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
409 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
410 } else {
411 $url = NULL;
413 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
415 // each instance decides how to configure itself or how many other nav items are exposed
416 foreach ($instances as $instance) {
417 if (!isset($plugins[$instance->enrol])) {
418 continue;
420 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
423 if (!$url) {
424 $instancesnode->trim_if_empty();
428 // Manage groups in this course or even frontpage
429 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
430 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
431 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
434 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
435 // Override roles
436 if (has_capability('moodle/role:review', $coursecontext)) {
437 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
438 } else {
439 $url = NULL;
441 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
443 // Add assign or override roles if allowed
444 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
445 if (has_capability('moodle/role:assign', $coursecontext)) {
446 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
447 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
450 // Check role permissions
451 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
452 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
453 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
457 // Deal somehow with users that are not enrolled but still got a role somehow
458 if ($course->id != SITEID) {
459 //TODO, create some new UI for role assignments at course level
460 if (has_capability('moodle/role:assign', $coursecontext)) {
461 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
462 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/roles', ''));
466 // just in case nothing was actually added
467 $usersnode->trim_if_empty();
469 if ($course->id != SITEID) {
470 if (isguestuser() or !isloggedin()) {
471 // guest account can not be enrolled - no links for them
472 } else if (is_enrolled($coursecontext)) {
473 // unenrol link if possible
474 foreach ($instances as $instance) {
475 if (!isset($plugins[$instance->enrol])) {
476 continue;
478 $plugin = $plugins[$instance->enrol];
479 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
480 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
481 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
482 break;
483 //TODO. deal with multiple unenrol links - not likely case, but still...
486 } else {
487 // enrol link if possible
488 if (is_viewing($coursecontext)) {
489 // better not show any enrol link, this is intended for managers and inspectors
490 } else {
491 foreach ($instances as $instance) {
492 if (!isset($plugins[$instance->enrol])) {
493 continue;
495 $plugin = $plugins[$instance->enrol];
496 if ($plugin->show_enrolme_link($instance)) {
497 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
498 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
499 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
500 break;
509 * Returns list of courses current $USER is enrolled in and can access
511 * - $fields is an array of field names to ADD
512 * so name the fields you really need, which will
513 * be added and uniq'd
515 * @param string|array $fields
516 * @param string $sort
517 * @param int $limit max number of courses
518 * @return array
520 function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
521 global $DB, $USER;
523 // Guest account does not have any courses
524 if (isguestuser() or !isloggedin()) {
525 return(array());
528 $basefields = array('id', 'category', 'sortorder',
529 'shortname', 'fullname', 'idnumber',
530 'startdate', 'visible',
531 'groupmode', 'groupmodeforce');
533 if (empty($fields)) {
534 $fields = $basefields;
535 } else if (is_string($fields)) {
536 // turn the fields from a string to an array
537 $fields = explode(',', $fields);
538 $fields = array_map('trim', $fields);
539 $fields = array_unique(array_merge($basefields, $fields));
540 } else if (is_array($fields)) {
541 $fields = array_unique(array_merge($basefields, $fields));
542 } else {
543 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
545 if (in_array('*', $fields)) {
546 $fields = array('*');
549 $orderby = "";
550 $sort = trim($sort);
551 if (!empty($sort)) {
552 $rawsorts = explode(',', $sort);
553 $sorts = array();
554 foreach ($rawsorts as $rawsort) {
555 $rawsort = trim($rawsort);
556 if (strpos($rawsort, 'c.') === 0) {
557 $rawsort = substr($rawsort, 2);
559 $sorts[] = trim($rawsort);
561 $sort = 'c.'.implode(',c.', $sorts);
562 $orderby = "ORDER BY $sort";
565 $wheres = array("c.id <> :siteid");
566 $params = array('siteid'=>SITEID);
568 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
569 // list _only_ this course - anything else is asking for trouble...
570 $wheres[] = "courseid = :loginas";
571 $params['loginas'] = $USER->loginascontext->instanceid;
574 $coursefields = 'c.' .join(',c.', $fields);
575 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
576 $wheres = implode(" AND ", $wheres);
578 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
579 $sql = "SELECT $coursefields $ccselect
580 FROM {course} c
581 JOIN (SELECT DISTINCT e.courseid
582 FROM {enrol} e
583 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
584 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
585 ) en ON (en.courseid = c.id)
586 $ccjoin
587 WHERE $wheres
588 $orderby";
589 $params['userid'] = $USER->id;
590 $params['active'] = ENROL_USER_ACTIVE;
591 $params['enabled'] = ENROL_INSTANCE_ENABLED;
592 $params['now1'] = round(time(), -2); // improves db caching
593 $params['now2'] = $params['now1'];
595 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
597 // preload contexts and check visibility
598 foreach ($courses as $id=>$course) {
599 context_instance_preload($course);
600 if (!$course->visible) {
601 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
602 unset($courses[$id]);
603 continue;
605 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
606 unset($courses[$id]);
607 continue;
610 $courses[$id] = $course;
613 //wow! Is that really all? :-D
615 return $courses;
619 * Returns course enrolment information icons.
621 * @param object $course
622 * @param array $instances enrol instances of this course, improves performance
623 * @return array of pix_icon
625 function enrol_get_course_info_icons($course, array $instances = NULL) {
626 $icons = array();
627 if (is_null($instances)) {
628 $instances = enrol_get_instances($course->id, true);
630 $plugins = enrol_get_plugins(true);
631 foreach ($plugins as $name => $plugin) {
632 $pis = array();
633 foreach ($instances as $instance) {
634 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
635 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
636 continue;
638 if ($instance->enrol == $name) {
639 $pis[$instance->id] = $instance;
642 if ($pis) {
643 $icons = array_merge($icons, $plugin->get_info_icons($pis));
646 return $icons;
650 * Returns course enrolment detailed information.
652 * @param object $course
653 * @return array of html fragments - can be used to construct lists
655 function enrol_get_course_description_texts($course) {
656 $lines = array();
657 $instances = enrol_get_instances($course->id, true);
658 $plugins = enrol_get_plugins(true);
659 foreach ($instances as $instance) {
660 if (!isset($plugins[$instance->enrol])) {
661 //weird
662 continue;
664 $plugin = $plugins[$instance->enrol];
665 $text = $plugin->get_description_text($instance);
666 if ($text !== NULL) {
667 $lines[] = $text;
670 return $lines;
674 * Returns list of courses user is enrolled into.
675 * (Note: use enrol_get_all_users_courses if you want to use the list wihtout any cap checks )
677 * - $fields is an array of fieldnames to ADD
678 * so name the fields you really need, which will
679 * be added and uniq'd
681 * @param int $userid
682 * @param bool $onlyactive return only active enrolments in courses user may see
683 * @param string|array $fields
684 * @param string $sort
685 * @return array
687 function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
688 global $DB;
690 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
692 // preload contexts and check visibility
693 if ($onlyactive) {
694 foreach ($courses as $id=>$course) {
695 context_instance_preload($course);
696 if (!$course->visible) {
697 if (!$context = context_course::instance($id)) {
698 unset($courses[$id]);
699 continue;
701 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
702 unset($courses[$id]);
703 continue;
709 return $courses;
714 * Returns list of courses user is enrolled into without any capability checks
715 * - $fields is an array of fieldnames to ADD
716 * so name the fields you really need, which will
717 * be added and uniq'd
719 * @param int $userid
720 * @param bool $onlyactive return only active enrolments in courses user may see
721 * @param string|array $fields
722 * @param string $sort
723 * @return array
725 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
726 global $DB;
728 // Guest account does not have any courses
729 if (isguestuser($userid) or empty($userid)) {
730 return(array());
733 $basefields = array('id', 'category', 'sortorder',
734 'shortname', 'fullname', 'idnumber',
735 'startdate', 'visible',
736 'groupmode', 'groupmodeforce');
738 if (empty($fields)) {
739 $fields = $basefields;
740 } else if (is_string($fields)) {
741 // turn the fields from a string to an array
742 $fields = explode(',', $fields);
743 $fields = array_map('trim', $fields);
744 $fields = array_unique(array_merge($basefields, $fields));
745 } else if (is_array($fields)) {
746 $fields = array_unique(array_merge($basefields, $fields));
747 } else {
748 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
750 if (in_array('*', $fields)) {
751 $fields = array('*');
754 $orderby = "";
755 $sort = trim($sort);
756 if (!empty($sort)) {
757 $rawsorts = explode(',', $sort);
758 $sorts = array();
759 foreach ($rawsorts as $rawsort) {
760 $rawsort = trim($rawsort);
761 if (strpos($rawsort, 'c.') === 0) {
762 $rawsort = substr($rawsort, 2);
764 $sorts[] = trim($rawsort);
766 $sort = 'c.'.implode(',c.', $sorts);
767 $orderby = "ORDER BY $sort";
770 $params = array('siteid'=>SITEID);
772 if ($onlyactive) {
773 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
774 $params['now1'] = round(time(), -2); // improves db caching
775 $params['now2'] = $params['now1'];
776 $params['active'] = ENROL_USER_ACTIVE;
777 $params['enabled'] = ENROL_INSTANCE_ENABLED;
778 } else {
779 $subwhere = "";
782 $coursefields = 'c.' .join(',c.', $fields);
783 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
785 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
786 $sql = "SELECT $coursefields $ccselect
787 FROM {course} c
788 JOIN (SELECT DISTINCT e.courseid
789 FROM {enrol} e
790 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
791 $subwhere
792 ) en ON (en.courseid = c.id)
793 $ccjoin
794 WHERE c.id <> :siteid
795 $orderby";
796 $params['userid'] = $userid;
798 $courses = $DB->get_records_sql($sql, $params);
800 return $courses;
806 * Called when user is about to be deleted.
807 * @param object $user
808 * @return void
810 function enrol_user_delete($user) {
811 global $DB;
813 $plugins = enrol_get_plugins(true);
814 foreach ($plugins as $plugin) {
815 $plugin->user_delete($user);
818 // force cleanup of all broken enrolments
819 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
823 * Called when course is about to be deleted.
824 * @param stdClass $course
825 * @return void
827 function enrol_course_delete($course) {
828 global $DB;
830 $instances = enrol_get_instances($course->id, false);
831 $plugins = enrol_get_plugins(true);
832 foreach ($instances as $instance) {
833 if (isset($plugins[$instance->enrol])) {
834 $plugins[$instance->enrol]->delete_instance($instance);
836 // low level delete in case plugin did not do it
837 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
838 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
839 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
840 $DB->delete_records('enrol', array('id'=>$instance->id));
845 * Try to enrol user via default internal auth plugin.
847 * For now this is always using the manual enrol plugin...
849 * @param $courseid
850 * @param $userid
851 * @param $roleid
852 * @param $timestart
853 * @param $timeend
854 * @return bool success
856 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
857 global $DB;
859 //note: this is hardcoded to manual plugin for now
861 if (!enrol_is_enabled('manual')) {
862 return false;
865 if (!$enrol = enrol_get_plugin('manual')) {
866 return false;
868 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
869 return false;
871 $instance = reset($instances);
873 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
875 return true;
879 * Is there a chance users might self enrol
880 * @param int $courseid
881 * @return bool
883 function enrol_selfenrol_available($courseid) {
884 $result = false;
886 $plugins = enrol_get_plugins(true);
887 $enrolinstances = enrol_get_instances($courseid, true);
888 foreach($enrolinstances as $instance) {
889 if (!isset($plugins[$instance->enrol])) {
890 continue;
892 if ($instance->enrol === 'guest') {
893 // blacklist known temporary guest plugins
894 continue;
896 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
897 $result = true;
898 break;
902 return $result;
906 * This function returns the end of current active user enrolment.
908 * It deals correctly with multiple overlapping user enrolments.
910 * @param int $courseid
911 * @param int $userid
912 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
914 function enrol_get_enrolment_end($courseid, $userid) {
915 global $DB;
917 $sql = "SELECT ue.*
918 FROM {user_enrolments} ue
919 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
920 JOIN {user} u ON u.id = ue.userid
921 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
922 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
924 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
925 return false;
928 $changes = array();
930 foreach ($enrolments as $ue) {
931 $start = (int)$ue->timestart;
932 $end = (int)$ue->timeend;
933 if ($end != 0 and $end < $start) {
934 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
935 continue;
937 if (isset($changes[$start])) {
938 $changes[$start] = $changes[$start] + 1;
939 } else {
940 $changes[$start] = 1;
942 if ($end === 0) {
943 // no end
944 } else if (isset($changes[$end])) {
945 $changes[$end] = $changes[$end] - 1;
946 } else {
947 $changes[$end] = -1;
951 // let's sort then enrolment starts&ends and go through them chronologically,
952 // looking for current status and the next future end of enrolment
953 ksort($changes);
955 $now = time();
956 $current = 0;
957 $present = null;
959 foreach ($changes as $time => $change) {
960 if ($time > $now) {
961 if ($present === null) {
962 // we have just went past current time
963 $present = $current;
964 if ($present < 1) {
965 // no enrolment active
966 return false;
969 if ($present !== null) {
970 // we are already in the future - look for possible end
971 if ($current + $change < 1) {
972 return $time;
976 $current += $change;
979 if ($current > 0) {
980 return 0;
981 } else {
982 return false;
988 * All enrol plugins should be based on this class,
989 * this is also the main source of documentation.
991 abstract class enrol_plugin {
992 protected $config = null;
995 * Returns name of this enrol plugin
996 * @return string
998 public function get_name() {
999 // second word in class is always enrol name, sorry, no fancy plugin names with _
1000 $words = explode('_', get_class($this));
1001 return $words[1];
1005 * Returns localised name of enrol instance
1007 * @param object $instance (null is accepted too)
1008 * @return string
1010 public function get_instance_name($instance) {
1011 if (empty($instance->name)) {
1012 $enrol = $this->get_name();
1013 return get_string('pluginname', 'enrol_'.$enrol);
1014 } else {
1015 $context = context_course::instance($instance->courseid);
1016 return format_string($instance->name, true, array('context'=>$context));
1021 * Returns optional enrolment information icons.
1023 * This is used in course list for quick overview of enrolment options.
1025 * We are not using single instance parameter because sometimes
1026 * we might want to prevent icon repetition when multiple instances
1027 * of one type exist. One instance may also produce several icons.
1029 * @param array $instances all enrol instances of this type in one course
1030 * @return array of pix_icon
1032 public function get_info_icons(array $instances) {
1033 return array();
1037 * Returns optional enrolment instance description text.
1039 * This is used in detailed course information.
1042 * @param object $instance
1043 * @return string short html text
1045 public function get_description_text($instance) {
1046 return null;
1050 * Makes sure config is loaded and cached.
1051 * @return void
1053 protected function load_config() {
1054 if (!isset($this->config)) {
1055 $name = $this->get_name();
1056 $this->config = get_config("enrol_$name");
1061 * Returns plugin config value
1062 * @param string $name
1063 * @param string $default value if config does not exist yet
1064 * @return string value or default
1066 public function get_config($name, $default = NULL) {
1067 $this->load_config();
1068 return isset($this->config->$name) ? $this->config->$name : $default;
1072 * Sets plugin config value
1073 * @param string $name name of config
1074 * @param string $value string config value, null means delete
1075 * @return string value
1077 public function set_config($name, $value) {
1078 $pluginname = $this->get_name();
1079 $this->load_config();
1080 if ($value === NULL) {
1081 unset($this->config->$name);
1082 } else {
1083 $this->config->$name = $value;
1085 set_config($name, $value, "enrol_$pluginname");
1089 * Does this plugin assign protected roles are can they be manually removed?
1090 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1092 public function roles_protected() {
1093 return true;
1097 * Does this plugin allow manual enrolments?
1099 * @param stdClass $instance course enrol instance
1100 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1102 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1104 public function allow_enrol(stdClass $instance) {
1105 return false;
1109 * Does this plugin allow manual unenrolment of all users?
1110 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1112 * @param stdClass $instance course enrol instance
1113 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1115 public function allow_unenrol(stdClass $instance) {
1116 return false;
1120 * Does this plugin allow manual unenrolment of a specific user?
1121 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1123 * This is useful especially for synchronisation plugins that
1124 * do suspend instead of full unenrolment.
1126 * @param stdClass $instance course enrol instance
1127 * @param stdClass $ue record from user_enrolments table, specifies user
1129 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1131 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1132 return $this->allow_unenrol($instance);
1136 * Does this plugin allow manual changes in user_enrolments table?
1138 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1140 * @param stdClass $instance course enrol instance
1141 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1143 public function allow_manage(stdClass $instance) {
1144 return false;
1148 * Does this plugin support some way to user to self enrol?
1150 * @param stdClass $instance course enrol instance
1152 * @return bool - true means show "Enrol me in this course" link in course UI
1154 public function show_enrolme_link(stdClass $instance) {
1155 return false;
1159 * Attempt to automatically enrol current user in course without any interaction,
1160 * calling code has to make sure the plugin and instance are active.
1162 * This should return either a timestamp in the future or false.
1164 * @param stdClass $instance course enrol instance
1165 * @return bool|int false means not enrolled, integer means timeend
1167 public function try_autoenrol(stdClass $instance) {
1168 global $USER;
1170 return false;
1174 * Attempt to automatically gain temporary guest access to course,
1175 * calling code has to make sure the plugin and instance are active.
1177 * This should return either a timestamp in the future or false.
1179 * @param stdClass $instance course enrol instance
1180 * @return bool|int false means no guest access, integer means timeend
1182 public function try_guestaccess(stdClass $instance) {
1183 global $USER;
1185 return false;
1189 * Enrol user into course via enrol instance.
1191 * @param stdClass $instance
1192 * @param int $userid
1193 * @param int $roleid optional role id
1194 * @param int $timestart 0 means unknown
1195 * @param int $timeend 0 means forever
1196 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1197 * @return void
1199 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
1200 global $DB, $USER, $CFG; // CFG necessary!!!
1202 if ($instance->courseid == SITEID) {
1203 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1206 $name = $this->get_name();
1207 $courseid = $instance->courseid;
1209 if ($instance->enrol !== $name) {
1210 throw new coding_exception('invalid enrol instance!');
1212 $context = context_course::instance($instance->courseid, MUST_EXIST);
1214 $inserted = false;
1215 $updated = false;
1216 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1217 //only update if timestart or timeend or status are different.
1218 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
1219 $ue->timestart = $timestart;
1220 $ue->timeend = $timeend;
1221 if (!is_null($status)) {
1222 $ue->status = $status;
1224 $ue->modifierid = $USER->id;
1225 $ue->timemodified = time();
1226 $DB->update_record('user_enrolments', $ue);
1228 $updated = true;
1230 } else {
1231 $ue = new stdClass();
1232 $ue->enrolid = $instance->id;
1233 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
1234 $ue->userid = $userid;
1235 $ue->timestart = $timestart;
1236 $ue->timeend = $timeend;
1237 $ue->modifierid = $USER->id;
1238 $ue->timecreated = time();
1239 $ue->timemodified = $ue->timecreated;
1240 $ue->id = $DB->insert_record('user_enrolments', $ue);
1242 $inserted = true;
1245 if ($inserted) {
1246 // add extra info and trigger event
1247 $ue->courseid = $courseid;
1248 $ue->enrol = $name;
1249 events_trigger('user_enrolled', $ue);
1250 } else if ($updated) {
1251 $ue->courseid = $courseid;
1252 $ue->enrol = $name;
1253 events_trigger('user_enrol_modified', $ue);
1254 // resets current enrolment caches
1255 $context->mark_dirty();
1258 if ($roleid) {
1259 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
1260 if ($this->roles_protected()) {
1261 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1262 } else {
1263 role_assign($roleid, $userid, $context->id);
1267 // reset current user enrolment caching
1268 if ($userid == $USER->id) {
1269 if (isset($USER->enrol['enrolled'][$courseid])) {
1270 unset($USER->enrol['enrolled'][$courseid]);
1272 if (isset($USER->enrol['tempguest'][$courseid])) {
1273 unset($USER->enrol['tempguest'][$courseid]);
1274 remove_temp_course_roles($context);
1280 * Store user_enrolments changes and trigger event.
1282 * @param stdClass $instance
1283 * @param int $userid
1284 * @param int $status
1285 * @param int $timestart
1286 * @param int $timeend
1287 * @return void
1289 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1290 global $DB, $USER;
1292 $name = $this->get_name();
1294 if ($instance->enrol !== $name) {
1295 throw new coding_exception('invalid enrol instance!');
1298 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1299 // weird, user not enrolled
1300 return;
1303 $modified = false;
1304 if (isset($status) and $ue->status != $status) {
1305 $ue->status = $status;
1306 $modified = true;
1308 if (isset($timestart) and $ue->timestart != $timestart) {
1309 $ue->timestart = $timestart;
1310 $modified = true;
1312 if (isset($timeend) and $ue->timeend != $timeend) {
1313 $ue->timeend = $timeend;
1314 $modified = true;
1317 if (!$modified) {
1318 // no change
1319 return;
1322 $ue->modifierid = $USER->id;
1323 $DB->update_record('user_enrolments', $ue);
1324 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches
1326 // trigger event
1327 $ue->courseid = $instance->courseid;
1328 $ue->enrol = $instance->name;
1329 events_trigger('user_enrol_modified', $ue);
1333 * Unenrol user from course,
1334 * the last unenrolment removes all remaining roles.
1336 * @param stdClass $instance
1337 * @param int $userid
1338 * @return void
1340 public function unenrol_user(stdClass $instance, $userid) {
1341 global $CFG, $USER, $DB;
1343 $name = $this->get_name();
1344 $courseid = $instance->courseid;
1346 if ($instance->enrol !== $name) {
1347 throw new coding_exception('invalid enrol instance!');
1349 $context = context_course::instance($instance->courseid, MUST_EXIST);
1351 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1352 // weird, user not enrolled
1353 return;
1356 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1357 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1359 // add extra info and trigger event
1360 $ue->courseid = $courseid;
1361 $ue->enrol = $name;
1363 $sql = "SELECT 'x'
1364 FROM {user_enrolments} ue
1365 JOIN {enrol} e ON (e.id = ue.enrolid)
1366 WHERE ue.userid = :userid AND e.courseid = :courseid";
1367 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1368 $ue->lastenrol = false;
1369 events_trigger('user_unenrolled', $ue);
1370 // user still has some enrolments, no big cleanup yet
1371 } else {
1372 // the big cleanup IS necessary!
1374 require_once("$CFG->dirroot/group/lib.php");
1375 require_once("$CFG->libdir/gradelib.php");
1377 // remove all remaining roles
1378 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1380 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1381 groups_delete_group_members($courseid, $userid);
1383 grade_user_unenrol($courseid, $userid);
1385 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1387 $ue->lastenrol = true; // means user not enrolled any more
1388 events_trigger('user_unenrolled', $ue);
1391 // reset all enrol caches
1392 $context->mark_dirty();
1394 // reset current user enrolment caching
1395 if ($userid == $USER->id) {
1396 if (isset($USER->enrol['enrolled'][$courseid])) {
1397 unset($USER->enrol['enrolled'][$courseid]);
1399 if (isset($USER->enrol['tempguest'][$courseid])) {
1400 unset($USER->enrol['tempguest'][$courseid]);
1401 remove_temp_course_roles($context);
1407 * Forces synchronisation of user enrolments.
1409 * This is important especially for external enrol plugins,
1410 * this function is called for all enabled enrol plugins
1411 * right after every user login.
1413 * @param object $user user record
1414 * @return void
1416 public function sync_user_enrolments($user) {
1417 // override if necessary
1421 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1422 * @param int $courseid
1423 * @return moodle_url page url
1425 public function get_newinstance_link($courseid) {
1426 // override for most plugins, check if instance already exists in cases only one instance is supported
1427 return NULL;
1431 * Is it possible to delete enrol instance via standard UI?
1433 * @param object $instance
1434 * @return bool
1436 public function instance_deleteable($instance) {
1437 return true;
1441 * Returns link to manual enrol UI if exists.
1442 * Does the access control tests automatically.
1444 * @param object $instance
1445 * @return moodle_url
1447 public function get_manual_enrol_link($instance) {
1448 return NULL;
1452 * Returns list of unenrol links for all enrol instances in course.
1454 * @param int $instance
1455 * @return moodle_url or NULL if self unenrolment not supported
1457 public function get_unenrolself_link($instance) {
1458 global $USER, $CFG, $DB;
1460 $name = $this->get_name();
1461 if ($instance->enrol !== $name) {
1462 throw new coding_exception('invalid enrol instance!');
1465 if ($instance->courseid == SITEID) {
1466 return NULL;
1469 if (!enrol_is_enabled($name)) {
1470 return NULL;
1473 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1474 return NULL;
1477 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1478 return NULL;
1481 $context = context_course::instance($instance->courseid, MUST_EXIST);
1483 if (!has_capability("enrol/$name:unenrolself", $context)) {
1484 return NULL;
1487 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1488 return NULL;
1491 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1495 * Adds enrol instance UI to course edit form
1497 * @param object $instance enrol instance or null if does not exist yet
1498 * @param MoodleQuickForm $mform
1499 * @param object $data
1500 * @param object $context context of existing course or parent category if course does not exist
1501 * @return void
1503 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1504 // override - usually at least enable/disable switch, has to add own form header
1508 * Validates course edit form data
1510 * @param object $instance enrol instance or null if does not exist yet
1511 * @param array $data
1512 * @param object $context context of existing course or parent category if course does not exist
1513 * @return array errors array
1515 public function course_edit_validation($instance, array $data, $context) {
1516 return array();
1520 * Called after updating/inserting course.
1522 * @param bool $inserted true if course just inserted
1523 * @param object $course
1524 * @param object $data form data
1525 * @return void
1527 public function course_updated($inserted, $course, $data) {
1528 if ($inserted) {
1529 if ($this->get_config('defaultenrol')) {
1530 $this->add_default_instance($course);
1536 * Add new instance of enrol plugin.
1537 * @param object $course
1538 * @param array instance fields
1539 * @return int id of new instance, null if can not be created
1541 public function add_instance($course, array $fields = NULL) {
1542 global $DB;
1544 if ($course->id == SITEID) {
1545 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1548 $instance = new stdClass();
1549 $instance->enrol = $this->get_name();
1550 $instance->status = ENROL_INSTANCE_ENABLED;
1551 $instance->courseid = $course->id;
1552 $instance->enrolstartdate = 0;
1553 $instance->enrolenddate = 0;
1554 $instance->timemodified = time();
1555 $instance->timecreated = $instance->timemodified;
1556 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1558 $fields = (array)$fields;
1559 unset($fields['enrol']);
1560 unset($fields['courseid']);
1561 unset($fields['sortorder']);
1562 foreach($fields as $field=>$value) {
1563 $instance->$field = $value;
1566 return $DB->insert_record('enrol', $instance);
1570 * Add new instance of enrol plugin with default settings,
1571 * called when adding new instance manually or when adding new course.
1573 * Not all plugins support this.
1575 * @param object $course
1576 * @return int id of new instance or null if no default supported
1578 public function add_default_instance($course) {
1579 return null;
1583 * Update instance status
1585 * Override when plugin needs to do some action when enabled or disabled.
1587 * @param stdClass $instance
1588 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
1589 * @return void
1591 public function update_status($instance, $newstatus) {
1592 global $DB;
1594 $instance->status = $newstatus;
1595 $DB->update_record('enrol', $instance);
1597 // invalidate all enrol caches
1598 $context = context_course::instance($instance->courseid);
1599 $context->mark_dirty();
1603 * Delete course enrol plugin instance, unenrol all users.
1604 * @param object $instance
1605 * @return void
1607 public function delete_instance($instance) {
1608 global $DB;
1610 $name = $this->get_name();
1611 if ($instance->enrol !== $name) {
1612 throw new coding_exception('invalid enrol instance!');
1615 //first unenrol all users
1616 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1617 foreach ($participants as $participant) {
1618 $this->unenrol_user($instance, $participant->userid);
1620 $participants->close();
1622 // now clean up all remainders that were not removed correctly
1623 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>$name));
1624 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1626 // finally drop the enrol row
1627 $DB->delete_records('enrol', array('id'=>$instance->id));
1629 // invalidate all enrol caches
1630 $context = context_course::instance($instance->courseid);
1631 $context->mark_dirty();
1635 * Creates course enrol form, checks if form submitted
1636 * and enrols user if necessary. It can also redirect.
1638 * @param stdClass $instance
1639 * @return string html text, usually a form in a text box
1641 public function enrol_page_hook(stdClass $instance) {
1642 return null;
1646 * Adds navigation links into course admin block.
1648 * By defaults looks for manage links only.
1650 * @param navigation_node $instancesnode
1651 * @param stdClass $instance
1652 * @return void
1654 public function add_course_navigation($instancesnode, stdClass $instance) {
1655 // usually adds manage users
1659 * Returns edit icons for the page with list of instances
1660 * @param stdClass $instance
1661 * @return array
1663 public function get_action_icons(stdClass $instance) {
1664 return array();
1668 * Reads version.php and determines if it is necessary
1669 * to execute the cron job now.
1670 * @return bool
1672 public function is_cron_required() {
1673 global $CFG;
1675 $name = $this->get_name();
1676 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
1677 $plugin = new stdClass();
1678 include($versionfile);
1679 if (empty($plugin->cron)) {
1680 return false;
1682 $lastexecuted = $this->get_config('lastcron', 0);
1683 if ($lastexecuted + $plugin->cron < time()) {
1684 return true;
1685 } else {
1686 return false;
1691 * Called for all enabled enrol plugins that returned true from is_cron_required().
1692 * @return void
1694 public function cron() {
1698 * Called when user is about to be deleted
1699 * @param object $user
1700 * @return void
1702 public function user_delete($user) {
1703 global $DB;
1705 $sql = "SELECT e.*
1706 FROM {enrol} e
1707 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1708 WHERE e.enrol = :name AND ue.userid = :userid";
1709 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1711 $rs = $DB->get_recordset_sql($sql, $params);
1712 foreach($rs as $instance) {
1713 $this->unenrol_user($instance, $user->id);
1715 $rs->close();
1719 * Returns an enrol_user_button that takes the user to a page where they are able to
1720 * enrol users into the managers course through this plugin.
1722 * Optional: If the plugin supports manual enrolments it can choose to override this
1723 * otherwise it shouldn't
1725 * @param course_enrolment_manager $manager
1726 * @return enrol_user_button|false
1728 public function get_manual_enrol_button(course_enrolment_manager $manager) {
1729 return false;
1733 * Gets an array of the user enrolment actions
1735 * @param course_enrolment_manager $manager
1736 * @param stdClass $ue
1737 * @return array An array of user_enrolment_actions
1739 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
1740 return array();
1744 * Returns true if the plugin has one or more bulk operations that can be performed on
1745 * user enrolments.
1747 * @param course_enrolment_manager $manager
1748 * @return bool
1750 public function has_bulk_operations(course_enrolment_manager $manager) {
1751 return false;
1755 * Return an array of enrol_bulk_enrolment_operation objects that define
1756 * the bulk actions that can be performed on user enrolments by the plugin.
1758 * @param course_enrolment_manager $manager
1759 * @return array
1761 public function get_bulk_operations(course_enrolment_manager $manager) {
1762 return array();
1766 * Automatic enrol sync executed during restore.
1767 * Useful for automatic sync by course->idnumber or course category.
1768 * @param stdClass $course course record
1770 public function restore_sync_course($course) {
1771 // Override if necessary.
1775 * Restore instance and map settings.
1777 * @param restore_enrolments_structure_step $step
1778 * @param stdClass $data
1779 * @param stdClass $course
1780 * @param int $oldid
1782 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
1783 // Do not call this from overridden methods, restore and set new id there.
1784 $step->set_mapping('enrol', $oldid, 0);
1788 * Restore user enrolment.
1790 * @param restore_enrolments_structure_step $step
1791 * @param stdClass $data
1792 * @param stdClass $instance
1793 * @param int $oldinstancestatus
1794 * @param int $userid
1796 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
1797 // Override as necessary if plugin supports restore of enrolments.
1801 * Restore role assignment.
1803 * @param stdClass $instance
1804 * @param int $roleid
1805 * @param int $userid
1806 * @param int $contextid
1808 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
1809 // No role assignment by default, override if necessary.