Merge branch 'MDL-40255_M25' of git://github.com/lazydaisy/moodle into MOODLE_25_STABLE
[moodle.git] / lib / enrollib.php
blobdb808f67a482b6d6a7c31ba97bdb3a3cf1667e3e
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * This library includes the basic parts of enrol api.
20 * It is available on each page.
22 * @package core
23 * @subpackage enrol
24 * @copyright 2010 Petr Skoda {@link http://skodak.org}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 /** Course enrol instance enabled. (used in enrol->status) */
31 define('ENROL_INSTANCE_ENABLED', 0);
33 /** Course enrol instance disabled, user may enter course if other enrol instance enabled. (used in enrol->status)*/
34 define('ENROL_INSTANCE_DISABLED', 1);
36 /** User is active participant (used in user_enrolments->status)*/
37 define('ENROL_USER_ACTIVE', 0);
39 /** User participation in course is suspended (used in user_enrolments->status) */
40 define('ENROL_USER_SUSPENDED', 1);
42 /** @deprecated - enrol caching was reworked, use ENROL_MAX_TIMESTAMP instead */
43 define('ENROL_REQUIRE_LOGIN_CACHE_PERIOD', 1800);
45 /** The timestamp indicating forever */
46 define('ENROL_MAX_TIMESTAMP', 2147483647);
48 /** When user disappears from external source, the enrolment is completely removed */
49 define('ENROL_EXT_REMOVED_UNENROL', 0);
51 /** When user disappears from external source, the enrolment is kept as is - one way sync */
52 define('ENROL_EXT_REMOVED_KEEP', 1);
54 /** @deprecated since 2.4 not used any more, migrate plugin to new restore methods */
55 define('ENROL_RESTORE_TYPE', 'enrolrestore');
57 /**
58 * When user disappears from external source, user enrolment is suspended, roles are kept as is.
59 * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook,
60 * assignments, etc.
62 define('ENROL_EXT_REMOVED_SUSPEND', 2);
64 /**
65 * When user disappears from external source, the enrolment is suspended and roles assigned
66 * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas.
67 * */
68 define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
70 /**
71 * Returns instances of enrol plugins
72 * @param bool $enabled return enabled only
73 * @return array of enrol plugins name=>instance
75 function enrol_get_plugins($enabled) {
76 global $CFG;
78 $result = array();
80 if ($enabled) {
81 // sorted by enabled plugin order
82 $enabled = explode(',', $CFG->enrol_plugins_enabled);
83 $plugins = array();
84 foreach ($enabled as $plugin) {
85 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
87 } else {
88 // sorted alphabetically
89 $plugins = get_plugin_list('enrol');
90 ksort($plugins);
93 foreach ($plugins as $plugin=>$location) {
94 if (!file_exists("$location/lib.php")) {
95 continue;
97 include_once("$location/lib.php");
98 $class = "enrol_{$plugin}_plugin";
99 if (!class_exists($class)) {
100 continue;
103 $result[$plugin] = new $class();
106 return $result;
110 * Returns instance of enrol plugin
111 * @param string $name name of enrol plugin ('manual', 'guest', ...)
112 * @return enrol_plugin
114 function enrol_get_plugin($name) {
115 global $CFG;
117 $name = clean_param($name, PARAM_PLUGIN);
119 if (empty($name)) {
120 // ignore malformed or missing plugin names completely
121 return null;
124 $location = "$CFG->dirroot/enrol/$name";
126 if (!file_exists("$location/lib.php")) {
127 return null;
129 include_once("$location/lib.php");
130 $class = "enrol_{$name}_plugin";
131 if (!class_exists($class)) {
132 return null;
135 return new $class();
139 * Returns enrolment instances in given course.
140 * @param int $courseid
141 * @param bool $enabled
142 * @return array of enrol instances
144 function enrol_get_instances($courseid, $enabled) {
145 global $DB, $CFG;
147 if (!$enabled) {
148 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
151 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
153 $enabled = explode(',', $CFG->enrol_plugins_enabled);
154 foreach ($result as $key=>$instance) {
155 if (!in_array($instance->enrol, $enabled)) {
156 unset($result[$key]);
157 continue;
159 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
160 // broken plugin
161 unset($result[$key]);
162 continue;
166 return $result;
170 * Checks if a given plugin is in the list of enabled enrolment plugins.
172 * @param string $enrol Enrolment plugin name
173 * @return boolean Whether the plugin is enabled
175 function enrol_is_enabled($enrol) {
176 global $CFG;
178 if (empty($CFG->enrol_plugins_enabled)) {
179 return false;
181 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
185 * Check all the login enrolment information for the given user object
186 * by querying the enrolment plugins
188 * This function may be very slow, use only once after log-in or login-as.
190 * @param stdClass $user
191 * @return void
193 function enrol_check_plugins($user) {
194 global $CFG;
196 if (empty($user->id) or isguestuser($user)) {
197 // shortcut - there is no enrolment work for guests and not-logged-in users
198 return;
201 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
202 // which proved it was actually not necessary.
204 static $inprogress = array(); // To prevent this function being called more than once in an invocation
206 if (!empty($inprogress[$user->id])) {
207 return;
210 $inprogress[$user->id] = true; // Set the flag
212 $enabled = enrol_get_plugins(true);
214 foreach($enabled as $enrol) {
215 $enrol->sync_user_enrolments($user);
218 unset($inprogress[$user->id]); // Unset the flag
222 * Do these two students share any course?
224 * The courses has to be visible and enrolments has to be active,
225 * timestart and timeend restrictions are ignored.
227 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
228 * to true.
230 * @param stdClass|int $user1
231 * @param stdClass|int $user2
232 * @return bool
234 function enrol_sharing_course($user1, $user2) {
235 return enrol_get_shared_courses($user1, $user2, false, true);
239 * Returns any courses shared by the two users
241 * The courses has to be visible and enrolments has to be active,
242 * timestart and timeend restrictions are ignored.
244 * @global moodle_database $DB
245 * @param stdClass|int $user1
246 * @param stdClass|int $user2
247 * @param bool $preloadcontexts If set to true contexts for the returned courses
248 * will be preloaded.
249 * @param bool $checkexistsonly If set to true then this function will return true
250 * if the users share any courses and false if not.
251 * @return array|bool An array of courses that both users are enrolled in OR if
252 * $checkexistsonly set returns true if the users share any courses
253 * and false if not.
255 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
256 global $DB, $CFG;
258 $user1 = isset($user1->id) ? $user1->id : $user1;
259 $user2 = isset($user2->id) ? $user2->id : $user2;
261 if (empty($user1) or empty($user2)) {
262 return false;
265 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
266 return false;
269 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee');
270 $params['enabled'] = ENROL_INSTANCE_ENABLED;
271 $params['active1'] = ENROL_USER_ACTIVE;
272 $params['active2'] = ENROL_USER_ACTIVE;
273 $params['user1'] = $user1;
274 $params['user2'] = $user2;
276 $ctxselect = '';
277 $ctxjoin = '';
278 if ($preloadcontexts) {
279 list($ctxselect, $ctxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
282 $sql = "SELECT c.* $ctxselect
283 FROM {course} c
284 JOIN (
285 SELECT DISTINCT c.id
286 FROM {enrol} e
287 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
288 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2)
289 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
290 WHERE e.status = :enabled AND e.enrol $plugins
291 ) ec ON ec.id = c.id
292 $ctxjoin";
294 if ($checkexistsonly) {
295 return $DB->record_exists_sql($sql, $params);
296 } else {
297 $courses = $DB->get_records_sql($sql, $params);
298 if ($preloadcontexts) {
299 array_map('context_instance_preload', $courses);
301 return $courses;
306 * This function adds necessary enrol plugins UI into the course edit form.
308 * @param MoodleQuickForm $mform
309 * @param object $data course edit form data
310 * @param object $context context of existing course or parent category if course does not exist
311 * @return void
313 function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
314 $plugins = enrol_get_plugins(true);
315 if (!empty($data->id)) {
316 $instances = enrol_get_instances($data->id, false);
317 foreach ($instances as $instance) {
318 if (!isset($plugins[$instance->enrol])) {
319 continue;
321 $plugin = $plugins[$instance->enrol];
322 $plugin->course_edit_form($instance, $mform, $data, $context);
324 } else {
325 foreach ($plugins as $plugin) {
326 $plugin->course_edit_form(NULL, $mform, $data, $context);
332 * Validate course edit form data
334 * @param array $data raw form data
335 * @param object $context context of existing course or parent category if course does not exist
336 * @return array errors array
338 function enrol_course_edit_validation(array $data, $context) {
339 $errors = array();
340 $plugins = enrol_get_plugins(true);
342 if (!empty($data['id'])) {
343 $instances = enrol_get_instances($data['id'], false);
344 foreach ($instances as $instance) {
345 if (!isset($plugins[$instance->enrol])) {
346 continue;
348 $plugin = $plugins[$instance->enrol];
349 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
351 } else {
352 foreach ($plugins as $plugin) {
353 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
357 return $errors;
361 * Update enrol instances after course edit form submission
362 * @param bool $inserted true means new course added, false course already existed
363 * @param object $course
364 * @param object $data form data
365 * @return void
367 function enrol_course_updated($inserted, $course, $data) {
368 global $DB, $CFG;
370 $plugins = enrol_get_plugins(true);
372 foreach ($plugins as $plugin) {
373 $plugin->course_updated($inserted, $course, $data);
378 * Add navigation nodes
379 * @param navigation_node $coursenode
380 * @param object $course
381 * @return void
383 function enrol_add_course_navigation(navigation_node $coursenode, $course) {
384 global $CFG;
386 $coursecontext = context_course::instance($course->id);
388 $instances = enrol_get_instances($course->id, true);
389 $plugins = enrol_get_plugins(true);
391 // we do not want to break all course pages if there is some borked enrol plugin, right?
392 foreach ($instances as $k=>$instance) {
393 if (!isset($plugins[$instance->enrol])) {
394 unset($instances[$k]);
398 $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
400 if ($course->id != SITEID) {
401 // list all participants - allows assigning roles, groups, etc.
402 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
403 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id));
404 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/enrolusers', ''));
407 // manage enrol plugin instances
408 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
409 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
410 } else {
411 $url = NULL;
413 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
415 // each instance decides how to configure itself or how many other nav items are exposed
416 foreach ($instances as $instance) {
417 if (!isset($plugins[$instance->enrol])) {
418 continue;
420 $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
423 if (!$url) {
424 $instancesnode->trim_if_empty();
428 // Manage groups in this course or even frontpage
429 if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
430 $url = new moodle_url('/group/index.php', array('id'=>$course->id));
431 $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
434 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
435 // Override roles
436 if (has_capability('moodle/role:review', $coursecontext)) {
437 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
438 } else {
439 $url = NULL;
441 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
443 // Add assign or override roles if allowed
444 if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
445 if (has_capability('moodle/role:assign', $coursecontext)) {
446 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
447 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
450 // Check role permissions
451 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:assign'), $coursecontext)) {
452 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
453 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
457 // Deal somehow with users that are not enrolled but still got a role somehow
458 if ($course->id != SITEID) {
459 //TODO, create some new UI for role assignments at course level
460 if (has_capability('moodle/role:assign', $coursecontext)) {
461 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
462 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
466 // just in case nothing was actually added
467 $usersnode->trim_if_empty();
469 if ($course->id != SITEID) {
470 if (isguestuser() or !isloggedin()) {
471 // guest account can not be enrolled - no links for them
472 } else if (is_enrolled($coursecontext)) {
473 // unenrol link if possible
474 foreach ($instances as $instance) {
475 if (!isset($plugins[$instance->enrol])) {
476 continue;
478 $plugin = $plugins[$instance->enrol];
479 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
480 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
481 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
482 break;
483 //TODO. deal with multiple unenrol links - not likely case, but still...
486 } else {
487 // enrol link if possible
488 if (is_viewing($coursecontext)) {
489 // better not show any enrol link, this is intended for managers and inspectors
490 } else {
491 foreach ($instances as $instance) {
492 if (!isset($plugins[$instance->enrol])) {
493 continue;
495 $plugin = $plugins[$instance->enrol];
496 if ($plugin->show_enrolme_link($instance)) {
497 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
498 $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
499 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
500 break;
509 * Returns list of courses current $USER is enrolled in and can access
511 * - $fields is an array of field names to ADD
512 * so name the fields you really need, which will
513 * be added and uniq'd
515 * @param string|array $fields
516 * @param string $sort
517 * @param int $limit max number of courses
518 * @return array
520 function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
521 global $DB, $USER;
523 // Guest account does not have any courses
524 if (isguestuser() or !isloggedin()) {
525 return(array());
528 $basefields = array('id', 'category', 'sortorder',
529 'shortname', 'fullname', 'idnumber',
530 'startdate', 'visible',
531 'groupmode', 'groupmodeforce');
533 if (empty($fields)) {
534 $fields = $basefields;
535 } else if (is_string($fields)) {
536 // turn the fields from a string to an array
537 $fields = explode(',', $fields);
538 $fields = array_map('trim', $fields);
539 $fields = array_unique(array_merge($basefields, $fields));
540 } else if (is_array($fields)) {
541 $fields = array_unique(array_merge($basefields, $fields));
542 } else {
543 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
545 if (in_array('*', $fields)) {
546 $fields = array('*');
549 $orderby = "";
550 $sort = trim($sort);
551 if (!empty($sort)) {
552 $rawsorts = explode(',', $sort);
553 $sorts = array();
554 foreach ($rawsorts as $rawsort) {
555 $rawsort = trim($rawsort);
556 if (strpos($rawsort, 'c.') === 0) {
557 $rawsort = substr($rawsort, 2);
559 $sorts[] = trim($rawsort);
561 $sort = 'c.'.implode(',c.', $sorts);
562 $orderby = "ORDER BY $sort";
565 $wheres = array("c.id <> :siteid");
566 $params = array('siteid'=>SITEID);
568 if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
569 // list _only_ this course - anything else is asking for trouble...
570 $wheres[] = "courseid = :loginas";
571 $params['loginas'] = $USER->loginascontext->instanceid;
574 $coursefields = 'c.' .join(',c.', $fields);
575 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
576 $wheres = implode(" AND ", $wheres);
578 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
579 $sql = "SELECT $coursefields $ccselect
580 FROM {course} c
581 JOIN (SELECT DISTINCT e.courseid
582 FROM {enrol} e
583 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
584 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
585 ) en ON (en.courseid = c.id)
586 $ccjoin
587 WHERE $wheres
588 $orderby";
589 $params['userid'] = $USER->id;
590 $params['active'] = ENROL_USER_ACTIVE;
591 $params['enabled'] = ENROL_INSTANCE_ENABLED;
592 $params['now1'] = round(time(), -2); // improves db caching
593 $params['now2'] = $params['now1'];
595 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
597 // preload contexts and check visibility
598 foreach ($courses as $id=>$course) {
599 context_instance_preload($course);
600 if (!$course->visible) {
601 if (!$context = context_course::instance($id, IGNORE_MISSING)) {
602 unset($courses[$id]);
603 continue;
605 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
606 unset($courses[$id]);
607 continue;
610 $courses[$id] = $course;
613 //wow! Is that really all? :-D
615 return $courses;
619 * Returns course enrolment information icons.
621 * @param object $course
622 * @param array $instances enrol instances of this course, improves performance
623 * @return array of pix_icon
625 function enrol_get_course_info_icons($course, array $instances = NULL) {
626 $icons = array();
627 if (is_null($instances)) {
628 $instances = enrol_get_instances($course->id, true);
630 $plugins = enrol_get_plugins(true);
631 foreach ($plugins as $name => $plugin) {
632 $pis = array();
633 foreach ($instances as $instance) {
634 if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
635 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
636 continue;
638 if ($instance->enrol == $name) {
639 $pis[$instance->id] = $instance;
642 if ($pis) {
643 $icons = array_merge($icons, $plugin->get_info_icons($pis));
646 return $icons;
650 * Returns course enrolment detailed information.
652 * @param object $course
653 * @return array of html fragments - can be used to construct lists
655 function enrol_get_course_description_texts($course) {
656 $lines = array();
657 $instances = enrol_get_instances($course->id, true);
658 $plugins = enrol_get_plugins(true);
659 foreach ($instances as $instance) {
660 if (!isset($plugins[$instance->enrol])) {
661 //weird
662 continue;
664 $plugin = $plugins[$instance->enrol];
665 $text = $plugin->get_description_text($instance);
666 if ($text !== NULL) {
667 $lines[] = $text;
670 return $lines;
674 * Returns list of courses user is enrolled into.
675 * (Note: use enrol_get_all_users_courses if you want to use the list wihtout any cap checks )
677 * - $fields is an array of fieldnames to ADD
678 * so name the fields you really need, which will
679 * be added and uniq'd
681 * @param int $userid
682 * @param bool $onlyactive return only active enrolments in courses user may see
683 * @param string|array $fields
684 * @param string $sort
685 * @return array
687 function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
688 global $DB;
690 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
692 // preload contexts and check visibility
693 if ($onlyactive) {
694 foreach ($courses as $id=>$course) {
695 context_instance_preload($course);
696 if (!$course->visible) {
697 if (!$context = context_course::instance($id)) {
698 unset($courses[$id]);
699 continue;
701 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
702 unset($courses[$id]);
703 continue;
709 return $courses;
714 * Can user access at least one enrolled course?
716 * Cheat if necessary, but find out as fast as possible!
718 * @param int|stdClass $user null means use current user
719 * @return bool
721 function enrol_user_sees_own_courses($user = null) {
722 global $USER;
724 if ($user === null) {
725 $user = $USER;
727 $userid = is_object($user) ? $user->id : $user;
729 // Guest account does not have any courses
730 if (isguestuser($userid) or empty($userid)) {
731 return false;
734 // Let's cheat here if this is the current user,
735 // if user accessed any course recently, then most probably
736 // we do not need to query the database at all.
737 if ($USER->id == $userid) {
738 if (!empty($USER->enrol['enrolled'])) {
739 foreach ($USER->enrol['enrolled'] as $until) {
740 if ($until > time()) {
741 return true;
747 // Now the slow way.
748 $courses = enrol_get_all_users_courses($userid, true);
749 foreach($courses as $course) {
750 if ($course->visible) {
751 return true;
753 context_helper::preload_from_record($course);
754 $context = context_course::instance($course->id);
755 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
756 return true;
760 return false;
764 * Returns list of courses user is enrolled into without any capability checks
765 * - $fields is an array of fieldnames to ADD
766 * so name the fields you really need, which will
767 * be added and uniq'd
769 * @param int $userid
770 * @param bool $onlyactive return only active enrolments in courses user may see
771 * @param string|array $fields
772 * @param string $sort
773 * @return array
775 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
776 global $DB;
778 // Guest account does not have any courses
779 if (isguestuser($userid) or empty($userid)) {
780 return(array());
783 $basefields = array('id', 'category', 'sortorder',
784 'shortname', 'fullname', 'idnumber',
785 'startdate', 'visible',
786 'groupmode', 'groupmodeforce');
788 if (empty($fields)) {
789 $fields = $basefields;
790 } else if (is_string($fields)) {
791 // turn the fields from a string to an array
792 $fields = explode(',', $fields);
793 $fields = array_map('trim', $fields);
794 $fields = array_unique(array_merge($basefields, $fields));
795 } else if (is_array($fields)) {
796 $fields = array_unique(array_merge($basefields, $fields));
797 } else {
798 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
800 if (in_array('*', $fields)) {
801 $fields = array('*');
804 $orderby = "";
805 $sort = trim($sort);
806 if (!empty($sort)) {
807 $rawsorts = explode(',', $sort);
808 $sorts = array();
809 foreach ($rawsorts as $rawsort) {
810 $rawsort = trim($rawsort);
811 if (strpos($rawsort, 'c.') === 0) {
812 $rawsort = substr($rawsort, 2);
814 $sorts[] = trim($rawsort);
816 $sort = 'c.'.implode(',c.', $sorts);
817 $orderby = "ORDER BY $sort";
820 $params = array('siteid'=>SITEID);
822 if ($onlyactive) {
823 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
824 $params['now1'] = round(time(), -2); // improves db caching
825 $params['now2'] = $params['now1'];
826 $params['active'] = ENROL_USER_ACTIVE;
827 $params['enabled'] = ENROL_INSTANCE_ENABLED;
828 } else {
829 $subwhere = "";
832 $coursefields = 'c.' .join(',c.', $fields);
833 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
835 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
836 $sql = "SELECT $coursefields $ccselect
837 FROM {course} c
838 JOIN (SELECT DISTINCT e.courseid
839 FROM {enrol} e
840 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
841 $subwhere
842 ) en ON (en.courseid = c.id)
843 $ccjoin
844 WHERE c.id <> :siteid
845 $orderby";
846 $params['userid'] = $userid;
848 $courses = $DB->get_records_sql($sql, $params);
850 return $courses;
856 * Called when user is about to be deleted.
857 * @param object $user
858 * @return void
860 function enrol_user_delete($user) {
861 global $DB;
863 $plugins = enrol_get_plugins(true);
864 foreach ($plugins as $plugin) {
865 $plugin->user_delete($user);
868 // force cleanup of all broken enrolments
869 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
873 * Called when course is about to be deleted.
874 * @param stdClass $course
875 * @return void
877 function enrol_course_delete($course) {
878 global $DB;
880 $instances = enrol_get_instances($course->id, false);
881 $plugins = enrol_get_plugins(true);
882 foreach ($instances as $instance) {
883 if (isset($plugins[$instance->enrol])) {
884 $plugins[$instance->enrol]->delete_instance($instance);
886 // low level delete in case plugin did not do it
887 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
888 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
889 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
890 $DB->delete_records('enrol', array('id'=>$instance->id));
895 * Try to enrol user via default internal auth plugin.
897 * For now this is always using the manual enrol plugin...
899 * @param $courseid
900 * @param $userid
901 * @param $roleid
902 * @param $timestart
903 * @param $timeend
904 * @return bool success
906 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
907 global $DB;
909 //note: this is hardcoded to manual plugin for now
911 if (!enrol_is_enabled('manual')) {
912 return false;
915 if (!$enrol = enrol_get_plugin('manual')) {
916 return false;
918 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
919 return false;
921 $instance = reset($instances);
923 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
925 return true;
929 * Is there a chance users might self enrol
930 * @param int $courseid
931 * @return bool
933 function enrol_selfenrol_available($courseid) {
934 $result = false;
936 $plugins = enrol_get_plugins(true);
937 $enrolinstances = enrol_get_instances($courseid, true);
938 foreach($enrolinstances as $instance) {
939 if (!isset($plugins[$instance->enrol])) {
940 continue;
942 if ($instance->enrol === 'guest') {
943 // blacklist known temporary guest plugins
944 continue;
946 if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
947 $result = true;
948 break;
952 return $result;
956 * This function returns the end of current active user enrolment.
958 * It deals correctly with multiple overlapping user enrolments.
960 * @param int $courseid
961 * @param int $userid
962 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
964 function enrol_get_enrolment_end($courseid, $userid) {
965 global $DB;
967 $sql = "SELECT ue.*
968 FROM {user_enrolments} ue
969 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
970 JOIN {user} u ON u.id = ue.userid
971 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
972 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
974 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
975 return false;
978 $changes = array();
980 foreach ($enrolments as $ue) {
981 $start = (int)$ue->timestart;
982 $end = (int)$ue->timeend;
983 if ($end != 0 and $end < $start) {
984 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
985 continue;
987 if (isset($changes[$start])) {
988 $changes[$start] = $changes[$start] + 1;
989 } else {
990 $changes[$start] = 1;
992 if ($end === 0) {
993 // no end
994 } else if (isset($changes[$end])) {
995 $changes[$end] = $changes[$end] - 1;
996 } else {
997 $changes[$end] = -1;
1001 // let's sort then enrolment starts&ends and go through them chronologically,
1002 // looking for current status and the next future end of enrolment
1003 ksort($changes);
1005 $now = time();
1006 $current = 0;
1007 $present = null;
1009 foreach ($changes as $time => $change) {
1010 if ($time > $now) {
1011 if ($present === null) {
1012 // we have just went past current time
1013 $present = $current;
1014 if ($present < 1) {
1015 // no enrolment active
1016 return false;
1019 if ($present !== null) {
1020 // we are already in the future - look for possible end
1021 if ($current + $change < 1) {
1022 return $time;
1026 $current += $change;
1029 if ($current > 0) {
1030 return 0;
1031 } else {
1032 return false;
1038 * All enrol plugins should be based on this class,
1039 * this is also the main source of documentation.
1041 abstract class enrol_plugin {
1042 protected $config = null;
1045 * Returns name of this enrol plugin
1046 * @return string
1048 public function get_name() {
1049 // second word in class is always enrol name, sorry, no fancy plugin names with _
1050 $words = explode('_', get_class($this));
1051 return $words[1];
1055 * Returns localised name of enrol instance
1057 * @param object $instance (null is accepted too)
1058 * @return string
1060 public function get_instance_name($instance) {
1061 if (empty($instance->name)) {
1062 $enrol = $this->get_name();
1063 return get_string('pluginname', 'enrol_'.$enrol);
1064 } else {
1065 $context = context_course::instance($instance->courseid);
1066 return format_string($instance->name, true, array('context'=>$context));
1071 * Returns optional enrolment information icons.
1073 * This is used in course list for quick overview of enrolment options.
1075 * We are not using single instance parameter because sometimes
1076 * we might want to prevent icon repetition when multiple instances
1077 * of one type exist. One instance may also produce several icons.
1079 * @param array $instances all enrol instances of this type in one course
1080 * @return array of pix_icon
1082 public function get_info_icons(array $instances) {
1083 return array();
1087 * Returns optional enrolment instance description text.
1089 * This is used in detailed course information.
1092 * @param object $instance
1093 * @return string short html text
1095 public function get_description_text($instance) {
1096 return null;
1100 * Makes sure config is loaded and cached.
1101 * @return void
1103 protected function load_config() {
1104 if (!isset($this->config)) {
1105 $name = $this->get_name();
1106 $this->config = get_config("enrol_$name");
1111 * Returns plugin config value
1112 * @param string $name
1113 * @param string $default value if config does not exist yet
1114 * @return string value or default
1116 public function get_config($name, $default = NULL) {
1117 $this->load_config();
1118 return isset($this->config->$name) ? $this->config->$name : $default;
1122 * Sets plugin config value
1123 * @param string $name name of config
1124 * @param string $value string config value, null means delete
1125 * @return string value
1127 public function set_config($name, $value) {
1128 $pluginname = $this->get_name();
1129 $this->load_config();
1130 if ($value === NULL) {
1131 unset($this->config->$name);
1132 } else {
1133 $this->config->$name = $value;
1135 set_config($name, $value, "enrol_$pluginname");
1139 * Does this plugin assign protected roles are can they be manually removed?
1140 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1142 public function roles_protected() {
1143 return true;
1147 * Does this plugin allow manual enrolments?
1149 * @param stdClass $instance course enrol instance
1150 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1152 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1154 public function allow_enrol(stdClass $instance) {
1155 return false;
1159 * Does this plugin allow manual unenrolment of all users?
1160 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1162 * @param stdClass $instance course enrol instance
1163 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1165 public function allow_unenrol(stdClass $instance) {
1166 return false;
1170 * Does this plugin allow manual unenrolment of a specific user?
1171 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1173 * This is useful especially for synchronisation plugins that
1174 * do suspend instead of full unenrolment.
1176 * @param stdClass $instance course enrol instance
1177 * @param stdClass $ue record from user_enrolments table, specifies user
1179 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1181 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
1182 return $this->allow_unenrol($instance);
1186 * Does this plugin allow manual changes in user_enrolments table?
1188 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1190 * @param stdClass $instance course enrol instance
1191 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1193 public function allow_manage(stdClass $instance) {
1194 return false;
1198 * Does this plugin support some way to user to self enrol?
1200 * @param stdClass $instance course enrol instance
1202 * @return bool - true means show "Enrol me in this course" link in course UI
1204 public function show_enrolme_link(stdClass $instance) {
1205 return false;
1209 * Attempt to automatically enrol current user in course without any interaction,
1210 * calling code has to make sure the plugin and instance are active.
1212 * This should return either a timestamp in the future or false.
1214 * @param stdClass $instance course enrol instance
1215 * @return bool|int false means not enrolled, integer means timeend
1217 public function try_autoenrol(stdClass $instance) {
1218 global $USER;
1220 return false;
1224 * Attempt to automatically gain temporary guest access to course,
1225 * calling code has to make sure the plugin and instance are active.
1227 * This should return either a timestamp in the future or false.
1229 * @param stdClass $instance course enrol instance
1230 * @return bool|int false means no guest access, integer means timeend
1232 public function try_guestaccess(stdClass $instance) {
1233 global $USER;
1235 return false;
1239 * Enrol user into course via enrol instance.
1241 * @param stdClass $instance
1242 * @param int $userid
1243 * @param int $roleid optional role id
1244 * @param int $timestart 0 means unknown
1245 * @param int $timeend 0 means forever
1246 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1247 * @param bool $recovergrades restore grade history
1248 * @return void
1250 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
1251 global $DB, $USER, $CFG; // CFG necessary!!!
1253 if ($instance->courseid == SITEID) {
1254 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1257 $name = $this->get_name();
1258 $courseid = $instance->courseid;
1260 if ($instance->enrol !== $name) {
1261 throw new coding_exception('invalid enrol instance!');
1263 $context = context_course::instance($instance->courseid, MUST_EXIST);
1264 if (!isset($recovergrades)) {
1265 $recovergrades = $CFG->recovergradesdefault;
1268 $inserted = false;
1269 $updated = false;
1270 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1271 //only update if timestart or timeend or status are different.
1272 if ($ue->timestart != $timestart or $ue->timeend != $timeend or (!is_null($status) and $ue->status != $status)) {
1273 $ue->timestart = $timestart;
1274 $ue->timeend = $timeend;
1275 if (!is_null($status)) {
1276 $ue->status = $status;
1278 $ue->modifierid = $USER->id;
1279 $ue->timemodified = time();
1280 $DB->update_record('user_enrolments', $ue);
1282 $updated = true;
1284 } else {
1285 $ue = new stdClass();
1286 $ue->enrolid = $instance->id;
1287 $ue->status = is_null($status) ? ENROL_USER_ACTIVE : $status;
1288 $ue->userid = $userid;
1289 $ue->timestart = $timestart;
1290 $ue->timeend = $timeend;
1291 $ue->modifierid = $USER->id;
1292 $ue->timecreated = time();
1293 $ue->timemodified = $ue->timecreated;
1294 $ue->id = $DB->insert_record('user_enrolments', $ue);
1296 $inserted = true;
1299 if ($inserted) {
1300 // add extra info and trigger event
1301 $ue->courseid = $courseid;
1302 $ue->enrol = $name;
1303 events_trigger('user_enrolled', $ue);
1304 } else if ($updated) {
1305 $ue->courseid = $courseid;
1306 $ue->enrol = $name;
1307 events_trigger('user_enrol_modified', $ue);
1308 // resets current enrolment caches
1309 $context->mark_dirty();
1312 if ($roleid) {
1313 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
1314 if ($this->roles_protected()) {
1315 role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
1316 } else {
1317 role_assign($roleid, $userid, $context->id);
1321 // Recover old grades if present.
1322 if ($recovergrades) {
1323 require_once("$CFG->libdir/gradelib.php");
1324 grade_recover_history_grades($userid, $courseid);
1327 // reset current user enrolment caching
1328 if ($userid == $USER->id) {
1329 if (isset($USER->enrol['enrolled'][$courseid])) {
1330 unset($USER->enrol['enrolled'][$courseid]);
1332 if (isset($USER->enrol['tempguest'][$courseid])) {
1333 unset($USER->enrol['tempguest'][$courseid]);
1334 remove_temp_course_roles($context);
1340 * Store user_enrolments changes and trigger event.
1342 * @param stdClass $instance
1343 * @param int $userid
1344 * @param int $status
1345 * @param int $timestart
1346 * @param int $timeend
1347 * @return void
1349 public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1350 global $DB, $USER;
1352 $name = $this->get_name();
1354 if ($instance->enrol !== $name) {
1355 throw new coding_exception('invalid enrol instance!');
1358 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1359 // weird, user not enrolled
1360 return;
1363 $modified = false;
1364 if (isset($status) and $ue->status != $status) {
1365 $ue->status = $status;
1366 $modified = true;
1368 if (isset($timestart) and $ue->timestart != $timestart) {
1369 $ue->timestart = $timestart;
1370 $modified = true;
1372 if (isset($timeend) and $ue->timeend != $timeend) {
1373 $ue->timeend = $timeend;
1374 $modified = true;
1377 if (!$modified) {
1378 // no change
1379 return;
1382 $ue->modifierid = $USER->id;
1383 $DB->update_record('user_enrolments', $ue);
1384 context_course::instance($instance->courseid)->mark_dirty(); // reset enrol caches
1386 // trigger event
1387 $ue->courseid = $instance->courseid;
1388 $ue->enrol = $instance->name;
1389 events_trigger('user_enrol_modified', $ue);
1393 * Unenrol user from course,
1394 * the last unenrolment removes all remaining roles.
1396 * @param stdClass $instance
1397 * @param int $userid
1398 * @return void
1400 public function unenrol_user(stdClass $instance, $userid) {
1401 global $CFG, $USER, $DB;
1402 require_once("$CFG->dirroot/group/lib.php");
1404 $name = $this->get_name();
1405 $courseid = $instance->courseid;
1407 if ($instance->enrol !== $name) {
1408 throw new coding_exception('invalid enrol instance!');
1410 $context = context_course::instance($instance->courseid, MUST_EXIST);
1412 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
1413 // weird, user not enrolled
1414 return;
1417 // Remove all users groups linked to this enrolment instance.
1418 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id))) {
1419 foreach ($gms as $gm) {
1420 groups_remove_member($gm->groupid, $gm->userid);
1424 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id));
1425 $DB->delete_records('user_enrolments', array('id'=>$ue->id));
1427 // add extra info and trigger event
1428 $ue->courseid = $courseid;
1429 $ue->enrol = $name;
1431 $sql = "SELECT 'x'
1432 FROM {user_enrolments} ue
1433 JOIN {enrol} e ON (e.id = ue.enrolid)
1434 WHERE ue.userid = :userid AND e.courseid = :courseid";
1435 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1436 $ue->lastenrol = false;
1437 events_trigger('user_unenrolled', $ue);
1438 // user still has some enrolments, no big cleanup yet
1440 } else {
1441 // the big cleanup IS necessary!
1442 require_once("$CFG->libdir/gradelib.php");
1444 // remove all remaining roles
1445 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id), true, false);
1447 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1448 groups_delete_group_members($courseid, $userid);
1450 grade_user_unenrol($courseid, $userid);
1452 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1454 $ue->lastenrol = true; // means user not enrolled any more
1455 events_trigger('user_unenrolled', $ue);
1458 // reset all enrol caches
1459 $context->mark_dirty();
1461 // reset current user enrolment caching
1462 if ($userid == $USER->id) {
1463 if (isset($USER->enrol['enrolled'][$courseid])) {
1464 unset($USER->enrol['enrolled'][$courseid]);
1466 if (isset($USER->enrol['tempguest'][$courseid])) {
1467 unset($USER->enrol['tempguest'][$courseid]);
1468 remove_temp_course_roles($context);
1474 * Forces synchronisation of user enrolments.
1476 * This is important especially for external enrol plugins,
1477 * this function is called for all enabled enrol plugins
1478 * right after every user login.
1480 * @param object $user user record
1481 * @return void
1483 public function sync_user_enrolments($user) {
1484 // override if necessary
1488 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1489 * @param int $courseid
1490 * @return moodle_url page url
1492 public function get_newinstance_link($courseid) {
1493 // override for most plugins, check if instance already exists in cases only one instance is supported
1494 return NULL;
1498 * Is it possible to delete enrol instance via standard UI?
1500 * @param object $instance
1501 * @return bool
1503 public function instance_deleteable($instance) {
1504 return true;
1508 * Returns link to manual enrol UI if exists.
1509 * Does the access control tests automatically.
1511 * @param object $instance
1512 * @return moodle_url
1514 public function get_manual_enrol_link($instance) {
1515 return NULL;
1519 * Returns list of unenrol links for all enrol instances in course.
1521 * @param int $instance
1522 * @return moodle_url or NULL if self unenrolment not supported
1524 public function get_unenrolself_link($instance) {
1525 global $USER, $CFG, $DB;
1527 $name = $this->get_name();
1528 if ($instance->enrol !== $name) {
1529 throw new coding_exception('invalid enrol instance!');
1532 if ($instance->courseid == SITEID) {
1533 return NULL;
1536 if (!enrol_is_enabled($name)) {
1537 return NULL;
1540 if ($instance->status != ENROL_INSTANCE_ENABLED) {
1541 return NULL;
1544 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1545 return NULL;
1548 $context = context_course::instance($instance->courseid, MUST_EXIST);
1550 if (!has_capability("enrol/$name:unenrolself", $context)) {
1551 return NULL;
1554 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$USER->id, 'status'=>ENROL_USER_ACTIVE))) {
1555 return NULL;
1558 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id));
1562 * Adds enrol instance UI to course edit form
1564 * @param object $instance enrol instance or null if does not exist yet
1565 * @param MoodleQuickForm $mform
1566 * @param object $data
1567 * @param object $context context of existing course or parent category if course does not exist
1568 * @return void
1570 public function course_edit_form($instance, MoodleQuickForm $mform, $data, $context) {
1571 // override - usually at least enable/disable switch, has to add own form header
1575 * Validates course edit form data
1577 * @param object $instance enrol instance or null if does not exist yet
1578 * @param array $data
1579 * @param object $context context of existing course or parent category if course does not exist
1580 * @return array errors array
1582 public function course_edit_validation($instance, array $data, $context) {
1583 return array();
1587 * Called after updating/inserting course.
1589 * @param bool $inserted true if course just inserted
1590 * @param object $course
1591 * @param object $data form data
1592 * @return void
1594 public function course_updated($inserted, $course, $data) {
1595 if ($inserted) {
1596 if ($this->get_config('defaultenrol')) {
1597 $this->add_default_instance($course);
1603 * Add new instance of enrol plugin.
1604 * @param object $course
1605 * @param array instance fields
1606 * @return int id of new instance, null if can not be created
1608 public function add_instance($course, array $fields = NULL) {
1609 global $DB;
1611 if ($course->id == SITEID) {
1612 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1615 $instance = new stdClass();
1616 $instance->enrol = $this->get_name();
1617 $instance->status = ENROL_INSTANCE_ENABLED;
1618 $instance->courseid = $course->id;
1619 $instance->enrolstartdate = 0;
1620 $instance->enrolenddate = 0;
1621 $instance->timemodified = time();
1622 $instance->timecreated = $instance->timemodified;
1623 $instance->sortorder = $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id));
1625 $fields = (array)$fields;
1626 unset($fields['enrol']);
1627 unset($fields['courseid']);
1628 unset($fields['sortorder']);
1629 foreach($fields as $field=>$value) {
1630 $instance->$field = $value;
1633 return $DB->insert_record('enrol', $instance);
1637 * Add new instance of enrol plugin with default settings,
1638 * called when adding new instance manually or when adding new course.
1640 * Not all plugins support this.
1642 * @param object $course
1643 * @return int id of new instance or null if no default supported
1645 public function add_default_instance($course) {
1646 return null;
1650 * Update instance status
1652 * Override when plugin needs to do some action when enabled or disabled.
1654 * @param stdClass $instance
1655 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
1656 * @return void
1658 public function update_status($instance, $newstatus) {
1659 global $DB;
1661 $instance->status = $newstatus;
1662 $DB->update_record('enrol', $instance);
1664 // invalidate all enrol caches
1665 $context = context_course::instance($instance->courseid);
1666 $context->mark_dirty();
1670 * Delete course enrol plugin instance, unenrol all users.
1671 * @param object $instance
1672 * @return void
1674 public function delete_instance($instance) {
1675 global $DB;
1677 $name = $this->get_name();
1678 if ($instance->enrol !== $name) {
1679 throw new coding_exception('invalid enrol instance!');
1682 //first unenrol all users
1683 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id));
1684 foreach ($participants as $participant) {
1685 $this->unenrol_user($instance, $participant->userid);
1687 $participants->close();
1689 // now clean up all remainders that were not removed correctly
1690 $DB->delete_records('groups_members', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
1691 $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$name));
1692 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
1694 // finally drop the enrol row
1695 $DB->delete_records('enrol', array('id'=>$instance->id));
1697 // invalidate all enrol caches
1698 $context = context_course::instance($instance->courseid);
1699 $context->mark_dirty();
1703 * Creates course enrol form, checks if form submitted
1704 * and enrols user if necessary. It can also redirect.
1706 * @param stdClass $instance
1707 * @return string html text, usually a form in a text box
1709 public function enrol_page_hook(stdClass $instance) {
1710 return null;
1714 * Adds navigation links into course admin block.
1716 * By defaults looks for manage links only.
1718 * @param navigation_node $instancesnode
1719 * @param stdClass $instance
1720 * @return void
1722 public function add_course_navigation($instancesnode, stdClass $instance) {
1723 // usually adds manage users
1727 * Returns edit icons for the page with list of instances
1728 * @param stdClass $instance
1729 * @return array
1731 public function get_action_icons(stdClass $instance) {
1732 return array();
1736 * Reads version.php and determines if it is necessary
1737 * to execute the cron job now.
1738 * @return bool
1740 public function is_cron_required() {
1741 global $CFG;
1743 $name = $this->get_name();
1744 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
1745 $plugin = new stdClass();
1746 include($versionfile);
1747 if (empty($plugin->cron)) {
1748 return false;
1750 $lastexecuted = $this->get_config('lastcron', 0);
1751 if ($lastexecuted + $plugin->cron < time()) {
1752 return true;
1753 } else {
1754 return false;
1759 * Called for all enabled enrol plugins that returned true from is_cron_required().
1760 * @return void
1762 public function cron() {
1766 * Called when user is about to be deleted
1767 * @param object $user
1768 * @return void
1770 public function user_delete($user) {
1771 global $DB;
1773 $sql = "SELECT e.*
1774 FROM {enrol} e
1775 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1776 WHERE e.enrol = :name AND ue.userid = :userid";
1777 $params = array('name'=>$this->get_name(), 'userid'=>$user->id);
1779 $rs = $DB->get_recordset_sql($sql, $params);
1780 foreach($rs as $instance) {
1781 $this->unenrol_user($instance, $user->id);
1783 $rs->close();
1787 * Returns an enrol_user_button that takes the user to a page where they are able to
1788 * enrol users into the managers course through this plugin.
1790 * Optional: If the plugin supports manual enrolments it can choose to override this
1791 * otherwise it shouldn't
1793 * @param course_enrolment_manager $manager
1794 * @return enrol_user_button|false
1796 public function get_manual_enrol_button(course_enrolment_manager $manager) {
1797 return false;
1801 * Gets an array of the user enrolment actions
1803 * @param course_enrolment_manager $manager
1804 * @param stdClass $ue
1805 * @return array An array of user_enrolment_actions
1807 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
1808 return array();
1812 * Returns true if the plugin has one or more bulk operations that can be performed on
1813 * user enrolments.
1815 * @param course_enrolment_manager $manager
1816 * @return bool
1818 public function has_bulk_operations(course_enrolment_manager $manager) {
1819 return false;
1823 * Return an array of enrol_bulk_enrolment_operation objects that define
1824 * the bulk actions that can be performed on user enrolments by the plugin.
1826 * @param course_enrolment_manager $manager
1827 * @return array
1829 public function get_bulk_operations(course_enrolment_manager $manager) {
1830 return array();
1834 * Do any enrolments need expiration processing.
1836 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
1838 * @param progress_trace $trace
1839 * @param int $courseid one course, empty mean all
1840 * @return bool true if any data processed, false if not
1842 public function process_expirations(progress_trace $trace, $courseid = null) {
1843 global $DB;
1845 $name = $this->get_name();
1846 if (!enrol_is_enabled($name)) {
1847 $trace->finished();
1848 return false;
1851 $processed = false;
1852 $params = array();
1853 $coursesql = "";
1854 if ($courseid) {
1855 $coursesql = "AND e.courseid = :courseid";
1858 // Deal with expired accounts.
1859 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
1861 if ($action == ENROL_EXT_REMOVED_UNENROL) {
1862 $instances = array();
1863 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
1864 FROM {user_enrolments} ue
1865 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
1866 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
1867 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
1868 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'enrol'=>$name, 'courseid'=>$courseid);
1870 $rs = $DB->get_recordset_sql($sql, $params);
1871 foreach ($rs as $ue) {
1872 if (!$processed) {
1873 $trace->output("Starting processing of enrol_$name expirations...");
1874 $processed = true;
1876 if (empty($instances[$ue->enrolid])) {
1877 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
1879 $instance = $instances[$ue->enrolid];
1880 if (!$this->roles_protected()) {
1881 // Let's just guess what extra roles are supposed to be removed.
1882 if ($instance->roleid) {
1883 role_unassign($instance->roleid, $ue->userid, $ue->contextid);
1886 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
1887 $this->unenrol_user($instance, $ue->userid);
1888 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
1890 $rs->close();
1891 unset($instances);
1893 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
1894 $instances = array();
1895 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
1896 FROM {user_enrolments} ue
1897 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
1898 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
1899 WHERE ue.timeend > 0 AND ue.timeend < :now
1900 AND ue.status = :useractive $coursesql";
1901 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE, 'useractive'=>ENROL_USER_ACTIVE, 'enrol'=>$name, 'courseid'=>$courseid);
1902 $rs = $DB->get_recordset_sql($sql, $params);
1903 foreach ($rs as $ue) {
1904 if (!$processed) {
1905 $trace->output("Starting processing of enrol_$name expirations...");
1906 $processed = true;
1908 if (empty($instances[$ue->enrolid])) {
1909 $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
1911 $instance = $instances[$ue->enrolid];
1913 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
1914 if (!$this->roles_protected()) {
1915 // Let's just guess what roles should be removed.
1916 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid));
1917 if ($count == 1) {
1918 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0));
1920 } else if ($count > 1 and $instance->roleid) {
1921 role_unassign($instance->roleid, $ue->userid, $ue->contextid, '', 0);
1924 // In any case remove all roles that belong to this instance and user.
1925 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id), true);
1926 // Final cleanup of subcontexts if there are no more course roles.
1927 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid, 'contextid'=>$ue->contextid))) {
1928 role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
1932 $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
1933 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
1935 $rs->close();
1936 unset($instances);
1938 } else {
1939 // ENROL_EXT_REMOVED_KEEP means no changes.
1942 if ($processed) {
1943 $trace->output("...finished processing of enrol_$name expirations");
1944 } else {
1945 $trace->output("No expired enrol_$name enrolments detected");
1947 $trace->finished();
1949 return $processed;
1953 * Send expiry notifications.
1955 * Plugin that wants to have expiry notification MUST implement following:
1956 * - expirynotifyhour plugin setting,
1957 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
1958 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
1959 * expirymessageenrolledsubject and expirymessageenrolledbody),
1960 * - expiry_notification provider in db/messages.php,
1961 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
1962 * - something that calls this method, such as cron.
1964 * @param progress_trace $trace (accepts bool for backwards compatibility only)
1966 public function send_expiry_notifications($trace) {
1967 global $DB, $CFG;
1969 $name = $this->get_name();
1970 if (!enrol_is_enabled($name)) {
1971 $trace->finished();
1972 return;
1975 // Unfortunately this may take a long time, it should not be interrupted,
1976 // otherwise users get duplicate notification.
1978 @set_time_limit(0);
1979 raise_memory_limit(MEMORY_HUGE);
1982 $expirynotifylast = $this->get_config('expirynotifylast', 0);
1983 $expirynotifyhour = $this->get_config('expirynotifyhour');
1984 if (is_null($expirynotifyhour)) {
1985 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
1986 $trace->finished();
1987 return;
1990 if (!($trace instanceof progress_trace)) {
1991 $trace = $trace ? new text_progress_trace() : new null_progress_trace();
1992 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER);
1995 $timenow = time();
1996 $notifytime = usergetmidnight($timenow, $CFG->timezone) + ($expirynotifyhour * 3600);
1998 if ($expirynotifylast > $notifytime) {
1999 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone).'.');
2000 $trace->finished();
2001 return;
2003 } else if ($timenow < $notifytime) {
2004 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone).'.');
2005 $trace->finished();
2006 return;
2009 $trace->output('Processing '.$name.' enrolment expiration notifications...');
2011 // Notify users responsible for enrolment once every day.
2012 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2013 FROM {user_enrolments} ue
2014 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2015 JOIN {course} c ON (c.id = e.courseid)
2016 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2017 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2018 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2019 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2021 $rs = $DB->get_recordset_sql($sql, $params);
2023 $lastenrollid = 0;
2024 $users = array();
2026 foreach($rs as $ue) {
2027 if ($lastenrollid and $lastenrollid != $ue->enrolid) {
2028 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2029 $users = array();
2031 $lastenrollid = $ue->enrolid;
2033 $enroller = $this->get_enroller($ue->enrolid);
2034 $context = context_course::instance($ue->courseid);
2036 $user = $DB->get_record('user', array('id'=>$ue->userid));
2038 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend);
2040 if (!$ue->notifyall) {
2041 continue;
2044 if ($ue->timeend - $ue->expirythreshold + 86400 < $timenow) {
2045 // Notify enrolled users only once at the start of the threshold.
2046 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2047 continue;
2050 $this->notify_expiry_enrolled($user, $ue, $trace);
2052 $rs->close();
2054 if ($lastenrollid and $users) {
2055 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2058 $trace->output('...notification processing finished.');
2059 $trace->finished();
2061 $this->set_config('expirynotifylast', $timenow);
2065 * Returns the user who is responsible for enrolments for given instance.
2067 * Override if plugin knows anybody better than admin.
2069 * @param int $instanceid enrolment instance id
2070 * @return stdClass user record
2072 protected function get_enroller($instanceid) {
2073 return get_admin();
2077 * Notify user about incoming expiration of their enrolment,
2078 * it is called only if notification of enrolled users (aka students) is enabled in course.
2080 * This is executed only once for each expiring enrolment right
2081 * at the start of the expiration threshold.
2083 * @param stdClass $user
2084 * @param stdClass $ue
2085 * @param progress_trace $trace
2087 protected function notify_expiry_enrolled($user, $ue, progress_trace $trace) {
2088 global $CFG, $SESSION;
2090 $name = $this->get_name();
2092 // Some nasty hackery to get strings and dates localised for target user.
2093 $sessionlang = isset($SESSION->lang) ? $SESSION->lang : null;
2094 if (get_string_manager()->translation_exists($user->lang, false)) {
2095 $SESSION->lang = $user->lang;
2096 moodle_setlocale();
2099 $enroller = $this->get_enroller($ue->enrolid);
2100 $context = context_course::instance($ue->courseid);
2102 $a = new stdClass();
2103 $a->course = format_string($ue->fullname, true, array('context'=>$context));
2104 $a->user = fullname($user, true);
2105 $a->timeend = userdate($ue->timeend, '', $user->timezone);
2106 $a->enroller = fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
2108 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
2109 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
2111 $message = new stdClass();
2112 $message->notification = 1;
2113 $message->component = 'enrol_'.$name;
2114 $message->name = 'expiry_notification';
2115 $message->userfrom = $enroller;
2116 $message->userto = $user;
2117 $message->subject = $subject;
2118 $message->fullmessage = $body;
2119 $message->fullmessageformat = FORMAT_MARKDOWN;
2120 $message->fullmessagehtml = markdown_to_html($body);
2121 $message->smallmessage = $subject;
2122 $message->contexturlname = $a->course;
2123 $message->contexturl = (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid));
2125 if (message_send($message)) {
2126 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2127 } else {
2128 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend, '', $CFG->timezone), 1);
2131 if ($SESSION->lang !== $sessionlang) {
2132 $SESSION->lang = $sessionlang;
2133 moodle_setlocale();
2138 * Notify person responsible for enrolments that some user enrolments will be expired soon,
2139 * it is called only if notification of enrollers (aka teachers) is enabled in course.
2141 * This is called repeatedly every day for each course if there are any pending expiration
2142 * in the expiration threshold.
2144 * @param int $eid
2145 * @param array $users
2146 * @param progress_trace $trace
2148 protected function notify_expiry_enroller($eid, $users, progress_trace $trace) {
2149 global $DB, $SESSION;
2151 $name = $this->get_name();
2153 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
2154 $context = context_course::instance($instance->courseid);
2155 $course = $DB->get_record('course', array('id'=>$instance->courseid));
2157 $enroller = $this->get_enroller($instance->id);
2158 $admin = get_admin();
2160 // Some nasty hackery to get strings and dates localised for target user.
2161 $sessionlang = isset($SESSION->lang) ? $SESSION->lang : null;
2162 if (get_string_manager()->translation_exists($enroller->lang, false)) {
2163 $SESSION->lang = $enroller->lang;
2164 moodle_setlocale();
2167 foreach($users as $key=>$info) {
2168 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone);
2171 $a = new stdClass();
2172 $a->course = format_string($course->fullname, true, array('context'=>$context));
2173 $a->threshold = get_string('numdays', '', $instance->expirythreshold / (60*60*24));
2174 $a->users = implode("\n", $users);
2175 $a->extendurl = (string)new moodle_url('/enrol/users.php', array('id'=>$instance->courseid));
2177 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
2178 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
2180 $message = new stdClass();
2181 $message->notification = 1;
2182 $message->component = 'enrol_'.$name;
2183 $message->name = 'expiry_notification';
2184 $message->userfrom = $admin;
2185 $message->userto = $enroller;
2186 $message->subject = $subject;
2187 $message->fullmessage = $body;
2188 $message->fullmessageformat = FORMAT_MARKDOWN;
2189 $message->fullmessagehtml = markdown_to_html($body);
2190 $message->smallmessage = $subject;
2191 $message->contexturlname = $a->course;
2192 $message->contexturl = $a->extendurl;
2194 if (message_send($message)) {
2195 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
2196 } else {
2197 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
2200 if ($SESSION->lang !== $sessionlang) {
2201 $SESSION->lang = $sessionlang;
2202 moodle_setlocale();
2207 * Automatic enrol sync executed during restore.
2208 * Useful for automatic sync by course->idnumber or course category.
2209 * @param stdClass $course course record
2211 public function restore_sync_course($course) {
2212 // Override if necessary.
2216 * Restore instance and map settings.
2218 * @param restore_enrolments_structure_step $step
2219 * @param stdClass $data
2220 * @param stdClass $course
2221 * @param int $oldid
2223 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
2224 // Do not call this from overridden methods, restore and set new id there.
2225 $step->set_mapping('enrol', $oldid, 0);
2229 * Restore user enrolment.
2231 * @param restore_enrolments_structure_step $step
2232 * @param stdClass $data
2233 * @param stdClass $instance
2234 * @param int $oldinstancestatus
2235 * @param int $userid
2237 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
2238 // Override as necessary if plugin supports restore of enrolments.
2242 * Restore role assignment.
2244 * @param stdClass $instance
2245 * @param int $roleid
2246 * @param int $userid
2247 * @param int $contextid
2249 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
2250 // No role assignment by default, override if necessary.
2254 * Restore user group membership.
2255 * @param stdClass $instance
2256 * @param int $groupid
2257 * @param int $userid
2259 public function restore_group_member($instance, $groupid, $userid) {
2260 // Implement if you want to restore protected group memberships,
2261 // usually this is not necessary because plugins should be able to recreate the memberships automatically.