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
563 * @param array $excludecourses IDs of hidden courses to exclude from search
566 function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false,
567 $offset = 0, $excludecourses = []) {
568 global $DB, $USER, $CFG;
570 // Re-Arrange the course sorting according to the admin settings.
571 $sort = enrol_get_courses_sortingsql($sort);
573 // Guest account does not have any enrolled courses.
574 if (!$allaccessible && (isguestuser() or !isloggedin())) {
579 'id', 'category', 'sortorder',
580 'shortname', 'fullname', 'idnumber',
581 'startdate', 'visible',
582 'groupmode', 'groupmodeforce', 'cacherev',
583 'showactivitydates', 'showcompletionconditions',
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);
657 if (!empty($excludecourses)) {
658 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($excludecourses, SQL_PARAMS_NAMED
, 'param', false);
659 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
660 $params = array_merge($params, $courseidsparams);
664 // Logged-in, non-guest users get their enrolled courses.
665 if (!isguestuser() && isloggedin()) {
667 SELECT DISTINCT e.courseid
669 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid1)
670 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart <= :now1
671 AND (ue.timeend = 0 OR ue.timeend > :now2)";
672 $params['userid1'] = $USER->id
;
673 $params['active'] = ENROL_USER_ACTIVE
;
674 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
675 $params['now1'] = $params['now2'] = time();
677 if ($sorttimeaccess) {
678 $params['userid2'] = $USER->id
;
679 $timeaccessselect = ', ul.timeaccess as lastaccessed';
680 $timeaccessjoin = "LEFT JOIN {user_lastaccess} ul ON (ul.courseid = c.id AND ul.userid = :userid2)";
684 // When including non-enrolled but accessible courses...
685 if ($allaccessible) {
686 if (is_siteadmin()) {
687 // Site admins can access all courses.
688 $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
690 // If we used the enrolment as well, then this will be UNIONed.
692 $courseidsql .= " UNION ";
695 // Include courses with guest access and no password.
697 SELECT DISTINCT e.courseid
699 WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
700 $params['emptypass'] = '';
701 $params['enabled2'] = ENROL_INSTANCE_ENABLED
;
703 // Include courses where the current user is currently using guest access (may include
704 // those which require a password).
706 $accessdata = get_user_accessdata($USER->id
);
707 foreach ($accessdata['ra'] as $contextpath => $roles) {
708 if (array_key_exists($CFG->guestroleid
, $roles)) {
709 // Work out the course id from context path.
710 $context = context
::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
711 if ($context instanceof context_course
) {
712 $courseids[$context->instanceid
] = true;
717 // Include courses where the current user has moodle/course:view capability.
718 $courses = get_user_capability_course('moodle/course:view', null, false);
722 foreach ($courses as $course) {
723 $courseids[$course->id
] = true;
726 // If there are any in either category, list them individually.
728 list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
729 array_keys($courseids), SQL_PARAMS_NAMED
);
732 SELECT DISTINCT c3.id AS courseid
734 WHERE c3.id $allowedsql";
735 $params = array_merge($params, $allowedparams);
740 // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
741 // we have the subselect there.
742 $sql = "SELECT $coursefields $ccselect $timeaccessselect
744 JOIN ($courseidsql) en ON (en.courseid = c.id)
750 $courses = $DB->get_records_sql($sql, $params, $offset, $limit);
752 // preload contexts and check visibility
753 foreach ($courses as $id=>$course) {
754 context_helper
::preload_from_record($course);
755 if (!$course->visible
) {
756 if (!$context = context_course
::instance($id, IGNORE_MISSING
)) {
757 unset($courses[$id]);
760 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
761 unset($courses[$id]);
765 $courses[$id] = $course;
768 //wow! Is that really all? :-D
774 * Returns course enrolment information icons.
776 * @param object $course
777 * @param array $instances enrol instances of this course, improves performance
778 * @return array of pix_icon
780 function enrol_get_course_info_icons($course, array $instances = NULL) {
782 if (is_null($instances)) {
783 $instances = enrol_get_instances($course->id
, true);
785 $plugins = enrol_get_plugins(true);
786 foreach ($plugins as $name => $plugin) {
788 foreach ($instances as $instance) {
789 if ($instance->status
!= ENROL_INSTANCE_ENABLED
or $instance->courseid
!= $course->id
) {
790 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
793 if ($instance->enrol
== $name) {
794 $pis[$instance->id
] = $instance;
798 $icons = array_merge($icons, $plugin->get_info_icons($pis));
805 * Returns SQL ORDER arguments which reflect the admin settings to sort my courses.
807 * @param string|null $sort SQL ORDER arguments which were originally requested (optionally).
808 * @return string SQL ORDER arguments.
810 function enrol_get_courses_sortingsql($sort = null) {
813 // Prepare the visible SQL fragment as empty.
815 // Only create a visible SQL fragment if the caller didn't already pass a sort order which contains the visible field.
816 if ($sort === null ||
strpos($sort, 'visible') === false) {
817 // If the admin did not explicitly want to have shown and hidden courses sorted as one list, we will sort hidden
818 // courses to the end of the course list.
819 if (!isset($CFG->navsortmycourseshiddenlast
) ||
$CFG->navsortmycourseshiddenlast
== true) {
820 $visible = 'visible DESC, ';
824 // Only create a sortorder SQL fragment if the caller didn't already pass one.
825 if ($sort === null) {
826 // If the admin has configured a course sort order, we will use this.
827 if (!empty($CFG->navsortmycoursessort
)) {
828 $sort = $CFG->navsortmycoursessort
. ' ASC';
830 // Otherwise we will fall back to the sortorder sorting.
832 $sort = 'sortorder ASC';
836 return $visible . $sort;
840 * Returns course enrolment detailed information.
842 * @param object $course
843 * @return array of html fragments - can be used to construct lists
845 function enrol_get_course_description_texts($course) {
847 $instances = enrol_get_instances($course->id
, true);
848 $plugins = enrol_get_plugins(true);
849 foreach ($instances as $instance) {
850 if (!isset($plugins[$instance->enrol
])) {
854 $plugin = $plugins[$instance->enrol
];
855 $text = $plugin->get_description_text($instance);
856 if ($text !== NULL) {
864 * Returns list of courses user is enrolled into.
866 * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
868 * The $fields param is a list of field names to ADD so name just the fields you really need,
869 * which will be added and uniq'd.
871 * @param int $userid User whose courses are returned, defaults to the current user.
872 * @param bool $onlyactive Return only active enrolments in courses user may see.
873 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
874 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
877 function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
880 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
882 // preload contexts and check visibility
884 foreach ($courses as $id=>$course) {
885 context_helper
::preload_from_record($course);
886 if (!$course->visible
) {
887 if (!$context = context_course
::instance($id)) {
888 unset($courses[$id]);
891 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
892 unset($courses[$id]);
903 * Returns list of roles per users into course.
905 * @param int $courseid Course id.
906 * @return array Array[$userid][$roleid] = role_assignment.
908 function enrol_get_course_users_roles(int $courseid) : array {
911 $context = context_course
::instance($courseid);
915 $records = $DB->get_recordset('role_assignments', array('contextid' => $context->id
));
916 foreach ($records as $record) {
917 if (isset($roles[$record->userid
]) === false) {
918 $roles[$record->userid
] = array();
920 $roles[$record->userid
][$record->roleid
] = $record;
928 * Can user access at least one enrolled course?
930 * Cheat if necessary, but find out as fast as possible!
932 * @param int|stdClass $user null means use current user
935 function enrol_user_sees_own_courses($user = null) {
938 if ($user === null) {
941 $userid = is_object($user) ?
$user->id
: $user;
943 // Guest account does not have any courses
944 if (isguestuser($userid) or empty($userid)) {
948 // Let's cheat here if this is the current user,
949 // if user accessed any course recently, then most probably
950 // we do not need to query the database at all.
951 if ($USER->id
== $userid) {
952 if (!empty($USER->enrol
['enrolled'])) {
953 foreach ($USER->enrol
['enrolled'] as $until) {
954 if ($until > time()) {
962 $courses = enrol_get_all_users_courses($userid, true);
963 foreach($courses as $course) {
964 if ($course->visible
) {
967 context_helper
::preload_from_record($course);
968 $context = context_course
::instance($course->id
);
969 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
978 * Returns list of courses user is enrolled into without performing any capability checks.
980 * The $fields param is a list of field names to ADD so name just the fields you really need,
981 * which will be added and uniq'd.
983 * @param int $userid User whose courses are returned, defaults to the current user.
984 * @param bool $onlyactive Return only active enrolments in courses user may see.
985 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
986 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
989 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
992 // Re-Arrange the course sorting according to the admin settings.
993 $sort = enrol_get_courses_sortingsql($sort);
995 // Guest account does not have any courses
996 if (isguestuser($userid) or empty($userid)) {
1000 $basefields = array('id', 'category', 'sortorder',
1001 'shortname', 'fullname', 'idnumber',
1002 'startdate', 'visible',
1003 'defaultgroupingid',
1004 'groupmode', 'groupmodeforce');
1006 if (empty($fields)) {
1007 $fields = $basefields;
1008 } else if (is_string($fields)) {
1009 // turn the fields from a string to an array
1010 $fields = explode(',', $fields);
1011 $fields = array_map('trim', $fields);
1012 $fields = array_unique(array_merge($basefields, $fields));
1013 } else if (is_array($fields)) {
1014 $fields = array_unique(array_merge($basefields, $fields));
1016 throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
1018 if (in_array('*', $fields)) {
1019 $fields = array('*');
1023 $sort = trim($sort);
1024 if (!empty($sort)) {
1025 $rawsorts = explode(',', $sort);
1027 foreach ($rawsorts as $rawsort) {
1028 $rawsort = trim($rawsort);
1029 if (strpos($rawsort, 'c.') === 0) {
1030 $rawsort = substr($rawsort, 2);
1032 $sorts[] = trim($rawsort);
1034 $sort = 'c.'.implode(',c.', $sorts);
1035 $orderby = "ORDER BY $sort";
1038 $params = array('siteid'=>SITEID
);
1041 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
1042 $params['now1'] = round(time(), -2); // improves db caching
1043 $params['now2'] = $params['now1'];
1044 $params['active'] = ENROL_USER_ACTIVE
;
1045 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
1050 $coursefields = 'c.' .join(',c.', $fields);
1051 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1052 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1053 $params['contextlevel'] = CONTEXT_COURSE
;
1055 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
1056 $sql = "SELECT $coursefields $ccselect
1058 JOIN (SELECT DISTINCT e.courseid
1060 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
1062 ) en ON (en.courseid = c.id)
1064 WHERE c.id <> :siteid
1066 $params['userid'] = $userid;
1068 $courses = $DB->get_records_sql($sql, $params);
1076 * Called when user is about to be deleted.
1077 * @param object $user
1080 function enrol_user_delete($user) {
1083 $plugins = enrol_get_plugins(true);
1084 foreach ($plugins as $plugin) {
1085 $plugin->user_delete($user);
1088 // force cleanup of all broken enrolments
1089 $DB->delete_records('user_enrolments', array('userid'=>$user->id
));
1093 * Called when course is about to be deleted.
1094 * If a user id is passed, only enrolments that the user has permission to un-enrol will be removed,
1095 * otherwise all enrolments in the course will be removed.
1097 * @param stdClass $course
1098 * @param int|null $userid
1101 function enrol_course_delete($course, $userid = null) {
1104 $context = context_course
::instance($course->id
);
1105 $instances = enrol_get_instances($course->id
, false);
1106 $plugins = enrol_get_plugins(true);
1109 // If the user id is present, include only course enrolment instances which allow manual unenrolment and
1110 // the given user have a capability to perform unenrolment.
1111 $instances = array_filter($instances, function($instance) use ($userid, $plugins, $context) {
1112 $unenrolcap = "enrol/{$instance->enrol}:unenrol";
1113 return $plugins[$instance->enrol
]->allow_unenrol($instance) &&
1114 has_capability($unenrolcap, $context, $userid);
1118 foreach ($instances as $instance) {
1119 if (isset($plugins[$instance->enrol
])) {
1120 $plugins[$instance->enrol
]->delete_instance($instance);
1122 // low level delete in case plugin did not do it
1123 $DB->delete_records('role_assignments', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$instance->enrol
));
1124 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
1125 $DB->delete_records('enrol', array('id'=>$instance->id
));
1130 * Try to enrol user via default internal auth plugin.
1132 * For now this is always using the manual enrol plugin...
1139 * @return bool success
1141 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
1144 //note: this is hardcoded to manual plugin for now
1146 if (!enrol_is_enabled('manual')) {
1150 if (!$enrol = enrol_get_plugin('manual')) {
1153 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder,id ASC')) {
1156 $instance = reset($instances);
1158 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
1164 * Is there a chance users might self enrol
1165 * @param int $courseid
1168 function enrol_selfenrol_available($courseid) {
1171 $plugins = enrol_get_plugins(true);
1172 $enrolinstances = enrol_get_instances($courseid, true);
1173 foreach($enrolinstances as $instance) {
1174 if (!isset($plugins[$instance->enrol
])) {
1177 if ($instance->enrol
=== 'guest') {
1180 if ($plugins[$instance->enrol
]->show_enrolme_link($instance)) {
1190 * This function returns the end of current active user enrolment.
1192 * It deals correctly with multiple overlapping user enrolments.
1194 * @param int $courseid
1195 * @param int $userid
1196 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
1198 function enrol_get_enrolment_end($courseid, $userid) {
1202 FROM {user_enrolments} ue
1203 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1204 JOIN {user} u ON u.id = ue.userid
1205 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1206 $params = array('enabled'=>ENROL_INSTANCE_ENABLED
, 'active'=>ENROL_USER_ACTIVE
, 'userid'=>$userid, 'courseid'=>$courseid);
1208 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1214 foreach ($enrolments as $ue) {
1215 $start = (int)$ue->timestart
;
1216 $end = (int)$ue->timeend
;
1217 if ($end != 0 and $end < $start) {
1218 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id
);
1221 if (isset($changes[$start])) {
1222 $changes[$start] = $changes[$start] +
1;
1224 $changes[$start] = 1;
1228 } else if (isset($changes[$end])) {
1229 $changes[$end] = $changes[$end] - 1;
1231 $changes[$end] = -1;
1235 // let's sort then enrolment starts&ends and go through them chronologically,
1236 // looking for current status and the next future end of enrolment
1243 foreach ($changes as $time => $change) {
1245 if ($present === null) {
1246 // we have just went past current time
1247 $present = $current;
1249 // no enrolment active
1253 if ($present !== null) {
1254 // we are already in the future - look for possible end
1255 if ($current +
$change < 1) {
1260 $current +
= $change;
1271 * Is current user accessing course via this enrolment method?
1273 * This is intended for operations that are going to affect enrol instances.
1275 * @param stdClass $instance enrol instance
1278 function enrol_accessing_via_instance(stdClass
$instance) {
1281 if (empty($instance->id
)) {
1285 if (is_siteadmin()) {
1286 // Admins may go anywhere.
1290 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id
, 'enrolid'=>$instance->id
));
1294 * Returns true if user is enrolled (is participating) in course
1295 * this is intended for students and teachers.
1297 * Since 2.2 the result for active enrolments and current user are cached.
1299 * @param context $context
1300 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1301 * @param string $withcapability extra capability name
1302 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1305 function is_enrolled(context
$context, $user = null, $withcapability = '', $onlyactive = false) {
1308 // First find the course context.
1309 $coursecontext = $context->get_course_context();
1311 // Make sure there is a real user specified.
1312 if ($user === null) {
1313 $userid = isset($USER->id
) ?
$USER->id
: 0;
1315 $userid = is_object($user) ?
$user->id
: $user;
1318 if (empty($userid)) {
1321 } else if (isguestuser($userid)) {
1322 // Guest account can not be enrolled anywhere.
1326 // Note everybody participates on frontpage, so for other contexts...
1327 if ($coursecontext->instanceid
!= SITEID
) {
1328 // Try cached info first - the enrolled flag is set only when active enrolment present.
1329 if ($USER->id
== $userid) {
1330 $coursecontext->reload_if_dirty();
1331 if (isset($USER->enrol
['enrolled'][$coursecontext->instanceid
])) {
1332 if ($USER->enrol
['enrolled'][$coursecontext->instanceid
] > time()) {
1333 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1342 // Look for active enrolments only.
1343 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $userid);
1345 if ($until === false) {
1349 if ($USER->id
== $userid) {
1351 $until = ENROL_MAX_TIMESTAMP
;
1353 $USER->enrol
['enrolled'][$coursecontext->instanceid
] = $until;
1354 if (isset($USER->enrol
['tempguest'][$coursecontext->instanceid
])) {
1355 unset($USER->enrol
['tempguest'][$coursecontext->instanceid
]);
1356 remove_temp_course_roles($coursecontext);
1361 // Any enrolment is good for us here, even outdated, disabled or inactive.
1363 FROM {user_enrolments} ue
1364 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1365 JOIN {user} u ON u.id = ue.userid
1366 WHERE ue.userid = :userid AND u.deleted = 0";
1367 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid
);
1368 if (!$DB->record_exists_sql($sql, $params)) {
1374 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1382 * Returns an array of joins, wheres and params that will limit the group of
1383 * users to only those enrolled and with given capability (if specified).
1385 * Note this join will return duplicate rows for users who have been enrolled
1386 * several times (e.g. as manual enrolment, and as self enrolment). You may
1387 * need to use a SELECT DISTINCT in your query (see get_enrolled_sql for example).
1389 * In case is guaranteed some of the joins never match any rows, the resulting
1390 * join_sql->cannotmatchanyrows will be true. This happens when the capability
1393 * @param context $context
1394 * @param string $prefix optional, a prefix to the user id column
1395 * @param string|array $capability optional, may include a capability name, or array of names.
1396 * If an array is provided then this is the equivalent of a logical 'OR',
1397 * i.e. the user needs to have one of these capabilities.
1398 * @param int $group optional, 0 indicates no current group and USERSWITHOUTGROUP users without any group; otherwise the group id
1399 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1400 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1401 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1402 * @return \core\dml\sql_join Contains joins, wheres, params and cannotmatchanyrows
1404 function get_enrolled_with_capabilities_join(context
$context, $prefix = '', $capability = '', $group = 0,
1405 $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1406 $uid = $prefix . 'u.id';
1409 $cannotmatchanyrows = false;
1411 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended, $enrolid);
1412 $joins[] = $enrolledjoin->joins
;
1413 $wheres[] = $enrolledjoin->wheres
;
1414 $params = $enrolledjoin->params
;
1415 $cannotmatchanyrows = $cannotmatchanyrows ||
$enrolledjoin->cannotmatchanyrows
;
1417 if (!empty($capability)) {
1418 $capjoin = get_with_capability_join($context, $capability, $uid);
1419 $joins[] = $capjoin->joins
;
1420 $wheres[] = $capjoin->wheres
;
1421 $params = array_merge($params, $capjoin->params
);
1422 $cannotmatchanyrows = $cannotmatchanyrows ||
$capjoin->cannotmatchanyrows
;
1426 $groupjoin = groups_get_members_join($group, $uid, $context);
1427 $joins[] = $groupjoin->joins
;
1428 $params = array_merge($params, $groupjoin->params
);
1429 if (!empty($groupjoin->wheres
)) {
1430 $wheres[] = $groupjoin->wheres
;
1432 $cannotmatchanyrows = $cannotmatchanyrows ||
$groupjoin->cannotmatchanyrows
;
1435 $joins = implode("\n", $joins);
1436 $wheres[] = "{$prefix}u.deleted = 0";
1437 $wheres = implode(" AND ", $wheres);
1439 return new \core\dml\
sql_join($joins, $wheres, $params, $cannotmatchanyrows);
1443 * Returns array with sql code and parameters returning all ids
1444 * of users enrolled into course.
1446 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1448 * @param context $context
1449 * @param string $withcapability
1450 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1451 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1452 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1453 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1454 * @return array list($sql, $params)
1456 function get_enrolled_sql(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false,
1459 // Use unique prefix just in case somebody makes some SQL magic with the result.
1462 $prefix = 'eu' . $i . '_';
1464 $capjoin = get_enrolled_with_capabilities_join(
1465 $context, $prefix, $withcapability, $groupid, $onlyactive, $onlysuspended, $enrolid);
1467 $sql = "SELECT DISTINCT {$prefix}u.id
1468 FROM {user} {$prefix}u
1470 WHERE $capjoin->wheres";
1472 return array($sql, $capjoin->params
);
1476 * Returns array with sql joins and parameters returning all ids
1477 * of users enrolled into course.
1479 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1481 * @throws coding_exception
1483 * @param context $context
1484 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1485 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1486 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1487 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1488 * @return \core\dml\sql_join Contains joins, wheres, params
1490 function get_enrolled_join(context
$context, $useridcolumn, $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1491 // Use unique prefix just in case somebody makes some SQL magic with the result.
1494 $prefix = 'ej' . $i . '_';
1496 // First find the course context.
1497 $coursecontext = $context->get_course_context();
1499 $isfrontpage = ($coursecontext->instanceid
== SITEID
);
1501 if ($onlyactive && $onlysuspended) {
1502 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1504 if ($isfrontpage && $onlysuspended) {
1505 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1512 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1514 // Note all users are "enrolled" on the frontpage, but for others...
1515 if (!$isfrontpage) {
1516 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1517 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1519 $enrolconditions = array(
1520 "{$prefix}e.id = {$prefix}ue.enrolid",
1521 "{$prefix}e.courseid = :{$prefix}courseid",
1524 $enrolconditions[] = "{$prefix}e.id = :{$prefix}enrolid";
1525 $params[$prefix . 'enrolid'] = $enrolid;
1527 $enrolconditionssql = implode(" AND ", $enrolconditions);
1528 $ejoin = "JOIN {enrol} {$prefix}e ON ($enrolconditionssql)";
1530 $params[$prefix.'courseid'] = $coursecontext->instanceid
;
1532 if (!$onlysuspended) {
1533 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1536 $wheres[] = "$where1 AND $where2";
1539 // Suspended only where there is enrolment but ALL are suspended.
1540 // Consider multiple enrols where one is not suspended or plain role_assign.
1541 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1542 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1543 $enrolconditions = array(
1544 "{$prefix}e1.id = {$prefix}ue1.enrolid",
1545 "{$prefix}e1.courseid = :{$prefix}_e1_courseid",
1548 $enrolconditions[] = "{$prefix}e1.id = :{$prefix}e1_enrolid";
1549 $params[$prefix . 'e1_enrolid'] = $enrolid;
1551 $enrolconditionssql = implode(" AND ", $enrolconditions);
1552 $joins[] = "JOIN {enrol} {$prefix}e1 ON ($enrolconditionssql)";
1553 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid
;
1554 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1557 if ($onlyactive ||
$onlysuspended) {
1558 $now = round(time(), -2); // Rounding helps caching in DB.
1559 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED
,
1560 $prefix . 'active' => ENROL_USER_ACTIVE
,
1561 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1565 $joins = implode("\n", $joins);
1566 $wheres = implode(" AND ", $wheres);
1568 return new \core\dml\
sql_join($joins, $wheres, $params);
1572 * Returns list of users enrolled into course.
1574 * @param context $context
1575 * @param string $withcapability
1576 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1577 * @param string $userfields requested user record fields
1578 * @param string $orderby
1579 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1580 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1581 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1582 * @return array of user records
1584 function get_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1585 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1588 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1589 $sql = "SELECT $userfields
1591 JOIN ($esql) je ON je.id = u.id
1592 WHERE u.deleted = 0";
1595 $sql = "$sql ORDER BY $orderby";
1597 list($sort, $sortparams) = users_order_by_sql('u');
1598 $sql = "$sql ORDER BY $sort";
1599 $params = array_merge($params, $sortparams);
1602 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1606 * Counts list of users enrolled into course (as per above function)
1608 * @param context $context
1609 * @param string $withcapability
1610 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1611 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1612 * @return array of user records
1614 function count_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1617 $capjoin = get_enrolled_with_capabilities_join(
1618 $context, '', $withcapability, $groupid, $onlyactive);
1620 $sql = "SELECT COUNT(DISTINCT u.id)
1623 WHERE $capjoin->wheres AND u.deleted = 0";
1625 return $DB->count_records_sql($sql, $capjoin->params
);
1629 * Send welcome email "from" options.
1631 * @return array list of from options
1633 function enrol_send_welcome_email_options() {
1635 ENROL_DO_NOT_SEND_EMAIL
=> get_string('no'),
1636 ENROL_SEND_EMAIL_FROM_COURSE_CONTACT
=> get_string('sendfromcoursecontact', 'enrol'),
1637 ENROL_SEND_EMAIL_FROM_KEY_HOLDER
=> get_string('sendfromkeyholder', 'enrol'),
1638 ENROL_SEND_EMAIL_FROM_NOREPLY
=> get_string('sendfromnoreply', 'enrol')
1643 * Serve the user enrolment form as a fragment.
1645 * @param array $args List of named arguments for the fragment loader.
1648 function enrol_output_fragment_user_enrolment_form($args) {
1651 $args = (object) $args;
1652 $context = $args->context
;
1653 require_capability('moodle/course:enrolreview', $context);
1655 $ueid = $args->ueid
;
1656 $userenrolment = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST
);
1657 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid
], '*', MUST_EXIST
);
1658 $plugin = enrol_get_plugin($instance->enrol
);
1660 'ue' => $userenrolment,
1662 'enrolinstancename' => $plugin->get_instance_name($instance)
1665 // Set the data if applicable.
1667 if (isset($args->formdata
)) {
1668 $serialiseddata = json_decode($args->formdata
);
1669 parse_str($serialiseddata, $data);
1672 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1673 $mform = new \
enrol_user_enrolment_form(null, $customdata, 'post', '', null, true, $data);
1675 if (!empty($data)) {
1676 $mform->set_data($data);
1677 $mform->is_validated();
1680 return $mform->render();
1684 * Returns the course where a user enrolment belong to.
1686 * @param int $ueid user_enrolments id
1689 function enrol_get_course_by_user_enrolment_id($ueid) {
1691 $sql = "SELECT c.* FROM {user_enrolments} ue
1692 JOIN {enrol} e ON e.id = ue.enrolid
1693 JOIN {course} c ON c.id = e.courseid
1694 WHERE ue.id = :ueid";
1695 return $DB->get_record_sql($sql, array('ueid' => $ueid));
1699 * Return all users enrolled in a course.
1701 * @param int $courseid Course id or false if using $uefilter (user enrolment ids may belong to different courses)
1702 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1703 * @param array $usersfilter Limit the results obtained to this list of user ids. $uefilter compatibility not guaranteed.
1704 * @param array $uefilter Limit the results obtained to this list of user enrolment ids. $usersfilter compatibility not guaranteed.
1705 * @return stdClass[]
1707 function enrol_get_course_users($courseid = false, $onlyactive = false, $usersfilter = array(), $uefilter = array()) {
1710 if (!$courseid && !$usersfilter && !$uefilter) {
1711 throw new \
coding_exception('You should specify at least 1 filter: courseid, users or user enrolments');
1714 $sql = "SELECT ue.id AS ueid, ue.status AS uestatus, ue.enrolid AS ueenrolid, ue.timestart AS uetimestart,
1715 ue.timeend AS uetimeend, ue.modifierid AS uemodifierid, ue.timecreated AS uetimecreated,
1716 ue.timemodified AS uetimemodified, e.status AS estatus,
1717 u.* FROM {user_enrolments} ue
1718 JOIN {enrol} e ON e.id = ue.enrolid
1719 JOIN {user} u ON ue.userid = u.id
1724 $conditions[] = "e.courseid = :courseid";
1725 $params['courseid'] = $courseid;
1729 $conditions[] = "ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND " .
1730 "(ue.timeend = 0 OR ue.timeend > :now2)";
1731 // Improves db caching.
1732 $params['now1'] = round(time(), -2);
1733 $params['now2'] = $params['now1'];
1734 $params['active'] = ENROL_USER_ACTIVE
;
1735 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
1739 list($usersql, $userparams) = $DB->get_in_or_equal($usersfilter, SQL_PARAMS_NAMED
);
1740 $conditions[] = "ue.userid $usersql";
1741 $params = $params +
$userparams;
1745 list($uesql, $ueparams) = $DB->get_in_or_equal($uefilter, SQL_PARAMS_NAMED
);
1746 $conditions[] = "ue.id $uesql";
1747 $params = $params +
$ueparams;
1750 return $DB->get_records_sql($sql . ' ' . implode(' AND ', $conditions), $params);
1754 * Get the list of options for the enrolment period dropdown
1756 * @return array List of options for the enrolment period dropdown
1758 function enrol_get_period_list() {
1760 $periodmenu[''] = get_string('unlimited');
1761 for ($i = 1; $i <= 365; $i++
) {
1762 $seconds = $i * DAYSECS
;
1763 $periodmenu[$seconds] = get_string('numdays', '', $i);
1769 * Calculate duration base on start time and end time
1771 * @param int $timestart Time start
1772 * @param int $timeend Time end
1773 * @return float|int Calculated duration
1775 function enrol_calculate_duration($timestart, $timeend) {
1776 $duration = floor(($timeend - $timestart) / DAYSECS
) * DAYSECS
;
1781 * Enrolment plugins abstract class.
1783 * All enrol plugins should be based on this class,
1784 * this is also the main source of documentation.
1786 * @copyright 2010 Petr Skoda {@link http://skodak.org}
1787 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1789 abstract class enrol_plugin
{
1790 protected $config = null;
1793 * Returns name of this enrol plugin
1796 public function get_name() {
1797 // second word in class is always enrol name, sorry, no fancy plugin names with _
1798 $words = explode('_', get_class($this));
1803 * Returns localised name of enrol instance
1805 * @param object $instance (null is accepted too)
1808 public function get_instance_name($instance) {
1809 if (empty($instance->name
)) {
1810 $enrol = $this->get_name();
1811 return get_string('pluginname', 'enrol_'.$enrol);
1813 $context = context_course
::instance($instance->courseid
);
1814 return format_string($instance->name
, true, array('context'=>$context));
1819 * Returns optional enrolment information icons.
1821 * This is used in course list for quick overview of enrolment options.
1823 * We are not using single instance parameter because sometimes
1824 * we might want to prevent icon repetition when multiple instances
1825 * of one type exist. One instance may also produce several icons.
1827 * @param array $instances all enrol instances of this type in one course
1828 * @return array of pix_icon
1830 public function get_info_icons(array $instances) {
1835 * Returns optional enrolment instance description text.
1837 * This is used in detailed course information.
1840 * @param object $instance
1841 * @return string short html text
1843 public function get_description_text($instance) {
1848 * Makes sure config is loaded and cached.
1851 protected function load_config() {
1852 if (!isset($this->config
)) {
1853 $name = $this->get_name();
1854 $this->config
= get_config("enrol_$name");
1859 * Returns plugin config value
1860 * @param string $name
1861 * @param string $default value if config does not exist yet
1862 * @return string value or default
1864 public function get_config($name, $default = NULL) {
1865 $this->load_config();
1866 return isset($this->config
->$name) ?
$this->config
->$name : $default;
1870 * Sets plugin config value
1871 * @param string $name name of config
1872 * @param string $value string config value, null means delete
1873 * @return string value
1875 public function set_config($name, $value) {
1876 $pluginname = $this->get_name();
1877 $this->load_config();
1878 if ($value === NULL) {
1879 unset($this->config
->$name);
1881 $this->config
->$name = $value;
1883 set_config($name, $value, "enrol_$pluginname");
1887 * Does this plugin assign protected roles are can they be manually removed?
1888 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1890 public function roles_protected() {
1895 * Does this plugin allow manual enrolments?
1897 * @param stdClass $instance course enrol instance
1898 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1900 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1902 public function allow_enrol(stdClass
$instance) {
1907 * Does this plugin allow manual unenrolment of all users?
1908 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1910 * @param stdClass $instance course enrol instance
1911 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1913 public function allow_unenrol(stdClass
$instance) {
1918 * Does this plugin allow manual unenrolment of a specific user?
1919 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1921 * This is useful especially for synchronisation plugins that
1922 * do suspend instead of full unenrolment.
1924 * @param stdClass $instance course enrol instance
1925 * @param stdClass $ue record from user_enrolments table, specifies user
1927 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1929 public function allow_unenrol_user(stdClass
$instance, stdClass
$ue) {
1930 return $this->allow_unenrol($instance);
1934 * Does this plugin allow manual changes in user_enrolments table?
1936 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1938 * @param stdClass $instance course enrol instance
1939 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1941 public function allow_manage(stdClass
$instance) {
1946 * Does this plugin support some way to user to self enrol?
1948 * @param stdClass $instance course enrol instance
1950 * @return bool - true means show "Enrol me in this course" link in course UI
1952 public function show_enrolme_link(stdClass
$instance) {
1957 * Attempt to automatically enrol current user in course without any interaction,
1958 * calling code has to make sure the plugin and instance are active.
1960 * This should return either a timestamp in the future or false.
1962 * @param stdClass $instance course enrol instance
1963 * @return bool|int false means not enrolled, integer means timeend
1965 public function try_autoenrol(stdClass
$instance) {
1972 * Attempt to automatically gain temporary guest access to course,
1973 * calling code has to make sure the plugin and instance are active.
1975 * This should return either a timestamp in the future or false.
1977 * @param stdClass $instance course enrol instance
1978 * @return bool|int false means no guest access, integer means timeend
1980 public function try_guestaccess(stdClass
$instance) {
1987 * Enrol user into course via enrol instance.
1989 * @param stdClass $instance
1990 * @param int $userid
1991 * @param int $roleid optional role id
1992 * @param int $timestart 0 means unknown
1993 * @param int $timeend 0 means forever
1994 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
1995 * @param bool $recovergrades restore grade history
1998 public function enrol_user(stdClass
$instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
1999 global $DB, $USER, $CFG; // CFG necessary!!!
2001 if ($instance->courseid
== SITEID
) {
2002 throw new coding_exception('invalid attempt to enrol into frontpage course!');
2005 $name = $this->get_name();
2006 $courseid = $instance->courseid
;
2008 if ($instance->enrol
!== $name) {
2009 throw new coding_exception('invalid enrol instance!');
2011 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
2012 if (!isset($recovergrades)) {
2013 $recovergrades = $CFG->recovergradesdefault
;
2018 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
2019 //only update if timestart or timeend or status are different.
2020 if ($ue->timestart
!= $timestart or $ue->timeend
!= $timeend or (!is_null($status) and $ue->status
!= $status)) {
2021 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
2024 $ue = new stdClass();
2025 $ue->enrolid
= $instance->id
;
2026 $ue->status
= is_null($status) ? ENROL_USER_ACTIVE
: $status;
2027 $ue->userid
= $userid;
2028 $ue->timestart
= $timestart;
2029 $ue->timeend
= $timeend;
2030 $ue->modifierid
= $USER->id
;
2031 $ue->timecreated
= time();
2032 $ue->timemodified
= $ue->timecreated
;
2033 $ue->id
= $DB->insert_record('user_enrolments', $ue);
2040 $event = \core\event\user_enrolment_created
::create(
2042 'objectid' => $ue->id
,
2043 'courseid' => $courseid,
2044 'context' => $context,
2045 'relateduserid' => $ue->userid
,
2046 'other' => array('enrol' => $name)
2050 // Check if course contacts cache needs to be cleared.
2051 core_course_category
::user_enrolment_changed($courseid, $ue->userid
,
2052 $ue->status
, $ue->timestart
, $ue->timeend
);
2056 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
2057 if ($this->roles_protected()) {
2058 role_assign($roleid, $userid, $context->id
, 'enrol_'.$name, $instance->id
);
2060 role_assign($roleid, $userid, $context->id
);
2064 // Recover old grades if present.
2065 if ($recovergrades) {
2066 require_once("$CFG->libdir/gradelib.php");
2067 grade_recover_history_grades($userid, $courseid);
2070 // reset current user enrolment caching
2071 if ($userid == $USER->id
) {
2072 if (isset($USER->enrol
['enrolled'][$courseid])) {
2073 unset($USER->enrol
['enrolled'][$courseid]);
2075 if (isset($USER->enrol
['tempguest'][$courseid])) {
2076 unset($USER->enrol
['tempguest'][$courseid]);
2077 remove_temp_course_roles($context);
2083 * Store user_enrolments changes and trigger event.
2085 * @param stdClass $instance
2086 * @param int $userid
2087 * @param int $status
2088 * @param int $timestart
2089 * @param int $timeend
2092 public function update_user_enrol(stdClass
$instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
2093 global $DB, $USER, $CFG;
2095 $name = $this->get_name();
2097 if ($instance->enrol
!== $name) {
2098 throw new coding_exception('invalid enrol instance!');
2101 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
2102 // weird, user not enrolled
2107 if (isset($status) and $ue->status
!= $status) {
2108 $ue->status
= $status;
2111 if (isset($timestart) and $ue->timestart
!= $timestart) {
2112 $ue->timestart
= $timestart;
2115 if (isset($timeend) and $ue->timeend
!= $timeend) {
2116 $ue->timeend
= $timeend;
2125 $ue->modifierid
= $USER->id
;
2126 $ue->timemodified
= time();
2127 $DB->update_record('user_enrolments', $ue);
2129 // User enrolments have changed, so mark user as dirty.
2130 mark_user_dirty($userid);
2132 // Invalidate core_access cache for get_suspended_userids.
2133 cache_helper
::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid
));
2136 $event = \core\event\user_enrolment_updated
::create(
2138 'objectid' => $ue->id
,
2139 'courseid' => $instance->courseid
,
2140 'context' => context_course
::instance($instance->courseid
),
2141 'relateduserid' => $ue->userid
,
2142 'other' => array('enrol' => $name)
2147 core_course_category
::user_enrolment_changed($instance->courseid
, $ue->userid
,
2148 $ue->status
, $ue->timestart
, $ue->timeend
);
2152 * Unenrol user from course,
2153 * the last unenrolment removes all remaining roles.
2155 * @param stdClass $instance
2156 * @param int $userid
2159 public function unenrol_user(stdClass
$instance, $userid) {
2160 global $CFG, $USER, $DB;
2161 require_once("$CFG->dirroot/group/lib.php");
2163 $name = $this->get_name();
2164 $courseid = $instance->courseid
;
2166 if ($instance->enrol
!== $name) {
2167 throw new coding_exception('invalid enrol instance!');
2169 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
2171 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
2172 // weird, user not enrolled
2176 // Remove all users groups linked to this enrolment instance.
2177 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
))) {
2178 foreach ($gms as $gm) {
2179 groups_remove_member($gm->groupid
, $gm->userid
);
2183 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id
, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
));
2184 $DB->delete_records('user_enrolments', array('id'=>$ue->id
));
2186 // add extra info and trigger event
2187 $ue->courseid
= $courseid;
2191 FROM {user_enrolments} ue
2192 JOIN {enrol} e ON (e.id = ue.enrolid)
2193 WHERE ue.userid = :userid AND e.courseid = :courseid";
2194 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
2195 $ue->lastenrol
= false;
2198 // the big cleanup IS necessary!
2199 require_once("$CFG->libdir/gradelib.php");
2201 // remove all remaining roles
2202 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id
), true, false);
2204 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
2205 groups_delete_group_members($courseid, $userid);
2207 grade_user_unenrol($courseid, $userid);
2209 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
2211 $ue->lastenrol
= true; // means user not enrolled any more
2214 $event = \core\event\user_enrolment_deleted
::create(
2216 'courseid' => $courseid,
2217 'context' => $context,
2218 'relateduserid' => $ue->userid
,
2219 'objectid' => $ue->id
,
2221 'userenrolment' => (array)$ue,
2228 // User enrolments have changed, so mark user as dirty.
2229 mark_user_dirty($userid);
2231 // Check if courrse contacts cache needs to be cleared.
2232 core_course_category
::user_enrolment_changed($courseid, $ue->userid
, ENROL_USER_SUSPENDED
);
2234 // reset current user enrolment caching
2235 if ($userid == $USER->id
) {
2236 if (isset($USER->enrol
['enrolled'][$courseid])) {
2237 unset($USER->enrol
['enrolled'][$courseid]);
2239 if (isset($USER->enrol
['tempguest'][$courseid])) {
2240 unset($USER->enrol
['tempguest'][$courseid]);
2241 remove_temp_course_roles($context);
2247 * Forces synchronisation of user enrolments.
2249 * This is important especially for external enrol plugins,
2250 * this function is called for all enabled enrol plugins
2251 * right after every user login.
2253 * @param object $user user record
2256 public function sync_user_enrolments($user) {
2257 // override if necessary
2261 * This returns false for backwards compatibility, but it is really recommended.
2266 public function use_standard_editing_ui() {
2271 * Return whether or not, given the current state, it is possible to add a new instance
2272 * of this enrolment plugin to the course.
2274 * Default implementation is just for backwards compatibility.
2276 * @param int $courseid
2279 public function can_add_instance($courseid) {
2280 $link = $this->get_newinstance_link($courseid);
2281 return !empty($link);
2285 * Return whether or not, given the current state, it is possible to edit an instance
2286 * of this enrolment plugin in the course. Used by the standard editing UI
2287 * to generate a link to the edit instance form if editing is allowed.
2289 * @param stdClass $instance
2292 public function can_edit_instance($instance) {
2293 $context = context_course
::instance($instance->courseid
);
2295 return has_capability('enrol/' . $instance->enrol
. ':config', $context);
2299 * Returns link to page which may be used to add new instance of enrolment plugin in course.
2300 * @param int $courseid
2301 * @return moodle_url page url
2303 public function get_newinstance_link($courseid) {
2304 // override for most plugins, check if instance already exists in cases only one instance is supported
2309 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
2311 public function instance_deleteable($instance) {
2312 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
2313 enrol_plugin::can_delete_instance() instead');
2317 * Is it possible to delete enrol instance via standard UI?
2319 * @param stdClass $instance
2322 public function can_delete_instance($instance) {
2327 * Is it possible to hide/show enrol instance via standard UI?
2329 * @param stdClass $instance
2332 public function can_hide_show_instance($instance) {
2333 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER
);
2338 * Returns link to manual enrol UI if exists.
2339 * Does the access control tests automatically.
2341 * @param object $instance
2342 * @return moodle_url
2344 public function get_manual_enrol_link($instance) {
2349 * Returns list of unenrol links for all enrol instances in course.
2351 * @param int $instance
2352 * @return moodle_url or NULL if self unenrolment not supported
2354 public function get_unenrolself_link($instance) {
2355 global $USER, $CFG, $DB;
2357 $name = $this->get_name();
2358 if ($instance->enrol
!== $name) {
2359 throw new coding_exception('invalid enrol instance!');
2362 if ($instance->courseid
== SITEID
) {
2366 if (!enrol_is_enabled($name)) {
2370 if ($instance->status
!= ENROL_INSTANCE_ENABLED
) {
2374 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2378 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
2380 if (!has_capability("enrol/$name:unenrolself", $context)) {
2384 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$USER->id
, 'status'=>ENROL_USER_ACTIVE
))) {
2388 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id
));
2392 * Adds enrol instance UI to course edit form
2394 * @param object $instance enrol instance or null if does not exist yet
2395 * @param MoodleQuickForm $mform
2396 * @param object $data
2397 * @param object $context context of existing course or parent category if course does not exist
2400 public function course_edit_form($instance, MoodleQuickForm
$mform, $data, $context) {
2401 // override - usually at least enable/disable switch, has to add own form header
2405 * Adds form elements to add/edit instance form.
2408 * @param object $instance enrol instance or null if does not exist yet
2409 * @param MoodleQuickForm $mform
2410 * @param context $context
2413 public function edit_instance_form($instance, MoodleQuickForm
$mform, $context) {
2414 // Do nothing by default.
2418 * Perform custom validation of the data used to edit the instance.
2421 * @param array $data array of ("fieldname"=>value) of submitted data
2422 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2423 * @param object $instance The instance data loaded from the DB.
2424 * @param context $context The context of the instance we are editing
2425 * @return array of "element_name"=>"error_description" if there are errors,
2426 * or an empty array if everything is OK.
2428 public function edit_instance_validation($data, $files, $instance, $context) {
2429 // No errors by default.
2430 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER
);
2435 * Validates course edit form data
2437 * @param object $instance enrol instance or null if does not exist yet
2438 * @param array $data
2439 * @param object $context context of existing course or parent category if course does not exist
2440 * @return array errors array
2442 public function course_edit_validation($instance, array $data, $context) {
2447 * Called after updating/inserting course.
2449 * @param bool $inserted true if course just inserted
2450 * @param object $course
2451 * @param object $data form data
2454 public function course_updated($inserted, $course, $data) {
2456 if ($this->get_config('defaultenrol')) {
2457 $this->add_default_instance($course);
2463 * Add new instance of enrol plugin.
2464 * @param object $course
2465 * @param array instance fields
2466 * @return int id of new instance, null if can not be created
2468 public function add_instance($course, array $fields = NULL) {
2471 if ($course->id
== SITEID
) {
2472 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2475 $instance = new stdClass();
2476 $instance->enrol
= $this->get_name();
2477 $instance->status
= ENROL_INSTANCE_ENABLED
;
2478 $instance->courseid
= $course->id
;
2479 $instance->enrolstartdate
= 0;
2480 $instance->enrolenddate
= 0;
2481 $instance->timemodified
= time();
2482 $instance->timecreated
= $instance->timemodified
;
2483 $instance->sortorder
= $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id
));
2485 $fields = (array)$fields;
2486 unset($fields['enrol']);
2487 unset($fields['courseid']);
2488 unset($fields['sortorder']);
2489 foreach($fields as $field=>$value) {
2490 $instance->$field = $value;
2493 $instance->id
= $DB->insert_record('enrol', $instance);
2495 \core\event\enrol_instance_created
::create_from_record($instance)->trigger();
2497 return $instance->id
;
2501 * Update instance of enrol plugin.
2504 * @param stdClass $instance
2505 * @param stdClass $data modified instance fields
2508 public function update_instance($instance, $data) {
2510 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2511 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2512 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2513 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2514 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2515 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2517 foreach ($properties as $key) {
2518 if (isset($data->$key)) {
2519 $instance->$key = $data->$key;
2522 $instance->timemodified
= time();
2524 $update = $DB->update_record('enrol', $instance);
2526 \core\event\enrol_instance_updated
::create_from_record($instance)->trigger();
2532 * Add new instance of enrol plugin with default settings,
2533 * called when adding new instance manually or when adding new course.
2535 * Not all plugins support this.
2537 * @param object $course
2538 * @return int id of new instance or null if no default supported
2540 public function add_default_instance($course) {
2545 * Update instance status
2547 * Override when plugin needs to do some action when enabled or disabled.
2549 * @param stdClass $instance
2550 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2553 public function update_status($instance, $newstatus) {
2556 $instance->status
= $newstatus;
2557 $DB->update_record('enrol', $instance);
2559 $context = context_course
::instance($instance->courseid
);
2560 \core\event\enrol_instance_updated
::create_from_record($instance)->trigger();
2562 // Invalidate all enrol caches.
2563 $context->mark_dirty();
2567 * Delete course enrol plugin instance, unenrol all users.
2568 * @param object $instance
2571 public function delete_instance($instance) {
2574 $name = $this->get_name();
2575 if ($instance->enrol
!== $name) {
2576 throw new coding_exception('invalid enrol instance!');
2579 //first unenrol all users
2580 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id
));
2581 foreach ($participants as $participant) {
2582 $this->unenrol_user($instance, $participant->userid
);
2584 $participants->close();
2586 // now clean up all remainders that were not removed correctly
2587 if ($gms = $DB->get_records('groups_members', array('itemid' => $instance->id
, 'component' => 'enrol_' . $name))) {
2588 foreach ($gms as $gm) {
2589 groups_remove_member($gm->groupid
, $gm->userid
);
2592 $DB->delete_records('role_assignments', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$name));
2593 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
2595 // finally drop the enrol row
2596 $DB->delete_records('enrol', array('id'=>$instance->id
));
2598 $context = context_course
::instance($instance->courseid
);
2599 \core\event\enrol_instance_deleted
::create_from_record($instance)->trigger();
2601 // Invalidate all enrol caches.
2602 $context->mark_dirty();
2606 * Creates course enrol form, checks if form submitted
2607 * and enrols user if necessary. It can also redirect.
2609 * @param stdClass $instance
2610 * @return string html text, usually a form in a text box
2612 public function enrol_page_hook(stdClass
$instance) {
2617 * Checks if user can self enrol.
2619 * @param stdClass $instance enrolment instance
2620 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2621 * used by navigation to improve performance.
2622 * @return bool|string true if successful, else error message or false
2624 public function can_self_enrol(stdClass
$instance, $checkuserenrolment = true) {
2629 * Return information for enrolment instance containing list of parameters required
2630 * for enrolment, name of enrolment plugin etc.
2632 * @param stdClass $instance enrolment instance
2633 * @return array instance info.
2635 public function get_enrol_info(stdClass
$instance) {
2640 * Adds navigation links into course admin block.
2642 * By defaults looks for manage links only.
2644 * @param navigation_node $instancesnode
2645 * @param stdClass $instance
2648 public function add_course_navigation($instancesnode, stdClass
$instance) {
2649 if ($this->use_standard_editing_ui()) {
2650 $context = context_course
::instance($instance->courseid
);
2651 $cap = 'enrol/' . $instance->enrol
. ':config';
2652 if (has_capability($cap, $context)) {
2653 $linkparams = array('courseid' => $instance->courseid
, 'id' => $instance->id
, 'type' => $instance->enrol
);
2654 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2655 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node
::TYPE_SETTING
);
2661 * Returns edit icons for the page with list of instances
2662 * @param stdClass $instance
2665 public function get_action_icons(stdClass
$instance) {
2669 if ($this->use_standard_editing_ui()) {
2670 $linkparams = array('courseid' => $instance->courseid
, 'id' => $instance->id
, 'type' => $instance->enrol
);
2671 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2672 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2673 array('class' => 'iconsmall')));
2679 * Reads version.php and determines if it is necessary
2680 * to execute the cron job now.
2683 public function is_cron_required() {
2686 $name = $this->get_name();
2687 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2688 $plugin = new stdClass();
2689 include($versionfile);
2690 if (empty($plugin->cron
)) {
2693 $lastexecuted = $this->get_config('lastcron', 0);
2694 if ($lastexecuted +
$plugin->cron
< time()) {
2702 * Called for all enabled enrol plugins that returned true from is_cron_required().
2705 public function cron() {
2709 * Called when user is about to be deleted
2710 * @param object $user
2713 public function user_delete($user) {
2718 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2719 WHERE e.enrol = :name AND ue.userid = :userid";
2720 $params = array('name'=>$this->get_name(), 'userid'=>$user->id
);
2722 $rs = $DB->get_recordset_sql($sql, $params);
2723 foreach($rs as $instance) {
2724 $this->unenrol_user($instance, $user->id
);
2730 * Returns an enrol_user_button that takes the user to a page where they are able to
2731 * enrol users into the managers course through this plugin.
2733 * Optional: If the plugin supports manual enrolments it can choose to override this
2734 * otherwise it shouldn't
2736 * @param course_enrolment_manager $manager
2737 * @return enrol_user_button|false
2739 public function get_manual_enrol_button(course_enrolment_manager
$manager) {
2744 * Gets an array of the user enrolment actions
2746 * @param course_enrolment_manager $manager
2747 * @param stdClass $ue
2748 * @return array An array of user_enrolment_actions
2750 public function get_user_enrolment_actions(course_enrolment_manager
$manager, $ue) {
2752 $context = $manager->get_context();
2753 $instance = $ue->enrolmentinstance
;
2754 $params = $manager->get_moodlepage()->url
->params();
2755 $params['ue'] = $ue->id
;
2757 // Edit enrolment action.
2758 if ($this->allow_manage($instance) && has_capability("enrol/{$instance->enrol}:manage", $context)) {
2759 $title = get_string('editenrolment', 'enrol');
2760 $icon = new pix_icon('t/edit', $title);
2761 $url = new moodle_url('/enrol/editenrolment.php', $params);
2763 'class' => 'editenrollink',
2765 'data-action' => ENROL_ACTION_EDIT
2767 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2771 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/{$instance->enrol}:unenrol", $context)) {
2772 $title = get_string('unenrol', 'enrol');
2773 $icon = new pix_icon('t/delete', $title);
2774 $url = new moodle_url('/enrol/unenroluser.php', $params);
2776 'class' => 'unenrollink',
2778 'data-action' => ENROL_ACTION_UNENROL
2780 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2786 * Returns true if the plugin has one or more bulk operations that can be performed on
2789 * @param course_enrolment_manager $manager
2792 public function has_bulk_operations(course_enrolment_manager
$manager) {
2797 * Return an array of enrol_bulk_enrolment_operation objects that define
2798 * the bulk actions that can be performed on user enrolments by the plugin.
2800 * @param course_enrolment_manager $manager
2803 public function get_bulk_operations(course_enrolment_manager
$manager) {
2808 * Do any enrolments need expiration processing.
2810 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2812 * @param progress_trace $trace
2813 * @param int $courseid one course, empty mean all
2814 * @return bool true if any data processed, false if not
2816 public function process_expirations(progress_trace
$trace, $courseid = null) {
2819 $name = $this->get_name();
2820 if (!enrol_is_enabled($name)) {
2829 $coursesql = "AND e.courseid = :courseid";
2832 // Deal with expired accounts.
2833 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP
);
2835 if ($action == ENROL_EXT_REMOVED_UNENROL
) {
2836 $instances = array();
2837 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2838 FROM {user_enrolments} ue
2839 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2840 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2841 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2842 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE
, 'enrol'=>$name, 'courseid'=>$courseid);
2844 $rs = $DB->get_recordset_sql($sql, $params);
2845 foreach ($rs as $ue) {
2847 $trace->output("Starting processing of enrol_$name expirations...");
2850 if (empty($instances[$ue->enrolid
])) {
2851 $instances[$ue->enrolid
] = $DB->get_record('enrol', array('id'=>$ue->enrolid
));
2853 $instance = $instances[$ue->enrolid
];
2854 if (!$this->roles_protected()) {
2855 // Let's just guess what extra roles are supposed to be removed.
2856 if ($instance->roleid
) {
2857 role_unassign($instance->roleid
, $ue->userid
, $ue->contextid
);
2860 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2861 $this->unenrol_user($instance, $ue->userid
);
2862 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2867 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES
or $action == ENROL_EXT_REMOVED_SUSPEND
) {
2868 $instances = array();
2869 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2870 FROM {user_enrolments} ue
2871 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2872 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2873 WHERE ue.timeend > 0 AND ue.timeend < :now
2874 AND ue.status = :useractive $coursesql";
2875 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE
, 'useractive'=>ENROL_USER_ACTIVE
, 'enrol'=>$name, 'courseid'=>$courseid);
2876 $rs = $DB->get_recordset_sql($sql, $params);
2877 foreach ($rs as $ue) {
2879 $trace->output("Starting processing of enrol_$name expirations...");
2882 if (empty($instances[$ue->enrolid
])) {
2883 $instances[$ue->enrolid
] = $DB->get_record('enrol', array('id'=>$ue->enrolid
));
2885 $instance = $instances[$ue->enrolid
];
2887 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES
) {
2888 if (!$this->roles_protected()) {
2889 // Let's just guess what roles should be removed.
2890 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
));
2892 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'', 'itemid'=>0));
2894 } else if ($count > 1 and $instance->roleid
) {
2895 role_unassign($instance->roleid
, $ue->userid
, $ue->contextid
, '', 0);
2898 // In any case remove all roles that belong to this instance and user.
2899 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
), true);
2900 // Final cleanup of subcontexts if there are no more course roles.
2901 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
))) {
2902 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'', 'itemid'=>0), true);
2906 $this->update_user_enrol($instance, $ue->userid
, ENROL_USER_SUSPENDED
);
2907 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2913 // ENROL_EXT_REMOVED_KEEP means no changes.
2917 $trace->output("...finished processing of enrol_$name expirations");
2919 $trace->output("No expired enrol_$name enrolments detected");
2927 * Send expiry notifications.
2929 * Plugin that wants to have expiry notification MUST implement following:
2930 * - expirynotifyhour plugin setting,
2931 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2932 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2933 * expirymessageenrolledsubject and expirymessageenrolledbody),
2934 * - expiry_notification provider in db/messages.php,
2935 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2936 * - something that calls this method, such as cron.
2938 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2940 public function send_expiry_notifications($trace) {
2943 $name = $this->get_name();
2944 if (!enrol_is_enabled($name)) {
2949 // Unfortunately this may take a long time, it should not be interrupted,
2950 // otherwise users get duplicate notification.
2952 core_php_time_limit
::raise();
2953 raise_memory_limit(MEMORY_HUGE
);
2956 $expirynotifylast = $this->get_config('expirynotifylast', 0);
2957 $expirynotifyhour = $this->get_config('expirynotifyhour');
2958 if (is_null($expirynotifyhour)) {
2959 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
2964 if (!($trace instanceof progress_trace
)) {
2965 $trace = $trace ?
new text_progress_trace() : new null_progress_trace();
2966 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER
);
2970 $notifytime = usergetmidnight($timenow, $CFG->timezone
) +
($expirynotifyhour * 3600);
2972 if ($expirynotifylast > $notifytime) {
2973 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone
).'.');
2977 } else if ($timenow < $notifytime) {
2978 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone
).'.');
2983 $trace->output('Processing '.$name.' enrolment expiration notifications...');
2985 // Notify users responsible for enrolment once every day.
2986 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
2987 FROM {user_enrolments} ue
2988 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
2989 JOIN {course} c ON (c.id = e.courseid)
2990 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
2991 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
2992 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
2993 $params = array('enabled'=>ENROL_INSTANCE_ENABLED
, 'active'=>ENROL_USER_ACTIVE
, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
2995 $rs = $DB->get_recordset_sql($sql, $params);
3000 foreach($rs as $ue) {
3001 if ($lastenrollid and $lastenrollid != $ue->enrolid
) {
3002 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3005 $lastenrollid = $ue->enrolid
;
3007 $enroller = $this->get_enroller($ue->enrolid
);
3008 $context = context_course
::instance($ue->courseid
);
3010 $user = $DB->get_record('user', array('id'=>$ue->userid
));
3012 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend
);
3014 if (!$ue->notifyall
) {
3018 if ($ue->timeend
- $ue->expirythreshold +
86400 < $timenow) {
3019 // Notify enrolled users only once at the start of the threshold.
3020 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
3024 $this->notify_expiry_enrolled($user, $ue, $trace);
3028 if ($lastenrollid and $users) {
3029 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3032 $trace->output('...notification processing finished.');
3035 $this->set_config('expirynotifylast', $timenow);
3039 * Returns the user who is responsible for enrolments for given instance.
3041 * Override if plugin knows anybody better than admin.
3043 * @param int $instanceid enrolment instance id
3044 * @return stdClass user record
3046 protected function get_enroller($instanceid) {
3051 * Notify user about incoming expiration of their enrolment,
3052 * it is called only if notification of enrolled users (aka students) is enabled in course.
3054 * This is executed only once for each expiring enrolment right
3055 * at the start of the expiration threshold.
3057 * @param stdClass $user
3058 * @param stdClass $ue
3059 * @param progress_trace $trace
3061 protected function notify_expiry_enrolled($user, $ue, progress_trace
$trace) {
3064 $name = $this->get_name();
3066 $oldforcelang = force_current_language($user->lang
);
3068 $enroller = $this->get_enroller($ue->enrolid
);
3069 $context = context_course
::instance($ue->courseid
);
3071 $a = new stdClass();
3072 $a->course
= format_string($ue->fullname
, true, array('context'=>$context));
3073 $a->user
= fullname($user, true);
3074 $a->timeend
= userdate($ue->timeend
, '', $user->timezone
);
3075 $a->enroller
= fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
3077 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
3078 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
3080 $message = new \core\message\
message();
3081 $message->courseid
= $ue->courseid
;
3082 $message->notification
= 1;
3083 $message->component
= 'enrol_'.$name;
3084 $message->name
= 'expiry_notification';
3085 $message->userfrom
= $enroller;
3086 $message->userto
= $user;
3087 $message->subject
= $subject;
3088 $message->fullmessage
= $body;
3089 $message->fullmessageformat
= FORMAT_MARKDOWN
;
3090 $message->fullmessagehtml
= markdown_to_html($body);
3091 $message->smallmessage
= $subject;
3092 $message->contexturlname
= $a->course
;
3093 $message->contexturl
= (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid
));
3095 if (message_send($message)) {
3096 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
3098 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
3101 force_current_language($oldforcelang);
3105 * Notify person responsible for enrolments that some user enrolments will be expired soon,
3106 * it is called only if notification of enrollers (aka teachers) is enabled in course.
3108 * This is called repeatedly every day for each course if there are any pending expiration
3109 * in the expiration threshold.
3112 * @param array $users
3113 * @param progress_trace $trace
3115 protected function notify_expiry_enroller($eid, $users, progress_trace
$trace) {
3118 $name = $this->get_name();
3120 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
3121 $context = context_course
::instance($instance->courseid
);
3122 $course = $DB->get_record('course', array('id'=>$instance->courseid
));
3124 $enroller = $this->get_enroller($instance->id
);
3125 $admin = get_admin();
3127 $oldforcelang = force_current_language($enroller->lang
);
3129 foreach($users as $key=>$info) {
3130 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone
);
3133 $a = new stdClass();
3134 $a->course
= format_string($course->fullname
, true, array('context'=>$context));
3135 $a->threshold
= get_string('numdays', '', $instance->expirythreshold
/ (60*60*24));
3136 $a->users
= implode("\n", $users);
3137 $a->extendurl
= (string)new moodle_url('/user/index.php', array('id'=>$instance->courseid
));
3139 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
3140 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
3142 $message = new \core\message\
message();
3143 $message->courseid
= $course->id
;
3144 $message->notification
= 1;
3145 $message->component
= 'enrol_'.$name;
3146 $message->name
= 'expiry_notification';
3147 $message->userfrom
= $admin;
3148 $message->userto
= $enroller;
3149 $message->subject
= $subject;
3150 $message->fullmessage
= $body;
3151 $message->fullmessageformat
= FORMAT_MARKDOWN
;
3152 $message->fullmessagehtml
= markdown_to_html($body);
3153 $message->smallmessage
= $subject;
3154 $message->contexturlname
= $a->course
;
3155 $message->contexturl
= $a->extendurl
;
3157 if (message_send($message)) {
3158 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3160 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3163 force_current_language($oldforcelang);
3167 * Backup execution step hook to annotate custom fields.
3169 * @param backup_enrolments_execution_step $step
3170 * @param stdClass $enrol
3172 public function backup_annotate_custom_fields(backup_enrolments_execution_step
$step, stdClass
$enrol) {
3173 // Override as necessary to annotate custom fields in the enrol table.
3177 * Automatic enrol sync executed during restore.
3178 * Useful for automatic sync by course->idnumber or course category.
3179 * @param stdClass $course course record
3181 public function restore_sync_course($course) {
3182 // Override if necessary.
3186 * Restore instance and map settings.
3188 * @param restore_enrolments_structure_step $step
3189 * @param stdClass $data
3190 * @param stdClass $course
3193 public function restore_instance(restore_enrolments_structure_step
$step, stdClass
$data, $course, $oldid) {
3194 // Do not call this from overridden methods, restore and set new id there.
3195 $step->set_mapping('enrol', $oldid, 0);
3199 * Restore user enrolment.
3201 * @param restore_enrolments_structure_step $step
3202 * @param stdClass $data
3203 * @param stdClass $instance
3204 * @param int $oldinstancestatus
3205 * @param int $userid
3207 public function restore_user_enrolment(restore_enrolments_structure_step
$step, $data, $instance, $userid, $oldinstancestatus) {
3208 // Override as necessary if plugin supports restore of enrolments.
3212 * Restore role assignment.
3214 * @param stdClass $instance
3215 * @param int $roleid
3216 * @param int $userid
3217 * @param int $contextid
3219 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
3220 // No role assignment by default, override if necessary.
3224 * Restore user group membership.
3225 * @param stdClass $instance
3226 * @param int $groupid
3227 * @param int $userid
3229 public function restore_group_member($instance, $groupid, $userid) {
3230 // Implement if you want to restore protected group memberships,
3231 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
3235 * Returns defaults for new instances.
3239 public function get_instance_defaults() {
3244 * Validate a list of parameter names and types.
3247 * @param array $data array of ("fieldname"=>value) of submitted data
3248 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
3249 * @return array of "element_name"=>"error_description" if there are errors,
3250 * or an empty array if everything is OK.
3252 public function validate_param_types($data, $rules) {
3254 $invalidstr = get_string('invaliddata', 'error');
3255 foreach ($rules as $fieldname => $rule) {
3256 if (is_array($rule)) {
3257 if (!in_array($data[$fieldname], $rule)) {
3258 $errors[$fieldname] = $invalidstr;
3261 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
3262 $errors[$fieldname] = $invalidstr;