MDL-24471, FILEMANAGER change <button> to <input type="button" />, moodle form may...
[moodle.git] / lib / enrollib.php
blobe579019ab79b3013631dad17c773d176aead91c5
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 * This function adds necessary enrol plugins UI into the course edit form.
226 * @param MoodleQuickForm $mform
227 * @param object $data course edit form data
228 * @param object $context context of existing course or parent category if course does not exist
229 * @return void
231 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
232 $plugins = enrol_get_plugins(true);
233 if (!empty($data->id)) {
234 $instances = enrol_get_instances($data->id, false);
235 foreach ($instances as $instance) {
236 if (!isset($plugins[$instance->enrol])) {
237 continue;
239 $plugin = $plugins[$instance->enrol];
240 $plugin->course_edit_form($instance, $mform, $data, $context);
242 } else {
243 foreach ($plugins as $plugin) {
244 $plugin->course_edit_form(NULL, $mform, $data, $context);
250 * Validate course edit form data
252 * @param array $data raw form data
253 * @param object $context context of existing course or parent category if course does not exist
254 * @return array errors array
256 function enrol_course_edit_validation(array $data, $context) {
257 $errors = array();
258 $plugins = enrol_get_plugins(true);
260 if (!empty($data['id'])) {
261 $instances = enrol_get_instances($data['id'], false);
262 foreach ($instances as $instance) {
263 if (!isset($plugins[$instance->enrol])) {
264 continue;
266 $plugin = $plugins[$instance->enrol];
267 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
269 } else {
270 foreach ($plugins as $plugin) {
271 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
275 return $errors;
279 * Update enrol instances after course edit form submission
280 * @param bool $inserted true means new course added, false course already existed
281 * @param object $course
282 * @param object $data form data
283 * @return void
285 function enrol_course_updated($inserted, $course, $data) {
286 global $DB, $CFG;
288 $plugins = enrol_get_plugins(true);
290 foreach ($plugins as $plugin) {
291 $plugin->course_updated($inserted, $course, $data);
296 * Add navigation nodes
297 * @param navigation_node $coursenode
298 * @param object $course
299 * @return void
301 function enrol_add_course_navigation(navigation_node $coursenode, $course) {
302 global $CFG;
304 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
306 $instances = enrol_get_instances($course->id, true);
307 $plugins = enrol_get_plugins(true);
309 // we do not want to break all course pages if there is some borked enrol plugin, right?
310 foreach ($instances as $k=>$instance) {
311 if (!isset($plugins[$instance->enrol])) {
312 unset($instances[$k]);
316 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
318 if ($course->id != SITEID) {
319 // list all participants - allows assigning roles, groups, etc.
320 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
321 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
322 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/users', ''));
325 // manage enrol plugin instances
326 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
327 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
328 } else {
329 $url = NULL;
331 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
333 // each instance decides how to configure itself or how many other nav items are exposed
334 foreach ($instances as $instance) {
335 if (!isset($plugins[$instance->enrol])) {
336 continue;
338 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
341 if (!$url) {
342 $instancesnode->trim_if_empty();
346 // Manage groups in this course or even frontpage
347 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
348 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
349 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
352 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
353 // Override roles
354 if (has_capability('moodle/role:review', $coursecontext)) {
355 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
356 } else {
357 $url = NULL;
359 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
361 // Add assign or override roles if allowed
362 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
363 if (has_capability('moodle/role:assign', $coursecontext)) {
364 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
365 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/roles', ''));
368 // Check role permissions
369 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
370 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
371 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
375 // Deal somehow with users that are not enrolled but still got a role somehow
376 if ($course->id != SITEID) {
377 //TODO, create some new UI for role assignments at course level
378 if (has_capability('moodle/role:assign', $coursecontext)) {
379 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
380 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/roles', ''));
384 // just in case nothing was actually added
385 $usersnode->trim_if_empty();
387 if ($course->id != SITEID) {
388 // Unenrol link
389 if (is_enrolled($coursecontext)) {
390 foreach ($instances as $instance) {
391 if (!isset($plugins[$instance->enrol])) {
392 continue;
394 $plugin = $plugins[$instance->enrol];
395 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
396 $coursenode->add(get_string('unenrolme', 'core_enrol', format_string($course->shortname)), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
397 break;
398 //TODO. deal with multiple unenrol links - not likely case, but still...
401 } else {
402 if (is_viewing($coursecontext)) {
403 // better not show any enrol link, this is intended for managers and inspectors
404 } else {
405 foreach ($instances as $instance) {
406 if (!isset($plugins[$instance->enrol])) {
407 continue;
409 $plugin = $plugins[$instance->enrol];
410 if ($plugin->show_enrolme_link($instance)) {
411 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
412 $coursenode->add(get_string('enrolme', 'core_enrol', format_string($course->shortname)), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
413 break;
422 * Returns list of courses current $USER is enrolled in and can access
424 * - $fields is an array of field names to ADD
425 * so name the fields you really need, which will
426 * be added and uniq'd
428 * @param string|array $fields
429 * @param string $sort
430 * @param int $limit max number of courses
431 * @return array
433 function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
434 global $DB, $USER;
436 // Guest account does not have any courses
437 if (isguestuser() or !isloggedin()) {
438 return(array());
441 $basefields = array('id', 'category', 'sortorder',
442 'shortname', 'fullname', 'idnumber',
443 'startdate', 'visible',
444 'groupmode', 'groupmodeforce');
446 if (empty($fields)) {
447 $fields = $basefields;
448 } else if (is_string($fields)) {
449 // turn the fields from a string to an array
450 $fields = explode(',', $fields);
451 $fields = array_map('trim', $fields);
452 $fields = array_unique(array_merge($basefields, $fields));
453 } else if (is_array($fields)) {
454 $fields = array_unique(array_merge($basefields, $fields));
455 } else {
456 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
458 if (in_array('*', $fields)) {
459 $fields = array('*');
462 $orderby = "";
463 $sort = trim($sort);
464 if (!empty($sort)) {
465 $rawsorts = explode(',', $sort);
466 $sorts = array();
467 foreach ($rawsorts as $rawsort) {
468 $rawsort = trim($rawsort);
469 if (strpos($rawsort, 'c.') === 0) {
470 $rawsort = substr($rawsort, 2);
472 $sorts[] = trim($rawsort);
474 $sort = 'c.'.implode(',c.', $sorts);
475 $orderby = "ORDER BY $sort";
478 $wheres = array("c.id <> :siteid");
479 $params = array('siteid'=>SITEID);
481 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
482 // list _only_ this course - anything else is asking for trouble...
483 $wheres[] = "courseid = :loginas";
484 $params['loginas'] = $USER->loginascontext->instanceid;
487 $coursefields = 'c.' .join(',c.', $fields);
488 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
489 $wheres = implode(" AND ", $wheres);
491 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
492 $sql = "SELECT $coursefields $ccselect
493 FROM {course} c
494 JOIN (SELECT DISTINCT e.courseid
495 FROM {enrol} e
496 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
497 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
498 ) en ON (en.courseid = c.id)
499 $ccjoin
500 WHERE $wheres
501 $orderby";
502 $params['userid'] = $USER->id;
503 $params['active'] = ENROL_USER_ACTIVE;
504 $params['enabled'] = ENROL_INSTANCE_ENABLED;
505 $params['now1'] = round(time(), -2); // improves db caching
506 $params['now2'] = $params['now1'];
508 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
510 // preload contexts and check visibility
511 foreach ($courses as $id=>$course) {
512 context_instance_preload($course);
513 if (!$course->visible) {
514 if (!$context = get_context_instance(CONTEXT_COURSE, $id)) {
515 unset($courses[$id]);
516 continue;
518 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
519 unset($courses[$id]);
520 continue;
523 $courses[$id] = $course;
526 //wow! Is that really all? :-D
528 return $courses;
532 * Returns course enrolment information icons.
534 * @param object $course
535 * @param array $instances enrol instances of this course, improves performance
536 * @return array of pix_icon
538 function enrol_get_course_info_icons($course, array $instances = NULL) {
539 $icons = array();
540 if (is_null($instances)) {
541 $instances = enrol_get_instances($course->id, true);
543 $plugins = enrol_get_plugins(true);
544 foreach ($plugins as $name => $plugin) {
545 $pis = array();
546 foreach ($instances as $instance) {
547 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
548 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
549 continue;
551 if ($instance->enrol == $name) {
552 $pis[$instance->id] = $instance;
555 if ($pis) {
556 $icons = array_merge($icons, $plugin->get_info_icons($pis));
559 return $icons;
563 * Returns course enrolment detailed information.
565 * @param object $course
566 * @return array of html fragments - can be used to construct lists
568 function enrol_get_course_description_texts($course) {
569 $lines = array();
570 $instances = enrol_get_instances($course->id, true);
571 $plugins = enrol_get_plugins(true);
572 foreach ($instances as $instance) {
573 if (!isset($plugins[$instance->enrol])) {
574 //weird
575 continue;
577 $plugin = $plugins[$instance->enrol];
578 $text = $plugin->get_description_text($instance);
579 if ($text !== NULL) {
580 $lines[] = $text;
583 return $lines;
587 * Returns list of courses user is enrolled into.
589 * - $fields is an array of fieldnames to ADD
590 * so name the fields you really need, which will
591 * be added and uniq'd
593 * @param int $userid
594 * @param bool $onlyactive return only active enrolments in courses user may see
595 * @param string|array $fields
596 * @param string $sort
597 * @return array
599 function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
600 global $DB;
602 // Guest account does not have any courses
603 if (isguestuser($userid) or empty($userid)) {
604 return(array());
607 $basefields = array('id', 'category', 'sortorder',
608 'shortname', 'fullname', 'idnumber',
609 'startdate', 'visible',
610 'groupmode', 'groupmodeforce');
612 if (empty($fields)) {
613 $fields = $basefields;
614 } else if (is_string($fields)) {
615 // turn the fields from a string to an array
616 $fields = explode(',', $fields);
617 $fields = array_map('trim', $fields);
618 $fields = array_unique(array_merge($basefields, $fields));
619 } else if (is_array($fields)) {
620 $fields = array_unique(array_merge($basefields, $fields));
621 } else {
622 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
624 if (in_array('*', $fields)) {
625 $fields = array('*');
628 $orderby = "";
629 $sort = trim($sort);
630 if (!empty($sort)) {
631 $rawsorts = explode(',', $sort);
632 $sorts = array();
633 foreach ($rawsorts as $rawsort) {
634 $rawsort = trim($rawsort);
635 if (strpos($rawsort, 'c.') === 0) {
636 $rawsort = substr($rawsort, 2);
638 $sorts[] = trim($rawsort);
640 $sort = 'c.'.implode(',c.', $sorts);
641 $orderby = "ORDER BY $sort";
644 $params = array('siteid'=>SITEID);
646 if ($onlyactive) {
647 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
648 $params['now1'] = round(time(), -2); // improves db caching
649 $params['now2'] = $params['now1'];
650 $params['active'] = ENROL_USER_ACTIVE;
651 $params['enabled'] = ENROL_INSTANCE_ENABLED;
652 } else {
653 $subwhere = "";
656 $coursefields = 'c.' .join(',c.', $fields);
657 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
659 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
660 $sql = "SELECT $coursefields $ccselect
661 FROM {course} c
662 JOIN (SELECT DISTINCT e.courseid
663 FROM {enrol} e
664 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
665 $subwhere
666 ) en ON (en.courseid = c.id)
667 $ccjoin
668 WHERE c.id <> :siteid
669 $orderby";
670 $params['userid'] = $userid;
672 $courses = $DB->get_records_sql($sql, $params);
674 // preload contexts and check visibility
675 foreach ($courses as $id=>$course) {
676 context_instance_preload($course);
677 if ($onlyactive) {
678 if (!$course->visible) {
679 if (!$context = get_context_instance(CONTEXT_COURSE, $id)) {
680 unset($courses[$id]);
681 continue;
683 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
684 unset($courses[$id]);
685 continue;
689 $courses[$id] = $course;
692 //wow! Is that really all? :-D
694 return $courses;
699 * Called when user is about to be deleted.
700 * @param object $user
701 * @return void
703 function enrol_user_delete($user) {
704 global $DB;
706 $plugins = enrol_get_plugins(true);
707 foreach ($plugins as $plugin) {
708 $plugin->user_delete($user);
711 // force cleanup of all broken enrolments
712 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
716 * Called when course is about to be deleted.
717 * @param stdClass $object
718 * @return void
720 function enrol_course_delete($course) {
721 global $DB;
723 $instances = enrol_get_instances($course->id, false);
724 $plugins = enrol_get_plugins(true);
725 foreach ($instances as $instance) {
726 if (isset($plugins[$instance->enrol])) {
727 $plugins[$instance->enrol]->delete_instance($instance);
729 // low level delete in case plugin did not do it
730 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
731 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
732 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
733 $DB->delete_records('enrol', array('id'=>$instance->id));
738 * Try to enrol user via default internal auth plugin.
740 * For now this is always using the manual enrol plugin...
742 * @param $courseid
743 * @param $userid
744 * @param $roleid
745 * @param $timestart
746 * @param $timeend
747 * @return bool success
749 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
750 global $DB;
752 //note: this is hardcoded to manual plugin for now
754 if (!enrol_is_enabled('manual')) {
755 return false;
758 if (!$enrol = enrol_get_plugin('manual')) {
759 return false;
761 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
762 return false;
764 $instance = reset($instances);
766 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
768 return true;
772 * All enrol plugins should be based on this class,
773 * this is also the main source of documentation.
775 abstract class enrol_plugin {
776 protected $config = null;
779 * Returns name of this enrol plugin
780 * @return string
782 public function get_name() {
783 // second word in class is always enrol name, sorry, no fancy plugin names with _
784 $words = explode('_', get_class($this));
785 return $words[1];
789 * Returns localised name of enrol instance
791 * @param object $instance (null is accepted too)
792 * @return string
794 public function get_instance_name($instance) {
795 if (empty($instance->name)) {
796 $enrol = $this->get_name();
797 return get_string('pluginname', 'enrol_'.$enrol);
798 } else {
799 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid);
800 return format_string($instance->name, true, array('context'=>$context));
805 * Returns optional enrolment information icons.
807 * This is used in course list for quick overview of enrolment options.
809 * We are not using single instance parameter because sometimes
810 * we might want to prevent icon repetition when multiple instances
811 * of one type exist. One instance may also produce several icons.
813 * @param array $instances all enrol instances of this type in one course
814 * @return array of pix_icon
816 public function get_info_icons(array $instances) {
817 return array();
821 * Returns optional enrolment instance description text.
823 * This is used in detailed course information.
826 * @param object $instance
827 * @return string short html text
829 public function get_description_text($instance) {
830 return null;
834 * Makes sure config is loaded and cached.
835 * @return void
837 protected function load_config() {
838 if (!isset($this->config)) {
839 $name = $this->get_name();
840 if (!$config = get_config("enrol_$name")) {
841 $config = new stdClass();
843 $this->config = $config;
848 * Returns plugin config value
849 * @param string $name
850 * @param string $default value if config does not exist yet
851 * @return string value or default
853 public function get_config($name, $default = NULL) {
854 $this->load_config();
855 return isset($this->config->$name) ? $this->config->$name : $default;
859 * Sets plugin config value
860 * @param string $name name of config
861 * @param string $value string config value, null means delete
862 * @return string value
864 public function set_config($name, $value) {
865 $pluginname = $this->get_name();
866 $this->load_config();
867 if ($value === NULL) {
868 unset($this->config->$name);
869 } else {
870 $this->config->$name = $value;
872 set_config($name, $value, "enrol_$pluginname");
876 * Does this plugin assign protected roles are can they be manually removed?
877 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
879 public function roles_protected() {
880 return true;
884 * Does this plugin allow manual enrolments?
886 * @param stdClass $instance course enrol instance
887 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
889 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, trues means nobody may add more enrolments manually
891 public function allow_enrol(stdClass $instance) {
892 return false;
896 * Does this plugin allow manual unenrolments?
898 * @param stdClass $instance course enrol instance
899 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
901 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, trues means nobody may touch user_enrolments
903 public function allow_unenrol(stdClass $instance) {
904 return false;
908 * Does this plugin allow manual changes in user_enrolments table?
910 * All plugins allowing this must implement 'enrol/xxx:manage' capability
912 * @param stdClass $instance course enrol instance
913 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
915 public function allow_manage(stdClass $instance) {
916 return false;
920 * Does this plugin support some way to user to self enrol?
922 * @param stdClass $instance course enrol instance
924 * @return bool - true means show "Enrol me in this course" link in course UI
926 public function show_enrolme_link(stdClass $instance) {
927 return false;
931 * Attempt to automatically enrol current user in course without any interaction,
932 * calling code has to make sure the plugin and instance are active.
934 * @param stdClass $instance course enrol instance
935 * @param stdClass $user record
936 * @return bool|int false means not enrolled, integer means timeend
938 public function try_autoenrol(stdClass $instance) {
939 global $USER;
941 return false;
945 * Attempt to automatically gain temporary guest access to course,
946 * calling code has to make sure the plugin and instance are active.
948 * @param stdClass $instance course enrol instance
949 * @param stdClass $user record
950 * @return bool|int false means no guest access, integer means timeend
952 public function try_guestaccess(stdClass $instance) {
953 global $USER;
955 return false;
959 * Enrol user into course via enrol instance.
961 * @param stdClass $instance
962 * @param int $userid
963 * @param int $roleid optional role id
964 * @param int $timestart 0 means unknown
965 * @param int $timeend 0 means forever
966 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
967 * @return void
969 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
970 global $DB, $USER, $CFG; // CFG necessary!!!
972 if ($instance->courseid == SITEID) {
973 throw new coding_exception('invalid attempt to enrol into frontpage course!');
976 $name = $this->get_name();
977 $courseid = $instance->courseid;
979 if ($instance->enrol !== $name) {
980 throw new coding_exception('invalid enrol instance!');
982 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
984 $inserted = false;
985 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
986 if ($ue->timestart != $timestart or $ue->timeend != $timeend) {
987 $ue->timestart = $timestart;
988 $ue->timeend = $timeend;
989 $ue->modifier = $USER->id;
990 $ue->timemodified = time();
991 $DB->update_record('user_enrolments', $ue);
993 } else {
994 $ue = new stdClass();
995 $ue->enrolid = $instance->id;
996 $ue->status = ENROL_USER_ACTIVE;
997 $ue->userid = $userid;
998 $ue->timestart = $timestart;
999 $ue->timeend = $timeend;
1000 $ue->modifier = $USER->id;
1001 $ue->timecreated = time();
1002 $ue->timemodified = $ue->timecreated;
1003 $ue->id = $DB->insert_record('user_enrolments', $ue);
1005 $inserted = true;
1008 if ($roleid) {
1009 if ($this->roles_protected()) {
1010 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1011 } else {
1012 role_assign($roleid, $userid, $context->id);
1016 if ($inserted) {
1017 // add extra info and trigger event
1018 $ue->courseid = $courseid;
1019 $ue->enrol = $name;
1020 events_trigger('user_enrolled', $ue);
1023 // reset primitive require_login() caching
1024 if ($userid == $USER->id) {
1025 if (isset($USER->enrol['enrolled'][$courseid])) {
1026 unset($USER->enrol['enrolled'][$courseid]);
1028 if (isset($USER->enrol['tempguest'][$courseid])) {
1029 unset($USER->enrol['tempguest'][$courseid]);
1030 $USER->access = remove_temp_roles($context, $USER->access);
1036 * Store user_enrolments changes and trigger event.
1038 * @param object $ue
1039 * @param int $user id
1040 * @param int $status
1041 * @param int $timestart
1042 * @param int $timeend
1043 * @return void
1045 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1046 global $DB, $USER;
1048 $name = $this->get_name();
1050 if ($instance->enrol !== $name) {
1051 throw new coding_exception('invalid enrol instance!');
1054 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1055 // weird, user not enrolled
1056 return;
1059 $modified = false;
1060 if (isset($status) and $ue->status != $status) {
1061 $ue->status = $status;
1062 $modified = true;
1064 if (isset($timestart) and $ue->timestart != $timestart) {
1065 $ue->timestart = $timestart;
1066 $modified = true;
1068 if (isset($timeend) and $ue->timeend != $timeend) {
1069 $ue->timeend = $timeend;
1070 $modified = true;
1073 if (!$modified) {
1074 // no change
1075 return;
1078 $ue->modifierid = $USER->id;
1079 $DB->update_record('user_enrolments', $ue);
1081 // trigger event
1082 $ue->courseid = $instance->courseid;
1083 $ue->enrol = $instance->name;
1084 events_trigger('user_unenrol_modified', $ue);
1088 * Unenrol user from course,
1089 * the last unenrolment removes all remaining roles.
1091 * @param stdClass $instance
1092 * @param int $userid
1093 * @return void
1095 public function unenrol_user(stdClass $instance, $userid) {
1096 global $CFG, $USER, $DB;
1098 $name = $this->get_name();
1099 $courseid = $instance->courseid;
1101 if ($instance->enrol !== $name) {
1102 throw new coding_exception('invalid enrol instance!');
1104 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1106 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1107 // weird, user not enrolled
1108 return;
1111 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1112 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1114 // add extra info and trigger event
1115 $ue->courseid = $courseid;
1116 $ue->enrol = $name;
1118 $sql = "SELECT 'x'
1119 FROM {user_enrolments} ue
1120 JOIN {enrol} e ON (e.id = ue.enrolid)
1121 WHERE ue.userid = :userid AND e.courseid = :courseid";
1122 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1123 $ue->lastenrol = false;
1124 events_trigger('user_unenrolled', $ue);
1125 // user still has some enrolments, no big cleanup yet
1126 } else {
1127 // the big cleanup IS necessary!
1129 require_once("$CFG->dirroot/group/lib.php");
1130 require_once("$CFG->libdir/gradelib.php");
1132 // remove all remaining roles
1133 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1135 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1136 groups_delete_group_members($courseid, $userid);
1138 grade_user_unenrol($courseid, $userid);
1140 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1142 $ue->lastenrol = true; // means user not enrolled any more
1143 events_trigger('user_unenrolled', $ue);
1145 // reset primitive require_login() caching
1146 if ($userid == $USER->id) {
1147 if (isset($USER->enrol['enrolled'][$courseid])) {
1148 unset($USER->enrol['enrolled'][$courseid]);
1150 if (isset($USER->enrol['tempguest'][$courseid])) {
1151 unset($USER->enrol['tempguest'][$courseid]);
1152 $USER->access = remove_temp_roles($context, $USER->access);
1158 * Forces synchronisation of user enrolments.
1160 * This is important especially for external enrol plugins,
1161 * this function is called for all enabled enrol plugins
1162 * right after every user login.
1164 * @param object $user user record
1165 * @return void
1167 public function sync_user_enrolments($user) {
1168 // override if necessary
1172 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1173 * @param int $courseid
1174 * @return moodle_url page url
1176 public function get_newinstance_link($courseid) {
1177 // override for most plugins, check if instance already exists in cases only one instance is supported
1178 return NULL;
1182 * Is it possible to delete enrol instance via standard UI?
1184 * @param object $instance
1185 * @return bool
1187 public function instance_deleteable($instance) {
1188 return true;
1192 * Returns link to manual enrol UI if exists.
1193 * Does the access control tests automatically.
1195 * @param object $instance
1196 * @return moodle_url
1198 public function get_manual_enrol_link($instance) {
1199 return NULL;
1203 * Returns list of unenrol links for all enrol instances in course.
1205 * @param int $instance
1206 * @return moodle_url or NULL if self unenrolment not supported
1208 public function get_unenrolself_link($instance) {
1209 global $USER, $CFG, $DB;
1211 $name = $this->get_name();
1212 if ($instance->enrol !== $name) {
1213 throw new coding_exception('invalid enrol instance!');
1216 if ($instance->courseid == SITEID) {
1217 return NULL;
1220 if (!enrol_is_enabled($name)) {
1221 return NULL;
1224 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1225 return NULL;
1228 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1229 return NULL;
1232 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1234 if (!has_capability("enrol/$name:unenrolself", $context)) {
1235 return NULL;
1238 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1239 return NULL;
1242 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1246 * Adds enrol instance UI to course edit form
1248 * @param object $instance enrol instance or null if does not exist yet
1249 * @param MoodleQuickForm $mform
1250 * @param object $data
1251 * @param object $context context of existing course or parent category if course does not exist
1252 * @return void
1254 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1255 // override - usually at least enable/disable switch, has to add own form header
1259 * Validates course edit form data
1261 * @param object $instance enrol instance or null if does not exist yet
1262 * @param array $data
1263 * @param object $context context of existing course or parent category if course does not exist
1264 * @return array errors array
1266 public function course_edit_validation($instance, array $data, $context) {
1267 return array();
1271 * Called after updating/inserting course.
1273 * @param bool $inserted true if course just inserted
1274 * @param object $course
1275 * @param object $data form data
1276 * @return void
1278 public function course_updated($inserted, $course, $data) {
1279 if ($inserted) {
1280 if ($this->get_config('defaultenrol')) {
1281 $this->add_default_instance($course);
1287 * Add new instance of enrol plugin.
1288 * @param object $course
1289 * @param array instance fields
1290 * @return int id of new instance, null if can not be created
1292 public function add_instance($course, array $fields = NULL) {
1293 global $DB;
1295 if ($course->id == SITEID) {
1296 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1299 $instance = new stdClass();
1300 $instance->enrol = $this->get_name();
1301 $instance->status = ENROL_INSTANCE_ENABLED;
1302 $instance->courseid = $course->id;
1303 $instance->enrolstartdate = 0;
1304 $instance->enrolenddate = 0;
1305 $instance->timemodified = time();
1306 $instance->timecreated = $instance->timemodified;
1307 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1309 $fields = (array)$fields;
1310 unset($fields['enrol']);
1311 unset($fields['courseid']);
1312 unset($fields['sortorder']);
1313 foreach($fields as $field=>$value) {
1314 $instance->$field = $value;
1317 return $DB->insert_record('enrol', $instance);
1321 * Add new instance of enrol plugin with default settings,
1322 * called when adding new instance manually or when adding new course.
1324 * Not all plugins support this.
1326 * @param object $course
1327 * @return int id of new instance or null if no default supported
1329 public function add_default_instance($course) {
1330 return null;
1334 * Delete course enrol plugin instance, unenrol all users.
1335 * @param object $instance
1336 * @return void
1338 public function delete_instance($instance) {
1339 global $DB;
1341 $name = $this->get_name();
1342 if ($instance->enrol !== $name) {
1343 throw new coding_exception('invalid enrol instance!');
1346 //first unenrol all users
1347 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1348 foreach ($participants as $participant) {
1349 $this->unenrol_user($instance, $participant->userid);
1351 $participants->close();
1353 // now clean up all remainders that were not removed correctly
1354 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>$name));
1355 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1357 // finally drop the enrol row
1358 $DB->delete_records('enrol', array('id'=>$instance->id));
1362 * Creates course enrol form, checks if form submitted
1363 * and enrols user if necessary. It can also redirect.
1365 * @param stdClass $instance
1366 * @return string html text, usually a form in a text box
1368 public function enrol_page_hook(stdClass $instance) {
1369 return null;
1373 * Adds navigation links into course admin block.
1375 * By defaults looks for manage links only.
1377 * @param navigation_node $instancesnode
1378 * @param object $instance
1379 * @return void
1381 public function add_course_navigation($instancesnode, stdClass $instance) {
1382 // usually adds manage users
1386 * Returns edit icons for the page with list of instances
1387 * @param stdClass $instance
1388 * @return array
1390 public function get_action_icons(stdClass $instance) {
1391 return array();
1395 * Reads version.php and determines if it is necessary
1396 * to execute the cron job now.
1397 * @return bool
1399 public function is_cron_required() {
1400 global $CFG;
1402 $name = $this->get_name();
1403 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
1404 $plugin = new stdClass();
1405 include($versionfile);
1406 if (empty($plugin->cron)) {
1407 return false;
1409 $lastexecuted = $this->get_config('lastcron', 0);
1410 if ($lastexecuted + $plugin->cron < time()) {
1411 return true;
1412 } else {
1413 return false;
1418 * Called for all enabled enrol plugins that returned true from is_cron_required().
1419 * @return void
1421 public function cron() {
1425 * Called when user is about to be deleted
1426 * @param object $user
1427 * @return void
1429 public function user_delete($user) {
1430 global $DB;
1432 $sql = "SELECT e.*
1433 FROM {enrol} e
1434 JOIN {user_enrolments} ue ON (ue.courseid = e.courseid)
1435 WHERE e.enrol = :meta AND ue.userid = :userid";
1436 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1438 $rs = $DB->get_records_recordset($sql, $params);
1439 foreach($rs as $instance) {
1440 $this->unenrol_user($instance, $user->id);
1442 $rs->close();