3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * This library includes the basic parts of enrol api.
20 * It is available on each page.
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');
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,
62 define('ENROL_EXT_REMOVED_SUSPEND', 2);
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.
68 define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
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) {
81 // sorted by enabled plugin order
82 $enabled = explode(',', $CFG->enrol_plugins_enabled
);
84 foreach ($enabled as $plugin) {
85 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
88 // sorted alphabetically
89 $plugins = core_component
::get_plugin_list('enrol');
93 foreach ($plugins as $plugin=>$location) {
94 $class = "enrol_{$plugin}_plugin";
95 if (!class_exists($class)) {
96 if (!file_exists("$location/lib.php")) {
99 include_once("$location/lib.php");
100 if (!class_exists($class)) {
105 $result[$plugin] = new $class();
112 * Returns instance of enrol plugin
113 * @param string $name name of enrol plugin ('manual', 'guest', ...)
114 * @return enrol_plugin
116 function enrol_get_plugin($name) {
119 $name = clean_param($name, PARAM_PLUGIN
);
122 // ignore malformed or missing plugin names completely
126 $location = "$CFG->dirroot/enrol/$name";
128 if (!file_exists("$location/lib.php")) {
131 include_once("$location/lib.php");
132 $class = "enrol_{$name}_plugin";
133 if (!class_exists($class)) {
141 * Returns enrolment instances in given course.
142 * @param int $courseid
143 * @param bool $enabled
144 * @return array of enrol instances
146 function enrol_get_instances($courseid, $enabled) {
150 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
153 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder,id');
155 $enabled = explode(',', $CFG->enrol_plugins_enabled
);
156 foreach ($result as $key=>$instance) {
157 if (!in_array($instance->enrol
, $enabled)) {
158 unset($result[$key]);
161 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
163 unset($result[$key]);
172 * Checks if a given plugin is in the list of enabled enrolment plugins.
174 * @param string $enrol Enrolment plugin name
175 * @return boolean Whether the plugin is enabled
177 function enrol_is_enabled($enrol) {
180 if (empty($CFG->enrol_plugins_enabled
)) {
183 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled
));
187 * Check all the login enrolment information for the given user object
188 * by querying the enrolment plugins
190 * This function may be very slow, use only once after log-in or login-as.
192 * @param stdClass $user
195 function enrol_check_plugins($user) {
198 if (empty($user->id
) or isguestuser($user)) {
199 // shortcut - there is no enrolment work for guests and not-logged-in users
203 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
204 // which proved it was actually not necessary.
206 static $inprogress = array(); // To prevent this function being called more than once in an invocation
208 if (!empty($inprogress[$user->id
])) {
212 $inprogress[$user->id
] = true; // Set the flag
214 $enabled = enrol_get_plugins(true);
216 foreach($enabled as $enrol) {
217 $enrol->sync_user_enrolments($user);
220 unset($inprogress[$user->id
]); // Unset the flag
224 * Do these two students share any course?
226 * The courses has to be visible and enrolments has to be active,
227 * timestart and timeend restrictions are ignored.
229 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
232 * @param stdClass|int $user1
233 * @param stdClass|int $user2
236 function enrol_sharing_course($user1, $user2) {
237 return enrol_get_shared_courses($user1, $user2, false, true);
241 * Returns any courses shared by the two users
243 * The courses has to be visible and enrolments has to be active,
244 * timestart and timeend restrictions are ignored.
246 * @global moodle_database $DB
247 * @param stdClass|int $user1
248 * @param stdClass|int $user2
249 * @param bool $preloadcontexts If set to true contexts for the returned courses
251 * @param bool $checkexistsonly If set to true then this function will return true
252 * if the users share any courses and false if not.
253 * @return array|bool An array of courses that both users are enrolled in OR if
254 * $checkexistsonly set returns true if the users share any courses
257 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
260 $user1 = isset($user1->id
) ?
$user1->id
: $user1;
261 $user2 = isset($user2->id
) ?
$user2->id
: $user2;
263 if (empty($user1) or empty($user2)) {
267 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled
)) {
271 list($plugins, $params) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED
, 'ee');
272 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
273 $params['active1'] = ENROL_USER_ACTIVE
;
274 $params['active2'] = ENROL_USER_ACTIVE
;
275 $params['user1'] = $user1;
276 $params['user2'] = $user2;
280 if ($preloadcontexts) {
281 $ctxselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
282 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
283 $params['contextlevel'] = CONTEXT_COURSE
;
286 $sql = "SELECT c.* $ctxselect
291 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e.id AND ue1.status = :active1 AND ue1.userid = :user1)
292 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e.id AND ue2.status = :active2 AND ue2.userid = :user2)
293 JOIN {course} c ON (c.id = e.courseid AND c.visible = 1)
294 WHERE e.status = :enabled AND e.enrol $plugins
298 if ($checkexistsonly) {
299 return $DB->record_exists_sql($sql, $params);
301 $courses = $DB->get_records_sql($sql, $params);
302 if ($preloadcontexts) {
303 array_map('context_helper::preload_from_record', $courses);
310 * This function adds necessary enrol plugins UI into the course edit form.
312 * @param MoodleQuickForm $mform
313 * @param object $data course edit form data
314 * @param object $context context of existing course or parent category if course does not exist
317 function enrol_course_edit_form(MoodleQuickForm
$mform, $data, $context) {
318 $plugins = enrol_get_plugins(true);
319 if (!empty($data->id
)) {
320 $instances = enrol_get_instances($data->id
, false);
321 foreach ($instances as $instance) {
322 if (!isset($plugins[$instance->enrol
])) {
325 $plugin = $plugins[$instance->enrol
];
326 $plugin->course_edit_form($instance, $mform, $data, $context);
329 foreach ($plugins as $plugin) {
330 $plugin->course_edit_form(NULL, $mform, $data, $context);
336 * Validate course edit form data
338 * @param array $data raw form data
339 * @param object $context context of existing course or parent category if course does not exist
340 * @return array errors array
342 function enrol_course_edit_validation(array $data, $context) {
344 $plugins = enrol_get_plugins(true);
346 if (!empty($data['id'])) {
347 $instances = enrol_get_instances($data['id'], false);
348 foreach ($instances as $instance) {
349 if (!isset($plugins[$instance->enrol
])) {
352 $plugin = $plugins[$instance->enrol
];
353 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
356 foreach ($plugins as $plugin) {
357 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
365 * Update enrol instances after course edit form submission
366 * @param bool $inserted true means new course added, false course already existed
367 * @param object $course
368 * @param object $data form data
371 function enrol_course_updated($inserted, $course, $data) {
374 $plugins = enrol_get_plugins(true);
376 foreach ($plugins as $plugin) {
377 $plugin->course_updated($inserted, $course, $data);
382 * Add navigation nodes
383 * @param navigation_node $coursenode
384 * @param object $course
387 function enrol_add_course_navigation(navigation_node
$coursenode, $course) {
390 $coursecontext = context_course
::instance($course->id
);
392 $instances = enrol_get_instances($course->id
, true);
393 $plugins = enrol_get_plugins(true);
395 // we do not want to break all course pages if there is some borked enrol plugin, right?
396 foreach ($instances as $k=>$instance) {
397 if (!isset($plugins[$instance->enrol
])) {
398 unset($instances[$k]);
402 $usersnode = $coursenode->add(get_string('users'), null, navigation_node
::TYPE_CONTAINER
, null, 'users');
404 if ($course->id
!= SITEID
) {
405 // list all participants - allows assigning roles, groups, etc.
406 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
407 $url = new moodle_url('/enrol/users.php', array('id'=>$course->id
));
408 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node
::TYPE_SETTING
, null, 'review', new pix_icon('i/enrolusers', ''));
411 // manage enrol plugin instances
412 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
413 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id
));
417 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node
::TYPE_SETTING
, null, 'manageinstances');
419 // each instance decides how to configure itself or how many other nav items are exposed
420 foreach ($instances as $instance) {
421 if (!isset($plugins[$instance->enrol
])) {
424 $plugins[$instance->enrol
]->add_course_navigation($instancesnode, $instance);
428 $instancesnode->trim_if_empty();
432 // Manage groups in this course or even frontpage
433 if (($course->groupmode ||
!$course->groupmodeforce
) && has_capability('moodle/course:managegroups', $coursecontext)) {
434 $url = new moodle_url('/group/index.php', array('id'=>$course->id
));
435 $usersnode->add(get_string('groups'), $url, navigation_node
::TYPE_SETTING
, null, 'groups', new pix_icon('i/group', ''));
438 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
440 if (has_capability('moodle/role:review', $coursecontext)) {
441 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id
));
445 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'override');
447 // Add assign or override roles if allowed
448 if ($course->id
== SITEID
or (!empty($CFG->adminsassignrolesincourse
) and is_siteadmin())) {
449 if (has_capability('moodle/role:assign', $coursecontext)) {
450 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id
));
451 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'roles', new pix_icon('i/assignroles', ''));
454 // Check role permissions
455 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
456 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id
));
457 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/checkpermissions', ''));
461 // Deal somehow with users that are not enrolled but still got a role somehow
462 if ($course->id
!= SITEID
) {
463 //TODO, create some new UI for role assignments at course level
464 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
465 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id
));
466 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node
::TYPE_SETTING
, null, 'otherusers', new pix_icon('i/assignroles', ''));
470 // just in case nothing was actually added
471 $usersnode->trim_if_empty();
473 if ($course->id
!= SITEID
) {
474 if (isguestuser() or !isloggedin()) {
475 // guest account can not be enrolled - no links for them
476 } else if (is_enrolled($coursecontext)) {
477 // unenrol link if possible
478 foreach ($instances as $instance) {
479 if (!isset($plugins[$instance->enrol
])) {
482 $plugin = $plugins[$instance->enrol
];
483 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
484 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
485 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node
::TYPE_SETTING
, null, 'unenrolself', new pix_icon('i/user', ''));
487 //TODO. deal with multiple unenrol links - not likely case, but still...
491 // enrol link if possible
492 if (is_viewing($coursecontext)) {
493 // better not show any enrol link, this is intended for managers and inspectors
495 foreach ($instances as $instance) {
496 if (!isset($plugins[$instance->enrol
])) {
499 $plugin = $plugins[$instance->enrol
];
500 if ($plugin->show_enrolme_link($instance)) {
501 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id
));
502 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
503 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node
::TYPE_SETTING
, null, 'enrolself', new pix_icon('i/user', ''));
513 * Returns list of courses current $USER is enrolled in and can access
515 * - $fields is an array of field names to ADD
516 * so name the fields you really need, which will
517 * be added and uniq'd
519 * @param string|array $fields
520 * @param string $sort
521 * @param int $limit max number of courses
524 function enrol_get_my_courses($fields = NULL, $sort = 'visible DESC,sortorder ASC', $limit = 0) {
527 // Guest account does not have any courses
528 if (isguestuser() or !isloggedin()) {
532 $basefields = array('id', 'category', 'sortorder',
533 'shortname', 'fullname', 'idnumber',
534 'startdate', 'visible',
535 'groupmode', 'groupmodeforce', 'cacherev');
537 if (empty($fields)) {
538 $fields = $basefields;
539 } else if (is_string($fields)) {
540 // turn the fields from a string to an array
541 $fields = explode(',', $fields);
542 $fields = array_map('trim', $fields);
543 $fields = array_unique(array_merge($basefields, $fields));
544 } else if (is_array($fields)) {
545 $fields = array_unique(array_merge($basefields, $fields));
547 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
549 if (in_array('*', $fields)) {
550 $fields = array('*');
556 $rawsorts = explode(',', $sort);
558 foreach ($rawsorts as $rawsort) {
559 $rawsort = trim($rawsort);
560 if (strpos($rawsort, 'c.') === 0) {
561 $rawsort = substr($rawsort, 2);
563 $sorts[] = trim($rawsort);
565 $sort = 'c.'.implode(',c.', $sorts);
566 $orderby = "ORDER BY $sort";
569 $wheres = array("c.id <> :siteid");
570 $params = array('siteid'=>SITEID
);
572 if (isset($USER->loginascontext
) and $USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
573 // list _only_ this course - anything else is asking for trouble...
574 $wheres[] = "courseid = :loginas";
575 $params['loginas'] = $USER->loginascontext
->instanceid
;
578 $coursefields = 'c.' .join(',c.', $fields);
579 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
580 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
581 $params['contextlevel'] = CONTEXT_COURSE
;
582 $wheres = implode(" AND ", $wheres);
584 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
585 $sql = "SELECT $coursefields $ccselect
587 JOIN (SELECT DISTINCT e.courseid
589 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
590 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)
591 ) en ON (en.courseid = c.id)
595 $params['userid'] = $USER->id
;
596 $params['active'] = ENROL_USER_ACTIVE
;
597 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
598 $params['now1'] = round(time(), -2); // improves db caching
599 $params['now2'] = $params['now1'];
601 $courses = $DB->get_records_sql($sql, $params, 0, $limit);
603 // preload contexts and check visibility
604 foreach ($courses as $id=>$course) {
605 context_helper
::preload_from_record($course);
606 if (!$course->visible
) {
607 if (!$context = context_course
::instance($id, IGNORE_MISSING
)) {
608 unset($courses[$id]);
611 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
612 unset($courses[$id]);
616 $courses[$id] = $course;
619 //wow! Is that really all? :-D
625 * Returns course enrolment information icons.
627 * @param object $course
628 * @param array $instances enrol instances of this course, improves performance
629 * @return array of pix_icon
631 function enrol_get_course_info_icons($course, array $instances = NULL) {
633 if (is_null($instances)) {
634 $instances = enrol_get_instances($course->id
, true);
636 $plugins = enrol_get_plugins(true);
637 foreach ($plugins as $name => $plugin) {
639 foreach ($instances as $instance) {
640 if ($instance->status
!= ENROL_INSTANCE_ENABLED
or $instance->courseid
!= $course->id
) {
641 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
644 if ($instance->enrol
== $name) {
645 $pis[$instance->id
] = $instance;
649 $icons = array_merge($icons, $plugin->get_info_icons($pis));
656 * Returns course enrolment detailed information.
658 * @param object $course
659 * @return array of html fragments - can be used to construct lists
661 function enrol_get_course_description_texts($course) {
663 $instances = enrol_get_instances($course->id
, true);
664 $plugins = enrol_get_plugins(true);
665 foreach ($instances as $instance) {
666 if (!isset($plugins[$instance->enrol
])) {
670 $plugin = $plugins[$instance->enrol
];
671 $text = $plugin->get_description_text($instance);
672 if ($text !== NULL) {
680 * Returns list of courses user is enrolled into.
681 * (Note: use enrol_get_all_users_courses if you want to use the list wihtout any cap checks )
683 * - $fields is an array of fieldnames to ADD
684 * so name the fields you really need, which will
685 * be added and uniq'd
688 * @param bool $onlyactive return only active enrolments in courses user may see
689 * @param string|array $fields
690 * @param string $sort
693 function enrol_get_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
696 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
698 // preload contexts and check visibility
700 foreach ($courses as $id=>$course) {
701 context_helper
::preload_from_record($course);
702 if (!$course->visible
) {
703 if (!$context = context_course
::instance($id)) {
704 unset($courses[$id]);
707 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
708 unset($courses[$id]);
720 * Can user access at least one enrolled course?
722 * Cheat if necessary, but find out as fast as possible!
724 * @param int|stdClass $user null means use current user
727 function enrol_user_sees_own_courses($user = null) {
730 if ($user === null) {
733 $userid = is_object($user) ?
$user->id
: $user;
735 // Guest account does not have any courses
736 if (isguestuser($userid) or empty($userid)) {
740 // Let's cheat here if this is the current user,
741 // if user accessed any course recently, then most probably
742 // we do not need to query the database at all.
743 if ($USER->id
== $userid) {
744 if (!empty($USER->enrol
['enrolled'])) {
745 foreach ($USER->enrol
['enrolled'] as $until) {
746 if ($until > time()) {
754 $courses = enrol_get_all_users_courses($userid, true);
755 foreach($courses as $course) {
756 if ($course->visible
) {
759 context_helper
::preload_from_record($course);
760 $context = context_course
::instance($course->id
);
761 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
770 * Returns list of courses user is enrolled into without any capability checks
771 * - $fields is an array of fieldnames to ADD
772 * so name the fields you really need, which will
773 * be added and uniq'd
776 * @param bool $onlyactive return only active enrolments in courses user may see
777 * @param string|array $fields
778 * @param string $sort
781 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = NULL, $sort = 'visible DESC,sortorder ASC') {
784 // Guest account does not have any courses
785 if (isguestuser($userid) or empty($userid)) {
789 $basefields = array('id', 'category', 'sortorder',
790 'shortname', 'fullname', 'idnumber',
791 'startdate', 'visible',
792 'groupmode', 'groupmodeforce');
794 if (empty($fields)) {
795 $fields = $basefields;
796 } else if (is_string($fields)) {
797 // turn the fields from a string to an array
798 $fields = explode(',', $fields);
799 $fields = array_map('trim', $fields);
800 $fields = array_unique(array_merge($basefields, $fields));
801 } else if (is_array($fields)) {
802 $fields = array_unique(array_merge($basefields, $fields));
804 throw new coding_exception('Invalid $fileds parameter in enrol_get_my_courses()');
806 if (in_array('*', $fields)) {
807 $fields = array('*');
813 $rawsorts = explode(',', $sort);
815 foreach ($rawsorts as $rawsort) {
816 $rawsort = trim($rawsort);
817 if (strpos($rawsort, 'c.') === 0) {
818 $rawsort = substr($rawsort, 2);
820 $sorts[] = trim($rawsort);
822 $sort = 'c.'.implode(',c.', $sorts);
823 $orderby = "ORDER BY $sort";
826 $params = array('siteid'=>SITEID
);
829 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
830 $params['now1'] = round(time(), -2); // improves db caching
831 $params['now2'] = $params['now1'];
832 $params['active'] = ENROL_USER_ACTIVE
;
833 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
838 $coursefields = 'c.' .join(',c.', $fields);
839 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
840 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
841 $params['contextlevel'] = CONTEXT_COURSE
;
843 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
844 $sql = "SELECT $coursefields $ccselect
846 JOIN (SELECT DISTINCT e.courseid
848 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
850 ) en ON (en.courseid = c.id)
852 WHERE c.id <> :siteid
854 $params['userid'] = $userid;
856 $courses = $DB->get_records_sql($sql, $params);
864 * Called when user is about to be deleted.
865 * @param object $user
868 function enrol_user_delete($user) {
871 $plugins = enrol_get_plugins(true);
872 foreach ($plugins as $plugin) {
873 $plugin->user_delete($user);
876 // force cleanup of all broken enrolments
877 $DB->delete_records('user_enrolments', array('userid'=>$user->id
));
881 * Called when course is about to be deleted.
882 * @param stdClass $course
885 function enrol_course_delete($course) {
888 $instances = enrol_get_instances($course->id
, false);
889 $plugins = enrol_get_plugins(true);
890 foreach ($instances as $instance) {
891 if (isset($plugins[$instance->enrol
])) {
892 $plugins[$instance->enrol
]->delete_instance($instance);
894 // low level delete in case plugin did not do it
895 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
896 $DB->delete_records('role_assignments', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$instance->enrol
));
897 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
898 $DB->delete_records('enrol', array('id'=>$instance->id
));
903 * Try to enrol user via default internal auth plugin.
905 * For now this is always using the manual enrol plugin...
912 * @return bool success
914 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
917 //note: this is hardcoded to manual plugin for now
919 if (!enrol_is_enabled('manual')) {
923 if (!$enrol = enrol_get_plugin('manual')) {
926 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder,id ASC')) {
929 $instance = reset($instances);
931 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
937 * Is there a chance users might self enrol
938 * @param int $courseid
941 function enrol_selfenrol_available($courseid) {
944 $plugins = enrol_get_plugins(true);
945 $enrolinstances = enrol_get_instances($courseid, true);
946 foreach($enrolinstances as $instance) {
947 if (!isset($plugins[$instance->enrol
])) {
950 if ($instance->enrol
=== 'guest') {
951 // blacklist known temporary guest plugins
954 if ($plugins[$instance->enrol
]->show_enrolme_link($instance)) {
964 * This function returns the end of current active user enrolment.
966 * It deals correctly with multiple overlapping user enrolments.
968 * @param int $courseid
970 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
972 function enrol_get_enrolment_end($courseid, $userid) {
976 FROM {user_enrolments} ue
977 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
978 JOIN {user} u ON u.id = ue.userid
979 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
980 $params = array('enabled'=>ENROL_INSTANCE_ENABLED
, 'active'=>ENROL_USER_ACTIVE
, 'userid'=>$userid, 'courseid'=>$courseid);
982 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
988 foreach ($enrolments as $ue) {
989 $start = (int)$ue->timestart
;
990 $end = (int)$ue->timeend
;
991 if ($end != 0 and $end < $start) {
992 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id
);
995 if (isset($changes[$start])) {
996 $changes[$start] = $changes[$start] +
1;
998 $changes[$start] = 1;
1002 } else if (isset($changes[$end])) {
1003 $changes[$end] = $changes[$end] - 1;
1005 $changes[$end] = -1;
1009 // let's sort then enrolment starts&ends and go through them chronologically,
1010 // looking for current status and the next future end of enrolment
1017 foreach ($changes as $time => $change) {
1019 if ($present === null) {
1020 // we have just went past current time
1021 $present = $current;
1023 // no enrolment active
1027 if ($present !== null) {
1028 // we are already in the future - look for possible end
1029 if ($current +
$change < 1) {
1034 $current +
= $change;
1045 * Is current user accessing course via this enrolment method?
1047 * This is intended for operations that are going to affect enrol instances.
1049 * @param stdClass $instance enrol instance
1052 function enrol_accessing_via_instance(stdClass
$instance) {
1055 if (empty($instance->id
)) {
1059 if (is_siteadmin()) {
1060 // Admins may go anywhere.
1064 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id
, 'enrolid'=>$instance->id
));
1069 * All enrol plugins should be based on this class,
1070 * this is also the main source of documentation.
1072 abstract class enrol_plugin
{
1073 protected $config = null;
1076 * Returns name of this enrol plugin
1079 public function get_name() {
1080 // second word in class is always enrol name, sorry, no fancy plugin names with _
1081 $words = explode('_', get_class($this));
1086 * Returns localised name of enrol instance
1088 * @param object $instance (null is accepted too)
1091 public function get_instance_name($instance) {
1092 if (empty($instance->name
)) {
1093 $enrol = $this->get_name();
1094 return get_string('pluginname', 'enrol_'.$enrol);
1096 $context = context_course
::instance($instance->courseid
);
1097 return format_string($instance->name
, true, array('context'=>$context));
1102 * Returns optional enrolment information icons.
1104 * This is used in course list for quick overview of enrolment options.
1106 * We are not using single instance parameter because sometimes
1107 * we might want to prevent icon repetition when multiple instances
1108 * of one type exist. One instance may also produce several icons.
1110 * @param array $instances all enrol instances of this type in one course
1111 * @return array of pix_icon
1113 public function get_info_icons(array $instances) {
1118 * Returns optional enrolment instance description text.
1120 * This is used in detailed course information.
1123 * @param object $instance
1124 * @return string short html text
1126 public function get_description_text($instance) {
1131 * Makes sure config is loaded and cached.
1134 protected function load_config() {
1135 if (!isset($this->config
)) {
1136 $name = $this->get_name();
1137 $this->config
= get_config("enrol_$name");
1142 * Returns plugin config value
1143 * @param string $name
1144 * @param string $default value if config does not exist yet
1145 * @return string value or default
1147 public function get_config($name, $default = NULL) {
1148 $this->load_config();
1149 return isset($this->config
->$name) ?
$this->config
->$name : $default;
1153 * Sets plugin config value
1154 * @param string $name name of config
1155 * @param string $value string config value, null means delete
1156 * @return string value
1158 public function set_config($name, $value) {
1159 $pluginname = $this->get_name();
1160 $this->load_config();
1161 if ($value === NULL) {
1162 unset($this->config
->$name);
1164 $this->config
->$name = $value;
1166 set_config($name, $value, "enrol_$pluginname");
1170 * Does this plugin assign protected roles are can they be manually removed?
1171 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1173 public function roles_protected() {
1178 * Does this plugin allow manual enrolments?
1180 * @param stdClass $instance course enrol instance
1181 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1183 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1185 public function allow_enrol(stdClass
$instance) {
1190 * Does this plugin allow manual unenrolment of all users?
1191 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1193 * @param stdClass $instance course enrol instance
1194 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1196 public function allow_unenrol(stdClass
$instance) {
1201 * Does this plugin allow manual unenrolment of a specific user?
1202 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1204 * This is useful especially for synchronisation plugins that
1205 * do suspend instead of full unenrolment.
1207 * @param stdClass $instance course enrol instance
1208 * @param stdClass $ue record from user_enrolments table, specifies user
1210 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1212 public function allow_unenrol_user(stdClass
$instance, stdClass
$ue) {
1213 return $this->allow_unenrol($instance);
1217 * Does this plugin allow manual changes in user_enrolments table?
1219 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1221 * @param stdClass $instance course enrol instance
1222 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1224 public function allow_manage(stdClass
$instance) {
1229 * Does this plugin support some way to user to self enrol?
1231 * @param stdClass $instance course enrol instance
1233 * @return bool - true means show "Enrol me in this course" link in course UI
1235 public function show_enrolme_link(stdClass
$instance) {
1240 * Attempt to automatically enrol current user in course without any interaction,
1241 * calling code has to make sure the plugin and instance are active.
1243 * This should return either a timestamp in the future or false.
1245 * @param stdClass $instance course enrol instance
1246 * @return bool|int false means not enrolled, integer means timeend
1248 public function try_autoenrol(stdClass
$instance) {
1255 * Attempt to automatically gain temporary guest access to course,
1256 * calling code has to make sure the plugin and instance are active.
1258 * This should return either a timestamp in the future or false.
1260 * @param stdClass $instance course enrol instance
1261 * @return bool|int false means no guest access, integer means timeend
1263 public function try_guestaccess(stdClass
$instance) {
1270 * Enrol user into course via enrol instance.
1272 * @param stdClass $instance
1273 * @param int $userid
1274 * @param int $roleid optional role id
1275 * @param int $timestart 0 means unknown
1276 * @param int $timeend 0 means forever
1277 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1278 * @param bool $recovergrades restore grade history
1281 public function enrol_user(stdClass
$instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
1282 global $DB, $USER, $CFG; // CFG necessary!!!
1284 if ($instance->courseid
== SITEID
) {
1285 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1288 $name = $this->get_name();
1289 $courseid = $instance->courseid
;
1291 if ($instance->enrol
!== $name) {
1292 throw new coding_exception('invalid enrol instance!');
1294 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
1295 if (!isset($recovergrades)) {
1296 $recovergrades = $CFG->recovergradesdefault
;
1301 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
1302 //only update if timestart or timeend or status are different.
1303 if ($ue->timestart
!= $timestart or $ue->timeend
!= $timeend or (!is_null($status) and $ue->status
!= $status)) {
1304 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
1307 $ue = new stdClass();
1308 $ue->enrolid
= $instance->id
;
1309 $ue->status
= is_null($status) ? ENROL_USER_ACTIVE
: $status;
1310 $ue->userid
= $userid;
1311 $ue->timestart
= $timestart;
1312 $ue->timeend
= $timeend;
1313 $ue->modifierid
= $USER->id
;
1314 $ue->timecreated
= time();
1315 $ue->timemodified
= $ue->timecreated
;
1316 $ue->id
= $DB->insert_record('user_enrolments', $ue);
1323 $event = \core\event\user_enrolment_created
::create(
1325 'objectid' => $ue->id
,
1326 'courseid' => $courseid,
1327 'context' => $context,
1328 'relateduserid' => $ue->userid
,
1329 'other' => array('enrol' => $name)
1333 // Check if course contacts cache needs to be cleared.
1334 require_once($CFG->libdir
. '/coursecatlib.php');
1335 coursecat
::user_enrolment_changed($courseid, $ue->userid
,
1336 $ue->status
, $ue->timestart
, $ue->timeend
);
1340 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
1341 if ($this->roles_protected()) {
1342 role_assign($roleid, $userid, $context->id
, 'enrol_'.$name, $instance->id
);
1344 role_assign($roleid, $userid, $context->id
);
1348 // Recover old grades if present.
1349 if ($recovergrades) {
1350 require_once("$CFG->libdir/gradelib.php");
1351 grade_recover_history_grades($userid, $courseid);
1354 // reset current user enrolment caching
1355 if ($userid == $USER->id
) {
1356 if (isset($USER->enrol
['enrolled'][$courseid])) {
1357 unset($USER->enrol
['enrolled'][$courseid]);
1359 if (isset($USER->enrol
['tempguest'][$courseid])) {
1360 unset($USER->enrol
['tempguest'][$courseid]);
1361 remove_temp_course_roles($context);
1367 * Store user_enrolments changes and trigger event.
1369 * @param stdClass $instance
1370 * @param int $userid
1371 * @param int $status
1372 * @param int $timestart
1373 * @param int $timeend
1376 public function update_user_enrol(stdClass
$instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1377 global $DB, $USER, $CFG;
1379 $name = $this->get_name();
1381 if ($instance->enrol
!== $name) {
1382 throw new coding_exception('invalid enrol instance!');
1385 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
1386 // weird, user not enrolled
1391 if (isset($status) and $ue->status
!= $status) {
1392 $ue->status
= $status;
1395 if (isset($timestart) and $ue->timestart
!= $timestart) {
1396 $ue->timestart
= $timestart;
1399 if (isset($timeend) and $ue->timeend
!= $timeend) {
1400 $ue->timeend
= $timeend;
1409 $ue->modifierid
= $USER->id
;
1410 $DB->update_record('user_enrolments', $ue);
1411 context_course
::instance($instance->courseid
)->mark_dirty(); // reset enrol caches
1413 // Invalidate core_access cache for get_suspended_userids.
1414 cache_helper
::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid
));
1417 $event = \core\event\user_enrolment_updated
::create(
1419 'objectid' => $ue->id
,
1420 'courseid' => $instance->courseid
,
1421 'context' => context_course
::instance($instance->courseid
),
1422 'relateduserid' => $ue->userid
,
1423 'other' => array('enrol' => $name)
1428 require_once($CFG->libdir
. '/coursecatlib.php');
1429 coursecat
::user_enrolment_changed($instance->courseid
, $ue->userid
,
1430 $ue->status
, $ue->timestart
, $ue->timeend
);
1434 * Unenrol user from course,
1435 * the last unenrolment removes all remaining roles.
1437 * @param stdClass $instance
1438 * @param int $userid
1441 public function unenrol_user(stdClass
$instance, $userid) {
1442 global $CFG, $USER, $DB;
1443 require_once("$CFG->dirroot/group/lib.php");
1445 $name = $this->get_name();
1446 $courseid = $instance->courseid
;
1448 if ($instance->enrol
!== $name) {
1449 throw new coding_exception('invalid enrol instance!');
1451 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
1453 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
1454 // weird, user not enrolled
1458 // Remove all users groups linked to this enrolment instance.
1459 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
))) {
1460 foreach ($gms as $gm) {
1461 groups_remove_member($gm->groupid
, $gm->userid
);
1465 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id
, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
));
1466 $DB->delete_records('user_enrolments', array('id'=>$ue->id
));
1468 // add extra info and trigger event
1469 $ue->courseid
= $courseid;
1473 FROM {user_enrolments} ue
1474 JOIN {enrol} e ON (e.id = ue.enrolid)
1475 WHERE ue.userid = :userid AND e.courseid = :courseid";
1476 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
1477 $ue->lastenrol
= false;
1480 // the big cleanup IS necessary!
1481 require_once("$CFG->libdir/gradelib.php");
1483 // remove all remaining roles
1484 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id
), true, false);
1486 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
1487 groups_delete_group_members($courseid, $userid);
1489 grade_user_unenrol($courseid, $userid);
1491 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
1493 $ue->lastenrol
= true; // means user not enrolled any more
1496 $event = \core\event\user_enrolment_deleted
::create(
1498 'courseid' => $courseid,
1499 'context' => $context,
1500 'relateduserid' => $ue->userid
,
1501 'objectid' => $ue->id
,
1503 'userenrolment' => (array)$ue,
1509 // reset all enrol caches
1510 $context->mark_dirty();
1512 // Check if courrse contacts cache needs to be cleared.
1513 require_once($CFG->libdir
. '/coursecatlib.php');
1514 coursecat
::user_enrolment_changed($courseid, $ue->userid
, ENROL_USER_SUSPENDED
);
1516 // reset current user enrolment caching
1517 if ($userid == $USER->id
) {
1518 if (isset($USER->enrol
['enrolled'][$courseid])) {
1519 unset($USER->enrol
['enrolled'][$courseid]);
1521 if (isset($USER->enrol
['tempguest'][$courseid])) {
1522 unset($USER->enrol
['tempguest'][$courseid]);
1523 remove_temp_course_roles($context);
1529 * Forces synchronisation of user enrolments.
1531 * This is important especially for external enrol plugins,
1532 * this function is called for all enabled enrol plugins
1533 * right after every user login.
1535 * @param object $user user record
1538 public function sync_user_enrolments($user) {
1539 // override if necessary
1543 * This returns false for backwards compatibility, but it is really recommended.
1548 public function use_standard_editing_ui() {
1553 * Return whether or not, given the current state, it is possible to add a new instance
1554 * of this enrolment plugin to the course.
1556 * Default implementation is just for backwards compatibility.
1558 * @param int $courseid
1561 public function can_add_instance($courseid) {
1562 $link = $this->get_newinstance_link($courseid);
1563 return !empty($link);
1567 * Return whether or not, given the current state, it is possible to edit an instance
1568 * of this enrolment plugin in the course. Used by the standard editing UI
1569 * to generate a link to the edit instance form if editing is allowed.
1571 * @param stdClass $instance
1574 public function can_edit_instance($instance) {
1575 $context = context_course
::instance($instance->courseid
);
1577 return has_capability('enrol/' . $instance->enrol
. ':config', $context);
1581 * Returns link to page which may be used to add new instance of enrolment plugin in course.
1582 * @param int $courseid
1583 * @return moodle_url page url
1585 public function get_newinstance_link($courseid) {
1586 // override for most plugins, check if instance already exists in cases only one instance is supported
1591 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
1593 public function instance_deleteable($instance) {
1594 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
1595 enrol_plugin::can_delete_instance() instead');
1599 * Is it possible to delete enrol instance via standard UI?
1601 * @param stdClass $instance
1604 public function can_delete_instance($instance) {
1609 * Is it possible to hide/show enrol instance via standard UI?
1611 * @param stdClass $instance
1614 public function can_hide_show_instance($instance) {
1615 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER
);
1620 * Returns link to manual enrol UI if exists.
1621 * Does the access control tests automatically.
1623 * @param object $instance
1624 * @return moodle_url
1626 public function get_manual_enrol_link($instance) {
1631 * Returns list of unenrol links for all enrol instances in course.
1633 * @param int $instance
1634 * @return moodle_url or NULL if self unenrolment not supported
1636 public function get_unenrolself_link($instance) {
1637 global $USER, $CFG, $DB;
1639 $name = $this->get_name();
1640 if ($instance->enrol
!== $name) {
1641 throw new coding_exception('invalid enrol instance!');
1644 if ($instance->courseid
== SITEID
) {
1648 if (!enrol_is_enabled($name)) {
1652 if ($instance->status
!= ENROL_INSTANCE_ENABLED
) {
1656 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
1660 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
1662 if (!has_capability("enrol/$name:unenrolself", $context)) {
1666 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$USER->id
, 'status'=>ENROL_USER_ACTIVE
))) {
1670 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id
));
1674 * Adds enrol instance UI to course edit form
1676 * @param object $instance enrol instance or null if does not exist yet
1677 * @param MoodleQuickForm $mform
1678 * @param object $data
1679 * @param object $context context of existing course or parent category if course does not exist
1682 public function course_edit_form($instance, MoodleQuickForm
$mform, $data, $context) {
1683 // override - usually at least enable/disable switch, has to add own form header
1687 * Adds form elements to add/edit instance form.
1690 * @param object $instance enrol instance or null if does not exist yet
1691 * @param MoodleQuickForm $mform
1692 * @param context $context
1695 public function edit_instance_form($instance, MoodleQuickForm
$mform, $context) {
1696 // Do nothing by default.
1700 * Perform custom validation of the data used to edit the instance.
1703 * @param array $data array of ("fieldname"=>value) of submitted data
1704 * @param array $files array of uploaded files "element_name"=>tmp_file_path
1705 * @param object $instance The instance data loaded from the DB.
1706 * @param context $context The context of the instance we are editing
1707 * @return array of "element_name"=>"error_description" if there are errors,
1708 * or an empty array if everything is OK.
1710 public function edit_instance_validation($data, $files, $instance, $context) {
1711 // No errors by default.
1712 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER
);
1717 * Validates course edit form data
1719 * @param object $instance enrol instance or null if does not exist yet
1720 * @param array $data
1721 * @param object $context context of existing course or parent category if course does not exist
1722 * @return array errors array
1724 public function course_edit_validation($instance, array $data, $context) {
1729 * Called after updating/inserting course.
1731 * @param bool $inserted true if course just inserted
1732 * @param object $course
1733 * @param object $data form data
1736 public function course_updated($inserted, $course, $data) {
1738 if ($this->get_config('defaultenrol')) {
1739 $this->add_default_instance($course);
1745 * Add new instance of enrol plugin.
1746 * @param object $course
1747 * @param array instance fields
1748 * @return int id of new instance, null if can not be created
1750 public function add_instance($course, array $fields = NULL) {
1753 if ($course->id
== SITEID
) {
1754 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
1757 $instance = new stdClass();
1758 $instance->enrol
= $this->get_name();
1759 $instance->status
= ENROL_INSTANCE_ENABLED
;
1760 $instance->courseid
= $course->id
;
1761 $instance->enrolstartdate
= 0;
1762 $instance->enrolenddate
= 0;
1763 $instance->timemodified
= time();
1764 $instance->timecreated
= $instance->timemodified
;
1765 $instance->sortorder
= $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id
));
1767 $fields = (array)$fields;
1768 unset($fields['enrol']);
1769 unset($fields['courseid']);
1770 unset($fields['sortorder']);
1771 foreach($fields as $field=>$value) {
1772 $instance->$field = $value;
1775 $instance->id
= $DB->insert_record('enrol', $instance);
1777 \core\event\enrol_instance_created
::create_from_record($instance)->trigger();
1779 return $instance->id
;
1783 * Update instance of enrol plugin.
1786 * @param stdClass $instance
1787 * @param stdClass $data modified instance fields
1790 public function update_instance($instance, $data) {
1792 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
1793 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
1794 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
1795 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
1796 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
1797 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
1799 foreach ($properties as $key) {
1800 if (isset($data->$key)) {
1801 $instance->$key = $data->$key;
1804 $instance->timemodified
= time();
1806 $update = $DB->update_record('enrol', $instance);
1808 \core\event\enrol_instance_updated
::create_from_record($instance)->trigger();
1814 * Add new instance of enrol plugin with default settings,
1815 * called when adding new instance manually or when adding new course.
1817 * Not all plugins support this.
1819 * @param object $course
1820 * @return int id of new instance or null if no default supported
1822 public function add_default_instance($course) {
1827 * Update instance status
1829 * Override when plugin needs to do some action when enabled or disabled.
1831 * @param stdClass $instance
1832 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
1835 public function update_status($instance, $newstatus) {
1838 $instance->status
= $newstatus;
1839 $DB->update_record('enrol', $instance);
1841 $context = context_course
::instance($instance->courseid
);
1842 \core\event\enrol_instance_updated
::create_from_record($instance)->trigger();
1844 // Invalidate all enrol caches.
1845 $context->mark_dirty();
1849 * Delete course enrol plugin instance, unenrol all users.
1850 * @param object $instance
1853 public function delete_instance($instance) {
1856 $name = $this->get_name();
1857 if ($instance->enrol
!== $name) {
1858 throw new coding_exception('invalid enrol instance!');
1861 //first unenrol all users
1862 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id
));
1863 foreach ($participants as $participant) {
1864 $this->unenrol_user($instance, $participant->userid
);
1866 $participants->close();
1868 // now clean up all remainders that were not removed correctly
1869 $DB->delete_records('groups_members', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$name));
1870 $DB->delete_records('role_assignments', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$name));
1871 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
1873 // finally drop the enrol row
1874 $DB->delete_records('enrol', array('id'=>$instance->id
));
1876 $context = context_course
::instance($instance->courseid
);
1877 \core\event\enrol_instance_deleted
::create_from_record($instance)->trigger();
1879 // Invalidate all enrol caches.
1880 $context->mark_dirty();
1884 * Creates course enrol form, checks if form submitted
1885 * and enrols user if necessary. It can also redirect.
1887 * @param stdClass $instance
1888 * @return string html text, usually a form in a text box
1890 public function enrol_page_hook(stdClass
$instance) {
1895 * Checks if user can self enrol.
1897 * @param stdClass $instance enrolment instance
1898 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
1899 * used by navigation to improve performance.
1900 * @return bool|string true if successful, else error message or false
1902 public function can_self_enrol(stdClass
$instance, $checkuserenrolment = true) {
1907 * Return information for enrolment instance containing list of parameters required
1908 * for enrolment, name of enrolment plugin etc.
1910 * @param stdClass $instance enrolment instance
1911 * @return array instance info.
1913 public function get_enrol_info(stdClass
$instance) {
1918 * Adds navigation links into course admin block.
1920 * By defaults looks for manage links only.
1922 * @param navigation_node $instancesnode
1923 * @param stdClass $instance
1926 public function add_course_navigation($instancesnode, stdClass
$instance) {
1927 if ($this->use_standard_editing_ui()) {
1928 $context = context_course
::instance($instance->courseid
);
1929 $cap = 'enrol/' . $instance->enrol
. ':config';
1930 if (has_capability($cap, $context)) {
1931 $linkparams = array('courseid' => $instance->courseid
, 'id' => $instance->id
, 'type' => $instance->enrol
);
1932 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
1933 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node
::TYPE_SETTING
);
1939 * Returns edit icons for the page with list of instances
1940 * @param stdClass $instance
1943 public function get_action_icons(stdClass
$instance) {
1947 if ($this->use_standard_editing_ui()) {
1948 $linkparams = array('courseid' => $instance->courseid
, 'id' => $instance->id
, 'type' => $instance->enrol
);
1949 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
1950 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
1951 array('class' => 'iconsmall')));
1957 * Reads version.php and determines if it is necessary
1958 * to execute the cron job now.
1961 public function is_cron_required() {
1964 $name = $this->get_name();
1965 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
1966 $plugin = new stdClass();
1967 include($versionfile);
1968 if (empty($plugin->cron
)) {
1971 $lastexecuted = $this->get_config('lastcron', 0);
1972 if ($lastexecuted +
$plugin->cron
< time()) {
1980 * Called for all enabled enrol plugins that returned true from is_cron_required().
1983 public function cron() {
1987 * Called when user is about to be deleted
1988 * @param object $user
1991 public function user_delete($user) {
1996 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
1997 WHERE e.enrol = :name AND ue.userid = :userid";
1998 $params = array('name'=>$this->get_name(), 'userid'=>$user->id
);
2000 $rs = $DB->get_recordset_sql($sql, $params);
2001 foreach($rs as $instance) {
2002 $this->unenrol_user($instance, $user->id
);
2008 * Returns an enrol_user_button that takes the user to a page where they are able to
2009 * enrol users into the managers course through this plugin.
2011 * Optional: If the plugin supports manual enrolments it can choose to override this
2012 * otherwise it shouldn't
2014 * @param course_enrolment_manager $manager
2015 * @return enrol_user_button|false
2017 public function get_manual_enrol_button(course_enrolment_manager
$manager) {
2022 * Gets an array of the user enrolment actions
2024 * @param course_enrolment_manager $manager
2025 * @param stdClass $ue
2026 * @return array An array of user_enrolment_actions
2028 public function get_user_enrolment_actions(course_enrolment_manager
$manager, $ue) {
2033 * Returns true if the plugin has one or more bulk operations that can be performed on
2036 * @param course_enrolment_manager $manager
2039 public function has_bulk_operations(course_enrolment_manager
$manager) {
2044 * Return an array of enrol_bulk_enrolment_operation objects that define
2045 * the bulk actions that can be performed on user enrolments by the plugin.
2047 * @param course_enrolment_manager $manager
2050 public function get_bulk_operations(course_enrolment_manager
$manager) {
2055 * Do any enrolments need expiration processing.
2057 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2059 * @param progress_trace $trace
2060 * @param int $courseid one course, empty mean all
2061 * @return bool true if any data processed, false if not
2063 public function process_expirations(progress_trace
$trace, $courseid = null) {
2066 $name = $this->get_name();
2067 if (!enrol_is_enabled($name)) {
2076 $coursesql = "AND e.courseid = :courseid";
2079 // Deal with expired accounts.
2080 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP
);
2082 if ($action == ENROL_EXT_REMOVED_UNENROL
) {
2083 $instances = array();
2084 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2085 FROM {user_enrolments} ue
2086 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2087 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2088 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2089 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE
, 'enrol'=>$name, 'courseid'=>$courseid);
2091 $rs = $DB->get_recordset_sql($sql, $params);
2092 foreach ($rs as $ue) {
2094 $trace->output("Starting processing of enrol_$name expirations...");
2097 if (empty($instances[$ue->enrolid
])) {
2098 $instances[$ue->enrolid
] = $DB->get_record('enrol', array('id'=>$ue->enrolid
));
2100 $instance = $instances[$ue->enrolid
];
2101 if (!$this->roles_protected()) {
2102 // Let's just guess what extra roles are supposed to be removed.
2103 if ($instance->roleid
) {
2104 role_unassign($instance->roleid
, $ue->userid
, $ue->contextid
);
2107 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2108 $this->unenrol_user($instance, $ue->userid
);
2109 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2114 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES
or $action == ENROL_EXT_REMOVED_SUSPEND
) {
2115 $instances = array();
2116 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2117 FROM {user_enrolments} ue
2118 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2119 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2120 WHERE ue.timeend > 0 AND ue.timeend < :now
2121 AND ue.status = :useractive $coursesql";
2122 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE
, 'useractive'=>ENROL_USER_ACTIVE
, 'enrol'=>$name, 'courseid'=>$courseid);
2123 $rs = $DB->get_recordset_sql($sql, $params);
2124 foreach ($rs as $ue) {
2126 $trace->output("Starting processing of enrol_$name expirations...");
2129 if (empty($instances[$ue->enrolid
])) {
2130 $instances[$ue->enrolid
] = $DB->get_record('enrol', array('id'=>$ue->enrolid
));
2132 $instance = $instances[$ue->enrolid
];
2134 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES
) {
2135 if (!$this->roles_protected()) {
2136 // Let's just guess what roles should be removed.
2137 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
));
2139 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'', 'itemid'=>0));
2141 } else if ($count > 1 and $instance->roleid
) {
2142 role_unassign($instance->roleid
, $ue->userid
, $ue->contextid
, '', 0);
2145 // In any case remove all roles that belong to this instance and user.
2146 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
), true);
2147 // Final cleanup of subcontexts if there are no more course roles.
2148 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
))) {
2149 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'', 'itemid'=>0), true);
2153 $this->update_user_enrol($instance, $ue->userid
, ENROL_USER_SUSPENDED
);
2154 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2160 // ENROL_EXT_REMOVED_KEEP means no changes.
2164 $trace->output("...finished processing of enrol_$name expirations");
2166 $trace->output("No expired enrol_$name enrolments detected");
2174 * Send expiry notifications.
2176 * Plugin that wants to have expiry notification MUST implement following:
2177 * - expirynotifyhour plugin setting,
2178 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2179 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2180 * expirymessageenrolledsubject and expirymessageenrolledbody),
2181 * - expiry_notification provider in db/messages.php,
2182 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2183 * - something that calls this method, such as cron.
2185 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2187 public function send_expiry_notifications($trace) {
2190 $name = $this->get_name();
2191 if (!enrol_is_enabled($name)) {
2196 // Unfortunately this may take a long time, it should not be interrupted,
2197 // otherwise users get duplicate notification.
2199 core_php_time_limit
::raise();
2200 raise_memory_limit(MEMORY_HUGE
);
2203 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2204 $expirynotifyhour = $this->get_config('expirynotifyhour');
2205 if (is_null($expirynotifyhour)) {
2206 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
2211 if (!($trace instanceof progress_trace
)) {
2212 $trace = $trace ?
new text_progress_trace() : new null_progress_trace();
2213 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER
);
2217 $notifytime = usergetmidnight($timenow, $CFG->timezone
) +
($expirynotifyhour * 3600);
2219 if ($expirynotifylast > $notifytime) {
2220 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone
).'.');
2224 } else if ($timenow < $notifytime) {
2225 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone
).'.');
2230 $trace->output('Processing '.$name.' enrolment expiration notifications...');
2232 // Notify users responsible for enrolment once every day.
2233 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2234 FROM {user_enrolments} ue
2235 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2236 JOIN {course} c ON (c.id = e.courseid)
2237 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2238 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2239 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2240 $params = array('enabled'=>ENROL_INSTANCE_ENABLED
, 'active'=>ENROL_USER_ACTIVE
, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2242 $rs = $DB->get_recordset_sql($sql, $params);
2247 foreach($rs as $ue) {
2248 if ($lastenrollid and $lastenrollid != $ue->enrolid
) {
2249 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2252 $lastenrollid = $ue->enrolid
;
2254 $enroller = $this->get_enroller($ue->enrolid
);
2255 $context = context_course
::instance($ue->courseid
);
2257 $user = $DB->get_record('user', array('id'=>$ue->userid
));
2259 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend
);
2261 if (!$ue->notifyall
) {
2265 if ($ue->timeend
- $ue->expirythreshold +
86400 < $timenow) {
2266 // Notify enrolled users only once at the start of the threshold.
2267 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
2271 $this->notify_expiry_enrolled($user, $ue, $trace);
2275 if ($lastenrollid and $users) {
2276 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2279 $trace->output('...notification processing finished.');
2282 $this->set_config('expirynotifylast', $timenow);
2286 * Returns the user who is responsible for enrolments for given instance.
2288 * Override if plugin knows anybody better than admin.
2290 * @param int $instanceid enrolment instance id
2291 * @return stdClass user record
2293 protected function get_enroller($instanceid) {
2298 * Notify user about incoming expiration of their enrolment,
2299 * it is called only if notification of enrolled users (aka students) is enabled in course.
2301 * This is executed only once for each expiring enrolment right
2302 * at the start of the expiration threshold.
2304 * @param stdClass $user
2305 * @param stdClass $ue
2306 * @param progress_trace $trace
2308 protected function notify_expiry_enrolled($user, $ue, progress_trace
$trace) {
2311 $name = $this->get_name();
2313 $oldforcelang = force_current_language($user->lang
);
2315 $enroller = $this->get_enroller($ue->enrolid
);
2316 $context = context_course
::instance($ue->courseid
);
2318 $a = new stdClass();
2319 $a->course
= format_string($ue->fullname
, true, array('context'=>$context));
2320 $a->user
= fullname($user, true);
2321 $a->timeend
= userdate($ue->timeend
, '', $user->timezone
);
2322 $a->enroller
= fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
2324 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
2325 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
2327 $message = new stdClass();
2328 $message->notification
= 1;
2329 $message->component
= 'enrol_'.$name;
2330 $message->name
= 'expiry_notification';
2331 $message->userfrom
= $enroller;
2332 $message->userto
= $user;
2333 $message->subject
= $subject;
2334 $message->fullmessage
= $body;
2335 $message->fullmessageformat
= FORMAT_MARKDOWN
;
2336 $message->fullmessagehtml
= markdown_to_html($body);
2337 $message->smallmessage
= $subject;
2338 $message->contexturlname
= $a->course
;
2339 $message->contexturl
= (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid
));
2341 if (message_send($message)) {
2342 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
2344 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
2347 force_current_language($oldforcelang);
2351 * Notify person responsible for enrolments that some user enrolments will be expired soon,
2352 * it is called only if notification of enrollers (aka teachers) is enabled in course.
2354 * This is called repeatedly every day for each course if there are any pending expiration
2355 * in the expiration threshold.
2358 * @param array $users
2359 * @param progress_trace $trace
2361 protected function notify_expiry_enroller($eid, $users, progress_trace
$trace) {
2364 $name = $this->get_name();
2366 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
2367 $context = context_course
::instance($instance->courseid
);
2368 $course = $DB->get_record('course', array('id'=>$instance->courseid
));
2370 $enroller = $this->get_enroller($instance->id
);
2371 $admin = get_admin();
2373 $oldforcelang = force_current_language($enroller->lang
);
2375 foreach($users as $key=>$info) {
2376 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone
);
2379 $a = new stdClass();
2380 $a->course
= format_string($course->fullname
, true, array('context'=>$context));
2381 $a->threshold
= get_string('numdays', '', $instance->expirythreshold
/ (60*60*24));
2382 $a->users
= implode("\n", $users);
2383 $a->extendurl
= (string)new moodle_url('/enrol/users.php', array('id'=>$instance->courseid
));
2385 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
2386 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
2388 $message = new stdClass();
2389 $message->notification
= 1;
2390 $message->component
= 'enrol_'.$name;
2391 $message->name
= 'expiry_notification';
2392 $message->userfrom
= $admin;
2393 $message->userto
= $enroller;
2394 $message->subject
= $subject;
2395 $message->fullmessage
= $body;
2396 $message->fullmessageformat
= FORMAT_MARKDOWN
;
2397 $message->fullmessagehtml
= markdown_to_html($body);
2398 $message->smallmessage
= $subject;
2399 $message->contexturlname
= $a->course
;
2400 $message->contexturl
= $a->extendurl
;
2402 if (message_send($message)) {
2403 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
2405 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
2408 force_current_language($oldforcelang);
2412 * Backup execution step hook to annotate custom fields.
2414 * @param backup_enrolments_execution_step $step
2415 * @param stdClass $enrol
2417 public function backup_annotate_custom_fields(backup_enrolments_execution_step
$step, stdClass
$enrol) {
2418 // Override as necessary to annotate custom fields in the enrol table.
2422 * Automatic enrol sync executed during restore.
2423 * Useful for automatic sync by course->idnumber or course category.
2424 * @param stdClass $course course record
2426 public function restore_sync_course($course) {
2427 // Override if necessary.
2431 * Restore instance and map settings.
2433 * @param restore_enrolments_structure_step $step
2434 * @param stdClass $data
2435 * @param stdClass $course
2438 public function restore_instance(restore_enrolments_structure_step
$step, stdClass
$data, $course, $oldid) {
2439 // Do not call this from overridden methods, restore and set new id there.
2440 $step->set_mapping('enrol', $oldid, 0);
2444 * Restore user enrolment.
2446 * @param restore_enrolments_structure_step $step
2447 * @param stdClass $data
2448 * @param stdClass $instance
2449 * @param int $oldinstancestatus
2450 * @param int $userid
2452 public function restore_user_enrolment(restore_enrolments_structure_step
$step, $data, $instance, $userid, $oldinstancestatus) {
2453 // Override as necessary if plugin supports restore of enrolments.
2457 * Restore role assignment.
2459 * @param stdClass $instance
2460 * @param int $roleid
2461 * @param int $userid
2462 * @param int $contextid
2464 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
2465 // No role assignment by default, override if necessary.
2469 * Restore user group membership.
2470 * @param stdClass $instance
2471 * @param int $groupid
2472 * @param int $userid
2474 public function restore_group_member($instance, $groupid, $userid) {
2475 // Implement if you want to restore protected group memberships,
2476 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
2480 * Returns defaults for new instances.
2484 public function get_instance_defaults() {
2489 * Validate a list of parameter names and types.
2492 * @param array $data array of ("fieldname"=>value) of submitted data
2493 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
2494 * @return array of "element_name"=>"error_description" if there are errors,
2495 * or an empty array if everything is OK.
2497 public function validate_param_types($data, $rules) {
2499 $invalidstr = get_string('invaliddata', 'error');
2500 foreach ($rules as $fieldname => $rule) {
2501 if (is_array($rule)) {
2502 if (!in_array($data[$fieldname], $rule)) {
2503 $errors[$fieldname] = $invalidstr;
2506 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
2507 $errors[$fieldname] = $invalidstr;