Automatic installer lang files (20110214)
[moodle.git] / lib / enrollib.php
blob5c338b5008ffd581d5ba99fa01f3ce50baed401d
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 * Is there a chance users might self enrol
773 * @param int $courseid
774 * @return bool
776 function enrol_selfenrol_available($courseid) {
777 $result = false;
779 $plugins = enrol_get_plugins(true);
780 $enrolinstances = enrol_get_instances($courseid, true);
781 foreach($enrolinstances as $instance) {
782 if (!isset($plugins[$instance->enrol])) {
783 continue;
785 if ($instance->enrol === 'guest') {
786 // blacklist known temporary guest plugins
787 continue;
789 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
790 $result = true;
791 break;
795 return $result;
799 * All enrol plugins should be based on this class,
800 * this is also the main source of documentation.
802 abstract class enrol_plugin {
803 protected $config = null;
806 * Returns name of this enrol plugin
807 * @return string
809 public function get_name() {
810 // second word in class is always enrol name, sorry, no fancy plugin names with _
811 $words = explode('_', get_class($this));
812 return $words[1];
816 * Returns localised name of enrol instance
818 * @param object $instance (null is accepted too)
819 * @return string
821 public function get_instance_name($instance) {
822 if (empty($instance->name)) {
823 $enrol = $this->get_name();
824 return get_string('pluginname', 'enrol_'.$enrol);
825 } else {
826 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid);
827 return format_string($instance->name, true, array('context'=>$context));
832 * Returns optional enrolment information icons.
834 * This is used in course list for quick overview of enrolment options.
836 * We are not using single instance parameter because sometimes
837 * we might want to prevent icon repetition when multiple instances
838 * of one type exist. One instance may also produce several icons.
840 * @param array $instances all enrol instances of this type in one course
841 * @return array of pix_icon
843 public function get_info_icons(array $instances) {
844 return array();
848 * Returns optional enrolment instance description text.
850 * This is used in detailed course information.
853 * @param object $instance
854 * @return string short html text
856 public function get_description_text($instance) {
857 return null;
861 * Makes sure config is loaded and cached.
862 * @return void
864 protected function load_config() {
865 if (!isset($this->config)) {
866 $name = $this->get_name();
867 if (!$config = get_config("enrol_$name")) {
868 $config = new stdClass();
870 $this->config = $config;
875 * Returns plugin config value
876 * @param string $name
877 * @param string $default value if config does not exist yet
878 * @return string value or default
880 public function get_config($name, $default = NULL) {
881 $this->load_config();
882 return isset($this->config->$name) ? $this->config->$name : $default;
886 * Sets plugin config value
887 * @param string $name name of config
888 * @param string $value string config value, null means delete
889 * @return string value
891 public function set_config($name, $value) {
892 $pluginname = $this->get_name();
893 $this->load_config();
894 if ($value === NULL) {
895 unset($this->config->$name);
896 } else {
897 $this->config->$name = $value;
899 set_config($name, $value, "enrol_$pluginname");
903 * Does this plugin assign protected roles are can they be manually removed?
904 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
906 public function roles_protected() {
907 return true;
911 * Does this plugin allow manual enrolments?
913 * @param stdClass $instance course enrol instance
914 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
916 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, trues means nobody may add more enrolments manually
918 public function allow_enrol(stdClass $instance) {
919 return false;
923 * Does this plugin allow manual unenrolments?
925 * @param stdClass $instance course enrol instance
926 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
928 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, trues means nobody may touch user_enrolments
930 public function allow_unenrol(stdClass $instance) {
931 return false;
935 * Does this plugin allow manual changes in user_enrolments table?
937 * All plugins allowing this must implement 'enrol/xxx:manage' capability
939 * @param stdClass $instance course enrol instance
940 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
942 public function allow_manage(stdClass $instance) {
943 return false;
947 * Does this plugin support some way to user to self enrol?
949 * @param stdClass $instance course enrol instance
951 * @return bool - true means show "Enrol me in this course" link in course UI
953 public function show_enrolme_link(stdClass $instance) {
954 return false;
958 * Attempt to automatically enrol current user in course without any interaction,
959 * calling code has to make sure the plugin and instance are active.
961 * This should return either a timestamp in the future or false.
963 * @param stdClass $instance course enrol instance
964 * @param stdClass $user record
965 * @return bool|int false means not enrolled, integer means timeend
967 public function try_autoenrol(stdClass $instance) {
968 global $USER;
970 return false;
974 * Attempt to automatically gain temporary guest access to course,
975 * calling code has to make sure the plugin and instance are active.
977 * This should return either a timestamp in the future or false.
979 * @param stdClass $instance course enrol instance
980 * @param stdClass $user record
981 * @return bool|int false means no guest access, integer means timeend
983 public function try_guestaccess(stdClass $instance) {
984 global $USER;
986 return false;
990 * Enrol user into course via enrol instance.
992 * @param stdClass $instance
993 * @param int $userid
994 * @param int $roleid optional role id
995 * @param int $timestart 0 means unknown
996 * @param int $timeend 0 means forever
997 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
998 * @return void
1000 public function enrol_user(stdClass $instance, $userid, $roleid = NULL, $timestart = 0, $timeend = 0, $status = NULL) {
1001 global $DB, $USER, $CFG; // CFG necessary!!!
1003 if ($instance->courseid == SITEID) {
1004 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1007 $name = $this->get_name();
1008 $courseid = $instance->courseid;
1010 if ($instance->enrol !== $name) {
1011 throw new coding_exception('invalid enrol instance!');
1013 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1015 $inserted = false;
1016 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1017 if ($ue->timestart != $timestart or $ue->timeend != $timeend) {
1018 $ue->timestart = $timestart;
1019 $ue->timeend = $timeend;
1020 $ue->modifier = $USER->id;
1021 $ue->timemodified = time();
1022 $DB->update_record('user_enrolments', $ue);
1024 } else {
1025 $ue = new stdClass();
1026 $ue->enrolid = $instance->id;
1027 $ue->status = ENROL_USER_ACTIVE;
1028 $ue->userid = $userid;
1029 $ue->timestart = $timestart;
1030 $ue->timeend = $timeend;
1031 $ue->modifier = $USER->id;
1032 $ue->timecreated = time();
1033 $ue->timemodified = $ue->timecreated;
1034 $ue->id = $DB->insert_record('user_enrolments', $ue);
1036 $inserted = true;
1039 if ($roleid) {
1040 if ($this->roles_protected()) {
1041 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1042 } else {
1043 role_assign($roleid, $userid, $context->id);
1047 if ($inserted) {
1048 // add extra info and trigger event
1049 $ue->courseid = $courseid;
1050 $ue->enrol = $name;
1051 events_trigger('user_enrolled', $ue);
1054 // reset primitive require_login() caching
1055 if ($userid == $USER->id) {
1056 if (isset($USER->enrol['enrolled'][$courseid])) {
1057 unset($USER->enrol['enrolled'][$courseid]);
1059 if (isset($USER->enrol['tempguest'][$courseid])) {
1060 unset($USER->enrol['tempguest'][$courseid]);
1061 $USER->access = remove_temp_roles($context, $USER->access);
1067 * Store user_enrolments changes and trigger event.
1069 * @param object $ue
1070 * @param int $user id
1071 * @param int $status
1072 * @param int $timestart
1073 * @param int $timeend
1074 * @return void
1076 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1077 global $DB, $USER;
1079 $name = $this->get_name();
1081 if ($instance->enrol !== $name) {
1082 throw new coding_exception('invalid enrol instance!');
1085 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1086 // weird, user not enrolled
1087 return;
1090 $modified = false;
1091 if (isset($status) and $ue->status != $status) {
1092 $ue->status = $status;
1093 $modified = true;
1095 if (isset($timestart) and $ue->timestart != $timestart) {
1096 $ue->timestart = $timestart;
1097 $modified = true;
1099 if (isset($timeend) and $ue->timeend != $timeend) {
1100 $ue->timeend = $timeend;
1101 $modified = true;
1104 if (!$modified) {
1105 // no change
1106 return;
1109 $ue->modifierid = $USER->id;
1110 $DB->update_record('user_enrolments', $ue);
1112 // trigger event
1113 $ue->courseid = $instance->courseid;
1114 $ue->enrol = $instance->name;
1115 events_trigger('user_unenrol_modified', $ue);
1119 * Unenrol user from course,
1120 * the last unenrolment removes all remaining roles.
1122 * @param stdClass $instance
1123 * @param int $userid
1124 * @return void
1126 public function unenrol_user(stdClass $instance, $userid) {
1127 global $CFG, $USER, $DB;
1129 $name = $this->get_name();
1130 $courseid = $instance->courseid;
1132 if ($instance->enrol !== $name) {
1133 throw new coding_exception('invalid enrol instance!');
1135 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1137 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1138 // weird, user not enrolled
1139 return;
1142 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1143 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1145 // add extra info and trigger event
1146 $ue->courseid = $courseid;
1147 $ue->enrol = $name;
1149 $sql = "SELECT 'x'
1150 FROM {user_enrolments} ue
1151 JOIN {enrol} e ON (e.id = ue.enrolid)
1152 WHERE ue.userid = :userid AND e.courseid = :courseid";
1153 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1154 $ue->lastenrol = false;
1155 events_trigger('user_unenrolled', $ue);
1156 // user still has some enrolments, no big cleanup yet
1157 } else {
1158 // the big cleanup IS necessary!
1160 require_once("$CFG->dirroot/group/lib.php");
1161 require_once("$CFG->libdir/gradelib.php");
1163 // remove all remaining roles
1164 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1166 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1167 groups_delete_group_members($courseid, $userid);
1169 grade_user_unenrol($courseid, $userid);
1171 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1173 $ue->lastenrol = true; // means user not enrolled any more
1174 events_trigger('user_unenrolled', $ue);
1176 // reset primitive require_login() caching
1177 if ($userid == $USER->id) {
1178 if (isset($USER->enrol['enrolled'][$courseid])) {
1179 unset($USER->enrol['enrolled'][$courseid]);
1181 if (isset($USER->enrol['tempguest'][$courseid])) {
1182 unset($USER->enrol['tempguest'][$courseid]);
1183 $USER->access = remove_temp_roles($context, $USER->access);
1189 * Forces synchronisation of user enrolments.
1191 * This is important especially for external enrol plugins,
1192 * this function is called for all enabled enrol plugins
1193 * right after every user login.
1195 * @param object $user user record
1196 * @return void
1198 public function sync_user_enrolments($user) {
1199 // override if necessary
1203 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1204 * @param int $courseid
1205 * @return moodle_url page url
1207 public function get_newinstance_link($courseid) {
1208 // override for most plugins, check if instance already exists in cases only one instance is supported
1209 return NULL;
1213 * Is it possible to delete enrol instance via standard UI?
1215 * @param object $instance
1216 * @return bool
1218 public function instance_deleteable($instance) {
1219 return true;
1223 * Returns link to manual enrol UI if exists.
1224 * Does the access control tests automatically.
1226 * @param object $instance
1227 * @return moodle_url
1229 public function get_manual_enrol_link($instance) {
1230 return NULL;
1234 * Returns list of unenrol links for all enrol instances in course.
1236 * @param int $instance
1237 * @return moodle_url or NULL if self unenrolment not supported
1239 public function get_unenrolself_link($instance) {
1240 global $USER, $CFG, $DB;
1242 $name = $this->get_name();
1243 if ($instance->enrol !== $name) {
1244 throw new coding_exception('invalid enrol instance!');
1247 if ($instance->courseid == SITEID) {
1248 return NULL;
1251 if (!enrol_is_enabled($name)) {
1252 return NULL;
1255 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1256 return NULL;
1259 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1260 return NULL;
1263 $context = get_context_instance(CONTEXT_COURSE, $instance->courseid, MUST_EXIST);
1265 if (!has_capability("enrol/$name:unenrolself", $context)) {
1266 return NULL;
1269 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1270 return NULL;
1273 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));;
1277 * Adds enrol instance UI to course edit form
1279 * @param object $instance enrol instance or null if does not exist yet
1280 * @param MoodleQuickForm $mform
1281 * @param object $data
1282 * @param object $context context of existing course or parent category if course does not exist
1283 * @return void
1285 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1286 // override - usually at least enable/disable switch, has to add own form header
1290 * Validates course edit form data
1292 * @param object $instance enrol instance or null if does not exist yet
1293 * @param array $data
1294 * @param object $context context of existing course or parent category if course does not exist
1295 * @return array errors array
1297 public function course_edit_validation($instance, array $data, $context) {
1298 return array();
1302 * Called after updating/inserting course.
1304 * @param bool $inserted true if course just inserted
1305 * @param object $course
1306 * @param object $data form data
1307 * @return void
1309 public function course_updated($inserted, $course, $data) {
1310 if ($inserted) {
1311 if ($this->get_config('defaultenrol')) {
1312 $this->add_default_instance($course);
1318 * Add new instance of enrol plugin.
1319 * @param object $course
1320 * @param array instance fields
1321 * @return int id of new instance, null if can not be created
1323 public function add_instance($course, array $fields = NULL) {
1324 global $DB;
1326 if ($course->id == SITEID) {
1327 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1330 $instance = new stdClass();
1331 $instance->enrol = $this->get_name();
1332 $instance->status = ENROL_INSTANCE_ENABLED;
1333 $instance->courseid = $course->id;
1334 $instance->enrolstartdate = 0;
1335 $instance->enrolenddate = 0;
1336 $instance->timemodified = time();
1337 $instance->timecreated = $instance->timemodified;
1338 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1340 $fields = (array)$fields;
1341 unset($fields['enrol']);
1342 unset($fields['courseid']);
1343 unset($fields['sortorder']);
1344 foreach($fields as $field=>$value) {
1345 $instance->$field = $value;
1348 return $DB->insert_record('enrol', $instance);
1352 * Add new instance of enrol plugin with default settings,
1353 * called when adding new instance manually or when adding new course.
1355 * Not all plugins support this.
1357 * @param object $course
1358 * @return int id of new instance or null if no default supported
1360 public function add_default_instance($course) {
1361 return null;
1365 * Delete course enrol plugin instance, unenrol all users.
1366 * @param object $instance
1367 * @return void
1369 public function delete_instance($instance) {
1370 global $DB;
1372 $name = $this->get_name();
1373 if ($instance->enrol !== $name) {
1374 throw new coding_exception('invalid enrol instance!');
1377 //first unenrol all users
1378 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1379 foreach ($participants as $participant) {
1380 $this->unenrol_user($instance, $participant->userid);
1382 $participants->close();
1384 // now clean up all remainders that were not removed correctly
1385 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>$name));
1386 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1388 // finally drop the enrol row
1389 $DB->delete_records('enrol', array('id'=>$instance->id));
1393 * Creates course enrol form, checks if form submitted
1394 * and enrols user if necessary. It can also redirect.
1396 * @param stdClass $instance
1397 * @return string html text, usually a form in a text box
1399 public function enrol_page_hook(stdClass $instance) {
1400 return null;
1404 * Adds navigation links into course admin block.
1406 * By defaults looks for manage links only.
1408 * @param navigation_node $instancesnode
1409 * @param object $instance
1410 * @return void
1412 public function add_course_navigation($instancesnode, stdClass $instance) {
1413 // usually adds manage users
1417 * Returns edit icons for the page with list of instances
1418 * @param stdClass $instance
1419 * @return array
1421 public function get_action_icons(stdClass $instance) {
1422 return array();
1426 * Reads version.php and determines if it is necessary
1427 * to execute the cron job now.
1428 * @return bool
1430 public function is_cron_required() {
1431 global $CFG;
1433 $name = $this->get_name();
1434 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
1435 $plugin = new stdClass();
1436 include($versionfile);
1437 if (empty($plugin->cron)) {
1438 return false;
1440 $lastexecuted = $this->get_config('lastcron', 0);
1441 if ($lastexecuted + $plugin->cron < time()) {
1442 return true;
1443 } else {
1444 return false;
1449 * Called for all enabled enrol plugins that returned true from is_cron_required().
1450 * @return void
1452 public function cron() {
1456 * Called when user is about to be deleted
1457 * @param object $user
1458 * @return void
1460 public function user_delete($user) {
1461 global $DB;
1463 $sql = "SELECT e.*
1464 FROM {enrol} e
1465 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1466 WHERE e.enrol = :name AND ue.userid = :userid";
1467 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1469 $rs = $DB->get_recordset_sql($sql, $params);
1470 foreach($rs as $instance) {
1471 $this->unenrol_user($instance, $user->id);
1473 $rs->close();