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 // List all participants - allows assigning roles, groups, etc.
437 // Have this available even in the site context as the page is still accessible from the frontpage.
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
,
441 null, 'review', new pix_icon('i/enrolusers', ''));
444 if ($course->id
!= SITEID
) {
445 // manage enrol plugin instances
446 if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
447 $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id
));
451 $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node
::TYPE_SETTING
, null, 'manageinstances');
453 // each instance decides how to configure itself or how many other nav items are exposed
454 foreach ($instances as $instance) {
455 if (!isset($plugins[$instance->enrol
])) {
458 $plugins[$instance->enrol
]->add_course_navigation($instancesnode, $instance);
462 $instancesnode->trim_if_empty();
466 // Manage groups in this course or even frontpage
467 if (($course->groupmode ||
!$course->groupmodeforce
) && has_capability('moodle/course:managegroups', $coursecontext)) {
468 $url = new moodle_url('/group/index.php', array('id'=>$course->id
));
469 $usersnode->add(get_string('groups'), $url, navigation_node
::TYPE_SETTING
, null, 'groups', new pix_icon('i/group', ''));
472 if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
474 if (has_capability('moodle/role:review', $coursecontext)) {
475 $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id
));
479 $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'override');
481 // Add assign or override roles if allowed
482 if ($course->id
== SITEID
or (!empty($CFG->adminsassignrolesincourse
) and is_siteadmin())) {
483 if (has_capability('moodle/role:assign', $coursecontext)) {
484 $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id
));
485 $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'roles', new pix_icon('i/assignroles', ''));
488 // Check role permissions
489 if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
490 $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id
));
491 $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node
::TYPE_SETTING
, null, 'permissions', new pix_icon('i/checkpermissions', ''));
495 // Deal somehow with users that are not enrolled but still got a role somehow
496 if ($course->id
!= SITEID
) {
497 //TODO, create some new UI for role assignments at course level
498 if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
499 $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id
));
500 $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node
::TYPE_SETTING
, null, 'otherusers', new pix_icon('i/assignroles', ''));
504 // just in case nothing was actually added
505 $usersnode->trim_if_empty();
507 if ($course->id
!= SITEID
) {
508 if (isguestuser() or !isloggedin()) {
509 // guest account can not be enrolled - no links for them
510 } else if (is_enrolled($coursecontext)) {
511 // unenrol link if possible
512 foreach ($instances as $instance) {
513 if (!isset($plugins[$instance->enrol
])) {
516 $plugin = $plugins[$instance->enrol
];
517 if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
518 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
519 $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node
::TYPE_SETTING
, null, 'unenrolself', new pix_icon('i/user', ''));
520 $coursenode->get('unenrolself')->set_force_into_more_menu();
522 //TODO. deal with multiple unenrol links - not likely case, but still...
526 // enrol link if possible
527 if (is_viewing($coursecontext)) {
528 // better not show any enrol link, this is intended for managers and inspectors
530 foreach ($instances as $instance) {
531 if (!isset($plugins[$instance->enrol
])) {
534 $plugin = $plugins[$instance->enrol
];
535 if ($plugin->show_enrolme_link($instance)) {
536 $url = new moodle_url('/enrol/index.php', array('id'=>$course->id
));
537 $shortname = format_string($course->shortname
, true, array('context' => $coursecontext));
538 $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node
::TYPE_SETTING
, null, 'enrolself', new pix_icon('i/user', ''));
548 * Returns list of courses current $USER is enrolled in and can access
550 * The $fields param is a list of field names to ADD so name just the fields you really need,
551 * which will be added and uniq'd.
553 * If $allaccessible is true, this will additionally return courses that the current user is not
554 * enrolled in, but can access because they are open to the user for other reasons (course view
555 * permission, currently viewing course as a guest, or course allows guest access without
558 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
559 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
560 * Allowed prefixes for sort fields are: "ul" for the user_lastaccess table, "c" for the courses table,
561 * "ue" for the user_enrolments table.
562 * @param int $limit max number of courses
563 * @param array $courseids the list of course ids to filter by
564 * @param bool $allaccessible Include courses user is not enrolled in, but can access
565 * @param int $offset Offset the result set by this number
566 * @param array $excludecourses IDs of hidden courses to exclude from search
569 function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false,
570 $offset = 0, $excludecourses = []) {
571 global $DB, $USER, $CFG;
573 // Allowed prefixes and field names.
574 $allowedprefixesandfields = ['c' => array_keys($DB->get_columns('course')),
575 'ul' => array_keys($DB->get_columns('user_lastaccess')),
576 'ue' => array_keys($DB->get_columns('user_enrolments'))];
578 // Re-Arrange the course sorting according to the admin settings.
579 $sort = enrol_get_courses_sortingsql($sort);
581 // Guest account does not have any enrolled courses.
582 if (!$allaccessible && (isguestuser() or !isloggedin())) {
587 'id', 'category', 'sortorder',
588 'shortname', 'fullname', 'idnumber',
589 'startdate', 'visible',
590 'groupmode', 'groupmodeforce', 'cacherev',
591 'showactivitydates', 'showcompletionconditions',
594 if (empty($fields)) {
595 $fields = $basefields;
596 } else if (is_string($fields)) {
597 // turn the fields from a string to an array
598 $fields = explode(',', $fields);
599 $fields = array_map('trim', $fields);
600 $fields = array_unique(array_merge($basefields, $fields));
601 } else if (is_array($fields)) {
602 $fields = array_unique(array_merge($basefields, $fields));
604 throw new coding_exception('Invalid $fields parameter in enrol_get_my_courses()');
606 if (in_array('*', $fields)) {
607 $fields = array('*');
612 $sorttimeaccess = false;
614 $rawsorts = explode(',', $sort);
616 foreach ($rawsorts as $rawsort) {
617 $rawsort = trim($rawsort);
618 // Make sure that there are no more white spaces in sortparams after explode.
619 $sortparams = array_values(array_filter(explode(' ', $rawsort)));
620 // If more than 2 values present then throw coding_exception.
621 if (isset($sortparams[2])) {
622 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
624 // Check the sort ordering if present, at the beginning.
625 if (isset($sortparams[1]) && (preg_match("/^(asc|desc)$/i", $sortparams[1]) === 0)) {
626 throw new coding_exception('Invalid sort direction in $sort parameter in enrol_get_my_courses()');
629 $sortfield = $sortparams[0];
630 $sortdirection = $sortparams[1] ??
'asc';
631 if (strpos($sortfield, '.') !== false) {
632 $sortfieldparams = explode('.', $sortfield);
633 // Check if more than one dots present in the prefix field.
634 if (isset($sortfieldparams[2])) {
635 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
637 list($prefix, $fieldname) = [$sortfieldparams[0], $sortfieldparams[1]];
638 // Check if the field name matches with the allowed prefix.
639 if (array_key_exists($prefix, $allowedprefixesandfields) &&
640 (in_array($fieldname, $allowedprefixesandfields[$prefix]))) {
641 if ($prefix === 'ul') {
642 $sorts[] = "COALESCE({$prefix}.{$fieldname}, 0) {$sortdirection}";
643 $sorttimeaccess = true;
645 // Check if the field name that matches with the prefix and just append to sorts.
649 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
652 // Check if the field name matches with $allowedprefixesandfields.
654 foreach (array_keys($allowedprefixesandfields) as $prefix) {
655 if (in_array($sortfield, $allowedprefixesandfields[$prefix])) {
656 if ($prefix === 'ul') {
657 $sorts[] = "COALESCE({$prefix}.{$sortfield}, 0) {$sortdirection}";
658 $sorttimeaccess = true;
660 $sorts[] = "{$prefix}.{$sortfield} {$sortdirection}";
667 // The param is not found in $allowedprefixesandfields.
668 throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
672 $sort = implode(',', $sorts);
673 $orderby = "ORDER BY $sort";
676 $wheres = array("c.id <> :siteid");
677 $params = array('siteid'=>SITEID
);
679 if (isset($USER->loginascontext
) and $USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
680 // list _only_ this course - anything else is asking for trouble...
681 $wheres[] = "courseid = :loginas";
682 $params['loginas'] = $USER->loginascontext
->instanceid
;
685 $coursefields = 'c.' .join(',c.', $fields);
686 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
687 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
688 $params['contextlevel'] = CONTEXT_COURSE
;
689 $wheres = implode(" AND ", $wheres);
691 $timeaccessselect = "";
692 $timeaccessjoin = "";
694 if (!empty($courseids)) {
695 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED
);
696 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
697 $params = array_merge($params, $courseidsparams);
700 if (!empty($excludecourses)) {
701 list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($excludecourses, SQL_PARAMS_NAMED
, 'param', false);
702 $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
703 $params = array_merge($params, $courseidsparams);
707 // Logged-in, non-guest users get their enrolled courses.
708 if (!isguestuser() && isloggedin()) {
710 SELECT DISTINCT e.courseid
712 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid1)
713 WHERE ue.status = :active AND e.status = :enabled AND ue.timestart <= :now1
714 AND (ue.timeend = 0 OR ue.timeend > :now2)";
715 $params['userid1'] = $USER->id
;
716 $params['active'] = ENROL_USER_ACTIVE
;
717 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
718 $params['now1'] = $params['now2'] = time();
720 if ($sorttimeaccess) {
721 $params['userid2'] = $USER->id
;
722 $timeaccessselect = ', ul.timeaccess as lastaccessed';
723 $timeaccessjoin = "LEFT JOIN {user_lastaccess} ul ON (ul.courseid = c.id AND ul.userid = :userid2)";
727 // When including non-enrolled but accessible courses...
728 if ($allaccessible) {
729 if (is_siteadmin()) {
730 // Site admins can access all courses.
731 $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
733 // If we used the enrolment as well, then this will be UNIONed.
735 $courseidsql .= " UNION ";
738 // Include courses with guest access and no password.
740 SELECT DISTINCT e.courseid
742 WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
743 $params['emptypass'] = '';
744 $params['enabled2'] = ENROL_INSTANCE_ENABLED
;
746 // Include courses where the current user is currently using guest access (may include
747 // those which require a password).
749 $accessdata = get_user_accessdata($USER->id
);
750 foreach ($accessdata['ra'] as $contextpath => $roles) {
751 if (array_key_exists($CFG->guestroleid
, $roles)) {
752 // Work out the course id from context path.
753 $context = context
::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
754 if ($context instanceof context_course
) {
755 $courseids[$context->instanceid
] = true;
760 // Include courses where the current user has moodle/course:view capability.
761 $courses = get_user_capability_course('moodle/course:view', null, false);
765 foreach ($courses as $course) {
766 $courseids[$course->id
] = true;
769 // If there are any in either category, list them individually.
771 list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
772 array_keys($courseids), SQL_PARAMS_NAMED
);
775 SELECT DISTINCT c3.id AS courseid
777 WHERE c3.id $allowedsql";
778 $params = array_merge($params, $allowedparams);
783 // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
784 // we have the subselect there.
785 $sql = "SELECT $coursefields $ccselect $timeaccessselect
787 JOIN ($courseidsql) en ON (en.courseid = c.id)
793 $courses = $DB->get_records_sql($sql, $params, $offset, $limit);
795 // preload contexts and check visibility
796 foreach ($courses as $id=>$course) {
797 context_helper
::preload_from_record($course);
798 if (!$course->visible
) {
799 if (!$context = context_course
::instance($id, IGNORE_MISSING
)) {
800 unset($courses[$id]);
803 if (!has_capability('moodle/course:viewhiddencourses', $context)) {
804 unset($courses[$id]);
808 $courses[$id] = $course;
811 //wow! Is that really all? :-D
817 * Returns course enrolment information icons.
819 * @param object $course
820 * @param array $instances enrol instances of this course, improves performance
821 * @return array of pix_icon
823 function enrol_get_course_info_icons($course, array $instances = NULL) {
825 if (is_null($instances)) {
826 $instances = enrol_get_instances($course->id
, true);
828 $plugins = enrol_get_plugins(true);
829 foreach ($plugins as $name => $plugin) {
831 foreach ($instances as $instance) {
832 if ($instance->status
!= ENROL_INSTANCE_ENABLED
or $instance->courseid
!= $course->id
) {
833 debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
836 if ($instance->enrol
== $name) {
837 $pis[$instance->id
] = $instance;
841 $icons = array_merge($icons, $plugin->get_info_icons($pis));
848 * Returns SQL ORDER arguments which reflect the admin settings to sort my courses.
850 * @param string|null $sort SQL ORDER arguments which were originally requested (optionally).
851 * @return string SQL ORDER arguments.
853 function enrol_get_courses_sortingsql($sort = null) {
856 // Prepare the visible SQL fragment as empty.
858 // Only create a visible SQL fragment if the caller didn't already pass a sort order which contains the visible field.
859 if ($sort === null ||
strpos($sort, 'visible') === false) {
860 // If the admin did not explicitly want to have shown and hidden courses sorted as one list, we will sort hidden
861 // courses to the end of the course list.
862 if (!isset($CFG->navsortmycourseshiddenlast
) ||
$CFG->navsortmycourseshiddenlast
== true) {
863 $visible = 'visible DESC, ';
867 // Only create a sortorder SQL fragment if the caller didn't already pass one.
868 if ($sort === null) {
869 // If the admin has configured a course sort order, we will use this.
870 if (!empty($CFG->navsortmycoursessort
)) {
871 $sort = $CFG->navsortmycoursessort
. ' ASC';
873 // Otherwise we will fall back to the sortorder sorting.
875 $sort = 'sortorder ASC';
879 return $visible . $sort;
883 * Returns course enrolment detailed information.
885 * @param object $course
886 * @return array of html fragments - can be used to construct lists
888 function enrol_get_course_description_texts($course) {
890 $instances = enrol_get_instances($course->id
, true);
891 $plugins = enrol_get_plugins(true);
892 foreach ($instances as $instance) {
893 if (!isset($plugins[$instance->enrol
])) {
897 $plugin = $plugins[$instance->enrol
];
898 $text = $plugin->get_description_text($instance);
899 if ($text !== NULL) {
907 * Returns list of courses user is enrolled into.
909 * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
911 * The $fields param is a list of field names to ADD so name just the fields you really need,
912 * which will be added and uniq'd.
914 * @param int $userid User whose courses are returned, defaults to the current user.
915 * @param bool $onlyactive Return only active enrolments in courses user may see.
916 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
917 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
920 function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
923 $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
925 // preload contexts and check visibility
927 foreach ($courses as $id=>$course) {
928 context_helper
::preload_from_record($course);
929 if (!$course->visible
) {
930 if (!$context = context_course
::instance($id)) {
931 unset($courses[$id]);
934 if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
935 unset($courses[$id]);
946 * Returns list of roles per users into course.
948 * @param int $courseid Course id.
949 * @return array Array[$userid][$roleid] = role_assignment.
951 function enrol_get_course_users_roles(int $courseid) : array {
954 $context = context_course
::instance($courseid);
958 $records = $DB->get_recordset('role_assignments', array('contextid' => $context->id
));
959 foreach ($records as $record) {
960 if (isset($roles[$record->userid
]) === false) {
961 $roles[$record->userid
] = array();
963 $roles[$record->userid
][$record->roleid
] = $record;
971 * Can user access at least one enrolled course?
973 * Cheat if necessary, but find out as fast as possible!
975 * @param int|stdClass $user null means use current user
978 function enrol_user_sees_own_courses($user = null) {
981 if ($user === null) {
984 $userid = is_object($user) ?
$user->id
: $user;
986 // Guest account does not have any courses
987 if (isguestuser($userid) or empty($userid)) {
991 // Let's cheat here if this is the current user,
992 // if user accessed any course recently, then most probably
993 // we do not need to query the database at all.
994 if ($USER->id
== $userid) {
995 if (!empty($USER->enrol
['enrolled'])) {
996 foreach ($USER->enrol
['enrolled'] as $until) {
997 if ($until > time()) {
1004 // Now the slow way.
1005 $courses = enrol_get_all_users_courses($userid, true);
1006 foreach($courses as $course) {
1007 if ($course->visible
) {
1010 context_helper
::preload_from_record($course);
1011 $context = context_course
::instance($course->id
);
1012 if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
1021 * Returns list of courses user is enrolled into without performing any capability checks.
1023 * The $fields param is a list of field names to ADD so name just the fields you really need,
1024 * which will be added and uniq'd.
1026 * @param int $userid User whose courses are returned, defaults to the current user.
1027 * @param bool $onlyactive Return only active enrolments in courses user may see.
1028 * @param string|array $fields Extra fields to be returned (array or comma-separated list).
1029 * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
1032 function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
1035 // Re-Arrange the course sorting according to the admin settings.
1036 $sort = enrol_get_courses_sortingsql($sort);
1038 // Guest account does not have any courses
1039 if (isguestuser($userid) or empty($userid)) {
1043 $basefields = array('id', 'category', 'sortorder',
1044 'shortname', 'fullname', 'idnumber',
1045 'startdate', 'visible',
1046 'defaultgroupingid',
1047 'groupmode', 'groupmodeforce');
1049 if (empty($fields)) {
1050 $fields = $basefields;
1051 } else if (is_string($fields)) {
1052 // turn the fields from a string to an array
1053 $fields = explode(',', $fields);
1054 $fields = array_map('trim', $fields);
1055 $fields = array_unique(array_merge($basefields, $fields));
1056 } else if (is_array($fields)) {
1057 $fields = array_unique(array_merge($basefields, $fields));
1059 throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
1061 if (in_array('*', $fields)) {
1062 $fields = array('*');
1066 $sort = trim($sort);
1067 if (!empty($sort)) {
1068 $rawsorts = explode(',', $sort);
1070 foreach ($rawsorts as $rawsort) {
1071 $rawsort = trim($rawsort);
1072 if (strpos($rawsort, 'c.') === 0) {
1073 $rawsort = substr($rawsort, 2);
1075 $sorts[] = trim($rawsort);
1077 $sort = 'c.'.implode(',c.', $sorts);
1078 $orderby = "ORDER BY $sort";
1081 $params = array('siteid'=>SITEID
);
1084 $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
1085 $params['now1'] = round(time(), -2); // improves db caching
1086 $params['now2'] = $params['now1'];
1087 $params['active'] = ENROL_USER_ACTIVE
;
1088 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
1093 $coursefields = 'c.' .join(',c.', $fields);
1094 $ccselect = ', ' . context_helper
::get_preload_record_columns_sql('ctx');
1095 $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
1096 $params['contextlevel'] = CONTEXT_COURSE
;
1098 //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
1099 $sql = "SELECT $coursefields $ccselect
1101 JOIN (SELECT DISTINCT e.courseid
1103 JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
1105 ) en ON (en.courseid = c.id)
1107 WHERE c.id <> :siteid
1109 $params['userid'] = $userid;
1111 $courses = $DB->get_records_sql($sql, $params);
1119 * Called when user is about to be deleted.
1120 * @param object $user
1123 function enrol_user_delete($user) {
1126 $plugins = enrol_get_plugins(true);
1127 foreach ($plugins as $plugin) {
1128 $plugin->user_delete($user);
1131 // force cleanup of all broken enrolments
1132 $DB->delete_records('user_enrolments', array('userid'=>$user->id
));
1136 * Called when course is about to be deleted.
1137 * If a user id is passed, only enrolments that the user has permission to un-enrol will be removed,
1138 * otherwise all enrolments in the course will be removed.
1140 * @param stdClass $course
1141 * @param int|null $userid
1144 function enrol_course_delete($course, $userid = null) {
1147 $context = context_course
::instance($course->id
);
1148 $instances = enrol_get_instances($course->id
, false);
1149 $plugins = enrol_get_plugins(true);
1152 // If the user id is present, include only course enrolment instances which allow manual unenrolment and
1153 // the given user have a capability to perform unenrolment.
1154 $instances = array_filter($instances, function($instance) use ($userid, $plugins, $context) {
1155 $unenrolcap = "enrol/{$instance->enrol}:unenrol";
1156 return $plugins[$instance->enrol
]->allow_unenrol($instance) &&
1157 has_capability($unenrolcap, $context, $userid);
1161 foreach ($instances as $instance) {
1162 if (isset($plugins[$instance->enrol
])) {
1163 $plugins[$instance->enrol
]->delete_instance($instance);
1165 // low level delete in case plugin did not do it
1166 $DB->delete_records('role_assignments', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$instance->enrol
));
1167 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
1168 $DB->delete_records('enrol', array('id'=>$instance->id
));
1173 * Try to enrol user via default internal auth plugin.
1175 * For now this is always using the manual enrol plugin...
1182 * @return bool success
1184 function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
1187 //note: this is hardcoded to manual plugin for now
1189 if (!enrol_is_enabled('manual')) {
1193 if (!$enrol = enrol_get_plugin('manual')) {
1196 if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder,id ASC')) {
1199 $instance = reset($instances);
1201 $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
1207 * Is there a chance users might self enrol
1208 * @param int $courseid
1211 function enrol_selfenrol_available($courseid) {
1214 $plugins = enrol_get_plugins(true);
1215 $enrolinstances = enrol_get_instances($courseid, true);
1216 foreach($enrolinstances as $instance) {
1217 if (!isset($plugins[$instance->enrol
])) {
1220 if ($instance->enrol
=== 'guest') {
1223 if ($plugins[$instance->enrol
]->show_enrolme_link($instance)) {
1233 * This function returns the end of current active user enrolment.
1235 * It deals correctly with multiple overlapping user enrolments.
1237 * @param int $courseid
1238 * @param int $userid
1239 * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
1241 function enrol_get_enrolment_end($courseid, $userid) {
1245 FROM {user_enrolments} ue
1246 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1247 JOIN {user} u ON u.id = ue.userid
1248 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1249 $params = array('enabled'=>ENROL_INSTANCE_ENABLED
, 'active'=>ENROL_USER_ACTIVE
, 'userid'=>$userid, 'courseid'=>$courseid);
1251 if (!$enrolments = $DB->get_records_sql($sql, $params)) {
1257 foreach ($enrolments as $ue) {
1258 $start = (int)$ue->timestart
;
1259 $end = (int)$ue->timeend
;
1260 if ($end != 0 and $end < $start) {
1261 debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id
);
1264 if (isset($changes[$start])) {
1265 $changes[$start] = $changes[$start] +
1;
1267 $changes[$start] = 1;
1271 } else if (isset($changes[$end])) {
1272 $changes[$end] = $changes[$end] - 1;
1274 $changes[$end] = -1;
1278 // let's sort then enrolment starts&ends and go through them chronologically,
1279 // looking for current status and the next future end of enrolment
1286 foreach ($changes as $time => $change) {
1288 if ($present === null) {
1289 // we have just went past current time
1290 $present = $current;
1292 // no enrolment active
1296 if ($present !== null) {
1297 // we are already in the future - look for possible end
1298 if ($current +
$change < 1) {
1303 $current +
= $change;
1314 * Is current user accessing course via this enrolment method?
1316 * This is intended for operations that are going to affect enrol instances.
1318 * @param stdClass $instance enrol instance
1321 function enrol_accessing_via_instance(stdClass
$instance) {
1324 if (empty($instance->id
)) {
1328 if (is_siteadmin()) {
1329 // Admins may go anywhere.
1333 return $DB->record_exists('user_enrolments', array('userid'=>$USER->id
, 'enrolid'=>$instance->id
));
1337 * Returns true if user is enrolled (is participating) in course
1338 * this is intended for students and teachers.
1340 * Since 2.2 the result for active enrolments and current user are cached.
1342 * @param context $context
1343 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1344 * @param string $withcapability extra capability name
1345 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1348 function is_enrolled(context
$context, $user = null, $withcapability = '', $onlyactive = false) {
1351 // First find the course context.
1352 $coursecontext = $context->get_course_context();
1354 // Make sure there is a real user specified.
1355 if ($user === null) {
1356 $userid = isset($USER->id
) ?
$USER->id
: 0;
1358 $userid = is_object($user) ?
$user->id
: $user;
1361 if (empty($userid)) {
1364 } else if (isguestuser($userid)) {
1365 // Guest account can not be enrolled anywhere.
1369 // Note everybody participates on frontpage, so for other contexts...
1370 if ($coursecontext->instanceid
!= SITEID
) {
1371 // Try cached info first - the enrolled flag is set only when active enrolment present.
1372 if ($USER->id
== $userid) {
1373 $coursecontext->reload_if_dirty();
1374 if (isset($USER->enrol
['enrolled'][$coursecontext->instanceid
])) {
1375 if ($USER->enrol
['enrolled'][$coursecontext->instanceid
] > time()) {
1376 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1385 // Look for active enrolments only.
1386 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $userid);
1388 if ($until === false) {
1392 if ($USER->id
== $userid) {
1394 $until = ENROL_MAX_TIMESTAMP
;
1396 $USER->enrol
['enrolled'][$coursecontext->instanceid
] = $until;
1397 if (isset($USER->enrol
['tempguest'][$coursecontext->instanceid
])) {
1398 unset($USER->enrol
['tempguest'][$coursecontext->instanceid
]);
1399 remove_temp_course_roles($coursecontext);
1404 // Any enrolment is good for us here, even outdated, disabled or inactive.
1406 FROM {user_enrolments} ue
1407 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1408 JOIN {user} u ON u.id = ue.userid
1409 WHERE ue.userid = :userid AND u.deleted = 0";
1410 $params = array('userid' => $userid, 'courseid' => $coursecontext->instanceid
);
1411 if (!$DB->record_exists_sql($sql, $params)) {
1417 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1425 * Returns an array of joins, wheres and params that will limit the group of
1426 * users to only those enrolled and with given capability (if specified).
1428 * Note this join will return duplicate rows for users who have been enrolled
1429 * several times (e.g. as manual enrolment, and as self enrolment). You may
1430 * need to use a SELECT DISTINCT in your query (see get_enrolled_sql for example).
1432 * In case is guaranteed some of the joins never match any rows, the resulting
1433 * join_sql->cannotmatchanyrows will be true. This happens when the capability
1436 * @param context $context
1437 * @param string $prefix optional, a prefix to the user id column
1438 * @param string|array $capability optional, may include a capability name, or array of names.
1439 * If an array is provided then this is the equivalent of a logical 'OR',
1440 * i.e. the user needs to have one of these capabilities.
1441 * @param int $group optional, 0 indicates no current group and USERSWITHOUTGROUP users without any group; otherwise the group id
1442 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1443 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1444 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1445 * @return \core\dml\sql_join Contains joins, wheres, params and cannotmatchanyrows
1447 function get_enrolled_with_capabilities_join(context
$context, $prefix = '', $capability = '', $group = 0,
1448 $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1449 $uid = $prefix . 'u.id';
1452 $cannotmatchanyrows = false;
1454 $enrolledjoin = get_enrolled_join($context, $uid, $onlyactive, $onlysuspended, $enrolid);
1455 $joins[] = $enrolledjoin->joins
;
1456 $wheres[] = $enrolledjoin->wheres
;
1457 $params = $enrolledjoin->params
;
1458 $cannotmatchanyrows = $cannotmatchanyrows ||
$enrolledjoin->cannotmatchanyrows
;
1460 if (!empty($capability)) {
1461 $capjoin = get_with_capability_join($context, $capability, $uid);
1462 $joins[] = $capjoin->joins
;
1463 $wheres[] = $capjoin->wheres
;
1464 $params = array_merge($params, $capjoin->params
);
1465 $cannotmatchanyrows = $cannotmatchanyrows ||
$capjoin->cannotmatchanyrows
;
1469 $groupjoin = groups_get_members_join($group, $uid, $context);
1470 $joins[] = $groupjoin->joins
;
1471 $params = array_merge($params, $groupjoin->params
);
1472 if (!empty($groupjoin->wheres
)) {
1473 $wheres[] = $groupjoin->wheres
;
1475 $cannotmatchanyrows = $cannotmatchanyrows ||
$groupjoin->cannotmatchanyrows
;
1478 $joins = implode("\n", $joins);
1479 $wheres[] = "{$prefix}u.deleted = 0";
1480 $wheres = implode(" AND ", $wheres);
1482 return new \core\dml\
sql_join($joins, $wheres, $params, $cannotmatchanyrows);
1486 * Returns array with sql code and parameters returning all ids
1487 * of users enrolled into course.
1489 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
1491 * @param context $context
1492 * @param string $withcapability
1493 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1494 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1495 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1496 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1497 * @return array list($sql, $params)
1499 function get_enrolled_sql(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false, $onlysuspended = false,
1502 // Use unique prefix just in case somebody makes some SQL magic with the result.
1505 $prefix = 'eu' . $i . '_';
1507 $capjoin = get_enrolled_with_capabilities_join(
1508 $context, $prefix, $withcapability, $groupid, $onlyactive, $onlysuspended, $enrolid);
1510 $sql = "SELECT DISTINCT {$prefix}u.id
1511 FROM {user} {$prefix}u
1513 WHERE $capjoin->wheres";
1515 return array($sql, $capjoin->params
);
1519 * Returns array with sql joins and parameters returning all ids
1520 * of users enrolled into course.
1522 * This function is using 'ej[0-9]+_' prefix for table names and parameters.
1524 * @throws coding_exception
1526 * @param context $context
1527 * @param string $useridcolumn User id column used the calling query, e.g. u.id
1528 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1529 * @param bool $onlysuspended inverse of onlyactive, consider only suspended enrolments
1530 * @param int $enrolid The enrolment ID. If not 0, only users enrolled using this enrolment method will be returned.
1531 * @return \core\dml\sql_join Contains joins, wheres, params
1533 function get_enrolled_join(context
$context, $useridcolumn, $onlyactive = false, $onlysuspended = false, $enrolid = 0) {
1534 // Use unique prefix just in case somebody makes some SQL magic with the result.
1537 $prefix = 'ej' . $i . '_';
1539 // First find the course context.
1540 $coursecontext = $context->get_course_context();
1542 $isfrontpage = ($coursecontext->instanceid
== SITEID
);
1544 if ($onlyactive && $onlysuspended) {
1545 throw new coding_exception("Both onlyactive and onlysuspended are set, this is probably not what you want!");
1547 if ($isfrontpage && $onlysuspended) {
1548 throw new coding_exception("onlysuspended is not supported on frontpage; please add your own early-exit!");
1555 $wheres[] = "1 = 1"; // Prevent broken where clauses later on.
1557 // Note all users are "enrolled" on the frontpage, but for others...
1558 if (!$isfrontpage) {
1559 $where1 = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
1560 $where2 = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
1562 $enrolconditions = array(
1563 "{$prefix}e.id = {$prefix}ue.enrolid",
1564 "{$prefix}e.courseid = :{$prefix}courseid",
1567 $enrolconditions[] = "{$prefix}e.id = :{$prefix}enrolid";
1568 $params[$prefix . 'enrolid'] = $enrolid;
1570 $enrolconditionssql = implode(" AND ", $enrolconditions);
1571 $ejoin = "JOIN {enrol} {$prefix}e ON ($enrolconditionssql)";
1573 $params[$prefix.'courseid'] = $coursecontext->instanceid
;
1575 if (!$onlysuspended) {
1576 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = $useridcolumn";
1579 $wheres[] = "$where1 AND $where2";
1582 // Suspended only where there is enrolment but ALL are suspended.
1583 // Consider multiple enrols where one is not suspended or plain role_assign.
1584 $enrolselect = "SELECT DISTINCT {$prefix}ue.userid FROM {user_enrolments} {$prefix}ue $ejoin WHERE $where1 AND $where2";
1585 $joins[] = "JOIN {user_enrolments} {$prefix}ue1 ON {$prefix}ue1.userid = $useridcolumn";
1586 $enrolconditions = array(
1587 "{$prefix}e1.id = {$prefix}ue1.enrolid",
1588 "{$prefix}e1.courseid = :{$prefix}_e1_courseid",
1591 $enrolconditions[] = "{$prefix}e1.id = :{$prefix}e1_enrolid";
1592 $params[$prefix . 'e1_enrolid'] = $enrolid;
1594 $enrolconditionssql = implode(" AND ", $enrolconditions);
1595 $joins[] = "JOIN {enrol} {$prefix}e1 ON ($enrolconditionssql)";
1596 $params["{$prefix}_e1_courseid"] = $coursecontext->instanceid
;
1597 $wheres[] = "$useridcolumn NOT IN ($enrolselect)";
1600 if ($onlyactive ||
$onlysuspended) {
1601 $now = round(time(), -2); // Rounding helps caching in DB.
1602 $params = array_merge($params, array($prefix . 'enabled' => ENROL_INSTANCE_ENABLED
,
1603 $prefix . 'active' => ENROL_USER_ACTIVE
,
1604 $prefix . 'now1' => $now, $prefix . 'now2' => $now));
1608 $joins = implode("\n", $joins);
1609 $wheres = implode(" AND ", $wheres);
1611 return new \core\dml\
sql_join($joins, $wheres, $params);
1615 * Returns list of users enrolled into course.
1617 * @param context $context
1618 * @param string $withcapability
1619 * @param int $groupid 0 means ignore groups, USERSWITHOUTGROUP without any group and any other value limits the result by group id
1620 * @param string $userfields requested user record fields
1621 * @param string $orderby
1622 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
1623 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
1624 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1625 * @return array of user records
1627 function get_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
1628 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
1631 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
1632 $sql = "SELECT $userfields
1634 JOIN ($esql) je ON je.id = u.id
1635 WHERE u.deleted = 0";
1638 $sql = "$sql ORDER BY $orderby";
1640 list($sort, $sortparams) = users_order_by_sql('u');
1641 $sql = "$sql ORDER BY $sort";
1642 $params = array_merge($params, $sortparams);
1645 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1649 * Counts list of users enrolled into course (as per above function)
1651 * @param context $context
1652 * @param string $withcapability
1653 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
1654 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1655 * @return int number of users enrolled into course
1657 function count_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false) {
1660 $capjoin = get_enrolled_with_capabilities_join(
1661 $context, '', $withcapability, $groupid, $onlyactive);
1663 $sql = "SELECT COUNT(DISTINCT u.id)
1666 WHERE $capjoin->wheres AND u.deleted = 0";
1668 return $DB->count_records_sql($sql, $capjoin->params
);
1672 * Send welcome email "from" options.
1674 * @return array list of from options
1676 function enrol_send_welcome_email_options() {
1678 ENROL_DO_NOT_SEND_EMAIL
=> get_string('no'),
1679 ENROL_SEND_EMAIL_FROM_COURSE_CONTACT
=> get_string('sendfromcoursecontact', 'enrol'),
1680 ENROL_SEND_EMAIL_FROM_KEY_HOLDER
=> get_string('sendfromkeyholder', 'enrol'),
1681 ENROL_SEND_EMAIL_FROM_NOREPLY
=> get_string('sendfromnoreply', 'enrol')
1686 * Serve the user enrolment form as a fragment.
1688 * @param array $args List of named arguments for the fragment loader.
1691 function enrol_output_fragment_user_enrolment_form($args) {
1694 $args = (object) $args;
1695 $context = $args->context
;
1696 require_capability('moodle/course:enrolreview', $context);
1698 $ueid = $args->ueid
;
1699 $userenrolment = $DB->get_record('user_enrolments', ['id' => $ueid], '*', MUST_EXIST
);
1700 $instance = $DB->get_record('enrol', ['id' => $userenrolment->enrolid
], '*', MUST_EXIST
);
1701 $plugin = enrol_get_plugin($instance->enrol
);
1703 'ue' => $userenrolment,
1705 'enrolinstancename' => $plugin->get_instance_name($instance)
1708 // Set the data if applicable.
1710 if (isset($args->formdata
)) {
1711 $serialiseddata = json_decode($args->formdata
);
1712 parse_str($serialiseddata, $data);
1715 require_once("$CFG->dirroot/enrol/editenrolment_form.php");
1716 $mform = new \
enrol_user_enrolment_form(null, $customdata, 'post', '', null, true, $data);
1718 if (!empty($data)) {
1719 $mform->set_data($data);
1720 $mform->is_validated();
1723 return $mform->render();
1727 * Returns the course where a user enrolment belong to.
1729 * @param int $ueid user_enrolments id
1732 function enrol_get_course_by_user_enrolment_id($ueid) {
1734 $sql = "SELECT c.* FROM {user_enrolments} ue
1735 JOIN {enrol} e ON e.id = ue.enrolid
1736 JOIN {course} c ON c.id = e.courseid
1737 WHERE ue.id = :ueid";
1738 return $DB->get_record_sql($sql, array('ueid' => $ueid));
1742 * Return all users enrolled in a course.
1744 * @param int $courseid Course id or false if using $uefilter (user enrolment ids may belong to different courses)
1745 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1746 * @param array $usersfilter Limit the results obtained to this list of user ids. $uefilter compatibility not guaranteed.
1747 * @param array $uefilter Limit the results obtained to this list of user enrolment ids. $usersfilter compatibility not guaranteed.
1748 * @return stdClass[]
1750 function enrol_get_course_users($courseid = false, $onlyactive = false, $usersfilter = array(), $uefilter = array()) {
1753 if (!$courseid && !$usersfilter && !$uefilter) {
1754 throw new \
coding_exception('You should specify at least 1 filter: courseid, users or user enrolments');
1757 $sql = "SELECT ue.id AS ueid, ue.status AS uestatus, ue.enrolid AS ueenrolid, ue.timestart AS uetimestart,
1758 ue.timeend AS uetimeend, ue.modifierid AS uemodifierid, ue.timecreated AS uetimecreated,
1759 ue.timemodified AS uetimemodified, e.status AS estatus,
1760 u.* FROM {user_enrolments} ue
1761 JOIN {enrol} e ON e.id = ue.enrolid
1762 JOIN {user} u ON ue.userid = u.id
1767 $conditions[] = "e.courseid = :courseid";
1768 $params['courseid'] = $courseid;
1772 $conditions[] = "ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND " .
1773 "(ue.timeend = 0 OR ue.timeend > :now2)";
1774 // Improves db caching.
1775 $params['now1'] = round(time(), -2);
1776 $params['now2'] = $params['now1'];
1777 $params['active'] = ENROL_USER_ACTIVE
;
1778 $params['enabled'] = ENROL_INSTANCE_ENABLED
;
1782 list($usersql, $userparams) = $DB->get_in_or_equal($usersfilter, SQL_PARAMS_NAMED
);
1783 $conditions[] = "ue.userid $usersql";
1784 $params = $params +
$userparams;
1788 list($uesql, $ueparams) = $DB->get_in_or_equal($uefilter, SQL_PARAMS_NAMED
);
1789 $conditions[] = "ue.id $uesql";
1790 $params = $params +
$ueparams;
1793 return $DB->get_records_sql($sql . ' ' . implode(' AND ', $conditions), $params);
1797 * Get the list of options for the enrolment period dropdown
1799 * @return array List of options for the enrolment period dropdown
1801 function enrol_get_period_list() {
1803 $periodmenu[''] = get_string('unlimited');
1804 for ($i = 1; $i <= 365; $i++
) {
1805 $seconds = $i * DAYSECS
;
1806 $periodmenu[$seconds] = get_string('numdays', '', $i);
1812 * Calculate duration base on start time and end time
1814 * @param int $timestart Time start
1815 * @param int $timeend Time end
1816 * @return float|int Calculated duration
1818 function enrol_calculate_duration($timestart, $timeend) {
1819 $duration = floor(($timeend - $timestart) / DAYSECS
) * DAYSECS
;
1824 * Enrolment plugins abstract class.
1826 * All enrol plugins should be based on this class,
1827 * this is also the main source of documentation.
1829 * @copyright 2010 Petr Skoda {@link http://skodak.org}
1830 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1832 abstract class enrol_plugin
{
1833 protected $config = null;
1836 * Returns name of this enrol plugin
1839 public function get_name() {
1840 // second word in class is always enrol name, sorry, no fancy plugin names with _
1841 $words = explode('_', get_class($this));
1846 * Returns localised name of enrol instance
1848 * @param object $instance (null is accepted too)
1851 public function get_instance_name($instance) {
1852 if (empty($instance->name
)) {
1853 $enrol = $this->get_name();
1854 return get_string('pluginname', 'enrol_'.$enrol);
1856 $context = context_course
::instance($instance->courseid
);
1857 return format_string($instance->name
, true, array('context'=>$context));
1862 * Returns optional enrolment information icons.
1864 * This is used in course list for quick overview of enrolment options.
1866 * We are not using single instance parameter because sometimes
1867 * we might want to prevent icon repetition when multiple instances
1868 * of one type exist. One instance may also produce several icons.
1870 * @param array $instances all enrol instances of this type in one course
1871 * @return array of pix_icon
1873 public function get_info_icons(array $instances) {
1878 * Returns optional enrolment instance description text.
1880 * This is used in detailed course information.
1883 * @param object $instance
1884 * @return string short html text
1886 public function get_description_text($instance) {
1891 * Makes sure config is loaded and cached.
1894 protected function load_config() {
1895 if (!isset($this->config
)) {
1896 $name = $this->get_name();
1897 $this->config
= get_config("enrol_$name");
1902 * Returns plugin config value
1903 * @param string $name
1904 * @param string $default value if config does not exist yet
1905 * @return string value or default
1907 public function get_config($name, $default = NULL) {
1908 $this->load_config();
1909 return isset($this->config
->$name) ?
$this->config
->$name : $default;
1913 * Sets plugin config value
1914 * @param string $name name of config
1915 * @param string $value string config value, null means delete
1916 * @return string value
1918 public function set_config($name, $value) {
1919 $pluginname = $this->get_name();
1920 $this->load_config();
1921 if ($value === NULL) {
1922 unset($this->config
->$name);
1924 $this->config
->$name = $value;
1926 set_config($name, $value, "enrol_$pluginname");
1930 * Does this plugin assign protected roles are can they be manually removed?
1931 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
1933 public function roles_protected() {
1938 * Does this plugin allow manual enrolments?
1940 * @param stdClass $instance course enrol instance
1941 * All plugins allowing this must implement 'enrol/xxx:enrol' capability
1943 * @return bool - true means user with 'enrol/xxx:enrol' may enrol others freely, false means nobody may add more enrolments manually
1945 public function allow_enrol(stdClass
$instance) {
1950 * Does this plugin allow manual unenrolment of all users?
1951 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1953 * @param stdClass $instance course enrol instance
1954 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
1956 public function allow_unenrol(stdClass
$instance) {
1961 * Does this plugin allow manual unenrolment of a specific user?
1962 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
1964 * This is useful especially for synchronisation plugins that
1965 * do suspend instead of full unenrolment.
1967 * @param stdClass $instance course enrol instance
1968 * @param stdClass $ue record from user_enrolments table, specifies user
1970 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
1972 public function allow_unenrol_user(stdClass
$instance, stdClass
$ue) {
1973 return $this->allow_unenrol($instance);
1977 * Does this plugin allow manual changes in user_enrolments table?
1979 * All plugins allowing this must implement 'enrol/xxx:manage' capability
1981 * @param stdClass $instance course enrol instance
1982 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
1984 public function allow_manage(stdClass
$instance) {
1989 * Does this plugin support some way to user to self enrol?
1991 * @param stdClass $instance course enrol instance
1993 * @return bool - true means show "Enrol me in this course" link in course UI
1995 public function show_enrolme_link(stdClass
$instance) {
2000 * Attempt to automatically enrol current user in course without any interaction,
2001 * calling code has to make sure the plugin and instance are active.
2003 * This should return either a timestamp in the future or false.
2005 * @param stdClass $instance course enrol instance
2006 * @return bool|int false means not enrolled, integer means timeend
2008 public function try_autoenrol(stdClass
$instance) {
2015 * Attempt to automatically gain temporary guest access to course,
2016 * calling code has to make sure the plugin and instance are active.
2018 * This should return either a timestamp in the future or false.
2020 * @param stdClass $instance course enrol instance
2021 * @return bool|int false means no guest access, integer means timeend
2023 public function try_guestaccess(stdClass
$instance) {
2030 * Enrol user into course via enrol instance.
2032 * @param stdClass $instance
2033 * @param int $userid
2034 * @param int $roleid optional role id
2035 * @param int $timestart 0 means unknown
2036 * @param int $timeend 0 means forever
2037 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
2038 * @param bool $recovergrades restore grade history
2041 public function enrol_user(stdClass
$instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
2042 global $DB, $USER, $CFG; // CFG necessary!!!
2044 if ($instance->courseid
== SITEID
) {
2045 throw new coding_exception('invalid attempt to enrol into frontpage course!');
2048 $name = $this->get_name();
2049 $courseid = $instance->courseid
;
2051 if ($instance->enrol
!== $name) {
2052 throw new coding_exception('invalid enrol instance!');
2054 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
2055 if (!isset($recovergrades)) {
2056 $recovergrades = $CFG->recovergradesdefault
;
2061 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
2062 //only update if timestart or timeend or status are different.
2063 if ($ue->timestart
!= $timestart or $ue->timeend
!= $timeend or (!is_null($status) and $ue->status
!= $status)) {
2064 $this->update_user_enrol($instance, $userid, $status, $timestart, $timeend);
2067 $ue = new stdClass();
2068 $ue->enrolid
= $instance->id
;
2069 $ue->status
= is_null($status) ? ENROL_USER_ACTIVE
: $status;
2070 $ue->userid
= $userid;
2071 $ue->timestart
= $timestart;
2072 $ue->timeend
= $timeend;
2073 $ue->modifierid
= $USER->id
;
2074 $ue->timecreated
= time();
2075 $ue->timemodified
= $ue->timecreated
;
2076 $ue->id
= $DB->insert_record('user_enrolments', $ue);
2083 $event = \core\event\user_enrolment_created
::create(
2085 'objectid' => $ue->id
,
2086 'courseid' => $courseid,
2087 'context' => $context,
2088 'relateduserid' => $ue->userid
,
2089 'other' => array('enrol' => $name)
2093 // Check if course contacts cache needs to be cleared.
2094 core_course_category
::user_enrolment_changed($courseid, $ue->userid
,
2095 $ue->status
, $ue->timestart
, $ue->timeend
);
2099 // this must be done after the enrolment event so that the role_assigned event is triggered afterwards
2100 if ($this->roles_protected()) {
2101 role_assign($roleid, $userid, $context->id
, 'enrol_'.$name, $instance->id
);
2103 role_assign($roleid, $userid, $context->id
);
2107 // Recover old grades if present.
2108 if ($recovergrades) {
2109 require_once("$CFG->libdir/gradelib.php");
2110 grade_recover_history_grades($userid, $courseid);
2113 // reset current user enrolment caching
2114 if ($userid == $USER->id
) {
2115 if (isset($USER->enrol
['enrolled'][$courseid])) {
2116 unset($USER->enrol
['enrolled'][$courseid]);
2118 if (isset($USER->enrol
['tempguest'][$courseid])) {
2119 unset($USER->enrol
['tempguest'][$courseid]);
2120 remove_temp_course_roles($context);
2126 * Store user_enrolments changes and trigger event.
2128 * @param stdClass $instance
2129 * @param int $userid
2130 * @param int $status
2131 * @param int $timestart
2132 * @param int $timeend
2135 public function update_user_enrol(stdClass
$instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
2136 global $DB, $USER, $CFG;
2138 $name = $this->get_name();
2140 if ($instance->enrol
!== $name) {
2141 throw new coding_exception('invalid enrol instance!');
2144 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
2145 // weird, user not enrolled
2150 if (isset($status) and $ue->status
!= $status) {
2151 $ue->status
= $status;
2154 if (isset($timestart) and $ue->timestart
!= $timestart) {
2155 $ue->timestart
= $timestart;
2158 if (isset($timeend) and $ue->timeend
!= $timeend) {
2159 $ue->timeend
= $timeend;
2168 $ue->modifierid
= $USER->id
;
2169 $ue->timemodified
= time();
2170 $DB->update_record('user_enrolments', $ue);
2172 // User enrolments have changed, so mark user as dirty.
2173 mark_user_dirty($userid);
2175 // Invalidate core_access cache for get_suspended_userids.
2176 cache_helper
::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid
));
2179 $event = \core\event\user_enrolment_updated
::create(
2181 'objectid' => $ue->id
,
2182 'courseid' => $instance->courseid
,
2183 'context' => context_course
::instance($instance->courseid
),
2184 'relateduserid' => $ue->userid
,
2185 'other' => array('enrol' => $name)
2190 core_course_category
::user_enrolment_changed($instance->courseid
, $ue->userid
,
2191 $ue->status
, $ue->timestart
, $ue->timeend
);
2195 * Unenrol user from course,
2196 * the last unenrolment removes all remaining roles.
2198 * @param stdClass $instance
2199 * @param int $userid
2202 public function unenrol_user(stdClass
$instance, $userid) {
2203 global $CFG, $USER, $DB;
2204 require_once("$CFG->dirroot/group/lib.php");
2206 $name = $this->get_name();
2207 $courseid = $instance->courseid
;
2209 if ($instance->enrol
!== $name) {
2210 throw new coding_exception('invalid enrol instance!');
2212 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
2214 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$userid))) {
2215 // weird, user not enrolled
2219 // Remove all users groups linked to this enrolment instance.
2220 if ($gms = $DB->get_records('groups_members', array('userid'=>$userid, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
))) {
2221 foreach ($gms as $gm) {
2222 groups_remove_member($gm->groupid
, $gm->userid
);
2226 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id
, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
));
2227 $DB->delete_records('user_enrolments', array('id'=>$ue->id
));
2229 // add extra info and trigger event
2230 $ue->courseid
= $courseid;
2234 FROM {user_enrolments} ue
2235 JOIN {enrol} e ON (e.id = ue.enrolid)
2236 WHERE ue.userid = :userid AND e.courseid = :courseid";
2237 if ($DB->record_exists_sql($sql, array('userid'=>$userid, 'courseid'=>$courseid))) {
2238 $ue->lastenrol
= false;
2241 // the big cleanup IS necessary!
2242 require_once("$CFG->libdir/gradelib.php");
2244 // remove all remaining roles
2245 role_unassign_all(array('userid'=>$userid, 'contextid'=>$context->id
), true, false);
2247 //clean up ALL invisible user data from course if this is the last enrolment - groups, grades, etc.
2248 groups_delete_group_members($courseid, $userid);
2250 grade_user_unenrol($courseid, $userid);
2252 $DB->delete_records('user_lastaccess', array('userid'=>$userid, 'courseid'=>$courseid));
2254 $ue->lastenrol
= true; // means user not enrolled any more
2257 $event = \core\event\user_enrolment_deleted
::create(
2259 'courseid' => $courseid,
2260 'context' => $context,
2261 'relateduserid' => $ue->userid
,
2262 'objectid' => $ue->id
,
2264 'userenrolment' => (array)$ue,
2271 // User enrolments have changed, so mark user as dirty.
2272 mark_user_dirty($userid);
2274 // Check if courrse contacts cache needs to be cleared.
2275 core_course_category
::user_enrolment_changed($courseid, $ue->userid
, ENROL_USER_SUSPENDED
);
2277 // reset current user enrolment caching
2278 if ($userid == $USER->id
) {
2279 if (isset($USER->enrol
['enrolled'][$courseid])) {
2280 unset($USER->enrol
['enrolled'][$courseid]);
2282 if (isset($USER->enrol
['tempguest'][$courseid])) {
2283 unset($USER->enrol
['tempguest'][$courseid]);
2284 remove_temp_course_roles($context);
2290 * Forces synchronisation of user enrolments.
2292 * This is important especially for external enrol plugins,
2293 * this function is called for all enabled enrol plugins
2294 * right after every user login.
2296 * @param object $user user record
2299 public function sync_user_enrolments($user) {
2300 // override if necessary
2304 * This returns false for backwards compatibility, but it is really recommended.
2309 public function use_standard_editing_ui() {
2314 * Return whether or not, given the current state, it is possible to add a new instance
2315 * of this enrolment plugin to the course.
2317 * Default implementation is just for backwards compatibility.
2319 * @param int $courseid
2322 public function can_add_instance($courseid) {
2323 $link = $this->get_newinstance_link($courseid);
2324 return !empty($link);
2328 * Return whether or not, given the current state, it is possible to edit an instance
2329 * of this enrolment plugin in the course. Used by the standard editing UI
2330 * to generate a link to the edit instance form if editing is allowed.
2332 * @param stdClass $instance
2335 public function can_edit_instance($instance) {
2336 $context = context_course
::instance($instance->courseid
);
2338 return has_capability('enrol/' . $instance->enrol
. ':config', $context);
2342 * Returns link to page which may be used to add new instance of enrolment plugin in course.
2343 * @param int $courseid
2344 * @return moodle_url page url
2346 public function get_newinstance_link($courseid) {
2347 // override for most plugins, check if instance already exists in cases only one instance is supported
2352 * @deprecated since Moodle 2.8 MDL-35864 - please use can_delete_instance() instead.
2354 public function instance_deleteable($instance) {
2355 throw new coding_exception('Function enrol_plugin::instance_deleteable() is deprecated, use
2356 enrol_plugin::can_delete_instance() instead');
2360 * Is it possible to delete enrol instance via standard UI?
2362 * @param stdClass $instance
2365 public function can_delete_instance($instance) {
2370 * Is it possible to hide/show enrol instance via standard UI?
2372 * @param stdClass $instance
2375 public function can_hide_show_instance($instance) {
2376 debugging("The enrolment plugin '".$this->get_name()."' should override the function can_hide_show_instance().", DEBUG_DEVELOPER
);
2381 * Returns link to manual enrol UI if exists.
2382 * Does the access control tests automatically.
2384 * @param object $instance
2385 * @return moodle_url
2387 public function get_manual_enrol_link($instance) {
2392 * Returns list of unenrol links for all enrol instances in course.
2394 * @param int $instance
2395 * @return moodle_url or NULL if self unenrolment not supported
2397 public function get_unenrolself_link($instance) {
2398 global $USER, $CFG, $DB;
2400 $name = $this->get_name();
2401 if ($instance->enrol
!== $name) {
2402 throw new coding_exception('invalid enrol instance!');
2405 if ($instance->courseid
== SITEID
) {
2409 if (!enrol_is_enabled($name)) {
2413 if ($instance->status
!= ENROL_INSTANCE_ENABLED
) {
2417 if (!file_exists("$CFG->dirroot/enrol/$name/unenrolself.php")) {
2421 $context = context_course
::instance($instance->courseid
, MUST_EXIST
);
2423 if (!has_capability("enrol/$name:unenrolself", $context)) {
2427 if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id
, 'userid'=>$USER->id
, 'status'=>ENROL_USER_ACTIVE
))) {
2431 return new moodle_url("/enrol/$name/unenrolself.php", array('enrolid'=>$instance->id
));
2435 * Adds enrol instance UI to course edit form
2437 * @param object $instance enrol instance or null if does not exist yet
2438 * @param MoodleQuickForm $mform
2439 * @param object $data
2440 * @param object $context context of existing course or parent category if course does not exist
2443 public function course_edit_form($instance, MoodleQuickForm
$mform, $data, $context) {
2444 // override - usually at least enable/disable switch, has to add own form header
2448 * Adds form elements to add/edit instance form.
2451 * @param object $instance enrol instance or null if does not exist yet
2452 * @param MoodleQuickForm $mform
2453 * @param context $context
2456 public function edit_instance_form($instance, MoodleQuickForm
$mform, $context) {
2457 // Do nothing by default.
2461 * Perform custom validation of the data used to edit the instance.
2464 * @param array $data array of ("fieldname"=>value) of submitted data
2465 * @param array $files array of uploaded files "element_name"=>tmp_file_path
2466 * @param object $instance The instance data loaded from the DB.
2467 * @param context $context The context of the instance we are editing
2468 * @return array of "element_name"=>"error_description" if there are errors,
2469 * or an empty array if everything is OK.
2471 public function edit_instance_validation($data, $files, $instance, $context) {
2472 // No errors by default.
2473 debugging('enrol_plugin::edit_instance_validation() is missing. This plugin has no validation!', DEBUG_DEVELOPER
);
2478 * Validates course edit form data
2480 * @param object $instance enrol instance or null if does not exist yet
2481 * @param array $data
2482 * @param object $context context of existing course or parent category if course does not exist
2483 * @return array errors array
2485 public function course_edit_validation($instance, array $data, $context) {
2490 * Called after updating/inserting course.
2492 * @param bool $inserted true if course just inserted
2493 * @param object $course
2494 * @param object $data form data
2497 public function course_updated($inserted, $course, $data) {
2499 if ($this->get_config('defaultenrol')) {
2500 $this->add_default_instance($course);
2506 * Add new instance of enrol plugin.
2507 * @param object $course
2508 * @param array instance fields
2509 * @return int id of new instance, null if can not be created
2511 public function add_instance($course, array $fields = NULL) {
2514 if ($course->id
== SITEID
) {
2515 throw new coding_exception('Invalid request to add enrol instance to frontpage.');
2518 $instance = new stdClass();
2519 $instance->enrol
= $this->get_name();
2520 $instance->status
= ENROL_INSTANCE_ENABLED
;
2521 $instance->courseid
= $course->id
;
2522 $instance->enrolstartdate
= 0;
2523 $instance->enrolenddate
= 0;
2524 $instance->timemodified
= time();
2525 $instance->timecreated
= $instance->timemodified
;
2526 $instance->sortorder
= $DB->get_field('enrol', 'COALESCE(MAX(sortorder), -1) + 1', array('courseid'=>$course->id
));
2528 $fields = (array)$fields;
2529 unset($fields['enrol']);
2530 unset($fields['courseid']);
2531 unset($fields['sortorder']);
2532 foreach($fields as $field=>$value) {
2533 $instance->$field = $value;
2536 $instance->id
= $DB->insert_record('enrol', $instance);
2538 \core\event\enrol_instance_created
::create_from_record($instance)->trigger();
2540 return $instance->id
;
2544 * Update instance of enrol plugin.
2547 * @param stdClass $instance
2548 * @param stdClass $data modified instance fields
2551 public function update_instance($instance, $data) {
2553 $properties = array('status', 'name', 'password', 'customint1', 'customint2', 'customint3',
2554 'customint4', 'customint5', 'customint6', 'customint7', 'customint8',
2555 'customchar1', 'customchar2', 'customchar3', 'customdec1', 'customdec2',
2556 'customtext1', 'customtext2', 'customtext3', 'customtext4', 'roleid',
2557 'enrolperiod', 'expirynotify', 'notifyall', 'expirythreshold',
2558 'enrolstartdate', 'enrolenddate', 'cost', 'currency');
2560 foreach ($properties as $key) {
2561 if (isset($data->$key)) {
2562 $instance->$key = $data->$key;
2565 $instance->timemodified
= time();
2567 $update = $DB->update_record('enrol', $instance);
2569 \core\event\enrol_instance_updated
::create_from_record($instance)->trigger();
2575 * Add new instance of enrol plugin with default settings,
2576 * called when adding new instance manually or when adding new course.
2578 * Not all plugins support this.
2580 * @param object $course
2581 * @return int id of new instance or null if no default supported
2583 public function add_default_instance($course) {
2588 * Update instance status
2590 * Override when plugin needs to do some action when enabled or disabled.
2592 * @param stdClass $instance
2593 * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
2596 public function update_status($instance, $newstatus) {
2599 $instance->status
= $newstatus;
2600 $DB->update_record('enrol', $instance);
2602 $context = context_course
::instance($instance->courseid
);
2603 \core\event\enrol_instance_updated
::create_from_record($instance)->trigger();
2605 // Invalidate all enrol caches.
2606 $context->mark_dirty();
2610 * Delete course enrol plugin instance, unenrol all users.
2611 * @param object $instance
2614 public function delete_instance($instance) {
2617 $name = $this->get_name();
2618 if ($instance->enrol
!== $name) {
2619 throw new coding_exception('invalid enrol instance!');
2622 //first unenrol all users
2623 $participants = $DB->get_recordset('user_enrolments', array('enrolid'=>$instance->id
));
2624 foreach ($participants as $participant) {
2625 $this->unenrol_user($instance, $participant->userid
);
2627 $participants->close();
2629 // now clean up all remainders that were not removed correctly
2630 if ($gms = $DB->get_records('groups_members', array('itemid' => $instance->id
, 'component' => 'enrol_' . $name))) {
2631 foreach ($gms as $gm) {
2632 groups_remove_member($gm->groupid
, $gm->userid
);
2635 $DB->delete_records('role_assignments', array('itemid'=>$instance->id
, 'component'=>'enrol_'.$name));
2636 $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id
));
2638 // finally drop the enrol row
2639 $DB->delete_records('enrol', array('id'=>$instance->id
));
2641 $context = context_course
::instance($instance->courseid
);
2642 \core\event\enrol_instance_deleted
::create_from_record($instance)->trigger();
2644 // Invalidate all enrol caches.
2645 $context->mark_dirty();
2649 * Creates course enrol form, checks if form submitted
2650 * and enrols user if necessary. It can also redirect.
2652 * @param stdClass $instance
2653 * @return string html text, usually a form in a text box
2655 public function enrol_page_hook(stdClass
$instance) {
2660 * Checks if user can self enrol.
2662 * @param stdClass $instance enrolment instance
2663 * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
2664 * used by navigation to improve performance.
2665 * @return bool|string true if successful, else error message or false
2667 public function can_self_enrol(stdClass
$instance, $checkuserenrolment = true) {
2672 * Return information for enrolment instance containing list of parameters required
2673 * for enrolment, name of enrolment plugin etc.
2675 * @param stdClass $instance enrolment instance
2676 * @return array instance info.
2678 public function get_enrol_info(stdClass
$instance) {
2683 * Adds navigation links into course admin block.
2685 * By defaults looks for manage links only.
2687 * @param navigation_node $instancesnode
2688 * @param stdClass $instance
2691 public function add_course_navigation($instancesnode, stdClass
$instance) {
2692 if ($this->use_standard_editing_ui()) {
2693 $context = context_course
::instance($instance->courseid
);
2694 $cap = 'enrol/' . $instance->enrol
. ':config';
2695 if (has_capability($cap, $context)) {
2696 $linkparams = array('courseid' => $instance->courseid
, 'id' => $instance->id
, 'type' => $instance->enrol
);
2697 $managelink = new moodle_url('/enrol/editinstance.php', $linkparams);
2698 $instancesnode->add($this->get_instance_name($instance), $managelink, navigation_node
::TYPE_SETTING
);
2704 * Returns edit icons for the page with list of instances
2705 * @param stdClass $instance
2708 public function get_action_icons(stdClass
$instance) {
2712 if ($this->use_standard_editing_ui()) {
2713 $linkparams = array('courseid' => $instance->courseid
, 'id' => $instance->id
, 'type' => $instance->enrol
);
2714 $editlink = new moodle_url("/enrol/editinstance.php", $linkparams);
2715 $icons[] = $OUTPUT->action_icon($editlink, new pix_icon('t/edit', get_string('edit'), 'core',
2716 array('class' => 'iconsmall')));
2722 * Reads version.php and determines if it is necessary
2723 * to execute the cron job now.
2726 public function is_cron_required() {
2729 $name = $this->get_name();
2730 $versionfile = "$CFG->dirroot/enrol/$name/version.php";
2731 $plugin = new stdClass();
2732 include($versionfile);
2733 if (empty($plugin->cron
)) {
2736 $lastexecuted = $this->get_config('lastcron', 0);
2737 if ($lastexecuted +
$plugin->cron
< time()) {
2745 * Called for all enabled enrol plugins that returned true from is_cron_required().
2748 public function cron() {
2752 * Called when user is about to be deleted
2753 * @param object $user
2756 public function user_delete($user) {
2761 JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
2762 WHERE e.enrol = :name AND ue.userid = :userid";
2763 $params = array('name'=>$this->get_name(), 'userid'=>$user->id
);
2765 $rs = $DB->get_recordset_sql($sql, $params);
2766 foreach($rs as $instance) {
2767 $this->unenrol_user($instance, $user->id
);
2773 * Returns an enrol_user_button that takes the user to a page where they are able to
2774 * enrol users into the managers course through this plugin.
2776 * Optional: If the plugin supports manual enrolments it can choose to override this
2777 * otherwise it shouldn't
2779 * @param course_enrolment_manager $manager
2780 * @return enrol_user_button|false
2782 public function get_manual_enrol_button(course_enrolment_manager
$manager) {
2787 * Gets an array of the user enrolment actions
2789 * @param course_enrolment_manager $manager
2790 * @param stdClass $ue
2791 * @return array An array of user_enrolment_actions
2793 public function get_user_enrolment_actions(course_enrolment_manager
$manager, $ue) {
2795 $context = $manager->get_context();
2796 $instance = $ue->enrolmentinstance
;
2797 $params = $manager->get_moodlepage()->url
->params();
2798 $params['ue'] = $ue->id
;
2800 // Edit enrolment action.
2801 if ($this->allow_manage($instance) && has_capability("enrol/{$instance->enrol}:manage", $context)) {
2802 $title = get_string('editenrolment', 'enrol');
2803 $icon = new pix_icon('t/edit', $title);
2804 $url = new moodle_url('/enrol/editenrolment.php', $params);
2806 'class' => 'editenrollink',
2808 'data-action' => ENROL_ACTION_EDIT
2810 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2814 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/{$instance->enrol}:unenrol", $context)) {
2815 $title = get_string('unenrol', 'enrol');
2816 $icon = new pix_icon('t/delete', $title);
2817 $url = new moodle_url('/enrol/unenroluser.php', $params);
2819 'class' => 'unenrollink',
2821 'data-action' => ENROL_ACTION_UNENROL
2823 $actions[] = new user_enrolment_action($icon, $title, $url, $actionparams);
2829 * Returns true if the plugin has one or more bulk operations that can be performed on
2832 * @param course_enrolment_manager $manager
2835 public function has_bulk_operations(course_enrolment_manager
$manager) {
2840 * Return an array of enrol_bulk_enrolment_operation objects that define
2841 * the bulk actions that can be performed on user enrolments by the plugin.
2843 * @param course_enrolment_manager $manager
2846 public function get_bulk_operations(course_enrolment_manager
$manager) {
2851 * Do any enrolments need expiration processing.
2853 * Plugins that want to call this functionality must implement 'expiredaction' config setting.
2855 * @param progress_trace $trace
2856 * @param int $courseid one course, empty mean all
2857 * @return bool true if any data processed, false if not
2859 public function process_expirations(progress_trace
$trace, $courseid = null) {
2862 $name = $this->get_name();
2863 if (!enrol_is_enabled($name)) {
2872 $coursesql = "AND e.courseid = :courseid";
2875 // Deal with expired accounts.
2876 $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP
);
2878 if ($action == ENROL_EXT_REMOVED_UNENROL
) {
2879 $instances = array();
2880 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2881 FROM {user_enrolments} ue
2882 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2883 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2884 WHERE ue.timeend > 0 AND ue.timeend < :now $coursesql";
2885 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE
, 'enrol'=>$name, 'courseid'=>$courseid);
2887 $rs = $DB->get_recordset_sql($sql, $params);
2888 foreach ($rs as $ue) {
2890 $trace->output("Starting processing of enrol_$name expirations...");
2893 if (empty($instances[$ue->enrolid
])) {
2894 $instances[$ue->enrolid
] = $DB->get_record('enrol', array('id'=>$ue->enrolid
));
2896 $instance = $instances[$ue->enrolid
];
2897 if (!$this->roles_protected()) {
2898 // Let's just guess what extra roles are supposed to be removed.
2899 if ($instance->roleid
) {
2900 role_unassign($instance->roleid
, $ue->userid
, $ue->contextid
);
2903 // The unenrol cleans up all subcontexts if this is the only course enrolment for this user.
2904 $this->unenrol_user($instance, $ue->userid
);
2905 $trace->output("Unenrolling expired user $ue->userid from course $instance->courseid", 1);
2910 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES
or $action == ENROL_EXT_REMOVED_SUSPEND
) {
2911 $instances = array();
2912 $sql = "SELECT ue.*, e.courseid, c.id AS contextid
2913 FROM {user_enrolments} ue
2914 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :enrol)
2915 JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
2916 WHERE ue.timeend > 0 AND ue.timeend < :now
2917 AND ue.status = :useractive $coursesql";
2918 $params = array('now'=>time(), 'courselevel'=>CONTEXT_COURSE
, 'useractive'=>ENROL_USER_ACTIVE
, 'enrol'=>$name, 'courseid'=>$courseid);
2919 $rs = $DB->get_recordset_sql($sql, $params);
2920 foreach ($rs as $ue) {
2922 $trace->output("Starting processing of enrol_$name expirations...");
2925 if (empty($instances[$ue->enrolid
])) {
2926 $instances[$ue->enrolid
] = $DB->get_record('enrol', array('id'=>$ue->enrolid
));
2928 $instance = $instances[$ue->enrolid
];
2930 if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES
) {
2931 if (!$this->roles_protected()) {
2932 // Let's just guess what roles should be removed.
2933 $count = $DB->count_records('role_assignments', array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
));
2935 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'', 'itemid'=>0));
2937 } else if ($count > 1 and $instance->roleid
) {
2938 role_unassign($instance->roleid
, $ue->userid
, $ue->contextid
, '', 0);
2941 // In any case remove all roles that belong to this instance and user.
2942 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'enrol_'.$name, 'itemid'=>$instance->id
), true);
2943 // Final cleanup of subcontexts if there are no more course roles.
2944 if (0 == $DB->count_records('role_assignments', array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
))) {
2945 role_unassign_all(array('userid'=>$ue->userid
, 'contextid'=>$ue->contextid
, 'component'=>'', 'itemid'=>0), true);
2949 $this->update_user_enrol($instance, $ue->userid
, ENROL_USER_SUSPENDED
);
2950 $trace->output("Suspending expired user $ue->userid in course $instance->courseid", 1);
2956 // ENROL_EXT_REMOVED_KEEP means no changes.
2960 $trace->output("...finished processing of enrol_$name expirations");
2962 $trace->output("No expired enrol_$name enrolments detected");
2970 * Send expiry notifications.
2972 * Plugin that wants to have expiry notification MUST implement following:
2973 * - expirynotifyhour plugin setting,
2974 * - configuration options in instance edit form (expirynotify, notifyall and expirythreshold),
2975 * - notification strings (expirymessageenrollersubject, expirymessageenrollerbody,
2976 * expirymessageenrolledsubject and expirymessageenrolledbody),
2977 * - expiry_notification provider in db/messages.php,
2978 * - upgrade code that sets default thresholds for existing courses (should be 1 day),
2979 * - something that calls this method, such as cron.
2981 * @param progress_trace $trace (accepts bool for backwards compatibility only)
2983 public function send_expiry_notifications($trace) {
2986 $name = $this->get_name();
2987 if (!enrol_is_enabled($name)) {
2992 // Unfortunately this may take a long time, it should not be interrupted,
2993 // otherwise users get duplicate notification.
2995 core_php_time_limit
::raise();
2996 raise_memory_limit(MEMORY_HUGE
);
2999 $expirynotifylast = $this->get_config('expirynotifylast', 0);
3000 $expirynotifyhour = $this->get_config('expirynotifyhour');
3001 if (is_null($expirynotifyhour)) {
3002 debugging("send_expiry_notifications() in $name enrolment plugin needs expirynotifyhour setting");
3007 if (!($trace instanceof progress_trace
)) {
3008 $trace = $trace ?
new text_progress_trace() : new null_progress_trace();
3009 debugging('enrol_plugin::send_expiry_notifications() now expects progress_trace instance as parameter!', DEBUG_DEVELOPER
);
3013 $notifytime = usergetmidnight($timenow, $CFG->timezone
) +
($expirynotifyhour * 3600);
3015 if ($expirynotifylast > $notifytime) {
3016 $trace->output($name.' enrolment expiry notifications were already sent today at '.userdate($expirynotifylast, '', $CFG->timezone
).'.');
3020 } else if ($timenow < $notifytime) {
3021 $trace->output($name.' enrolment expiry notifications will be sent at '.userdate($notifytime, '', $CFG->timezone
).'.');
3026 $trace->output('Processing '.$name.' enrolment expiration notifications...');
3028 // Notify users responsible for enrolment once every day.
3029 $sql = "SELECT ue.*, e.expirynotify, e.notifyall, e.expirythreshold, e.courseid, c.fullname
3030 FROM {user_enrolments} ue
3031 JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = :name AND e.expirynotify > 0 AND e.status = :enabled)
3032 JOIN {course} c ON (c.id = e.courseid)
3033 JOIN {user} u ON (u.id = ue.userid AND u.deleted = 0 AND u.suspended = 0)
3034 WHERE ue.status = :active AND ue.timeend > 0 AND ue.timeend > :now1 AND ue.timeend < (e.expirythreshold + :now2)
3035 ORDER BY ue.enrolid ASC, u.lastname ASC, u.firstname ASC, u.id ASC";
3036 $params = array('enabled'=>ENROL_INSTANCE_ENABLED
, 'active'=>ENROL_USER_ACTIVE
, 'now1'=>$timenow, 'now2'=>$timenow, 'name'=>$name);
3038 $rs = $DB->get_recordset_sql($sql, $params);
3043 foreach($rs as $ue) {
3044 if ($lastenrollid and $lastenrollid != $ue->enrolid
) {
3045 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3048 $lastenrollid = $ue->enrolid
;
3050 $enroller = $this->get_enroller($ue->enrolid
);
3051 $context = context_course
::instance($ue->courseid
);
3053 $user = $DB->get_record('user', array('id'=>$ue->userid
));
3055 $users[] = array('fullname'=>fullname($user, has_capability('moodle/site:viewfullnames', $context, $enroller)), 'timeend'=>$ue->timeend
);
3057 if (!$ue->notifyall
) {
3061 if ($ue->timeend
- $ue->expirythreshold +
86400 < $timenow) {
3062 // Notify enrolled users only once at the start of the threshold.
3063 $trace->output("user $ue->userid was already notified that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
3067 $this->notify_expiry_enrolled($user, $ue, $trace);
3071 if ($lastenrollid and $users) {
3072 $this->notify_expiry_enroller($lastenrollid, $users, $trace);
3075 $trace->output('...notification processing finished.');
3078 $this->set_config('expirynotifylast', $timenow);
3082 * Returns the user who is responsible for enrolments for given instance.
3084 * Override if plugin knows anybody better than admin.
3086 * @param int $instanceid enrolment instance id
3087 * @return stdClass user record
3089 protected function get_enroller($instanceid) {
3094 * Notify user about incoming expiration of their enrolment,
3095 * it is called only if notification of enrolled users (aka students) is enabled in course.
3097 * This is executed only once for each expiring enrolment right
3098 * at the start of the expiration threshold.
3100 * @param stdClass $user
3101 * @param stdClass $ue
3102 * @param progress_trace $trace
3104 protected function notify_expiry_enrolled($user, $ue, progress_trace
$trace) {
3107 $name = $this->get_name();
3109 $oldforcelang = force_current_language($user->lang
);
3111 $enroller = $this->get_enroller($ue->enrolid
);
3112 $context = context_course
::instance($ue->courseid
);
3114 $a = new stdClass();
3115 $a->course
= format_string($ue->fullname
, true, array('context'=>$context));
3116 $a->user
= fullname($user, true);
3117 $a->timeend
= userdate($ue->timeend
, '', $user->timezone
);
3118 $a->enroller
= fullname($enroller, has_capability('moodle/site:viewfullnames', $context, $user));
3120 $subject = get_string('expirymessageenrolledsubject', 'enrol_'.$name, $a);
3121 $body = get_string('expirymessageenrolledbody', 'enrol_'.$name, $a);
3123 $message = new \core\message\
message();
3124 $message->courseid
= $ue->courseid
;
3125 $message->notification
= 1;
3126 $message->component
= 'enrol_'.$name;
3127 $message->name
= 'expiry_notification';
3128 $message->userfrom
= $enroller;
3129 $message->userto
= $user;
3130 $message->subject
= $subject;
3131 $message->fullmessage
= $body;
3132 $message->fullmessageformat
= FORMAT_MARKDOWN
;
3133 $message->fullmessagehtml
= markdown_to_html($body);
3134 $message->smallmessage
= $subject;
3135 $message->contexturlname
= $a->course
;
3136 $message->contexturl
= (string)new moodle_url('/course/view.php', array('id'=>$ue->courseid
));
3138 if (message_send($message)) {
3139 $trace->output("notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
3141 $trace->output("error notifying user $ue->userid that enrolment in course $ue->courseid expires on ".userdate($ue->timeend
, '', $CFG->timezone
), 1);
3144 force_current_language($oldforcelang);
3148 * Notify person responsible for enrolments that some user enrolments will be expired soon,
3149 * it is called only if notification of enrollers (aka teachers) is enabled in course.
3151 * This is called repeatedly every day for each course if there are any pending expiration
3152 * in the expiration threshold.
3155 * @param array $users
3156 * @param progress_trace $trace
3158 protected function notify_expiry_enroller($eid, $users, progress_trace
$trace) {
3161 $name = $this->get_name();
3163 $instance = $DB->get_record('enrol', array('id'=>$eid, 'enrol'=>$name));
3164 $context = context_course
::instance($instance->courseid
);
3165 $course = $DB->get_record('course', array('id'=>$instance->courseid
));
3167 $enroller = $this->get_enroller($instance->id
);
3168 $admin = get_admin();
3170 $oldforcelang = force_current_language($enroller->lang
);
3172 foreach($users as $key=>$info) {
3173 $users[$key] = '* '.$info['fullname'].' - '.userdate($info['timeend'], '', $enroller->timezone
);
3176 $a = new stdClass();
3177 $a->course
= format_string($course->fullname
, true, array('context'=>$context));
3178 $a->threshold
= get_string('numdays', '', $instance->expirythreshold
/ (60*60*24));
3179 $a->users
= implode("\n", $users);
3180 $a->extendurl
= (string)new moodle_url('/user/index.php', array('id'=>$instance->courseid
));
3182 $subject = get_string('expirymessageenrollersubject', 'enrol_'.$name, $a);
3183 $body = get_string('expirymessageenrollerbody', 'enrol_'.$name, $a);
3185 $message = new \core\message\
message();
3186 $message->courseid
= $course->id
;
3187 $message->notification
= 1;
3188 $message->component
= 'enrol_'.$name;
3189 $message->name
= 'expiry_notification';
3190 $message->userfrom
= $admin;
3191 $message->userto
= $enroller;
3192 $message->subject
= $subject;
3193 $message->fullmessage
= $body;
3194 $message->fullmessageformat
= FORMAT_MARKDOWN
;
3195 $message->fullmessagehtml
= markdown_to_html($body);
3196 $message->smallmessage
= $subject;
3197 $message->contexturlname
= $a->course
;
3198 $message->contexturl
= $a->extendurl
;
3200 if (message_send($message)) {
3201 $trace->output("notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3203 $trace->output("error notifying user $enroller->id about all expiring $name enrolments in course $instance->courseid", 1);
3206 force_current_language($oldforcelang);
3210 * Backup execution step hook to annotate custom fields.
3212 * @param backup_enrolments_execution_step $step
3213 * @param stdClass $enrol
3215 public function backup_annotate_custom_fields(backup_enrolments_execution_step
$step, stdClass
$enrol) {
3216 // Override as necessary to annotate custom fields in the enrol table.
3220 * Automatic enrol sync executed during restore.
3221 * Useful for automatic sync by course->idnumber or course category.
3222 * @param stdClass $course course record
3224 public function restore_sync_course($course) {
3225 // Override if necessary.
3229 * Restore instance and map settings.
3231 * @param restore_enrolments_structure_step $step
3232 * @param stdClass $data
3233 * @param stdClass $course
3236 public function restore_instance(restore_enrolments_structure_step
$step, stdClass
$data, $course, $oldid) {
3237 // Do not call this from overridden methods, restore and set new id there.
3238 $step->set_mapping('enrol', $oldid, 0);
3242 * Restore user enrolment.
3244 * @param restore_enrolments_structure_step $step
3245 * @param stdClass $data
3246 * @param stdClass $instance
3247 * @param int $oldinstancestatus
3248 * @param int $userid
3250 public function restore_user_enrolment(restore_enrolments_structure_step
$step, $data, $instance, $userid, $oldinstancestatus) {
3251 // Override as necessary if plugin supports restore of enrolments.
3255 * Restore role assignment.
3257 * @param stdClass $instance
3258 * @param int $roleid
3259 * @param int $userid
3260 * @param int $contextid
3262 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
3263 // No role assignment by default, override if necessary.
3267 * Restore user group membership.
3268 * @param stdClass $instance
3269 * @param int $groupid
3270 * @param int $userid
3272 public function restore_group_member($instance, $groupid, $userid) {
3273 // Implement if you want to restore protected group memberships,
3274 // usually this is not necessary because plugins should be able to recreate the memberships automatically.
3278 * Returns defaults for new instances.
3282 public function get_instance_defaults() {
3287 * Validate a list of parameter names and types.
3290 * @param array $data array of ("fieldname"=>value) of submitted data
3291 * @param array $rules array of ("fieldname"=>PARAM_X types - or "fieldname"=>array( list of valid options )
3292 * @return array of "element_name"=>"error_description" if there are errors,
3293 * or an empty array if everything is OK.
3295 public function validate_param_types($data, $rules) {
3297 $invalidstr = get_string('invaliddata', 'error');
3298 foreach ($rules as $fieldname => $rule) {
3299 if (is_array($rule)) {
3300 if (!in_array($data[$fieldname], $rule)) {
3301 $errors[$fieldname] = $invalidstr;
3304 if ($data[$fieldname] != clean_param($data[$fieldname], $rule)) {
3305 $errors[$fieldname] = $invalidstr;