MDL-27588 Fixed up several bugs with the formal_white theme
[moodle.git] / lib / enrollib.php
blob1484e4be85f75b1e98ff381c035a1bee610f2972
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 /** Enrol info is cached for this number of seconds in require_login() */
43 define('ENROL_REQUIRE_LOGIN_CACHE_PERIOD', 1800);
45 /** When user disappears from external source, the enrolment is completely removed */
46 define('ENROL_EXT_REMOVED_UNENROL', 0);
48 /** When user disappears from external source, the enrolment is kept as is - one way sync */
49 define('ENROL_EXT_REMOVED_KEEP', 1);
51 /** enrol plugin feature describing requested restore type */
52 define('ENROL_RESTORE_TYPE', 'enrolrestore');
53 /** User custom backup/restore class stored in backup/moodle2/ subdirectory */
54 define('ENROL_RESTORE_CLASS', 'class');
55 /** Restore all custom fields from enrol table without any changes and all user_enrolments records */
56 define('ENROL_RESTORE_EXACT', 'exact');
57 /** Restore enrol record like ENROL_RESTORE_EXACT, but no user enrolments */
58 define('ENROL_RESTORE_NOUSERS', 'nousers');
60 /**
61 * When user disappears from external source, user enrolment is suspended, roles are kept as is.
62 * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook,
63 * assignments, etc.
65 define('ENROL_EXT_REMOVED_SUSPEND', 2);
67 /**
68 * When user disappears from external source, the enrolment is suspended and roles assigned
69 * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas.
70 * */
71 define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
73 /**
74 * Returns instances of enrol plugins
75 * @param bool $enable return enabled only
76 * @return array of enrol plugins name=>instance
78 function enrol_get_plugins($enabled) {
79 global $CFG;
81 $result = array();
83 if ($enabled) {
84 // sorted by enabled plugin order
85 $enabled = explode(',', $CFG->enrol_plugins_enabled);
86 $plugins = array();
87 foreach ($enabled as $plugin) {
88 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
90 } else {
91 // sorted alphabetically
92 $plugins = get_plugin_list('enrol');
93 ksort($plugins);
96 foreach ($plugins as $plugin=>$location) {
97 if (!file_exists("$location/lib.php")) {
98 continue;
100 include_once("$location/lib.php");
101 $class = "enrol_{$plugin}_plugin";
102 if (!class_exists($class)) {
103 continue;
106 $result[$plugin] = new $class();
109 return $result;
113 * Returns instance of enrol plugin
114 * @param string $name name of enrol plugin ('manual', 'guest', ...)
115 * @return enrol_plugin
117 function enrol_get_plugin($name) {
118 global $CFG;
120 if ($name !== clean_param($name, PARAM_SAFEDIR)) {
121 // ignore malformed plugin names completely
122 return null;
125 $location = "$CFG->dirroot/enrol/$name";
127 if (!file_exists("$location/lib.php")) {
128 return null;
130 include_once("$location/lib.php");
131 $class = "enrol_{$name}_plugin";
132 if (!class_exists($class)) {
133 return null;
136 return new $class();
140 * Returns enrolment instances in given course.
141 * @param int $courseid
142 * @param bool $enabled
143 * @return array of enrol instances
145 function enrol_get_instances($courseid, $enabled) {
146 global $DB, $CFG;
148 if (!$enabled) {
149 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
152 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
154 $enabled = explode(',', $CFG->enrol_plugins_enabled);
155 foreach ($result as $key=>$instance) {
156 if (!in_array($instance->enrol, $enabled)) {
157 unset($result[$key]);
158 continue;
160 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
161 // broken plugin
162 unset($result[$key]);
163 continue;
167 return $result;
171 * Checks if a given plugin is in the list of enabled enrolment plugins.
173 * @param string $enrol Enrolment plugin name
174 * @return boolean Whether the plugin is enabled
176 function enrol_is_enabled($enrol) {
177 global $CFG;
179 if (empty($CFG->enrol_plugins_enabled)) {
180 return false;
182 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
186 * Check all the login enrolment information for the given user object
187 * by querying the enrolment plugins
189 * @param object $user
190 * @return void
192 function enrol_check_plugins($user) {
193 global $CFG;
195 if (empty($user->id) or isguestuser($user)) {
196 // shortcut - there is no enrolment work for guests and not-logged-in users
197 return;
200 if (is_siteadmin()) {
201 // no sync for admin user, please use admin accounts only for admin tasks like the unix root user!
202 // if plugin fails on sync admins need to be able to log in
203 return;
206 static $inprogress = array(); // To prevent this function being called more than once in an invocation
208 if (!empty($inprogress[$user->id])) {
209 return;
212 $inprogress[$user->id] = true; // Set the flag
214 $enabled = enrol_get_plugins(true);
216 foreach($enabled as $enrol) {
217 $enrol->sync_user_enrolments($user);
220 unset($inprogress[$user->id]); // Unset the flag
224 * Do these two students share any course?
226 * The courses has to be visible and enrolments has to be active,
227 * timestart and timeend restrictions are ignored.
229 * @param stdClass|int $user1
230 * @param stdClass|int $user2
231 * @return bool
233 function enrol_sharing_course($user1, $user2) {
234 global $DB, $CFG;
236 $user1 = !empty($user1->id) ? $user1->id : $user1;
237 $user2 = !empty($user2->id) ? $user2->id : $user2;
239 if (empty($user1) or empty($user2)) {
240 return false;
243 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
244 return false;
247 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
248 $params['enabled'] = ENROL_INSTANCE_ENABLED;
249 $params['active1'] = ENROL_USER_ACTIVE;
250 $params['active2'] = ENROL_USER_ACTIVE;
251 $params['user1'] = $user1;
252 $params['user2'] = $user2;
254 $sql = "SELECT DISTINCT 'x'
255 FROM {enrol} e
256 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
257 JOIN {user_enrolments} ue2 ON (ue1.enrolid = e.id AND ue1.status = :active2 AND ue2.userid = :user2)
258 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
259 WHERE e.status = :enabled AND e.enrol $plugins";
261 return $DB->record_exists_sql($sql, $params);
265 * This function adds necessary enrol plugins UI into the course edit form.
267 * @param MoodleQuickForm $mform
268 * @param object $data course edit form data
269 * @param object $context context of existing course or parent category if course does not exist
270 * @return void
272 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
273 $plugins = enrol_get_plugins(true);
274 if (!empty($data->id)) {
275 $instances = enrol_get_instances($data->id, false);
276 foreach ($instances as $instance) {
277 if (!isset($plugins[$instance->enrol])) {
278 continue;
280 $plugin = $plugins[$instance->enrol];
281 $plugin->course_edit_form($instance, $mform, $data, $context);
283 } else {
284 foreach ($plugins as $plugin) {
285 $plugin->course_edit_form(NULL, $mform, $data, $context);
291 * Validate course edit form data
293 * @param array $data raw form data
294 * @param object $context context of existing course or parent category if course does not exist
295 * @return array errors array
297 function enrol_course_edit_validation(array $data, $context) {
298 $errors = array();
299 $plugins = enrol_get_plugins(true);
301 if (!empty($data['id'])) {
302 $instances = enrol_get_instances($data['id'], false);
303 foreach ($instances as $instance) {
304 if (!isset($plugins[$instance->enrol])) {
305 continue;
307 $plugin = $plugins[$instance->enrol];
308 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
310 } else {
311 foreach ($plugins as $plugin) {
312 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
316 return $errors;
320 * Update enrol instances after course edit form submission
321 * @param bool $inserted true means new course added, false course already existed
322 * @param object $course
323 * @param object $data form data
324 * @return void
326 function enrol_course_updated($inserted, $course, $data) {
327 global $DB, $CFG;
329 $plugins = enrol_get_plugins(true);
331 foreach ($plugins as $plugin) {
332 $plugin->course_updated($inserted, $course, $data);
337 * Add navigation nodes
338 * @param navigation_node $coursenode
339 * @param object $course
340 * @return void
342 function enrol_add_course_navigation(navigation_node $coursenode, $course) {
343 global $CFG;
345 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
347 $instances = enrol_get_instances($course->id, true);
348 $plugins = enrol_get_plugins(true);
350 // we do not want to break all course pages if there is some borked enrol plugin, right?
351 foreach ($instances as $k=>$instance) {
352 if (!isset($plugins[$instance->enrol])) {
353 unset($instances[$k]);
357 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
359 if ($course->id != SITEID) {
360 // list all participants - allows assigning roles, groups, etc.
361 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
362 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
363 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/users', ''));
366 // manage enrol plugin instances
367 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
368 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
369 } else {
370 $url = NULL;
372 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
374 // each instance decides how to configure itself or how many other nav items are exposed
375 foreach ($instances as $instance) {
376 if (!isset($plugins[$instance->enrol])) {
377 continue;
379 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
382 if (!$url) {
383 $instancesnode->trim_if_empty();
387 // Manage groups in this course or even frontpage
388 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
389 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
390 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
393 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
394 // Override roles
395 if (has_capability('moodle/role:review', $coursecontext)) {
396 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
397 } else {
398 $url = NULL;
400 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
402 // Add assign or override roles if allowed
403 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
404 if (has_capability('moodle/role:assign', $coursecontext)) {
405 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
406 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
409 // Check role permissions
410 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
411 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
412 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
416 // Deal somehow with users that are not enrolled but still got a role somehow
417 if ($course->id != SITEID) {
418 //TODO, create some new UI for role assignments at course level
419 if (has_capability('moodle/role:assign', $coursecontext)) {
420 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
421 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/roles', ''));
425 // just in case nothing was actually added
426 $usersnode->trim_if_empty();
428 if ($course->id != SITEID) {
429 // Unenrol link
430 if (is_enrolled($coursecontext)) {
431 foreach ($instances as $instance) {
432 if (!isset($plugins[$instance->enrol])) {
433 continue;
435 $plugin = $plugins[$instance->enrol];
436 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
437 $coursenode->add(get_string('unenrolme', 'core_enrol', format_string($course->shortname)), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
438 break;
439 //TODO. deal with multiple unenrol links - not likely case, but still...
442 } else {
443 if (is_viewing($coursecontext)) {
444 // better not show any enrol link, this is intended for managers and inspectors
445 } else {
446 foreach ($instances as $instance) {
447 if (!isset($plugins[$instance->enrol])) {
448 continue;
450 $plugin = $plugins[$instance->enrol];
451 if ($plugin->show_enrolme_link($instance)) {
452 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
453 $coursenode->add(get_string('enrolme', 'core_enrol', format_string($course->shortname)), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
454 break;
463 * Returns list of courses current $USER is enrolled in and can access
465 * - $fields is an array of field names to ADD
466 * so name the fields you really need, which will
467 * be added and uniq'd
469 * @param string|array $fields
470 * @param string $sort
471 * @param int $limit max number of courses
472 * @return array
474 function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
475 global $DB, $USER;
477 // Guest account does not have any courses
478 if (isguestuser() or !isloggedin()) {
479 return(array());
482 $basefields = array('id', 'category', 'sortorder',
483 'shortname', 'fullname', 'idnumber',
484 'startdate', 'visible',
485 'groupmode', 'groupmodeforce');
487 if (empty($fields)) {
488 $fields = $basefields;
489 } else if (is_string($fields)) {
490 // turn the fields from a string to an array
491 $fields = explode(',', $fields);
492 $fields = array_map('trim', $fields);
493 $fields = array_unique(array_merge($basefields, $fields));
494 } else if (is_array($fields)) {
495 $fields = array_unique(array_merge($basefields, $fields));
496 } else {
497 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
499 if (in_array('*', $fields)) {
500 $fields = array('*');
503 $orderby = "";
504 $sort = trim($sort);
505 if (!empty($sort)) {
506 $rawsorts = explode(',', $sort);
507 $sorts = array();
508 foreach ($rawsorts as $rawsort) {
509 $rawsort = trim($rawsort);
510 if (strpos($rawsort, 'c.') === 0) {
511 $rawsort = substr($rawsort, 2);
513 $sorts[] = trim($rawsort);
515 $sort = 'c.'.implode(',c.', $sorts);
516 $orderby = "ORDER BY $sort";
519 $wheres = array("c.id <> :siteid");
520 $params = array('siteid'=>SITEID);
522 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
523 // list _only_ this course - anything else is asking for trouble...
524 $wheres[] = "courseid = :loginas";
525 $params['loginas'] = $USER->loginascontext->instanceid;
528 $coursefields = 'c.' .join(',c.', $fields);
529 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
530 $wheres = implode(" AND ", $wheres);
532 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
533 $sql = "SELECT $coursefields $ccselect
534 FROM {course} c
535 JOIN (SELECT DISTINCT e.courseid
536 FROM {enrol} e
537 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
538 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
539 ) en ON (en.courseid = c.id)
540 $ccjoin
541 WHERE $wheres
542 $orderby";
543 $params['userid'] = $USER->id;
544 $params['active'] = ENROL_USER_ACTIVE;
545 $params['enabled'] = ENROL_INSTANCE_ENABLED;
546 $params['now1'] = round(time(), -2); // improves db caching
547 $params['now2'] = $params['now1'];
549 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
551 // preload contexts and check visibility
552 foreach ($courses as $id=>$course) {
553 context_instance_preload($course);
554 if (!$course->visible) {
555 if (!$context = get_context_instance(CONTEXT_COURSE, $id)) {
556 unset($courses[$id]);
557 continue;
559 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
560 unset($courses[$id]);
561 continue;
564 $courses[$id] = $course;
567 //wow! Is that really all? :-D
569 return $courses;
573 * Returns course enrolment information icons.
575 * @param object $course
576 * @param array $instances enrol instances of this course, improves performance
577 * @return array of pix_icon
579 function enrol_get_course_info_icons($course, array $instances = NULL) {
580 $icons = array();
581 if (is_null($instances)) {
582 $instances = enrol_get_instances($course->id, true);
584 $plugins = enrol_get_plugins(true);
585 foreach ($plugins as $name => $plugin) {
586 $pis = array();
587 foreach ($instances as $instance) {
588 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
589 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
590 continue;
592 if ($instance->enrol == $name) {
593 $pis[$instance->id] = $instance;
596 if ($pis) {
597 $icons = array_merge($icons, $plugin->get_info_icons($pis));
600 return $icons;
604 * Returns course enrolment detailed information.
606 * @param object $course
607 * @return array of html fragments - can be used to construct lists
609 function enrol_get_course_description_texts($course) {
610 $lines = array();
611 $instances = enrol_get_instances($course->id, true);
612 $plugins = enrol_get_plugins(true);
613 foreach ($instances as $instance) {
614 if (!isset($plugins[$instance->enrol])) {
615 //weird
616 continue;
618 $plugin = $plugins[$instance->enrol];
619 $text = $plugin->get_description_text($instance);
620 if ($text !== NULL) {
621 $lines[] = $text;
624 return $lines;
628 * Returns list of courses user is enrolled into.
630 * - $fields is an array of fieldnames to ADD
631 * so name the fields you really need, which will
632 * be added and uniq'd
634 * @param int $userid
635 * @param bool $onlyactive return only active enrolments in courses user may see
636 * @param string|array $fields
637 * @param string $sort
638 * @return array
640 function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
641 global $DB;
643 // Guest account does not have any courses
644 if (isguestuser($userid) or empty($userid)) {
645 return(array());
648 $basefields = array('id', 'category', 'sortorder',
649 'shortname', 'fullname', 'idnumber',
650 'startdate', 'visible',
651 'groupmode', 'groupmodeforce');
653 if (empty($fields)) {
654 $fields = $basefields;
655 } else if (is_string($fields)) {
656 // turn the fields from a string to an array
657 $fields = explode(',', $fields);
658 $fields = array_map('trim', $fields);
659 $fields = array_unique(array_merge($basefields, $fields));
660 } else if (is_array($fields)) {
661 $fields = array_unique(array_merge($basefields, $fields));
662 } else {
663 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
665 if (in_array('*', $fields)) {
666 $fields = array('*');
669 $orderby = "";
670 $sort = trim($sort);
671 if (!empty($sort)) {
672 $rawsorts = explode(',', $sort);
673 $sorts = array();
674 foreach ($rawsorts as $rawsort) {
675 $rawsort = trim($rawsort);
676 if (strpos($rawsort, 'c.') === 0) {
677 $rawsort = substr($rawsort, 2);
679 $sorts[] = trim($rawsort);
681 $sort = 'c.'.implode(',c.', $sorts);
682 $orderby = "ORDER BY $sort";
685 $params = array('siteid'=>SITEID);
687 if ($onlyactive) {
688 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
689 $params['now1'] = round(time(), -2); // improves db caching
690 $params['now2'] = $params['now1'];
691 $params['active'] = ENROL_USER_ACTIVE;
692 $params['enabled'] = ENROL_INSTANCE_ENABLED;
693 } else {
694 $subwhere = "";
697 $coursefields = 'c.' .join(',c.', $fields);
698 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
700 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
701 $sql = "SELECT $coursefields $ccselect
702 FROM {course} c
703 JOIN (SELECT DISTINCT e.courseid
704 FROM {enrol} e
705 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
706 $subwhere
707 ) en ON (en.courseid = c.id)
708 $ccjoin
709 WHERE c.id <> :siteid
710 $orderby";
711 $params['userid'] = $userid;
713 $courses = $DB->get_records_sql($sql, $params);
715 // preload contexts and check visibility
716 foreach ($courses as $id=>$course) {
717 context_instance_preload($course);
718 if ($onlyactive) {
719 if (!$course->visible) {
720 if (!$context = get_context_instance(CONTEXT_COURSE, $id)) {
721 unset($courses[$id]);
722 continue;
724 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
725 unset($courses[$id]);
726 continue;
730 $courses[$id] = $course;
733 //wow! Is that really all? :-D
735 return $courses;
740 * Called when user is about to be deleted.
741 * @param object $user
742 * @return void
744 function enrol_user_delete($user) {
745 global $DB;
747 $plugins = enrol_get_plugins(true);
748 foreach ($plugins as $plugin) {
749 $plugin->user_delete($user);
752 // force cleanup of all broken enrolments
753 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
757 * Called when course is about to be deleted.
758 * @param stdClass $object
759 * @return void
761 function enrol_course_delete($course) {
762 global $DB;
764 $instances = enrol_get_instances($course->id, false);
765 $plugins = enrol_get_plugins(true);
766 foreach ($instances as $instance) {
767 if (isset($plugins[$instance->enrol])) {
768 $plugins[$instance->enrol]->delete_instance($instance);
770 // low level delete in case plugin did not do it
771 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
772 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
773 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
774 $DB->delete_records('enrol', array('id'=>$instance->id));
779 * Try to enrol user via default internal auth plugin.
781 * For now this is always using the manual enrol plugin...
783 * @param $courseid
784 * @param $userid
785 * @param $roleid
786 * @param $timestart
787 * @param $timeend
788 * @return bool success
790 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
791 global $DB;
793 //note: this is hardcoded to manual plugin for now
795 if (!enrol_is_enabled('manual')) {
796 return false;
799 if (!$enrol = enrol_get_plugin('manual')) {
800 return false;
802 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
803 return false;
805 $instance = reset($instances);
807 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
809 return true;
813 * Is there a chance users might self enrol
814 * @param int $courseid
815 * @return bool
817 function enrol_selfenrol_available($courseid) {
818 $result = false;
820 $plugins = enrol_get_plugins(true);
821 $enrolinstances = enrol_get_instances($courseid, true);
822 foreach($enrolinstances as $instance) {
823 if (!isset($plugins[$instance->enrol])) {
824 continue;
826 if ($instance->enrol === 'guest') {
827 // blacklist known temporary guest plugins
828 continue;
830 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
831 $result = true;
832 break;
836 return $result;
840 * All enrol plugins should be based on this class,
841 * this is also the main source of documentation.
843 abstract class enrol_plugin {
844 protected $config = null;
847 * Returns name of this enrol plugin
848 * @return string
850 public function get_name() {
851 // second word in class is always enrol name, sorry, no fancy plugin names with _
852 $words = explode('_', get_class($this));
853 return $words[1];
857 * Returns localised name of enrol instance
859 * @param object $instance (null is accepted too)
860 * @return string
862 public function get_instance_name($instance) {
863 if (empty($instance->name)) {
864 $enrol = $this->get_name();
865 return get_string('pluginname', 'enrol_'.$enrol);
866 } else {
867 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid);
868 return format_string($instance->name, true, array('context'=>$context));
873 * Returns optional enrolment information icons.
875 * This is used in course list for quick overview of enrolment options.
877 * We are not using single instance parameter because sometimes
878 * we might want to prevent icon repetition when multiple instances
879 * of one type exist. One instance may also produce several icons.
881 * @param array $instances all enrol instances of this type in one course
882 * @return array of pix_icon
884 public function get_info_icons(array $instances) {
885 return array();
889 * Returns optional enrolment instance description text.
891 * This is used in detailed course information.
894 * @param object $instance
895 * @return string short html text
897 public function get_description_text($instance) {
898 return null;
902 * Makes sure config is loaded and cached.
903 * @return void
905 protected function load_config() {
906 if (!isset($this->config)) {
907 $name = $this->get_name();
908 if (!$config = get_config("enrol_$name")) {
909 $config = new stdClass();
911 $this->config = $config;
916 * Returns plugin config value
917 * @param string $name
918 * @param string $default value if config does not exist yet
919 * @return string value or default
921 public function get_config($name, $default = NULL) {
922 $this->load_config();
923 return isset($this->config->$name) ? $this->config->$name : $default;
927 * Sets plugin config value
928 * @param string $name name of config
929 * @param string $value string config value, null means delete
930 * @return string value
932 public function set_config($name, $value) {
933 $pluginname = $this->get_name();
934 $this->load_config();
935 if ($value === NULL) {
936 unset($this->config->$name);
937 } else {
938 $this->config->$name = $value;
940 set_config($name, $value, "enrol_$pluginname");
944 * Does this plugin assign protected roles are can they be manually removed?
945 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
947 public function roles_protected() {
948 return true;
952 * Does this plugin allow manual enrolments?
954 * @param stdClass $instance course enrol instance
955 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
957 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, trues means nobody may add more enrolments manually
959 public function allow_enrol(stdClass $instance) {
960 return false;
964 * Does this plugin allow manual unenrolments?
966 * @param stdClass $instance course enrol instance
967 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
969 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, trues means nobody may touch user_enrolments
971 public function allow_unenrol(stdClass $instance) {
972 return false;
976 * Does this plugin allow manual changes in user_enrolments table?
978 * All plugins allowing this must implement 'enrol/xxx:manage' capability
980 * @param stdClass $instance course enrol instance
981 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
983 public function allow_manage(stdClass $instance) {
984 return false;
988 * Does this plugin support some way to user to self enrol?
990 * @param stdClass $instance course enrol instance
992 * @return bool - true means show "Enrol me in this course" link in course UI
994 public function show_enrolme_link(stdClass $instance) {
995 return false;
999 * Attempt to automatically enrol current user in course without any interaction,
1000 * calling code has to make sure the plugin and instance are active.
1002 * This should return either a timestamp in the future or false.
1004 * @param stdClass $instance course enrol instance
1005 * @param stdClass $user record
1006 * @return bool|int false means not enrolled, integer means timeend
1008 public function try_autoenrol(stdClass $instance) {
1009 global $USER;
1011 return false;
1015 * Attempt to automatically gain temporary guest access to course,
1016 * calling code has to make sure the plugin and instance are active.
1018 * This should return either a timestamp in the future or false.
1020 * @param stdClass $instance course enrol instance
1021 * @param stdClass $user record
1022 * @return bool|int false means no guest access, integer means timeend
1024 public function try_guestaccess(stdClass $instance) {
1025 global $USER;
1027 return false;
1031 * Enrol user into course via enrol instance.
1033 * @param stdClass $instance
1034 * @param int $userid
1035 * @param int $roleid optional role id
1036 * @param int $timestart 0 means unknown
1037 * @param int $timeend 0 means forever
1038 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1039 * @return void
1041 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
1042 global $DB, $USER, $CFG; // CFG necessary!!!
1044 if ($instance->courseid == SITEID) {
1045 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1048 $name = $this->get_name();
1049 $courseid = $instance->courseid;
1051 if ($instance->enrol !== $name) {
1052 throw new coding_exception('invalid enrol instance!');
1054 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1056 $inserted = false;
1057 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1058 //only update if timestart or timeend or status are different.
1059 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
1060 $ue->timestart = $timestart;
1061 $ue->timeend = $timeend;
1062 if (!is_null($status)) {
1063 $ue->status = $status;
1065 $ue->modifierid = $USER->id;
1066 $ue->timemodified = time();
1067 $DB->update_record('user_enrolments', $ue);
1069 } else {
1070 $ue = new stdClass();
1071 $ue->enrolid = $instance->id;
1072 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
1073 $ue->userid = $userid;
1074 $ue->timestart = $timestart;
1075 $ue->timeend = $timeend;
1076 $ue->modifierid = $USER->id;
1077 $ue->timecreated = time();
1078 $ue->timemodified = $ue->timecreated;
1079 $ue->id = $DB->insert_record('user_enrolments', $ue);
1081 $inserted = true;
1084 if ($roleid) {
1085 if ($this->roles_protected()) {
1086 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1087 } else {
1088 role_assign($roleid, $userid, $context->id);
1092 if ($inserted) {
1093 // add extra info and trigger event
1094 $ue->courseid = $courseid;
1095 $ue->enrol = $name;
1096 events_trigger('user_enrolled', $ue);
1099 // reset primitive require_login() caching
1100 if ($userid == $USER->id) {
1101 if (isset($USER->enrol['enrolled'][$courseid])) {
1102 unset($USER->enrol['enrolled'][$courseid]);
1104 if (isset($USER->enrol['tempguest'][$courseid])) {
1105 unset($USER->enrol['tempguest'][$courseid]);
1106 $USER->access = remove_temp_roles($context, $USER->access);
1112 * Store user_enrolments changes and trigger event.
1114 * @param object $ue
1115 * @param int $user id
1116 * @param int $status
1117 * @param int $timestart
1118 * @param int $timeend
1119 * @return void
1121 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1122 global $DB, $USER;
1124 $name = $this->get_name();
1126 if ($instance->enrol !== $name) {
1127 throw new coding_exception('invalid enrol instance!');
1130 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1131 // weird, user not enrolled
1132 return;
1135 $modified = false;
1136 if (isset($status) and $ue->status != $status) {
1137 $ue->status = $status;
1138 $modified = true;
1140 if (isset($timestart) and $ue->timestart != $timestart) {
1141 $ue->timestart = $timestart;
1142 $modified = true;
1144 if (isset($timeend) and $ue->timeend != $timeend) {
1145 $ue->timeend = $timeend;
1146 $modified = true;
1149 if (!$modified) {
1150 // no change
1151 return;
1154 $ue->modifierid = $USER->id;
1155 $DB->update_record('user_enrolments', $ue);
1157 // trigger event
1158 $ue->courseid = $instance->courseid;
1159 $ue->enrol = $instance->name;
1160 events_trigger('user_unenrol_modified', $ue);
1164 * Unenrol user from course,
1165 * the last unenrolment removes all remaining roles.
1167 * @param stdClass $instance
1168 * @param int $userid
1169 * @return void
1171 public function unenrol_user(stdClass $instance, $userid) {
1172 global $CFG, $USER, $DB;
1174 $name = $this->get_name();
1175 $courseid = $instance->courseid;
1177 if ($instance->enrol !== $name) {
1178 throw new coding_exception('invalid enrol instance!');
1180 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1182 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1183 // weird, user not enrolled
1184 return;
1187 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1188 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1190 // add extra info and trigger event
1191 $ue->courseid = $courseid;
1192 $ue->enrol = $name;
1194 $sql = "SELECT 'x'
1195 FROM {user_enrolments} ue
1196 JOIN {enrol} e ON (e.id = ue.enrolid)
1197 WHERE ue.userid = :userid AND e.courseid = :courseid";
1198 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1199 $ue->lastenrol = false;
1200 events_trigger('user_unenrolled', $ue);
1201 // user still has some enrolments, no big cleanup yet
1202 } else {
1203 // the big cleanup IS necessary!
1205 require_once("$CFG->dirroot/group/lib.php");
1206 require_once("$CFG->libdir/gradelib.php");
1208 // remove all remaining roles
1209 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1211 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1212 groups_delete_group_members($courseid, $userid);
1214 grade_user_unenrol($courseid, $userid);
1216 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1218 $ue->lastenrol = true; // means user not enrolled any more
1219 events_trigger('user_unenrolled', $ue);
1221 // reset primitive require_login() caching
1222 if ($userid == $USER->id) {
1223 if (isset($USER->enrol['enrolled'][$courseid])) {
1224 unset($USER->enrol['enrolled'][$courseid]);
1226 if (isset($USER->enrol['tempguest'][$courseid])) {
1227 unset($USER->enrol['tempguest'][$courseid]);
1228 $USER->access = remove_temp_roles($context, $USER->access);
1234 * Forces synchronisation of user enrolments.
1236 * This is important especially for external enrol plugins,
1237 * this function is called for all enabled enrol plugins
1238 * right after every user login.
1240 * @param object $user user record
1241 * @return void
1243 public function sync_user_enrolments($user) {
1244 // override if necessary
1248 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1249 * @param int $courseid
1250 * @return moodle_url page url
1252 public function get_newinstance_link($courseid) {
1253 // override for most plugins, check if instance already exists in cases only one instance is supported
1254 return NULL;
1258 * Is it possible to delete enrol instance via standard UI?
1260 * @param object $instance
1261 * @return bool
1263 public function instance_deleteable($instance) {
1264 return true;
1268 * Returns link to manual enrol UI if exists.
1269 * Does the access control tests automatically.
1271 * @param object $instance
1272 * @return moodle_url
1274 public function get_manual_enrol_link($instance) {
1275 return NULL;
1279 * Returns list of unenrol links for all enrol instances in course.
1281 * @param int $instance
1282 * @return moodle_url or NULL if self unenrolment not supported
1284 public function get_unenrolself_link($instance) {
1285 global $USER, $CFG, $DB;
1287 $name = $this->get_name();
1288 if ($instance->enrol !== $name) {
1289 throw new coding_exception('invalid enrol instance!');
1292 if ($instance->courseid == SITEID) {
1293 return NULL;
1296 if (!enrol_is_enabled($name)) {
1297 return NULL;
1300 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1301 return NULL;
1304 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1305 return NULL;
1308 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1310 if (!has_capability("enrol/$name:unenrolself", $context)) {
1311 return NULL;
1314 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1315 return NULL;
1318 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1322 * Adds enrol instance UI to course edit form
1324 * @param object $instance enrol instance or null if does not exist yet
1325 * @param MoodleQuickForm $mform
1326 * @param object $data
1327 * @param object $context context of existing course or parent category if course does not exist
1328 * @return void
1330 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1331 // override - usually at least enable/disable switch, has to add own form header
1335 * Validates course edit form data
1337 * @param object $instance enrol instance or null if does not exist yet
1338 * @param array $data
1339 * @param object $context context of existing course or parent category if course does not exist
1340 * @return array errors array
1342 public function course_edit_validation($instance, array $data, $context) {
1343 return array();
1347 * Called after updating/inserting course.
1349 * @param bool $inserted true if course just inserted
1350 * @param object $course
1351 * @param object $data form data
1352 * @return void
1354 public function course_updated($inserted, $course, $data) {
1355 if ($inserted) {
1356 if ($this->get_config('defaultenrol')) {
1357 $this->add_default_instance($course);
1363 * Add new instance of enrol plugin.
1364 * @param object $course
1365 * @param array instance fields
1366 * @return int id of new instance, null if can not be created
1368 public function add_instance($course, array $fields = NULL) {
1369 global $DB;
1371 if ($course->id == SITEID) {
1372 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1375 $instance = new stdClass();
1376 $instance->enrol = $this->get_name();
1377 $instance->status = ENROL_INSTANCE_ENABLED;
1378 $instance->courseid = $course->id;
1379 $instance->enrolstartdate = 0;
1380 $instance->enrolenddate = 0;
1381 $instance->timemodified = time();
1382 $instance->timecreated = $instance->timemodified;
1383 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1385 $fields = (array)$fields;
1386 unset($fields['enrol']);
1387 unset($fields['courseid']);
1388 unset($fields['sortorder']);
1389 foreach($fields as $field=>$value) {
1390 $instance->$field = $value;
1393 return $DB->insert_record('enrol', $instance);
1397 * Add new instance of enrol plugin with default settings,
1398 * called when adding new instance manually or when adding new course.
1400 * Not all plugins support this.
1402 * @param object $course
1403 * @return int id of new instance or null if no default supported
1405 public function add_default_instance($course) {
1406 return null;
1410 * Delete course enrol plugin instance, unenrol all users.
1411 * @param object $instance
1412 * @return void
1414 public function delete_instance($instance) {
1415 global $DB;
1417 $name = $this->get_name();
1418 if ($instance->enrol !== $name) {
1419 throw new coding_exception('invalid enrol instance!');
1422 //first unenrol all users
1423 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1424 foreach ($participants as $participant) {
1425 $this->unenrol_user($instance, $participant->userid);
1427 $participants->close();
1429 // now clean up all remainders that were not removed correctly
1430 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>$name));
1431 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1433 // finally drop the enrol row
1434 $DB->delete_records('enrol', array('id'=>$instance->id));
1438 * Creates course enrol form, checks if form submitted
1439 * and enrols user if necessary. It can also redirect.
1441 * @param stdClass $instance
1442 * @return string html text, usually a form in a text box
1444 public function enrol_page_hook(stdClass $instance) {
1445 return null;
1449 * Adds navigation links into course admin block.
1451 * By defaults looks for manage links only.
1453 * @param navigation_node $instancesnode
1454 * @param object $instance
1455 * @return void
1457 public function add_course_navigation($instancesnode, stdClass $instance) {
1458 // usually adds manage users
1462 * Returns edit icons for the page with list of instances
1463 * @param stdClass $instance
1464 * @return array
1466 public function get_action_icons(stdClass $instance) {
1467 return array();
1471 * Reads version.php and determines if it is necessary
1472 * to execute the cron job now.
1473 * @return bool
1475 public function is_cron_required() {
1476 global $CFG;
1478 $name = $this->get_name();
1479 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
1480 $plugin = new stdClass();
1481 include($versionfile);
1482 if (empty($plugin->cron)) {
1483 return false;
1485 $lastexecuted = $this->get_config('lastcron', 0);
1486 if ($lastexecuted + $plugin->cron < time()) {
1487 return true;
1488 } else {
1489 return false;
1494 * Called for all enabled enrol plugins that returned true from is_cron_required().
1495 * @return void
1497 public function cron() {
1501 * Called when user is about to be deleted
1502 * @param object $user
1503 * @return void
1505 public function user_delete($user) {
1506 global $DB;
1508 $sql = "SELECT e.*
1509 FROM {enrol} e
1510 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1511 WHERE e.enrol = :name AND ue.userid = :userid";
1512 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1514 $rs = $DB->get_recordset_sql($sql, $params);
1515 foreach($rs as $instance) {
1516 $this->unenrol_user($instance, $user->id);
1518 $rs->close();
1522 * Returns an enrol_user_button that takes the user to a page where they are able to
1523 * enrol users into the managers course through this plugin.
1525 * Optional: If the plugin supports manual enrolments it can choose to override this
1526 * otherwise it shouldn't
1528 * @param course_enrolment_manager $manager
1529 * @return enrol_user_button|false
1531 public function get_manual_enrol_button(course_enrolment_manager $manager) {
1532 return false;
1536 * Gets an array of the user enrolment actions
1538 * @param course_enrolment_manager $manager
1539 * @param stdClass $ue
1540 * @return array An array of user_enrolment_actions
1542 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
1543 return array();
1547 * Returns true if the plugin has one or more bulk operations that can be performed on
1548 * user enrolments.
1550 * @return bool
1552 public function has_bulk_operations() {
1553 return false;
1557 * Return an array of enrol_bulk_enrolment_operation objects that define
1558 * the bulk actions that can be performed on user enrolments by the plugin.
1560 * @return array
1562 public function get_bulk_operations() {
1563 return array();