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);
73 define('ENROL_DO_NOT_SEND_EMAIL', 0);
76 * Send email from course contact.
78 define('ENROL_SEND_EMAIL_FROM_COURSE_CONTACT', 1);
81 * Send email from enrolment key holder.
83 define('ENROL_SEND_EMAIL_FROM_KEY_HOLDER', 2);
86 * Send email from no reply address.
88 define('ENROL_SEND_EMAIL_FROM_NOREPLY', 3);
90 /** Edit enrolment action. */
91 define('ENROL_ACTION_EDIT', 'editenrolment');
93 /** Unenrol action. */
94 define('ENROL_ACTION_UNENROL', 'unenrol');
97 * Returns instances of enrol plugins
98 * @param bool $enabled return enabled only
99 * @return array of enrol plugins name=>instance
101 function enrol_get_plugins($enabled) {
107 // sorted by enabled plugin order
108 $enabled = explode(',', $CFG->enrol_plugins_enabled
);
110 foreach ($enabled as $plugin) {
111 $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
114 // sorted alphabetically
115 $plugins = core_component
::get_plugin_list('enrol');
119 foreach ($plugins as $plugin=>$location) {
120 $class = "enrol_{$plugin}_plugin";
121 if (!class_exists($class)) {
122 if (!file_exists("$location/lib.php")) {
125 include_once("$location/lib.php");
126 if (!class_exists($class)) {
131 $result[$plugin] = new $class();
138 * Returns instance of enrol plugin
139 * @param string $name name of enrol plugin ('manual', 'guest', ...)
140 * @return enrol_plugin
142 function enrol_get_plugin($name) {
145 $name = clean_param($name, PARAM_PLUGIN
);
148 // ignore malformed or missing plugin names completely
152 $location = "$CFG->dirroot/enrol/$name";
154 $class = "enrol_{$name}_plugin";
155 if (!class_exists($class)) {
156 if (!file_exists("$location/lib.php")) {
159 include_once("$location/lib.php");
160 if (!class_exists($class)) {
169 * Returns enrolment instances in given course.
170 * @param int $courseid
171 * @param bool $enabled
172 * @return array of enrol instances
174 function enrol_get_instances($courseid, $enabled) {
178 return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
181 $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder,id');
183 $enabled = explode(',', $CFG->enrol_plugins_enabled
);
184 foreach ($result as $key=>$instance) {
185 if (!in_array($instance->enrol
, $enabled)) {
186 unset($result[$key]);
189 if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
191 unset($result[$key]);
200 * Checks if a given plugin is in the list of enabled enrolment plugins.
202 * @param string $enrol Enrolment plugin name
203 * @return boolean Whether the plugin is enabled
205 function enrol_is_enabled($enrol) {
208 if (empty($CFG->enrol_plugins_enabled
)) {
211 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled
));
215 * Check all the login enrolment information for the given user object
216 * by querying the enrolment plugins
218 * This function may be very slow, use only once after log-in or login-as.
220 * @param stdClass $user
223 function enrol_check_plugins($user) {
226 if (empty($user->id
) or isguestuser($user)) {
227 // shortcut - there is no enrolment work for guests and not-logged-in users
231 // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
232 // which proved it was actually not necessary.
234 static $inprogress = array(); // To prevent this function being called more than once in an invocation
236 if (!empty($inprogress[$user->id
])) {
240 $inprogress[$user->id
] = true; // Set the flag
242 $enabled = enrol_get_plugins(true);
244 foreach($enabled as $enrol) {
245 $enrol->sync_user_enrolments($user);
248 unset($inprogress[$user->id
]); // Unset the flag
252 * Do these two students share any course?
254 * The courses has to be visible and enrolments has to be active,
255 * timestart and timeend restrictions are ignored.
257 * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
260 * @param stdClass|int $user1
261 * @param stdClass|int $user2
264 function enrol_sharing_course($user1, $user2) {
265 return enrol_get_shared_courses($user1, $user2, false, true);
269 * Returns any courses shared by the two users
271 * The courses has to be visible and enrolments has to be active,
272 * timestart and timeend restrictions are ignored.
274 * @global moodle_database $DB
275 * @param stdClass|int $user1
276 * @param stdClass|int $user2
277 * @param bool $preloadcontexts If set to true contexts for the returned courses
279 * @param bool $checkexistsonly If set to true then this function will return true
280 * if the users share any courses and false if not.
281 * @return array|bool An array of courses that both users are enrolled in OR if
282 * $checkexistsonly set returns true if the users share any courses
285 function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
288 $user1 = isset($user1->id
) ?
$user1->id
: $user1;
289 $user2 = isset($user2->id
) ?
$user2->id
: $user2;
291 if (empty($user1) or empty($user2)) {
295 if (!$plugins = explode(',', $CFG->enrol_plugins_enabled
)) {
299 list($plugins1, $params1) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED
, 'ee1');
300 list($plugins2, $params2) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED
, 'ee2');
301 $params = array_merge($params1, $params2);
302 $params['enabled1'] = ENROL_INSTANCE_ENABLED
;
303 $params['enabled2'] = ENROL_INSTANCE_ENABLED
;
304 $params['active1'] = ENROL_USER_ACTIVE
;
305 $params['active2'] = ENROL_USER_ACTIVE
;
306 $params['user1'] = $user1;
307 $params['user2'] = $user2;
311 if ($preloadcontexts) {
312 $ctxselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
313 $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
314 $params['contextlevel'] = CONTEXT_COURSE
;
317 $sql = "SELECT c.* $ctxselect
322 JOIN {enrol} e1 ON (c.id = e1.courseid AND e1.status = :enabled1 AND e1.enrol $plugins1)
323 JOIN {user_enrolments} ue1 ON (ue1.enrolid = e1.id AND ue1.status = :active1 AND ue1.userid = :user1)
324 JOIN {enrol} e2 ON (c.id = e2.courseid AND e2.status = :enabled2 AND e2.enrol $plugins2)
325 JOIN {user_enrolments} ue2 ON (ue2.enrolid = e2.id AND ue2.status = :active2 AND ue2.userid = :user2)
330 if ($checkexistsonly) {
331 return $DB->record_exists_sql($sql, $params);
333 $courses = $DB->get_records_sql($sql, $params);
334 if ($preloadcontexts) {
335 array_map('context_helper::preload_from_record', $courses);
342 * This function adds necessary enrol plugins UI into the course edit form.
344 * @param MoodleQuickForm $mform
345 * @param object $data course edit form data
346 * @param object $context context of existing course or parent category if course does not exist
349 function enrol_course_edit_form(MoodleQuickForm
$mform, $data, $context) {
350 $plugins = enrol_get_plugins(true);
351 if (!empty($data->id
)) {
352 $instances = enrol_get_instances($data->id
, false);
353 foreach ($instances as $instance) {
354 if (!isset($plugins[$instance->enrol
])) {
357 $plugin = $plugins[$instance->enrol
];
358 $plugin->course_edit_form($instance, $mform, $data, $context);
361 foreach ($plugins as $plugin) {
362 $plugin->course_edit_form(NULL, $mform, $data, $context);
368 * Validate course edit form data
370 * @param array $data raw form data
371 * @param object $context context of existing course or parent category if course does not exist
372 * @return array errors array
374 function enrol_course_edit_validation(array $data, $context) {
376 $plugins = enrol_get_plugins(true);
378 if (!empty($data['id'])) {
379 $instances = enrol_get_instances($data['id'], false);
380 foreach ($instances as $instance) {
381 if (!isset($plugins[$instance->enrol
])) {
384 $plugin = $plugins[$instance->enrol
];
385 $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
388 foreach ($plugins as $plugin) {
389 $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
397 * Update enrol instances after course edit form submission
398 * @param bool $inserted true means new course added, false course already existed
399 * @param object $course
400 * @param object $data form data
403 function enrol_course_updated($inserted, $course, $data) {
406 $plugins = enrol_get_plugins(true);
408 foreach ($plugins as $plugin) {
409 $plugin->course_updated($inserted, $course, $data);
414 * Add navigation nodes
415 * @param navigation_node $coursenode
416 * @param object $course
419 function enrol_add_course_navigation(navigation_node
$coursenode, $course) {
422 $coursecontext = context_course
::instance($course->id
);
424 $instances = enrol_get_instances($course->id
, true);
425 $plugins = enrol_get_plugins(true);
427 // we do not want to break all course pages if there is some borked enrol plugin, right?
428 foreach ($instances as $k=>$instance) {
429 if (!isset($plugins[$instance->enrol
])) {
430 unset($instances[$k]);
434 $usersnode = $coursenode->add(get_string('users'), null, navigation_node
::TYPE_CONTAINER
, null, 'users');
436 if ($course->id
!= SITEID
) {
437 // list all participants - allows assigning roles, groups, etc.
438 if (has_capability('moodle/course:enrolreview', $coursecontext)) {
439 $url = new moodle_url('/user/index.php', array('id'=>$course->id
));
440 $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node
::TYPE_SETTING
, null, 'review', new pix_icon('i/enrolusers', ''));
443 // manage enrol plugin instances
444 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
445 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id
));
449 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node
::TYPE_SETTING
, null, 'manageinstances');
451 // each instance decides how to configure itself or how many other nav items are exposed
452 foreach ($instances as $instance) {
453 if (!isset($plugins[$instance->enrol
])) {
456 $plugins[$instance->enrol
]->add_course_navigation($instancesnode, $instance);
460 $instancesnode->trim_if_empty();
464 // Manage groups in this course or even frontpage
465 if (($course->groupmode ||
!$course->groupmodeforce
) && has_capability('moodle/course:managegroups', $coursecontext)) {
466 $url = new moodle_url('/group/index.php', array('id'=>$course->id
));
467 $usersnode->add(get_string('groups'), $url, navigation_node
::TYPE_SETTING
, null, 'groups', new pix_icon('i/group', ''));
470 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
472 if (has_capability('moodle/role:review', $coursecontext)) {
473 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id
));
477 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'override');
479 // Add assign or override roles if allowed
480 if ($course->id
== SITEID
or (!empty($CFG->adminsassignrolesincourse
) and is_siteadmin())) {
481 if (has_capability('moodle/role:assign', $coursecontext)) {
482 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id
));
483 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'roles', new pix_icon('i/assignroles', ''));
486 // Check role permissions
487 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
488 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id
));
489 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/checkpermissions', ''));
493 // Deal somehow with users that are not enrolled but still got a role somehow
494 if ($course->id
!= SITEID
) {
495 //TODO, create some new UI for role assignments at course level
496 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
497 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id
));
498 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node
::TYPE_SETTING
, null, 'otherusers', new pix_icon('i/assignroles', ''));
502 // just in case nothing was actually added
503 $usersnode->trim_if_empty();
505 if ($course->id
!= SITEID
) {
506 if (isguestuser() or !isloggedin()) {
507 // guest account can not be enrolled - no links for them
508 } else if (is_enrolled($coursecontext)) {
509 // unenrol link if possible
510 foreach ($instances as $instance) {
511 if (!isset($plugins[$instance->enrol
])) {
514 $plugin = $plugins[$instance->enrol
];
515 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
516 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
517 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node
::TYPE_SETTING
, null, 'unenrolself', new pix_icon('i/user', ''));
519 //TODO. deal with multiple unenrol links - not likely case, but still...
523 // enrol link if possible
524 if (is_viewing($coursecontext)) {
525 // better not show any enrol link, this is intended for managers and inspectors
527 foreach ($instances as $instance) {
528 if (!isset($plugins[$instance->enrol
])) {
531 $plugin = $plugins[$instance->enrol
];
532 if ($plugin->show_enrolme_link($instance)) {
533 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id
));
534 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
535 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node
::TYPE_SETTING
, null, 'enrolself', new pix_icon('i/user', ''));
545 * Returns list of courses current $USER is enrolled in and can access
547 * The $fields param is a list of field names to ADD so name just the fields you really need,
548 * which will be added and uniq'd.
550 * If $allaccessible is true, this will additionally return courses that the current user is not
551 * enrolled in, but can access because they are open to the user for other reasons (course view
552 * permission, currently viewing course as a guest, or course allows guest access without
555 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
556 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
557 * Allowed prefixes for sort fields are: "ul" for the user_lastaccess table, "c" for the courses table,
558 * "ue" for the user_enrolments table.
559 * @param int $limit max number of courses
560 * @param array $courseids the list of course ids to filter by
561 * @param bool $allaccessible Include courses user is not enrolled in, but can access
562 * @param int $offset Offset the result set by this number
565 function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false, $offset = 0) {
566 global $DB, $USER, $CFG;
568 if ($sort === null) {
569 if (empty($CFG->navsortmycoursessort
)) {
570 $sort = 'visible DESC, sortorder ASC';
572 $sort = 'visible DESC, '.$CFG->navsortmycoursessort
.' ASC';
576 // Guest account does not have any enrolled courses.
577 if (!$allaccessible && (isguestuser() or !isloggedin())) {
581 $basefields = array('id', 'category', 'sortorder',
582 'shortname', 'fullname', 'idnumber',
583 'startdate', 'visible',
584 'groupmode', 'groupmodeforce', 'cacherev');
586 if (empty($fields)) {
587 $fields = $basefields;
588 } else if (is_string($fields)) {
589 // turn the fields from a string to an array
590 $fields = explode(',', $fields);
591 $fields = array_map('trim', $fields);
592 $fields = array_unique(array_merge($basefields, $fields));
593 } else if (is_array($fields)) {
594 $fields = array_unique(array_merge($basefields, $fields));
596 throw new coding_exception('Invalid $fields parameter in enrol_get_my_courses()');
598 if (in_array('*', $fields)) {
599 $fields = array('*');
604 $sorttimeaccess = false;
605 $allowedsortprefixes = array('c', 'ul', 'ue');
607 $rawsorts = explode(',', $sort);
609 foreach ($rawsorts as $rawsort) {
610 $rawsort = trim($rawsort);
611 if (preg_match('/^ul\.(\S*)\s(asc|desc)/i', $rawsort, $matches)) {
612 if (strcasecmp($matches[2], 'asc') == 0) {
613 $sorts[] = 'COALESCE(ul.' . $matches[1] . ', 0) ASC';
615 $sorts[] = 'COALESCE(ul.' . $matches[1] . ', 0) DESC';
617 $sorttimeaccess = true;
618 } else if (strpos($rawsort, '.') !== false) {
619 $prefix = explode('.', $rawsort);
620 if (in_array($prefix[0], $allowedsortprefixes)) {
621 $sorts[] = trim($rawsort);
623 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
626 $sorts[] = 'c.'.trim($rawsort);
629 $sort = implode(',', $sorts);
630 $orderby = "ORDER BY $sort";
633 $wheres = array("c.id <> :siteid");
634 $params = array('siteid'=>SITEID
);
636 if (isset($USER->loginascontext
) and $USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
637 // list _only_ this course - anything else is asking for trouble...
638 $wheres[] = "courseid = :loginas";
639 $params['loginas'] = $USER->loginascontext
->instanceid
;
642 $coursefields = 'c.' .join(',c.', $fields);
643 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
644 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
645 $params['contextlevel'] = CONTEXT_COURSE
;
646 $wheres = implode(" AND ", $wheres);
648 $timeaccessselect = "";
649 $timeaccessjoin = "";
651 if (!empty($courseids)) {
652 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
653 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
654 $params = array_merge($params, $courseidsparams);
658 // Logged-in, non-guest users get their enrolled courses.
659 if (!isguestuser() && isloggedin()) {
661 SELECT DISTINCT e.courseid
663 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid1)
664 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
665 AND (ue.timeend = 0 OR ue.timeend > :now2)";
666 $params['userid1'] = $USER->id
;
667 $params['active'] = ENROL_USER_ACTIVE
;
668 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
669 $params['now1'] = round(time(), -2); // Improves db caching.
670 $params['now2'] = $params['now1'];
672 if ($sorttimeaccess) {
673 $params['userid2'] = $USER->id
;
674 $timeaccessselect = ', ul.timeaccess as lastaccessed';
675 $timeaccessjoin = "LEFT JOIN {user_lastaccess} ul ON (ul.courseid = c.id AND ul.userid = :userid2)";
679 // When including non-enrolled but accessible courses...
680 if ($allaccessible) {
681 if (is_siteadmin()) {
682 // Site admins can access all courses.
683 $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
685 // If we used the enrolment as well, then this will be UNIONed.
687 $courseidsql .= " UNION ";
690 // Include courses with guest access and no password.
692 SELECT DISTINCT e.courseid
694 WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
695 $params['emptypass'] = '';
696 $params['enabled2'] = ENROL_INSTANCE_ENABLED
;
698 // Include courses where the current user is currently using guest access (may include
699 // those which require a password).
701 $accessdata = get_user_accessdata($USER->id
);
702 foreach ($accessdata['ra'] as $contextpath => $roles) {
703 if (array_key_exists($CFG->guestroleid
, $roles)) {
704 // Work out the course id from context path.
705 $context = context
::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
706 if ($context instanceof context_course
) {
707 $courseids[$context->instanceid
] = true;
712 // Include courses where the current user has moodle/course:view capability.
713 $courses = get_user_capability_course('moodle/course:view', null, false);
717 foreach ($courses as $course) {
718 $courseids[$course->id
] = true;
721 // If there are any in either category, list them individually.
723 list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
724 array_keys($courseids), SQL_PARAMS_NAMED
);
727 SELECT DISTINCT c3.id AS courseid
729 WHERE c3.id $allowedsql";
730 $params = array_merge($params, $allowedparams);
735 // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
736 // we have the subselect there.
737 $sql = "SELECT $coursefields $ccselect $timeaccessselect
739 JOIN ($courseidsql) en ON (en.courseid = c.id)
745 $courses = $DB->get_records_sql($sql, $params, $offset, $limit);
747 // preload contexts and check visibility
748 foreach ($courses as $id=>$course) {
749 context_helper
::preload_from_record($course);
750 if (!$course->visible
) {
751 if (!$context = context_course
::instance($id, IGNORE_MISSING
)) {
752 unset($courses[$id]);
755 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
756 unset($courses[$id]);
760 $courses[$id] = $course;
763 //wow! Is that really all? :-D
769 * Returns course enrolment information icons.
771 * @param object $course
772 * @param array $instances enrol instances of this course, improves performance
773 * @return array of pix_icon
775 function enrol_get_course_info_icons($course, array $instances = NULL) {
777 if (is_null($instances)) {
778 $instances = enrol_get_instances($course->id
, true);
780 $plugins = enrol_get_plugins(true);
781 foreach ($plugins as $name => $plugin) {
783 foreach ($instances as $instance) {
784 if ($instance->status
!= ENROL_INSTANCE_ENABLED
or $instance->courseid
!= $course->id
) {
785 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
788 if ($instance->enrol
== $name) {
789 $pis[$instance->id
] = $instance;
793 $icons = array_merge($icons, $plugin->get_info_icons($pis));
800 * Returns course enrolment detailed information.
802 * @param object $course
803 * @return array of html fragments - can be used to construct lists
805 function enrol_get_course_description_texts($course) {
807 $instances = enrol_get_instances($course->id
, true);
808 $plugins = enrol_get_plugins(true);
809 foreach ($instances as $instance) {
810 if (!isset($plugins[$instance->enrol
])) {
814 $plugin = $plugins[$instance->enrol
];
815 $text = $plugin->get_description_text($instance);
816 if ($text !== NULL) {
824 * Returns list of courses user is enrolled into.
826 * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
828 * The $fields param is a list of field names to ADD so name just the fields you really need,
829 * which will be added and uniq'd.
831 * @param int $userid User whose courses are returned, defaults to the current user.
832 * @param bool $onlyactive Return only active enrolments in courses user may see.
833 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
834 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
837 function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
840 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
842 // preload contexts and check visibility
844 foreach ($courses as $id=>$course) {
845 context_helper
::preload_from_record($course);
846 if (!$course->visible
) {
847 if (!$context = context_course
::instance($id)) {
848 unset($courses[$id]);
851 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
852 unset($courses[$id]);
864 * Can user access at least one enrolled course?
866 * Cheat if necessary, but find out as fast as possible!
868 * @param int|stdClass $user null means use current user
871 function enrol_user_sees_own_courses($user = null) {
874 if ($user === null) {
877 $userid = is_object($user) ?
$user->id
: $user;
879 // Guest account does not have any courses
880 if (isguestuser($userid) or empty($userid)) {
884 // Let's cheat here if this is the current user,
885 // if user accessed any course recently, then most probably
886 // we do not need to query the database at all.
887 if ($USER->id
== $userid) {
888 if (!empty($USER->enrol
['enrolled'])) {
889 foreach ($USER->enrol
['enrolled'] as $until) {
890 if ($until > time()) {
898 $courses = enrol_get_all_users_courses($userid, true);
899 foreach($courses as $course) {
900 if ($course->visible
) {
903 context_helper
::preload_from_record($course);
904 $context = context_course
::instance($course->id
);
905 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
914 * Returns list of courses user is enrolled into without performing any capability checks.
916 * The $fields param is a list of field names to ADD so name just the fields you really need,
917 * which will be added and uniq'd.
919 * @param int $userid User whose courses are returned, defaults to the current user.
920 * @param bool $onlyactive Return only active enrolments in courses user may see.
921 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
922 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
925 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
928 if ($sort === null) {
929 if (empty($CFG->navsortmycoursessort
)) {
930 $sort = 'visible DESC, sortorder ASC';
932 $sort = 'visible DESC, '.$CFG->navsortmycoursessort
.' ASC';
936 // Guest account does not have any courses
937 if (isguestuser($userid) or empty($userid)) {
941 $basefields = array('id', 'category', 'sortorder',
942 'shortname', 'fullname', 'idnumber',
943 'startdate', 'visible',
945 'groupmode', 'groupmodeforce');
947 if (empty($fields)) {
948 $fields = $basefields;
949 } else if (is_string($fields)) {
950 // turn the fields from a string to an array
951 $fields = explode(',', $fields);
952 $fields = array_map('trim', $fields);
953 $fields = array_unique(array_merge($basefields, $fields));
954 } else if (is_array($fields)) {
955 $fields = array_unique(array_merge($basefields, $fields));
957 throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
959 if (in_array('*', $fields)) {
960 $fields = array('*');
966 $rawsorts = explode(',', $sort);
968 foreach ($rawsorts as $rawsort) {
969 $rawsort = trim($rawsort);
970 if (strpos($rawsort, 'c.') === 0) {
971 $rawsort = substr($rawsort, 2);
973 $sorts[] = trim($rawsort);
975 $sort = 'c.'.implode(',c.', $sorts);
976 $orderby = "ORDER BY $sort";
979 $params = array('siteid'=>SITEID
);
982 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
983 $params['now1'] = round(time(), -2); // improves db caching
984 $params['now2'] = $params['now1'];
985 $params['active'] = ENROL_USER_ACTIVE
;
986 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
991 $coursefields = 'c.' .join(',c.', $fields);
992 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
993 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
994 $params['contextlevel'] = CONTEXT_COURSE
;
996 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
997 $sql = "SELECT $coursefields $ccselect
999 JOIN (SELECT DISTINCT e.courseid
1001 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
1003 ) en ON (en.courseid = c.id)
1005 WHERE c.id <> :siteid
1007 $params['userid'] = $userid;
1009 $courses = $DB->get_records_sql($sql, $params);
1017 * Called when user is about to be deleted.
1018 * @param object $user
1021 function enrol_user_delete($user) {
1024 $plugins = enrol_get_plugins(true);
1025 foreach ($plugins as $plugin) {
1026 $plugin->user_delete($user);
1029 // force cleanup of all broken enrolments
1030 $DB->delete_records('user_enrolments', array('userid'=>$user->id
));
1034 * Called when course is about to be deleted.
1035 * @param stdClass $course
1038 function enrol_course_delete($course) {
1041 $instances = enrol_get_instances($course->id
, false);
1042 $plugins = enrol_get_plugins(true);
1043 foreach ($instances as $instance) {
1044 if (isset($plugins[$instance->enrol
])) {
1045 $plugins[$instance->enrol
]->delete_instance($instance);
1047 // low level delete in case plugin did not do it
1048 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
1049 $DB->delete_records('role_assignments', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$instance->enrol
));
1050 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
1051 $DB->delete_records('enrol', array('id'=>$instance->id
));
1056 * Try to enrol user via default internal auth plugin.
1058 * For now this is always using the manual enrol plugin...
1065 * @return bool success
1067 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
1070 //note: this is hardcoded to manual plugin for now
1072 if (!enrol_is_enabled('manual')) {
1076 if (!$enrol = enrol_get_plugin('manual')) {
1079 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder,id ASC')) {
1082 $instance = reset($instances);
1084 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
1090 * Is there a chance users might self enrol
1091 * @param int $courseid
1094 function enrol_selfenrol_available($courseid) {
1097 $plugins = enrol_get_plugins(true);
1098 $enrolinstances = enrol_get_instances($courseid, true);
1099 foreach($enrolinstances as $instance) {
1100 if (!isset($plugins[$instance->enrol
])) {
1103 if ($instance->enrol
=== 'guest') {
1104 // blacklist known temporary guest plugins
1107 if ($plugins[$instance->enrol
]->show_enrolme_link($instance)) {
1117 * This function returns the end of current active user enrolment.
1119 * It deals correctly with multiple overlapping user enrolments.
1121 * @param int $courseid
1122 * @param int $userid
1123 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
1125 function enrol_get_enrolment_end($courseid, $userid) {
1129 FROM {user_enrolments} ue
1130 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1131 JOIN {user} u ON u.id = ue.userid
1132 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1133 $params = array('enabled'=>ENROL_INSTANCE_ENABLED
, 'active'=>ENROL_USER_ACTIVE
, 'userid'=>$userid, 'courseid'=>$courseid);
1135 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1141 foreach ($enrolments as $ue) {
1142 $start = (int)$ue->timestart
;
1143 $end = (int)$ue->timeend
;
1144 if ($end != 0 and $end < $start) {
1145 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id
);
1148 if (isset($changes[$start])) {
1149 $changes[$start] = $changes[$start] +
1;
1151 $changes[$start] = 1;
1155 } else if (isset($changes[$end])) {
1156 $changes[$end] = $changes[$end] - 1;
1158 $changes[$end] = -1;
1162 // let's sort then enrolment starts&ends and go through them chronologically,
1163 // looking for current status and the next future end of enrolment
1170 foreach ($changes as $time => $change) {
1172 if ($present === null) {
1173 // we have just went past current time
1174 $present = $current;
1176 // no enrolment active
1180 if ($present !== null) {
1181 // we are already in the future - look for possible end
1182 if ($current +
$change < 1) {
1187 $current +
= $change;
1198 * Is current user accessing course via this enrolment method?
1200 * This is intended for operations that are going to affect enrol instances.
1202 * @param stdClass $instance enrol instance
1205 function enrol_accessing_via_instance(stdClass
$instance) {
1208 if (empty($instance->id
)) {
1212 if (is_siteadmin()) {
1213 // Admins may go anywhere.
1217 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id
, 'enrolid'=>$instance->id
));
1221 * Returns true if user is enrolled (is participating) in course
1222 * this is intended for students and teachers.
1224 * Since 2.2 the result for active enrolments and current user are cached.
1226 * @param context $context
1227 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1228 * @param string $withcapability extra capability name
1229 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1232 function is_enrolled(context
$context, $user = null, $withcapability = '', $onlyactive = false) {
1235 // First find the course context.
1236 $coursecontext = $context->get_course_context();
1238 // Make sure there is a real user specified.
1239 if ($user === null) {
1240 $userid = isset($USER->id
) ?
$USER->id
: 0;
1242 $userid = is_object($user) ?
$user->id
: $user;
1245 if (empty($userid)) {
1248 } else if (isguestuser($userid)) {
1249 // Guest account can not be enrolled anywhere.
1253 // Note everybody participates on frontpage, so for other contexts...
1254 if ($coursecontext->instanceid
!= SITEID
) {
1255 // Try cached info first - the enrolled flag is set only when active enrolment present.
1256 if ($USER->id
== $userid) {
1257 $coursecontext->reload_if_dirty();
1258 if (isset($USER->enrol
['enrolled'][$coursecontext->instanceid
])) {
1259 if ($USER->enrol
['enrolled'][$coursecontext->instanceid
] > time()) {
1260 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1269 // Look for active enrolments only.
1270 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $userid);
1272 if ($until === false) {
1276 if ($USER->id
== $userid) {
1278 $until = ENROL_MAX_TIMESTAMP
;
1280 $USER->enrol
['enrolled'][$coursecontext->instanceid
] = $until;
1281 if (isset($USER->enrol
['tempguest'][$coursecontext->instanceid
])) {
1282 unset($USER->enrol
['tempguest'][$coursecontext->instanceid
]);
1283 remove_temp_course_roles($coursecontext);
1288 // Any enrolment is good for us here, even outdated, disabled or inactive.
1290 FROM {user_enrolments} ue
1291 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1292 JOIN {user} u ON u.id = ue.userid
1293 WHERE ue.userid = :userid AND u.deleted = 0";
1294 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid
);
1295 if (!$DB->record_exists_sql($sql, $params)) {
1301 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1309 * Returns an array of joins, wheres and params that will limit the group of
1310 * users to only those enrolled and with given capability (if specified).
1312 * Note this join will return duplicate rows for users who have been enrolled
1313 * several times (e.g. as manual enrolment, and as self enrolment). You may
1314 * need to use a SELECT DISTINCT in your query (see get_enrolled_sql for example).
1316 * @param context $context
1317 * @param string $prefix optional, a prefix to the user id column
1318 * @param string|array $capability optional, may include a capability name, or array of names.
1319 * If an array is provided then this is the equivalent of a logical 'OR',
1320 * i.e. the user needs to have one of these capabilities.
1321 * @param int $group optional, 0 indicates no current group and USERSWITHOUTGROUP users without any group; otherwise the group id
1322 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1323 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1324 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1325 * @return \core\dml\sql_join Contains joins, wheres, params
1327 function get_enrolled_with_capabilities_join(context
$context, $prefix = '', $capability = '', $group = 0,
1328 $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1329 $uid = $prefix . 'u.id';
1333 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended, $enrolid);
1334 $joins[] = $enrolledjoin->joins
;
1335 $wheres[] = $enrolledjoin->wheres
;
1336 $params = $enrolledjoin->params
;
1338 if (!empty($capability)) {
1339 $capjoin = get_with_capability_join($context, $capability, $uid);
1340 $joins[] = $capjoin->joins
;
1341 $wheres[] = $capjoin->wheres
;
1342 $params = array_merge($params, $capjoin->params
);
1346 $groupjoin = groups_get_members_join($group, $uid, $context);
1347 $joins[] = $groupjoin->joins
;
1348 $params = array_merge($params, $groupjoin->params
);
1349 if (!empty($groupjoin->wheres
)) {
1350 $wheres[] = $groupjoin->wheres
;
1354 $joins = implode("\n", $joins);
1355 $wheres[] = "{$prefix}u.deleted = 0";
1356 $wheres = implode(" AND ", $wheres);
1358 return new \core\dml\
sql_join($joins, $wheres, $params);
1362 * Returns array with sql code and parameters returning all ids
1363 * of users enrolled into course.
1365 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1367 * @param context $context
1368 * @param string $withcapability
1369 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1370 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1371 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1372 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1373 * @return array list($sql, $params)
1375 function get_enrolled_sql(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false,
1378 // Use unique prefix just in case somebody makes some SQL magic with the result.
1381 $prefix = 'eu' . $i . '_';
1383 $capjoin = get_enrolled_with_capabilities_join(
1384 $context, $prefix, $withcapability, $groupid, $onlyactive, $onlysuspended, $enrolid);
1386 $sql = "SELECT DISTINCT {$prefix}u.id
1387 FROM {user} {$prefix}u
1389 WHERE $capjoin->wheres";
1391 return array($sql, $capjoin->params
);
1395 * Returns array with sql joins and parameters returning all ids
1396 * of users enrolled into course.
1398 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1400 * @throws coding_exception
1402 * @param context $context
1403 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1404 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1405 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1406 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1407 * @return \core\dml\sql_join Contains joins, wheres, params
1409 function get_enrolled_join(context
$context, $useridcolumn, $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1410 // Use unique prefix just in case somebody makes some SQL magic with the result.
1413 $prefix = 'ej' . $i . '_';
1415 // First find the course context.
1416 $coursecontext = $context->get_course_context();
1418 $isfrontpage = ($coursecontext->instanceid
== SITEID
);
1420 if ($onlyactive && $onlysuspended) {
1421 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1423 if ($isfrontpage && $onlysuspended) {
1424 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1431 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1433 // Note all users are "enrolled" on the frontpage, but for others...
1434 if (!$isfrontpage) {
1435 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1436 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1438 $enrolconditions = array(
1439 "{$prefix}e.id = {$prefix}ue.enrolid",
1440 "{$prefix}e.courseid = :{$prefix}courseid",
1443 $enrolconditions[] = "{$prefix}e.id = :{$prefix}enrolid";
1444 $params[$prefix . 'enrolid'] = $enrolid;
1446 $enrolconditionssql = implode(" AND ", $enrolconditions);
1447 $ejoin = "JOIN {enrol} {$prefix}e ON ($enrolconditionssql)";
1449 $params[$prefix.'courseid'] = $coursecontext->instanceid
;
1451 if (!$onlysuspended) {
1452 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1455 $wheres[] = "$where1 AND $where2";
1458 // Suspended only where there is enrolment but ALL are suspended.
1459 // Consider multiple enrols where one is not suspended or plain role_assign.
1460 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1461 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1462 $enrolconditions = array(
1463 "{$prefix}e1.id = {$prefix}ue1.enrolid",
1464 "{$prefix}e1.courseid = :{$prefix}_e1_courseid",
1467 $enrolconditions[] = "{$prefix}e1.id = :{$prefix}e1_enrolid";
1468 $params[$prefix . 'e1_enrolid'] = $enrolid;
1470 $enrolconditionssql = implode(" AND ", $enrolconditions);
1471 $joins[] = "JOIN {enrol} {$prefix}e1 ON ($enrolconditionssql)";
1472 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid
;
1473 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1476 if ($onlyactive ||
$onlysuspended) {
1477 $now = round(time(), -2); // Rounding helps caching in DB.
1478 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED
,
1479 $prefix . 'active' => ENROL_USER_ACTIVE
,
1480 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1484 $joins = implode("\n", $joins);
1485 $wheres = implode(" AND ", $wheres);
1487 return new \core\dml\
sql_join($joins, $wheres, $params);
1491 * Returns list of users enrolled into course.
1493 * @param context $context
1494 * @param string $withcapability
1495 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1496 * @param string $userfields requested user record fields
1497 * @param string $orderby
1498 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1499 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1500 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1501 * @return array of user records
1503 function get_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1504 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1507 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1508 $sql = "SELECT $userfields
1510 JOIN ($esql) je ON je.id = u.id
1511 WHERE u.deleted = 0";
1514 $sql = "$sql ORDER BY $orderby";
1516 list($sort, $sortparams) = users_order_by_sql('u');
1517 $sql = "$sql ORDER BY $sort";
1518 $params = array_merge($params, $sortparams);
1521 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1525 * Counts list of users enrolled into course (as per above function)
1527 * @param context $context
1528 * @param string $withcapability
1529 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1530 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1531 * @return array of user records
1533 function count_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1536 $capjoin = get_enrolled_with_capabilities_join(
1537 $context, '', $withcapability, $groupid, $onlyactive);
1539 $sql = "SELECT COUNT(DISTINCT u.id)
1542 WHERE $capjoin->wheres AND u.deleted = 0";
1544 return $DB->count_records_sql($sql, $capjoin->params
);
1548 * Send welcome email "from" options.
1550 * @return array list of from options
1552 function enrol_send_welcome_email_options() {
1554 ENROL_DO_NOT_SEND_EMAIL
=> get_string('no'),
1555 ENROL_SEND_EMAIL_FROM_COURSE_CONTACT
=> get_string('sendfromcoursecontact', 'enrol'),
1556 ENROL_SEND_EMAIL_FROM_KEY_HOLDER
=> get_string('sendfromkeyholder', 'enrol'),
1557 ENROL_SEND_EMAIL_FROM_NOREPLY
=> get_string('sendfromnoreply', 'enrol')
1562 * Serve the user enrolment form as a fragment.
1564 * @param array $args List of named arguments for the fragment loader.
1567 function enrol_output_fragment_user_enrolment_form($args) {
1570 $args = (object) $args;
1571 $context = $args->context
;
1572 require_capability('moodle/course:enrolreview', $context);
1574 $ueid = $args->ueid
;
1575 $userenrolment = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST
);
1576 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid
], '*', MUST_EXIST
);
1577 $plugin = enrol_get_plugin($instance->enrol
);
1579 'ue' => $userenrolment,
1581 'enrolinstancename' => $plugin->get_instance_name($instance)
1584 // Set the data if applicable.
1586 if (isset($args->formdata
)) {
1587 $serialiseddata = json_decode($args->formdata
);
1588 parse_str($serialiseddata, $data);
1591 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1592 $mform = new \
enrol_user_enrolment_form(null, $customdata, 'post', '', null, true, $data);
1594 if (!empty($data)) {
1595 $mform->set_data($data);
1596 $mform->is_validated();
1599 return $mform->render();
1603 * Returns the course where a user enrolment belong to.
1605 * @param int $ueid user_enrolments id
1608 function enrol_get_course_by_user_enrolment_id($ueid) {
1610 $sql = "SELECT c.* FROM {user_enrolments} ue
1611 JOIN {enrol} e ON e.id = ue.enrolid
1612 JOIN {course} c ON c.id = e.courseid
1613 WHERE ue.id = :ueid";
1614 return $DB->get_record_sql($sql, array('ueid' => $ueid));
1618 * Return all users enrolled in a course.
1620 * @param int $courseid Course id or false if using $uefilter (user enrolment ids may belong to different courses)
1621 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1622 * @param array $usersfilter Limit the results obtained to this list of user ids. $uefilter compatibility not guaranteed.
1623 * @param array $uefilter Limit the results obtained to this list of user enrolment ids. $usersfilter compatibility not guaranteed.
1624 * @return stdClass[]
1626 function enrol_get_course_users($courseid = false, $onlyactive = false, $usersfilter = array(), $uefilter = array()) {
1629 if (!$courseid && !$usersfilter && !$uefilter) {
1630 throw new \
coding_exception('You should specify at least 1 filter: courseid, users or user enrolments');
1633 $sql = "SELECT ue.id AS ueid, ue.status AS uestatus, ue.enrolid AS ueenrolid, ue.timestart AS uetimestart,
1634 ue.timeend AS uetimeend, ue.modifierid AS uemodifierid, ue.timecreated AS uetimecreated,
1635 ue.timemodified AS uetimemodified,
1636 u.* FROM {user_enrolments} ue
1637 JOIN {enrol} e ON e.id = ue.enrolid
1638 JOIN {user} u ON ue.userid = u.id
1643 $conditions[] = "e.courseid = :courseid";
1644 $params['courseid'] = $courseid;
1648 $conditions[] = "ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND " .
1649 "(ue.timeend = 0 OR ue.timeend > :now2)";
1650 // Improves db caching.
1651 $params['now1'] = round(time(), -2);
1652 $params['now2'] = $params['now1'];
1653 $params['active'] = ENROL_USER_ACTIVE
;
1654 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
1658 list($usersql, $userparams) = $DB->get_in_or_equal($usersfilter, SQL_PARAMS_NAMED
);
1659 $conditions[] = "ue.userid $usersql";
1660 $params = $params +
$userparams;
1664 list($uesql, $ueparams) = $DB->get_in_or_equal($uefilter, SQL_PARAMS_NAMED
);
1665 $conditions[] = "ue.id $uesql";
1666 $params = $params +
$ueparams;
1669 return $DB->get_records_sql($sql . ' ' . implode(' AND ', $conditions), $params);
1673 * Enrolment plugins abstract class.
1675 * All enrol plugins should be based on this class,
1676 * this is also the main source of documentation.
1678 * @copyright 2010 Petr Skoda {@link http://skodak.org}
1679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1681 abstract class enrol_plugin
{
1682 protected $config = null;
1685 * Returns name of this enrol plugin
1688 public function get_name() {
1689 // second word in class is always enrol name, sorry, no fancy plugin names with _
1690 $words = explode('_', get_class($this));
1695 * Returns localised name of enrol instance
1697 * @param object $instance (null is accepted too)
1700 public function get_instance_name($instance) {
1701 if (empty($instance->name
)) {
1702 $enrol = $this->get_name();
1703 return get_string('pluginname', 'enrol_'.$enrol);
1705 $context = context_course
::instance($instance->courseid
);
1706 return format_string($instance->name
, true, array('context'=>$context));
1711 * Returns optional enrolment information icons.
1713 * This is used in course list for quick overview of enrolment options.
1715 * We are not using single instance parameter because sometimes
1716 * we might want to prevent icon repetition when multiple instances
1717 * of one type exist. One instance may also produce several icons.
1719 * @param array $instances all enrol instances of this type in one course
1720 * @return array of pix_icon
1722 public function get_info_icons(array $instances) {
1727 * Returns optional enrolment instance description text.
1729 * This is used in detailed course information.
1732 * @param object $instance
1733 * @return string short html text
1735 public function get_description_text($instance) {
1740 * Makes sure config is loaded and cached.
1743 protected function load_config() {
1744 if (!isset($this->config
)) {
1745 $name = $this->get_name();
1746 $this->config
= get_config("enrol_$name");
1751 * Returns plugin config value
1752 * @param string $name
1753 * @param string $default value if config does not exist yet
1754 * @return string value or default
1756 public function get_config($name, $default = NULL) {
1757 $this->load_config();
1758 return isset($this->config
->$name) ?
$this->config
->$name : $default;
1762 * Sets plugin config value
1763 * @param string $name name of config
1764 * @param string $value string config value, null means delete
1765 * @return string value
1767 public function set_config($name, $value) {
1768 $pluginname = $this->get_name();
1769 $this->load_config();
1770 if ($value === NULL) {
1771 unset($this->config
->$name);
1773 $this->config
->$name = $value;
1775 set_config($name, $value, "enrol_$pluginname");
1779 * Does this plugin assign protected roles are can they be manually removed?
1780 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1782 public function roles_protected() {
1787 * Does this plugin allow manual enrolments?
1789 * @param stdClass $instance course enrol instance
1790 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1792 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1794 public function allow_enrol(stdClass
$instance) {
1799 * Does this plugin allow manual unenrolment of all users?
1800 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1802 * @param stdClass $instance course enrol instance
1803 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1805 public function allow_unenrol(stdClass
$instance) {
1810 * Does this plugin allow manual unenrolment of a specific user?
1811 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1813 * This is useful especially for synchronisation plugins that
1814 * do suspend instead of full unenrolment.
1816 * @param stdClass $instance course enrol instance
1817 * @param stdClass $ue record from user_enrolments table, specifies user
1819 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1821 public function allow_unenrol_user(stdClass
$instance, stdClass
$ue) {
1822 return $this->allow_unenrol($instance);
1826 * Does this plugin allow manual changes in user_enrolments table?
1828 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1830 * @param stdClass $instance course enrol instance
1831 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1833 public function allow_manage(stdClass
$instance) {
1838 * Does this plugin support some way to user to self enrol?
1840 * @param stdClass $instance course enrol instance
1842 * @return bool - true means show "Enrol me in this course" link in course UI
1844 public function show_enrolme_link(stdClass
$instance) {
1849 * Attempt to automatically enrol current user in course without any interaction,
1850 * calling code has to make sure the plugin and instance are active.
1852 * This should return either a timestamp in the future or false.
1854 * @param stdClass $instance course enrol instance
1855 * @return bool|int false means not enrolled, integer means timeend
1857 public function try_autoenrol(stdClass
$instance) {
1864 * Attempt to automatically gain temporary guest access to course,
1865 * calling code has to make sure the plugin and instance are active.
1867 * This should return either a timestamp in the future or false.
1869 * @param stdClass $instance course enrol instance
1870 * @return bool|int false means no guest access, integer means timeend
1872 public function try_guestaccess(stdClass
$instance) {
1879 * Enrol user into course via enrol instance.
1881 * @param stdClass $instance
1882 * @param int $userid
1883 * @param int $roleid optional role id
1884 * @param int $timestart 0 means unknown
1885 * @param int $timeend 0 means forever
1886 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1887 * @param bool $recovergrades restore grade history
1890 public function enrol_user(stdClass
$instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
1891 global $DB, $USER, $CFG; // CFG necessary!!!
1893 if ($instance->courseid
== SITEID
) {
1894 throw new coding_exception('invalid attempt to enrol into frontpage course!');
1897 $name = $this->get_name();
1898 $courseid = $instance->courseid
;
1900 if ($instance->enrol
!== $name) {
1901 throw new coding_exception('invalid enrol instance!');
1903 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
1904 if (!isset($recovergrades)) {
1905 $recovergrades = $CFG->recovergradesdefault
;
1910 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
1911 //only update if timestart or timeend or status are different.
1912 if ($ue->timestart
!= $timestart or $ue->timeend
!= $timeend or (!is_null($status) and $ue->status
!= $status)) {
1913 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
1916 $ue = new stdClass();
1917 $ue->enrolid
= $instance->id
;
1918 $ue->status
= is_null($status) ? ENROL_USER_ACTIVE
: $status;
1919 $ue->userid
= $userid;
1920 $ue->timestart
= $timestart;
1921 $ue->timeend
= $timeend;
1922 $ue->modifierid
= $USER->id
;
1923 $ue->timecreated
= time();
1924 $ue->timemodified
= $ue->timecreated
;
1925 $ue->id
= $DB->insert_record('user_enrolments', $ue);
1932 $event = \core\event\user_enrolment_created
::create(
1934 'objectid' => $ue->id
,
1935 'courseid' => $courseid,
1936 'context' => $context,
1937 'relateduserid' => $ue->userid
,
1938 'other' => array('enrol' => $name)
1942 // Check if course contacts cache needs to be cleared.
1943 core_course_category
::user_enrolment_changed($courseid, $ue->userid
,
1944 $ue->status
, $ue->timestart
, $ue->timeend
);
1948 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
1949 if ($this->roles_protected()) {
1950 role_assign($roleid, $userid, $context->id
, 'enrol_'.$name, $instance->id
);
1952 role_assign($roleid, $userid, $context->id
);
1956 // Recover old grades if present.
1957 if ($recovergrades) {
1958 require_once("$CFG->libdir/gradelib.php");
1959 grade_recover_history_grades($userid, $courseid);
1962 // reset current user enrolment caching
1963 if ($userid == $USER->id
) {
1964 if (isset($USER->enrol
['enrolled'][$courseid])) {
1965 unset($USER->enrol
['enrolled'][$courseid]);
1967 if (isset($USER->enrol
['tempguest'][$courseid])) {
1968 unset($USER->enrol
['tempguest'][$courseid]);
1969 remove_temp_course_roles($context);
1975 * Store user_enrolments changes and trigger event.
1977 * @param stdClass $instance
1978 * @param int $userid
1979 * @param int $status
1980 * @param int $timestart
1981 * @param int $timeend
1984 public function update_user_enrol(stdClass
$instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
1985 global $DB, $USER, $CFG;
1987 $name = $this->get_name();
1989 if ($instance->enrol
!== $name) {
1990 throw new coding_exception('invalid enrol instance!');
1993 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
1994 // weird, user not enrolled
1999 if (isset($status) and $ue->status
!= $status) {
2000 $ue->status
= $status;
2003 if (isset($timestart) and $ue->timestart
!= $timestart) {
2004 $ue->timestart
= $timestart;
2007 if (isset($timeend) and $ue->timeend
!= $timeend) {
2008 $ue->timeend
= $timeend;
2017 $ue->modifierid
= $USER->id
;
2018 $ue->timemodified
= time();
2019 $DB->update_record('user_enrolments', $ue);
2021 // User enrolments have changed, so mark user as dirty.
2022 mark_user_dirty($userid);
2024 // Invalidate core_access cache for get_suspended_userids.
2025 cache_helper
::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid
));
2028 $event = \core\event\user_enrolment_updated
::create(
2030 'objectid' => $ue->id
,
2031 'courseid' => $instance->courseid
,
2032 'context' => context_course
::instance($instance->courseid
),
2033 'relateduserid' => $ue->userid
,
2034 'other' => array('enrol' => $name)
2039 core_course_category
::user_enrolment_changed($instance->courseid
, $ue->userid
,
2040 $ue->status
, $ue->timestart
, $ue->timeend
);
2044 * Unenrol user from course,
2045 * the last unenrolment removes all remaining roles.
2047 * @param stdClass $instance
2048 * @param int $userid
2051 public function unenrol_user(stdClass
$instance, $userid) {
2052 global $CFG, $USER, $DB;
2053 require_once("$CFG->dirroot/group/lib.php");
2055 $name = $this->get_name();
2056 $courseid = $instance->courseid
;
2058 if ($instance->enrol
!== $name) {
2059 throw new coding_exception('invalid enrol instance!');
2061 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
2063 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
2064 // weird, user not enrolled
2068 // Remove all users groups linked to this enrolment instance.
2069 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
))) {
2070 foreach ($gms as $gm) {
2071 groups_remove_member($gm->groupid
, $gm->userid
);
2075 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id
, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
));
2076 $DB->delete_records('user_enrolments', array('id'=>$ue->id
));
2078 // add extra info and trigger event
2079 $ue->courseid
= $courseid;
2083 FROM {user_enrolments} ue
2084 JOIN {enrol} e ON (e.id = ue.enrolid)
2085 WHERE ue.userid = :userid AND e.courseid = :courseid";
2086 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
2087 $ue->lastenrol
= false;
2090 // the big cleanup IS necessary!
2091 require_once("$CFG->libdir/gradelib.php");
2093 // remove all remaining roles
2094 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id
), true, false);
2096 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
2097 groups_delete_group_members($courseid, $userid);
2099 grade_user_unenrol($courseid, $userid);
2101 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
2103 $ue->lastenrol
= true; // means user not enrolled any more
2106 $event = \core\event\user_enrolment_deleted
::create(
2108 'courseid' => $courseid,
2109 'context' => $context,
2110 'relateduserid' => $ue->userid
,
2111 'objectid' => $ue->id
,
2113 'userenrolment' => (array)$ue,
2120 // User enrolments have changed, so mark user as dirty.
2121 mark_user_dirty($userid);
2123 // Check if courrse contacts cache needs to be cleared.
2124 core_course_category
::user_enrolment_changed($courseid, $ue->userid
, ENROL_USER_SUSPENDED
);
2126 // reset current user enrolment caching
2127 if ($userid == $USER->id
) {
2128 if (isset($USER->enrol
['enrolled'][$courseid])) {
2129 unset($USER->enrol
['enrolled'][$courseid]);
2131 if (isset($USER->enrol
['tempguest'][$courseid])) {
2132 unset($USER->enrol
['tempguest'][$courseid]);
2133 remove_temp_course_roles($context);
2139 * Forces synchronisation of user enrolments.
2141 * This is important especially for external enrol plugins,
2142 * this function is called for all enabled enrol plugins
2143 * right after every user login.
2145 * @param object $user user record
2148 public function sync_user_enrolments($user) {
2149 // override if necessary
2153 * This returns false for backwards compatibility, but it is really recommended.
2158 public function use_standard_editing_ui() {
2163 * Return whether or not, given the current state, it is possible to add a new instance
2164 * of this enrolment plugin to the course.
2166 * Default implementation is just for backwards compatibility.
2168 * @param int $courseid
2171 public function can_add_instance($courseid) {
2172 $link = $this->get_newinstance_link($courseid);
2173 return !empty($link);
2177 * Return whether or not, given the current state, it is possible to edit an instance
2178 * of this enrolment plugin in the course. Used by the standard editing UI
2179 * to generate a link to the edit instance form if editing is allowed.
2181 * @param stdClass $instance
2184 public function can_edit_instance($instance) {
2185 $context = context_course
::instance($instance->courseid
);
2187 return has_capability('enrol/' . $instance->enrol
. ':config', $context);
2191 * Returns link to page which may be used to add new instance of enrolment plugin in course.
2192 * @param int $courseid
2193 * @return moodle_url page url
2195 public function get_newinstance_link($courseid) {
2196 // override for most plugins, check if instance already exists in cases only one instance is supported
2201 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
2203 public function instance_deleteable($instance) {
2204 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
2205 enrol_plugin::can_delete_instance() instead');
2209 * Is it possible to delete enrol instance via standard UI?
2211 * @param stdClass $instance
2214 public function can_delete_instance($instance) {
2219 * Is it possible to hide/show enrol instance via standard UI?
2221 * @param stdClass $instance
2224 public function can_hide_show_instance($instance) {
2225 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER
);
2230 * Returns link to manual enrol UI if exists.
2231 * Does the access control tests automatically.
2233 * @param object $instance
2234 * @return moodle_url
2236 public function get_manual_enrol_link($instance) {
2241 * Returns list of unenrol links for all enrol instances in course.
2243 * @param int $instance
2244 * @return moodle_url or NULL if self unenrolment not supported
2246 public function get_unenrolself_link($instance) {
2247 global $USER, $CFG, $DB;
2249 $name = $this->get_name();
2250 if ($instance->enrol
!== $name) {
2251 throw new coding_exception('invalid enrol instance!');
2254 if ($instance->courseid
== SITEID
) {
2258 if (!enrol_is_enabled($name)) {
2262 if ($instance->status
!= ENROL_INSTANCE_ENABLED
) {
2266 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2270 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
2272 if (!has_capability("enrol/$name:unenrolself", $context)) {
2276 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$USER->id
, 'status'=>ENROL_USER_ACTIVE
))) {
2280 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id
));
2284 * Adds enrol instance UI to course edit form
2286 * @param object $instance enrol instance or null if does not exist yet
2287 * @param MoodleQuickForm $mform
2288 * @param object $data
2289 * @param object $context context of existing course or parent category if course does not exist
2292 public function course_edit_form($instance, MoodleQuickForm
$mform, $data, $context) {
2293 // override - usually at least enable/disable switch, has to add own form header
2297 * Adds form elements to add/edit instance form.
2300 * @param object $instance enrol instance or null if does not exist yet
2301 * @param MoodleQuickForm $mform
2302 * @param context $context
2305 public function edit_instance_form($instance, MoodleQuickForm
$mform, $context) {
2306 // Do nothing by default.
2310 * Perform custom validation of the data used to edit the instance.
2313 * @param array $data array of ("fieldname"=>value) of submitted data
2314 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2315 * @param object $instance The instance data loaded from the DB.
2316 * @param context $context The context of the instance we are editing
2317 * @return array of "element_name"=>"error_description" if there are errors,
2318 * or an empty array if everything is OK.
2320 public function edit_instance_validation($data, $files, $instance, $context) {
2321 // No errors by default.
2322 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER
);
2327 * Validates course edit form data
2329 * @param object $instance enrol instance or null if does not exist yet
2330 * @param array $data
2331 * @param object $context context of existing course or parent category if course does not exist
2332 * @return array errors array
2334 public function course_edit_validation($instance, array $data, $context) {
2339 * Called after updating/inserting course.
2341 * @param bool $inserted true if course just inserted
2342 * @param object $course
2343 * @param object $data form data
2346 public function course_updated($inserted, $course, $data) {
2348 if ($this->get_config('defaultenrol')) {
2349 $this->add_default_instance($course);
2355 * Add new instance of enrol plugin.
2356 * @param object $course
2357 * @param array instance fields
2358 * @return int id of new instance, null if can not be created
2360 public function add_instance($course, array $fields = NULL) {
2363 if ($course->id
== SITEID
) {
2364 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2367 $instance = new stdClass();
2368 $instance->enrol
= $this->get_name();
2369 $instance->status
= ENROL_INSTANCE_ENABLED
;
2370 $instance->courseid
= $course->id
;
2371 $instance->enrolstartdate
= 0;
2372 $instance->enrolenddate
= 0;
2373 $instance->timemodified
= time();
2374 $instance->timecreated
= $instance->timemodified
;
2375 $instance->sortorder
= $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id
));
2377 $fields = (array)$fields;
2378 unset($fields['enrol']);
2379 unset($fields['courseid']);
2380 unset($fields['sortorder']);
2381 foreach($fields as $field=>$value) {
2382 $instance->$field = $value;
2385 $instance->id
= $DB->insert_record('enrol', $instance);
2387 \core\event\enrol_instance_created
::create_from_record($instance)->trigger();
2389 return $instance->id
;
2393 * Update instance of enrol plugin.
2396 * @param stdClass $instance
2397 * @param stdClass $data modified instance fields
2400 public function update_instance($instance, $data) {
2402 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2403 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2404 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2405 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2406 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2407 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2409 foreach ($properties as $key) {
2410 if (isset($data->$key)) {
2411 $instance->$key = $data->$key;
2414 $instance->timemodified
= time();
2416 $update = $DB->update_record('enrol', $instance);
2418 \core\event\enrol_instance_updated
::create_from_record($instance)->trigger();
2424 * Add new instance of enrol plugin with default settings,
2425 * called when adding new instance manually or when adding new course.
2427 * Not all plugins support this.
2429 * @param object $course
2430 * @return int id of new instance or null if no default supported
2432 public function add_default_instance($course) {
2437 * Update instance status
2439 * Override when plugin needs to do some action when enabled or disabled.
2441 * @param stdClass $instance
2442 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2445 public function update_status($instance, $newstatus) {
2448 $instance->status
= $newstatus;
2449 $DB->update_record('enrol', $instance);
2451 $context = context_course
::instance($instance->courseid
);
2452 \core\event\enrol_instance_updated
::create_from_record($instance)->trigger();
2454 // Invalidate all enrol caches.
2455 $context->mark_dirty();
2459 * Delete course enrol plugin instance, unenrol all users.
2460 * @param object $instance
2463 public function delete_instance($instance) {
2466 $name = $this->get_name();
2467 if ($instance->enrol
!== $name) {
2468 throw new coding_exception('invalid enrol instance!');
2471 //first unenrol all users
2472 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id
));
2473 foreach ($participants as $participant) {
2474 $this->unenrol_user($instance, $participant->userid
);
2476 $participants->close();
2478 // now clean up all remainders that were not removed correctly
2479 if ($gms = $DB->get_records('groups_members', array('itemid' => $instance->id
, 'component' => 'enrol_' . $name))) {
2480 foreach ($gms as $gm) {
2481 groups_remove_member($gm->groupid
, $gm->userid
);
2484 $DB->delete_records('role_assignments', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$name));
2485 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
2487 // finally drop the enrol row
2488 $DB->delete_records('enrol', array('id'=>$instance->id
));
2490 $context = context_course
::instance($instance->courseid
);
2491 \core\event\enrol_instance_deleted
::create_from_record($instance)->trigger();
2493 // Invalidate all enrol caches.
2494 $context->mark_dirty();
2498 * Creates course enrol form, checks if form submitted
2499 * and enrols user if necessary. It can also redirect.
2501 * @param stdClass $instance
2502 * @return string html text, usually a form in a text box
2504 public function enrol_page_hook(stdClass
$instance) {
2509 * Checks if user can self enrol.
2511 * @param stdClass $instance enrolment instance
2512 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2513 * used by navigation to improve performance.
2514 * @return bool|string true if successful, else error message or false
2516 public function can_self_enrol(stdClass
$instance, $checkuserenrolment = true) {
2521 * Return information for enrolment instance containing list of parameters required
2522 * for enrolment, name of enrolment plugin etc.
2524 * @param stdClass $instance enrolment instance
2525 * @return array instance info.
2527 public function get_enrol_info(stdClass
$instance) {
2532 * Adds navigation links into course admin block.
2534 * By defaults looks for manage links only.
2536 * @param navigation_node $instancesnode
2537 * @param stdClass $instance
2540 public function add_course_navigation($instancesnode, stdClass
$instance) {
2541 if ($this->use_standard_editing_ui()) {
2542 $context = context_course
::instance($instance->courseid
);
2543 $cap = 'enrol/' . $instance->enrol
. ':config';
2544 if (has_capability($cap, $context)) {
2545 $linkparams = array('courseid' => $instance->courseid
, 'id' => $instance->id
, 'type' => $instance->enrol
);
2546 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2547 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node
::TYPE_SETTING
);
2553 * Returns edit icons for the page with list of instances
2554 * @param stdClass $instance
2557 public function get_action_icons(stdClass
$instance) {
2561 if ($this->use_standard_editing_ui()) {
2562 $linkparams = array('courseid' => $instance->courseid
, 'id' => $instance->id
, 'type' => $instance->enrol
);
2563 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2564 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2565 array('class' => 'iconsmall')));
2571 * Reads version.php and determines if it is necessary
2572 * to execute the cron job now.
2575 public function is_cron_required() {
2578 $name = $this->get_name();
2579 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2580 $plugin = new stdClass();
2581 include($versionfile);
2582 if (empty($plugin->cron
)) {
2585 $lastexecuted = $this->get_config('lastcron', 0);
2586 if ($lastexecuted +
$plugin->cron
< time()) {
2594 * Called for all enabled enrol plugins that returned true from is_cron_required().
2597 public function cron() {
2601 * Called when user is about to be deleted
2602 * @param object $user
2605 public function user_delete($user) {
2610 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2611 WHERE e.enrol = :name AND ue.userid = :userid";
2612 $params = array('name'=>$this->get_name(), 'userid'=>$user->id
);
2614 $rs = $DB->get_recordset_sql($sql, $params);
2615 foreach($rs as $instance) {
2616 $this->unenrol_user($instance, $user->id
);
2622 * Returns an enrol_user_button that takes the user to a page where they are able to
2623 * enrol users into the managers course through this plugin.
2625 * Optional: If the plugin supports manual enrolments it can choose to override this
2626 * otherwise it shouldn't
2628 * @param course_enrolment_manager $manager
2629 * @return enrol_user_button|false
2631 public function get_manual_enrol_button(course_enrolment_manager
$manager) {
2636 * Gets an array of the user enrolment actions
2638 * @param course_enrolment_manager $manager
2639 * @param stdClass $ue
2640 * @return array An array of user_enrolment_actions
2642 public function get_user_enrolment_actions(course_enrolment_manager
$manager, $ue) {
2644 $context = $manager->get_context();
2645 $instance = $ue->enrolmentinstance
;
2646 $params = $manager->get_moodlepage()->url
->params();
2647 $params['ue'] = $ue->id
;
2649 // Edit enrolment action.
2650 if ($this->allow_manage($instance) && has_capability("enrol/{$instance->enrol}:manage", $context)) {
2651 $title = get_string('editenrolment', 'enrol');
2652 $icon = new pix_icon('t/edit', $title);
2653 $url = new moodle_url('/enrol/editenrolment.php', $params);
2655 'class' => 'editenrollink',
2657 'data-action' => ENROL_ACTION_EDIT
2659 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2663 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/{$instance->enrol}:unenrol", $context)) {
2664 $title = get_string('unenrol', 'enrol');
2665 $icon = new pix_icon('t/delete', $title);
2666 $url = new moodle_url('/enrol/unenroluser.php', $params);
2668 'class' => 'unenrollink',
2670 'data-action' => ENROL_ACTION_UNENROL
2672 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2678 * Returns true if the plugin has one or more bulk operations that can be performed on
2681 * @param course_enrolment_manager $manager
2684 public function has_bulk_operations(course_enrolment_manager
$manager) {
2689 * Return an array of enrol_bulk_enrolment_operation objects that define
2690 * the bulk actions that can be performed on user enrolments by the plugin.
2692 * @param course_enrolment_manager $manager
2695 public function get_bulk_operations(course_enrolment_manager
$manager) {
2700 * Do any enrolments need expiration processing.
2702 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2704 * @param progress_trace $trace
2705 * @param int $courseid one course, empty mean all
2706 * @return bool true if any data processed, false if not
2708 public function process_expirations(progress_trace
$trace, $courseid = null) {
2711 $name = $this->get_name();
2712 if (!enrol_is_enabled($name)) {
2721 $coursesql = "AND e.courseid = :courseid";
2724 // Deal with expired accounts.
2725 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP
);
2727 if ($action == ENROL_EXT_REMOVED_UNENROL
) {
2728 $instances = array();
2729 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2730 FROM {user_enrolments} ue
2731 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2732 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2733 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2734 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE
, 'enrol'=>$name, 'courseid'=>$courseid);
2736 $rs = $DB->get_recordset_sql($sql, $params);
2737 foreach ($rs as $ue) {
2739 $trace->output("Starting processing of enrol_$name expirations...");
2742 if (empty($instances[$ue->enrolid
])) {
2743 $instances[$ue->enrolid
] = $DB->get_record('enrol', array('id'=>$ue->enrolid
));
2745 $instance = $instances[$ue->enrolid
];
2746 if (!$this->roles_protected()) {
2747 // Let's just guess what extra roles are supposed to be removed.
2748 if ($instance->roleid
) {
2749 role_unassign($instance->roleid
, $ue->userid
, $ue->contextid
);
2752 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2753 $this->unenrol_user($instance, $ue->userid
);
2754 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2759 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES
or $action == ENROL_EXT_REMOVED_SUSPEND
) {
2760 $instances = array();
2761 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2762 FROM {user_enrolments} ue
2763 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2764 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2765 WHERE ue.timeend > 0 AND ue.timeend < :now
2766 AND ue.status = :useractive $coursesql";
2767 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE
, 'useractive'=>ENROL_USER_ACTIVE
, 'enrol'=>$name, 'courseid'=>$courseid);
2768 $rs = $DB->get_recordset_sql($sql, $params);
2769 foreach ($rs as $ue) {
2771 $trace->output("Starting processing of enrol_$name expirations...");
2774 if (empty($instances[$ue->enrolid
])) {
2775 $instances[$ue->enrolid
] = $DB->get_record('enrol', array('id'=>$ue->enrolid
));
2777 $instance = $instances[$ue->enrolid
];
2779 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES
) {
2780 if (!$this->roles_protected()) {
2781 // Let's just guess what roles should be removed.
2782 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
));
2784 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'', 'itemid'=>0));
2786 } else if ($count > 1 and $instance->roleid
) {
2787 role_unassign($instance->roleid
, $ue->userid
, $ue->contextid
, '', 0);
2790 // In any case remove all roles that belong to this instance and user.
2791 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
), true);
2792 // Final cleanup of subcontexts if there are no more course roles.
2793 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
))) {
2794 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'', 'itemid'=>0), true);
2798 $this->update_user_enrol($instance, $ue->userid
, ENROL_USER_SUSPENDED
);
2799 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2805 // ENROL_EXT_REMOVED_KEEP means no changes.
2809 $trace->output("...finished processing of enrol_$name expirations");
2811 $trace->output("No expired enrol_$name enrolments detected");
2819 * Send expiry notifications.
2821 * Plugin that wants to have expiry notification MUST implement following:
2822 * - expirynotifyhour plugin setting,
2823 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2824 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2825 * expirymessageenrolledsubject and expirymessageenrolledbody),
2826 * - expiry_notification provider in db/messages.php,
2827 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2828 * - something that calls this method, such as cron.
2830 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2832 public function send_expiry_notifications($trace) {
2835 $name = $this->get_name();
2836 if (!enrol_is_enabled($name)) {
2841 // Unfortunately this may take a long time, it should not be interrupted,
2842 // otherwise users get duplicate notification.
2844 core_php_time_limit
::raise();
2845 raise_memory_limit(MEMORY_HUGE
);
2848 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2849 $expirynotifyhour = $this->get_config('expirynotifyhour');
2850 if (is_null($expirynotifyhour)) {
2851 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
2856 if (!($trace instanceof progress_trace
)) {
2857 $trace = $trace ?
new text_progress_trace() : new null_progress_trace();
2858 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER
);
2862 $notifytime = usergetmidnight($timenow, $CFG->timezone
) +
($expirynotifyhour * 3600);
2864 if ($expirynotifylast > $notifytime) {
2865 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone
).'.');
2869 } else if ($timenow < $notifytime) {
2870 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone
).'.');
2875 $trace->output('Processing '.$name.' enrolment expiration notifications...');
2877 // Notify users responsible for enrolment once every day.
2878 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2879 FROM {user_enrolments} ue
2880 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2881 JOIN {course} c ON (c.id = e.courseid)
2882 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2883 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2884 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2885 $params = array('enabled'=>ENROL_INSTANCE_ENABLED
, 'active'=>ENROL_USER_ACTIVE
, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2887 $rs = $DB->get_recordset_sql($sql, $params);
2892 foreach($rs as $ue) {
2893 if ($lastenrollid and $lastenrollid != $ue->enrolid
) {
2894 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2897 $lastenrollid = $ue->enrolid
;
2899 $enroller = $this->get_enroller($ue->enrolid
);
2900 $context = context_course
::instance($ue->courseid
);
2902 $user = $DB->get_record('user', array('id'=>$ue->userid
));
2904 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend
);
2906 if (!$ue->notifyall
) {
2910 if ($ue->timeend
- $ue->expirythreshold +
86400 < $timenow) {
2911 // Notify enrolled users only once at the start of the threshold.
2912 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
2916 $this->notify_expiry_enrolled($user, $ue, $trace);
2920 if ($lastenrollid and $users) {
2921 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
2924 $trace->output('...notification processing finished.');
2927 $this->set_config('expirynotifylast', $timenow);
2931 * Returns the user who is responsible for enrolments for given instance.
2933 * Override if plugin knows anybody better than admin.
2935 * @param int $instanceid enrolment instance id
2936 * @return stdClass user record
2938 protected function get_enroller($instanceid) {
2943 * Notify user about incoming expiration of their enrolment,
2944 * it is called only if notification of enrolled users (aka students) is enabled in course.
2946 * This is executed only once for each expiring enrolment right
2947 * at the start of the expiration threshold.
2949 * @param stdClass $user
2950 * @param stdClass $ue
2951 * @param progress_trace $trace
2953 protected function notify_expiry_enrolled($user, $ue, progress_trace
$trace) {
2956 $name = $this->get_name();
2958 $oldforcelang = force_current_language($user->lang
);
2960 $enroller = $this->get_enroller($ue->enrolid
);
2961 $context = context_course
::instance($ue->courseid
);
2963 $a = new stdClass();
2964 $a->course
= format_string($ue->fullname
, true, array('context'=>$context));
2965 $a->user
= fullname($user, true);
2966 $a->timeend
= userdate($ue->timeend
, '', $user->timezone
);
2967 $a->enroller
= fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
2969 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
2970 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
2972 $message = new \core\message\
message();
2973 $message->courseid
= $ue->courseid
;
2974 $message->notification
= 1;
2975 $message->component
= 'enrol_'.$name;
2976 $message->name
= 'expiry_notification';
2977 $message->userfrom
= $enroller;
2978 $message->userto
= $user;
2979 $message->subject
= $subject;
2980 $message->fullmessage
= $body;
2981 $message->fullmessageformat
= FORMAT_MARKDOWN
;
2982 $message->fullmessagehtml
= markdown_to_html($body);
2983 $message->smallmessage
= $subject;
2984 $message->contexturlname
= $a->course
;
2985 $message->contexturl
= (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid
));
2987 if (message_send($message)) {
2988 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
2990 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
2993 force_current_language($oldforcelang);
2997 * Notify person responsible for enrolments that some user enrolments will be expired soon,
2998 * it is called only if notification of enrollers (aka teachers) is enabled in course.
3000 * This is called repeatedly every day for each course if there are any pending expiration
3001 * in the expiration threshold.
3004 * @param array $users
3005 * @param progress_trace $trace
3007 protected function notify_expiry_enroller($eid, $users, progress_trace
$trace) {
3010 $name = $this->get_name();
3012 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
3013 $context = context_course
::instance($instance->courseid
);
3014 $course = $DB->get_record('course', array('id'=>$instance->courseid
));
3016 $enroller = $this->get_enroller($instance->id
);
3017 $admin = get_admin();
3019 $oldforcelang = force_current_language($enroller->lang
);
3021 foreach($users as $key=>$info) {
3022 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone
);
3025 $a = new stdClass();
3026 $a->course
= format_string($course->fullname
, true, array('context'=>$context));
3027 $a->threshold
= get_string('numdays', '', $instance->expirythreshold
/ (60*60*24));
3028 $a->users
= implode("\n", $users);
3029 $a->extendurl
= (string)new moodle_url('/user/index.php', array('id'=>$instance->courseid
));
3031 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
3032 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
3034 $message = new \core\message\
message();
3035 $message->courseid
= $course->id
;
3036 $message->notification
= 1;
3037 $message->component
= 'enrol_'.$name;
3038 $message->name
= 'expiry_notification';
3039 $message->userfrom
= $admin;
3040 $message->userto
= $enroller;
3041 $message->subject
= $subject;
3042 $message->fullmessage
= $body;
3043 $message->fullmessageformat
= FORMAT_MARKDOWN
;
3044 $message->fullmessagehtml
= markdown_to_html($body);
3045 $message->smallmessage
= $subject;
3046 $message->contexturlname
= $a->course
;
3047 $message->contexturl
= $a->extendurl
;
3049 if (message_send($message)) {
3050 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3052 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3055 force_current_language($oldforcelang);
3059 * Backup execution step hook to annotate custom fields.
3061 * @param backup_enrolments_execution_step $step
3062 * @param stdClass $enrol
3064 public function backup_annotate_custom_fields(backup_enrolments_execution_step
$step, stdClass
$enrol) {
3065 // Override as necessary to annotate custom fields in the enrol table.
3069 * Automatic enrol sync executed during restore.
3070 * Useful for automatic sync by course->idnumber or course category.
3071 * @param stdClass $course course record
3073 public function restore_sync_course($course) {
3074 // Override if necessary.
3078 * Restore instance and map settings.
3080 * @param restore_enrolments_structure_step $step
3081 * @param stdClass $data
3082 * @param stdClass $course
3085 public function restore_instance(restore_enrolments_structure_step
$step, stdClass
$data, $course, $oldid) {
3086 // Do not call this from overridden methods, restore and set new id there.
3087 $step->set_mapping('enrol', $oldid, 0);
3091 * Restore user enrolment.
3093 * @param restore_enrolments_structure_step $step
3094 * @param stdClass $data
3095 * @param stdClass $instance
3096 * @param int $oldinstancestatus
3097 * @param int $userid
3099 public function restore_user_enrolment(restore_enrolments_structure_step
$step, $data, $instance, $userid, $oldinstancestatus) {
3100 // Override as necessary if plugin supports restore of enrolments.
3104 * Restore role assignment.
3106 * @param stdClass $instance
3107 * @param int $roleid
3108 * @param int $userid
3109 * @param int $contextid
3111 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
3112 // No role assignment by default, override if necessary.
3116 * Restore user group membership.
3117 * @param stdClass $instance
3118 * @param int $groupid
3119 * @param int $userid
3121 public function restore_group_member($instance, $groupid, $userid) {
3122 // Implement if you want to restore protected group memberships,
3123 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
3127 * Returns defaults for new instances.
3131 public function get_instance_defaults() {
3136 * Validate a list of parameter names and types.
3139 * @param array $data array of ("fieldname"=>value) of submitted data
3140 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
3141 * @return array of "element_name"=>"error_description" if there are errors,
3142 * or an empty array if everything is OK.
3144 public function validate_param_types($data, $rules) {
3146 $invalidstr = get_string('invaliddata', 'error');
3147 foreach ($rules as $fieldname => $rule) {
3148 if (is_array($rule)) {
3149 if (!in_array($data[$fieldname], $rule)) {
3150 $errors[$fieldname] = $invalidstr;
3153 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
3154 $errors[$fieldname] = $invalidstr;