/lib/enrollib.php
PHP | 3308 lines | 1856 code | 419 blank | 1033 comment | 339 complexity | 3b86461fbdce7716244b6aa12eb51c80 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?php
- // This file is part of Moodle - http://moodle.org/
- //
- // Moodle is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // Moodle is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
- /**
- * This library includes the basic parts of enrol api.
- * It is available on each page.
- *
- * @package core
- * @subpackage enrol
- * @copyright 2010 Petr Skoda {@link http://skodak.org}
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
- defined('MOODLE_INTERNAL') || die();
- /** Course enrol instance enabled. (used in enrol->status) */
- define('ENROL_INSTANCE_ENABLED', 0);
- /** Course enrol instance disabled, user may enter course if other enrol instance enabled. (used in enrol->status)*/
- define('ENROL_INSTANCE_DISABLED', 1);
- /** User is active participant (used in user_enrolments->status)*/
- define('ENROL_USER_ACTIVE', 0);
- /** User participation in course is suspended (used in user_enrolments->status) */
- define('ENROL_USER_SUSPENDED', 1);
- /** @deprecated - enrol caching was reworked, use ENROL_MAX_TIMESTAMP instead */
- define('ENROL_REQUIRE_LOGIN_CACHE_PERIOD', 1800);
- /** The timestamp indicating forever */
- define('ENROL_MAX_TIMESTAMP', 2147483647);
- /** When user disappears from external source, the enrolment is completely removed */
- define('ENROL_EXT_REMOVED_UNENROL', 0);
- /** When user disappears from external source, the enrolment is kept as is - one way sync */
- define('ENROL_EXT_REMOVED_KEEP', 1);
- /** @deprecated since 2.4 not used any more, migrate plugin to new restore methods */
- define('ENROL_RESTORE_TYPE', 'enrolrestore');
- /**
- * When user disappears from external source, user enrolment is suspended, roles are kept as is.
- * In some cases user needs a role with some capability to be visible in UI - suc has in gradebook,
- * assignments, etc.
- */
- define('ENROL_EXT_REMOVED_SUSPEND', 2);
- /**
- * When user disappears from external source, the enrolment is suspended and roles assigned
- * by enrol instance are removed. Please note that user may "disappear" from gradebook and other areas.
- * */
- define('ENROL_EXT_REMOVED_SUSPENDNOROLES', 3);
- /**
- * Do not send email.
- */
- define('ENROL_DO_NOT_SEND_EMAIL', 0);
- /**
- * Send email from course contact.
- */
- define('ENROL_SEND_EMAIL_FROM_COURSE_CONTACT', 1);
- /**
- * Send email from enrolment key holder.
- */
- define('ENROL_SEND_EMAIL_FROM_KEY_HOLDER', 2);
- /**
- * Send email from no reply address.
- */
- define('ENROL_SEND_EMAIL_FROM_NOREPLY', 3);
- /** Edit enrolment action. */
- define('ENROL_ACTION_EDIT', 'editenrolment');
- /** Unenrol action. */
- define('ENROL_ACTION_UNENROL', 'unenrol');
- /**
- * Returns instances of enrol plugins
- * @param bool $enabled return enabled only
- * @return array of enrol plugins name=>instance
- */
- function enrol_get_plugins($enabled) {
- global $CFG;
- $result = array();
- if ($enabled) {
- // sorted by enabled plugin order
- $enabled = explode(',', $CFG->enrol_plugins_enabled);
- $plugins = array();
- foreach ($enabled as $plugin) {
- $plugins[$plugin] = "$CFG->dirroot/enrol/$plugin";
- }
- } else {
- // sorted alphabetically
- $plugins = core_component::get_plugin_list('enrol');
- ksort($plugins);
- }
- foreach ($plugins as $plugin=>$location) {
- $class = "enrol_{$plugin}_plugin";
- if (!class_exists($class)) {
- if (!file_exists("$location/lib.php")) {
- continue;
- }
- include_once("$location/lib.php");
- if (!class_exists($class)) {
- continue;
- }
- }
- $result[$plugin] = new $class();
- }
- return $result;
- }
- /**
- * Returns instance of enrol plugin
- * @param string $name name of enrol plugin ('manual', 'guest', ...)
- * @return enrol_plugin
- */
- function enrol_get_plugin($name) {
- global $CFG;
- $name = clean_param($name, PARAM_PLUGIN);
- if (empty($name)) {
- // ignore malformed or missing plugin names completely
- return null;
- }
- $location = "$CFG->dirroot/enrol/$name";
- $class = "enrol_{$name}_plugin";
- if (!class_exists($class)) {
- if (!file_exists("$location/lib.php")) {
- return null;
- }
- include_once("$location/lib.php");
- if (!class_exists($class)) {
- return null;
- }
- }
- return new $class();
- }
- /**
- * Returns enrolment instances in given course.
- * @param int $courseid
- * @param bool $enabled
- * @return array of enrol instances
- */
- function enrol_get_instances($courseid, $enabled) {
- global $DB, $CFG;
- if (!$enabled) {
- return $DB->get_records('enrol', array('courseid'=>$courseid), 'sortorder,id');
- }
- $result = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id');
- $enabled = explode(',', $CFG->enrol_plugins_enabled);
- foreach ($result as $key=>$instance) {
- if (!in_array($instance->enrol, $enabled)) {
- unset($result[$key]);
- continue;
- }
- if (!file_exists("$CFG->dirroot/enrol/$instance->enrol/lib.php")) {
- // broken plugin
- unset($result[$key]);
- continue;
- }
- }
- return $result;
- }
- /**
- * Checks if a given plugin is in the list of enabled enrolment plugins.
- *
- * @param string $enrol Enrolment plugin name
- * @return boolean Whether the plugin is enabled
- */
- function enrol_is_enabled($enrol) {
- global $CFG;
- if (empty($CFG->enrol_plugins_enabled)) {
- return false;
- }
- return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
- }
- /**
- * Check all the login enrolment information for the given user object
- * by querying the enrolment plugins
- *
- * This function may be very slow, use only once after log-in or login-as.
- *
- * @param stdClass $user
- * @return void
- */
- function enrol_check_plugins($user) {
- global $CFG;
- if (empty($user->id) or isguestuser($user)) {
- // shortcut - there is no enrolment work for guests and not-logged-in users
- return;
- }
- // originally there was a broken admin test, but accidentally it was non-functional in 2.2,
- // which proved it was actually not necessary.
- static $inprogress = array(); // To prevent this function being called more than once in an invocation
- if (!empty($inprogress[$user->id])) {
- return;
- }
- $inprogress[$user->id] = true; // Set the flag
- $enabled = enrol_get_plugins(true);
- foreach($enabled as $enrol) {
- $enrol->sync_user_enrolments($user);
- }
- unset($inprogress[$user->id]); // Unset the flag
- }
- /**
- * Do these two students share any course?
- *
- * The courses has to be visible and enrolments has to be active,
- * timestart and timeend restrictions are ignored.
- *
- * This function calls {@see enrol_get_shared_courses()} setting checkexistsonly
- * to true.
- *
- * @param stdClass|int $user1
- * @param stdClass|int $user2
- * @return bool
- */
- function enrol_sharing_course($user1, $user2) {
- return enrol_get_shared_courses($user1, $user2, false, true);
- }
- /**
- * Returns any courses shared by the two users
- *
- * The courses has to be visible and enrolments has to be active,
- * timestart and timeend restrictions are ignored.
- *
- * @global moodle_database $DB
- * @param stdClass|int $user1
- * @param stdClass|int $user2
- * @param bool $preloadcontexts If set to true contexts for the returned courses
- * will be preloaded.
- * @param bool $checkexistsonly If set to true then this function will return true
- * if the users share any courses and false if not.
- * @return array|bool An array of courses that both users are enrolled in OR if
- * $checkexistsonly set returns true if the users share any courses
- * and false if not.
- */
- function enrol_get_shared_courses($user1, $user2, $preloadcontexts = false, $checkexistsonly = false) {
- global $DB, $CFG;
- $user1 = isset($user1->id) ? $user1->id : $user1;
- $user2 = isset($user2->id) ? $user2->id : $user2;
- if (empty($user1) or empty($user2)) {
- return false;
- }
- if (!$plugins = explode(',', $CFG->enrol_plugins_enabled)) {
- return false;
- }
- list($plugins1, $params1) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee1');
- list($plugins2, $params2) = $DB->get_in_or_equal($plugins, SQL_PARAMS_NAMED, 'ee2');
- $params = array_merge($params1, $params2);
- $params['enabled1'] = ENROL_INSTANCE_ENABLED;
- $params['enabled2'] = ENROL_INSTANCE_ENABLED;
- $params['active1'] = ENROL_USER_ACTIVE;
- $params['active2'] = ENROL_USER_ACTIVE;
- $params['user1'] = $user1;
- $params['user2'] = $user2;
- $ctxselect = '';
- $ctxjoin = '';
- if ($preloadcontexts) {
- $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
- $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
- $params['contextlevel'] = CONTEXT_COURSE;
- }
- $sql = "SELECT c.* $ctxselect
- FROM {course} c
- JOIN (
- SELECT DISTINCT c.id
- FROM {course} c
- JOIN {enrol} e1 ON (c.id = e1.courseid AND e1.status = :enabled1 AND e1.enrol $plugins1)
- JOIN {user_enrolments} ue1 ON (ue1.enrolid = e1.id AND ue1.status = :active1 AND ue1.userid = :user1)
- JOIN {enrol} e2 ON (c.id = e2.courseid AND e2.status = :enabled2 AND e2.enrol $plugins2)
- JOIN {user_enrolments} ue2 ON (ue2.enrolid = e2.id AND ue2.status = :active2 AND ue2.userid = :user2)
- WHERE c.visible = 1
- ) ec ON ec.id = c.id
- $ctxjoin";
- if ($checkexistsonly) {
- return $DB->record_exists_sql($sql, $params);
- } else {
- $courses = $DB->get_records_sql($sql, $params);
- if ($preloadcontexts) {
- array_map('context_helper::preload_from_record', $courses);
- }
- return $courses;
- }
- }
- /**
- * This function adds necessary enrol plugins UI into the course edit form.
- *
- * @param MoodleQuickForm $mform
- * @param object $data course edit form data
- * @param object $context context of existing course or parent category if course does not exist
- * @return void
- */
- function enrol_course_edit_form(MoodleQuickForm $mform, $data, $context) {
- $plugins = enrol_get_plugins(true);
- if (!empty($data->id)) {
- $instances = enrol_get_instances($data->id, false);
- foreach ($instances as $instance) {
- if (!isset($plugins[$instance->enrol])) {
- continue;
- }
- $plugin = $plugins[$instance->enrol];
- $plugin->course_edit_form($instance, $mform, $data, $context);
- }
- } else {
- foreach ($plugins as $plugin) {
- $plugin->course_edit_form(NULL, $mform, $data, $context);
- }
- }
- }
- /**
- * Validate course edit form data
- *
- * @param array $data raw form data
- * @param object $context context of existing course or parent category if course does not exist
- * @return array errors array
- */
- function enrol_course_edit_validation(array $data, $context) {
- $errors = array();
- $plugins = enrol_get_plugins(true);
- if (!empty($data['id'])) {
- $instances = enrol_get_instances($data['id'], false);
- foreach ($instances as $instance) {
- if (!isset($plugins[$instance->enrol])) {
- continue;
- }
- $plugin = $plugins[$instance->enrol];
- $errors = array_merge($errors, $plugin->course_edit_validation($instance, $data, $context));
- }
- } else {
- foreach ($plugins as $plugin) {
- $errors = array_merge($errors, $plugin->course_edit_validation(NULL, $data, $context));
- }
- }
- return $errors;
- }
- /**
- * Update enrol instances after course edit form submission
- * @param bool $inserted true means new course added, false course already existed
- * @param object $course
- * @param object $data form data
- * @return void
- */
- function enrol_course_updated($inserted, $course, $data) {
- global $DB, $CFG;
- $plugins = enrol_get_plugins(true);
- foreach ($plugins as $plugin) {
- $plugin->course_updated($inserted, $course, $data);
- }
- }
- /**
- * Add navigation nodes
- * @param navigation_node $coursenode
- * @param object $course
- * @return void
- */
- function enrol_add_course_navigation(navigation_node $coursenode, $course) {
- global $CFG;
- $coursecontext = context_course::instance($course->id);
- $instances = enrol_get_instances($course->id, true);
- $plugins = enrol_get_plugins(true);
- // we do not want to break all course pages if there is some borked enrol plugin, right?
- foreach ($instances as $k=>$instance) {
- if (!isset($plugins[$instance->enrol])) {
- unset($instances[$k]);
- }
- }
- $usersnode = $coursenode->add(get_string('users'), null, navigation_node::TYPE_CONTAINER, null, 'users');
- if ($course->id != SITEID) {
- // list all participants - allows assigning roles, groups, etc.
- if (has_capability('moodle/course:enrolreview', $coursecontext)) {
- $url = new moodle_url('/user/index.php', array('id'=>$course->id));
- $usersnode->add(get_string('enrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'review', new pix_icon('i/enrolusers', ''));
- }
- // manage enrol plugin instances
- if (has_capability('moodle/course:enrolconfig', $coursecontext) or has_capability('moodle/course:enrolreview', $coursecontext)) {
- $url = new moodle_url('/enrol/instances.php', array('id'=>$course->id));
- } else {
- $url = NULL;
- }
- $instancesnode = $usersnode->add(get_string('enrolmentinstances', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'manageinstances');
- // each instance decides how to configure itself or how many other nav items are exposed
- foreach ($instances as $instance) {
- if (!isset($plugins[$instance->enrol])) {
- continue;
- }
- $plugins[$instance->enrol]->add_course_navigation($instancesnode, $instance);
- }
- if (!$url) {
- $instancesnode->trim_if_empty();
- }
- }
- // Manage groups in this course or even frontpage
- if (($course->groupmode || !$course->groupmodeforce) && has_capability('moodle/course:managegroups', $coursecontext)) {
- $url = new moodle_url('/group/index.php', array('id'=>$course->id));
- $usersnode->add(get_string('groups'), $url, navigation_node::TYPE_SETTING, null, 'groups', new pix_icon('i/group', ''));
- }
- if (has_any_capability(array( 'moodle/role:assign', 'moodle/role:safeoverride','moodle/role:override', 'moodle/role:review'), $coursecontext)) {
- // Override roles
- if (has_capability('moodle/role:review', $coursecontext)) {
- $url = new moodle_url('/admin/roles/permissions.php', array('contextid'=>$coursecontext->id));
- } else {
- $url = NULL;
- }
- $permissionsnode = $usersnode->add(get_string('permissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'override');
- // Add assign or override roles if allowed
- if ($course->id == SITEID or (!empty($CFG->adminsassignrolesincourse) and is_siteadmin())) {
- if (has_capability('moodle/role:assign', $coursecontext)) {
- $url = new moodle_url('/admin/roles/assign.php', array('contextid'=>$coursecontext->id));
- $permissionsnode->add(get_string('assignedroles', 'role'), $url, navigation_node::TYPE_SETTING, null, 'roles', new pix_icon('i/assignroles', ''));
- }
- }
- // Check role permissions
- if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override'), $coursecontext)) {
- $url = new moodle_url('/admin/roles/check.php', array('contextid'=>$coursecontext->id));
- $permissionsnode->add(get_string('checkpermissions', 'role'), $url, navigation_node::TYPE_SETTING, null, 'permissions', new pix_icon('i/checkpermissions', ''));
- }
- }
- // Deal somehow with users that are not enrolled but still got a role somehow
- if ($course->id != SITEID) {
- //TODO, create some new UI for role assignments at course level
- if (has_capability('moodle/course:reviewotherusers', $coursecontext)) {
- $url = new moodle_url('/enrol/otherusers.php', array('id'=>$course->id));
- $usersnode->add(get_string('notenrolledusers', 'enrol'), $url, navigation_node::TYPE_SETTING, null, 'otherusers', new pix_icon('i/assignroles', ''));
- }
- }
- // just in case nothing was actually added
- $usersnode->trim_if_empty();
- if ($course->id != SITEID) {
- if (isguestuser() or !isloggedin()) {
- // guest account can not be enrolled - no links for them
- } else if (is_enrolled($coursecontext)) {
- // unenrol link if possible
- foreach ($instances as $instance) {
- if (!isset($plugins[$instance->enrol])) {
- continue;
- }
- $plugin = $plugins[$instance->enrol];
- if ($unenrollink = $plugin->get_unenrolself_link($instance)) {
- $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
- $coursenode->add(get_string('unenrolme', 'core_enrol', $shortname), $unenrollink, navigation_node::TYPE_SETTING, null, 'unenrolself', new pix_icon('i/user', ''));
- break;
- //TODO. deal with multiple unenrol links - not likely case, but still...
- }
- }
- } else {
- // enrol link if possible
- if (is_viewing($coursecontext)) {
- // better not show any enrol link, this is intended for managers and inspectors
- } else {
- foreach ($instances as $instance) {
- if (!isset($plugins[$instance->enrol])) {
- continue;
- }
- $plugin = $plugins[$instance->enrol];
- if ($plugin->show_enrolme_link($instance)) {
- $url = new moodle_url('/enrol/index.php', array('id'=>$course->id));
- $shortname = format_string($course->shortname, true, array('context' => $coursecontext));
- $coursenode->add(get_string('enrolme', 'core_enrol', $shortname), $url, navigation_node::TYPE_SETTING, null, 'enrolself', new pix_icon('i/user', ''));
- break;
- }
- }
- }
- }
- }
- }
- /**
- * Returns list of courses current $USER is enrolled in and can access
- *
- * The $fields param is a list of field names to ADD so name just the fields you really need,
- * which will be added and uniq'd.
- *
- * If $allaccessible is true, this will additionally return courses that the current user is not
- * enrolled in, but can access because they are open to the user for other reasons (course view
- * permission, currently viewing course as a guest, or course allows guest access without
- * password).
- *
- * @param string|array $fields Extra fields to be returned (array or comma-separated list).
- * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
- * Allowed prefixes for sort fields are: "ul" for the user_lastaccess table, "c" for the courses table,
- * "ue" for the user_enrolments table.
- * @param int $limit max number of courses
- * @param array $courseids the list of course ids to filter by
- * @param bool $allaccessible Include courses user is not enrolled in, but can access
- * @param int $offset Offset the result set by this number
- * @param array $excludecourses IDs of hidden courses to exclude from search
- * @return array
- */
- function enrol_get_my_courses($fields = null, $sort = null, $limit = 0, $courseids = [], $allaccessible = false,
- $offset = 0, $excludecourses = []) {
- global $DB, $USER, $CFG;
- // Allowed prefixes and field names.
- $allowedprefixesandfields = ['c' => array_keys($DB->get_columns('course')),
- 'ul' => array_keys($DB->get_columns('user_lastaccess')),
- 'ue' => array_keys($DB->get_columns('user_enrolments'))];
- // Re-Arrange the course sorting according to the admin settings.
- $sort = enrol_get_courses_sortingsql($sort);
- // Guest account does not have any enrolled courses.
- if (!$allaccessible && (isguestuser() or !isloggedin())) {
- return array();
- }
- $basefields = [
- 'id', 'category', 'sortorder',
- 'shortname', 'fullname', 'idnumber',
- 'startdate', 'visible',
- 'groupmode', 'groupmodeforce', 'cacherev',
- 'showactivitydates', 'showcompletionconditions',
- ];
- if (empty($fields)) {
- $fields = $basefields;
- } else if (is_string($fields)) {
- // turn the fields from a string to an array
- $fields = explode(',', $fields);
- $fields = array_map('trim', $fields);
- $fields = array_unique(array_merge($basefields, $fields));
- } else if (is_array($fields)) {
- $fields = array_unique(array_merge($basefields, $fields));
- } else {
- throw new coding_exception('Invalid $fields parameter in enrol_get_my_courses()');
- }
- if (in_array('*', $fields)) {
- $fields = array('*');
- }
- $orderby = "";
- $sort = trim($sort);
- $sorttimeaccess = false;
- if (!empty($sort)) {
- $rawsorts = explode(',', $sort);
- $sorts = array();
- foreach ($rawsorts as $rawsort) {
- $rawsort = trim($rawsort);
- // Make sure that there are no more white spaces in sortparams after explode.
- $sortparams = array_values(array_filter(explode(' ', $rawsort)));
- // If more than 2 values present then throw coding_exception.
- if (isset($sortparams[2])) {
- throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
- }
- // Check the sort ordering if present, at the beginning.
- if (isset($sortparams[1]) && (preg_match("/^(asc|desc)$/i", $sortparams[1]) === 0)) {
- throw new coding_exception('Invalid sort direction in $sort parameter in enrol_get_my_courses()');
- }
- $sortfield = $sortparams[0];
- $sortdirection = $sortparams[1] ?? 'asc';
- if (strpos($sortfield, '.') !== false) {
- $sortfieldparams = explode('.', $sortfield);
- // Check if more than one dots present in the prefix field.
- if (isset($sortfieldparams[2])) {
- throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
- }
- list($prefix, $fieldname) = [$sortfieldparams[0], $sortfieldparams[1]];
- // Check if the field name matches with the allowed prefix.
- if (array_key_exists($prefix, $allowedprefixesandfields) &&
- (in_array($fieldname, $allowedprefixesandfields[$prefix]))) {
- if ($prefix === 'ul') {
- $sorts[] = "COALESCE({$prefix}.{$fieldname}, 0) {$sortdirection}";
- $sorttimeaccess = true;
- } else {
- // Check if the field name that matches with the prefix and just append to sorts.
- $sorts[] = $rawsort;
- }
- } else {
- throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
- }
- } else {
- // Check if the field name matches with $allowedprefixesandfields.
- $found = false;
- foreach (array_keys($allowedprefixesandfields) as $prefix) {
- if (in_array($sortfield, $allowedprefixesandfields[$prefix])) {
- if ($prefix === 'ul') {
- $sorts[] = "COALESCE({$prefix}.{$sortfield}, 0) {$sortdirection}";
- $sorttimeaccess = true;
- } else {
- $sorts[] = "{$prefix}.{$sortfield} {$sortdirection}";
- }
- $found = true;
- break;
- }
- }
- if (!$found) {
- // The param is not found in $allowedprefixesandfields.
- throw new coding_exception('Invalid $sort parameter in enrol_get_my_courses()');
- }
- }
- }
- $sort = implode(',', $sorts);
- $orderby = "ORDER BY $sort";
- }
- $wheres = array("c.id <> :siteid");
- $params = array('siteid'=>SITEID);
- if (isset($USER->loginascontext) and $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
- // list _only_ this course - anything else is asking for trouble...
- $wheres[] = "courseid = :loginas";
- $params['loginas'] = $USER->loginascontext->instanceid;
- }
- $coursefields = 'c.' .join(',c.', $fields);
- $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
- $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
- $params['contextlevel'] = CONTEXT_COURSE;
- $wheres = implode(" AND ", $wheres);
- $timeaccessselect = "";
- $timeaccessjoin = "";
- if (!empty($courseids)) {
- list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
- $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
- $params = array_merge($params, $courseidsparams);
- }
- if (!empty($excludecourses)) {
- list($courseidssql, $courseidsparams) = $DB->get_in_or_equal($excludecourses, SQL_PARAMS_NAMED, 'param', false);
- $wheres = sprintf("%s AND c.id %s", $wheres, $courseidssql);
- $params = array_merge($params, $courseidsparams);
- }
- $courseidsql = "";
- // Logged-in, non-guest users get their enrolled courses.
- if (!isguestuser() && isloggedin()) {
- $courseidsql .= "
- SELECT DISTINCT e.courseid
- FROM {enrol} e
- JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid1)
- WHERE ue.status = :active AND e.status = :enabled AND ue.timestart <= :now1
- AND (ue.timeend = 0 OR ue.timeend > :now2)";
- $params['userid1'] = $USER->id;
- $params['active'] = ENROL_USER_ACTIVE;
- $params['enabled'] = ENROL_INSTANCE_ENABLED;
- $params['now1'] = $params['now2'] = time();
- if ($sorttimeaccess) {
- $params['userid2'] = $USER->id;
- $timeaccessselect = ', ul.timeaccess as lastaccessed';
- $timeaccessjoin = "LEFT JOIN {user_lastaccess} ul ON (ul.courseid = c.id AND ul.userid = :userid2)";
- }
- }
- // When including non-enrolled but accessible courses...
- if ($allaccessible) {
- if (is_siteadmin()) {
- // Site admins can access all courses.
- $courseidsql = "SELECT DISTINCT c2.id AS courseid FROM {course} c2";
- } else {
- // If we used the enrolment as well, then this will be UNIONed.
- if ($courseidsql) {
- $courseidsql .= " UNION ";
- }
- // Include courses with guest access and no password.
- $courseidsql .= "
- SELECT DISTINCT e.courseid
- FROM {enrol} e
- WHERE e.enrol = 'guest' AND e.password = :emptypass AND e.status = :enabled2";
- $params['emptypass'] = '';
- $params['enabled2'] = ENROL_INSTANCE_ENABLED;
- // Include courses where the current user is currently using guest access (may include
- // those which require a password).
- $courseids = [];
- $accessdata = get_user_accessdata($USER->id);
- foreach ($accessdata['ra'] as $contextpath => $roles) {
- if (array_key_exists($CFG->guestroleid, $roles)) {
- // Work out the course id from context path.
- $context = context::instance_by_id(preg_replace('~^.*/~', '', $contextpath));
- if ($context instanceof context_course) {
- $courseids[$context->instanceid] = true;
- }
- }
- }
- // Include courses where the current user has moodle/course:view capability.
- $courses = get_user_capability_course('moodle/course:view', null, false);
- if (!$courses) {
- $courses = [];
- }
- foreach ($courses as $course) {
- $courseids[$course->id] = true;
- }
- // If there are any in either category, list them individually.
- if ($courseids) {
- list ($allowedsql, $allowedparams) = $DB->get_in_or_equal(
- array_keys($courseids), SQL_PARAMS_NAMED);
- $courseidsql .= "
- UNION
- SELECT DISTINCT c3.id AS courseid
- FROM {course} c3
- WHERE c3.id $allowedsql";
- $params = array_merge($params, $allowedparams);
- }
- }
- }
- // Note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why
- // we have the subselect there.
- $sql = "SELECT $coursefields $ccselect $timeaccessselect
- FROM {course} c
- JOIN ($courseidsql) en ON (en.courseid = c.id)
- $timeaccessjoin
- $ccjoin
- WHERE $wheres
- $orderby";
- $courses = $DB->get_records_sql($sql, $params, $offset, $limit);
- // preload contexts and check visibility
- foreach ($courses as $id=>$course) {
- context_helper::preload_from_record($course);
- if (!$course->visible) {
- if (!$context = context_course::instance($id, IGNORE_MISSING)) {
- unset($courses[$id]);
- continue;
- }
- if (!has_capability('moodle/course:viewhiddencourses', $context)) {
- unset($courses[$id]);
- continue;
- }
- }
- $courses[$id] = $course;
- }
- //wow! Is that really all? :-D
- return $courses;
- }
- /**
- * Returns course enrolment information icons.
- *
- * @param object $course
- * @param array $instances enrol instances of this course, improves performance
- * @return array of pix_icon
- */
- function enrol_get_course_info_icons($course, array $instances = NULL) {
- $icons = array();
- if (is_null($instances)) {
- $instances = enrol_get_instances($course->id, true);
- }
- $plugins = enrol_get_plugins(true);
- foreach ($plugins as $name => $plugin) {
- $pis = array();
- foreach ($instances as $instance) {
- if ($instance->status != ENROL_INSTANCE_ENABLED or $instance->courseid != $course->id) {
- debugging('Invalid instances parameter submitted in enrol_get_info_icons()');
- continue;
- }
- if ($instance->enrol == $name) {
- $pis[$instance->id] = $instance;
- }
- }
- if ($pis) {
- $icons = array_merge($icons, $plugin->get_info_icons($pis));
- }
- }
- return $icons;
- }
- /**
- * Returns SQL ORDER arguments which reflect the admin settings to sort my courses.
- *
- * @param string|null $sort SQL ORDER arguments which were originally requested (optionally).
- * @return string SQL ORDER arguments.
- */
- function enrol_get_courses_sortingsql($sort = null) {
- global $CFG;
- // Prepare the visible SQL fragment as empty.
- $visible = '';
- // Only create a visible SQL fragment if the caller didn't already pass a sort order which contains the visible field.
- if ($sort === null || strpos($sort, 'visible') === false) {
- // If the admin did not explicitly want to have shown and hidden courses sorted as one list, we will sort hidden
- // courses to the end of the course list.
- if (!isset($CFG->navsortmycourseshiddenlast) || $CFG->navsortmycourseshiddenlast == true) {
- $visible = 'visible DESC, ';
- }
- }
- // Only create a sortorder SQL fragment if the caller didn't already pass one.
- if ($sort === null) {
- // If the admin has configured a course sort order, we will use this.
- if (!empty($CFG->navsortmycoursessort)) {
- $sort = $CFG->navsortmycoursessort . ' ASC';
- // Otherwise we will fall back to the sortorder sorting.
- } else {
- $sort = 'sortorder ASC';
- }
- }
- return $visible . $sort;
- }
- /**
- * Returns course enrolment detailed information.
- *
- * @param object $course
- * @return array of html fragments - can be used to construct lists
- */
- function enrol_get_course_description_texts($course) {
- $lines = array();
- $instances = enrol_get_instances($course->id, true);
- $plugins = enrol_get_plugins(true);
- foreach ($instances as $instance) {
- if (!isset($plugins[$instance->enrol])) {
- //weird
- continue;
- }
- $plugin = $plugins[$instance->enrol];
- $text = $plugin->get_description_text($instance);
- if ($text !== NULL) {
- $lines[] = $text;
- }
- }
- return $lines;
- }
- /**
- * Returns list of courses user is enrolled into.
- *
- * Note: Use {@link enrol_get_all_users_courses()} if you need the list without any capability checks.
- *
- * The $fields param is a list of field names to ADD so name just the fields you really need,
- * which will be added and uniq'd.
- *
- * @param int $userid User whose courses are returned, defaults to the current user.
- * @param bool $onlyactive Return only active enrolments in courses user may see.
- * @param string|array $fields Extra fields to be returned (array or comma-separated list).
- * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
- * @return array
- */
- function enrol_get_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
- global $DB;
- $courses = enrol_get_all_users_courses($userid, $onlyactive, $fields, $sort);
- // preload contexts and check visibility
- if ($onlyactive) {
- foreach ($courses as $id=>$course) {
- context_helper::preload_from_record($course);
- if (!$course->visible) {
- if (!$context = context_course::instance($id)) {
- unset($courses[$id]);
- continue;
- }
- if (!has_capability('moodle/course:viewhiddencourses', $context, $userid)) {
- unset($courses[$id]);
- continue;
- }
- }
- }
- }
- return $courses;
- }
- /**
- * Returns list of roles per users into course.
- *
- * @param int $courseid Course id.
- * @return array Array[$userid][$roleid] = role_assignment.
- */
- function enrol_get_course_users_roles(int $courseid) : array {
- global $DB;
- $context = context_course::instance($courseid);
- $roles = array();
- $records = $DB->get_recordset('role_assignments', array('contextid' => $context->id));
- foreach ($records as $record) {
- if (isset($roles[$record->userid]) === false) {
- $roles[$record->userid] = array();
- }
- $roles[$record->userid][$record->roleid] = $record;
- }
- $records->close();
- return $roles;
- }
- /**
- * Can user access at least one enrolled course?
- *
- * Cheat if necessary, but find out as fast as possible!
- *
- * @param int|stdClass $user null means use current user
- * @return bool
- */
- function enrol_user_sees_own_courses($user = null) {
- global $USER;
- if ($user === null) {
- $user = $USER;
- }
- $userid = is_object($user) ? $user->id : $user;
- // Guest account does not have any courses
- if (isguestuser($userid) or empty($userid)) {
- return false;
- }
- // Let's cheat here if this is the current user,
- // if user accessed any course recently, then most probably
- // we do not need to query the database at all.
- if ($USER->id == $userid) {
- if (!empty($USER->enrol['enrolled'])) {
- foreach ($USER->enrol['enrolled'] as $until) {
- if ($until > time()) {
- return true;
- }
- }
- }
- }
- // Now the slow way.
- $courses = enrol_get_all_users_courses($userid, true);
- foreach($courses as $course) {
- if ($course->visible) {
- return true;
- }
- context_helper::preload_from_record($course);
- $context = context_course::instance($course->id);
- if (has_capability('moodle/course:viewhiddencourses', $context, $user)) {
- return true;
- }
- }
- return false;
- }
- /**
- * Returns list of courses user is enrolled into without performing any capability checks.
- *
- * The $fields param is a list of field names to ADD so name just the fields you really need,
- * which will be added and uniq'd.
- *
- * @param int $userid User whose courses are returned, defaults to the current user.
- * @param bool $onlyactive Return only active enrolments in courses user may see.
- * @param string|array $fields Extra fields to be returned (array or comma-separated list).
- * @param string|null $sort Comma separated list of fields to sort by, defaults to respecting navsortmycoursessort.
- * @return array
- */
- function enrol_get_all_users_courses($userid, $onlyactive = false, $fields = null, $sort = null) {
- global $DB;
- // Re-Arrange the course sorting according to the admin settings.
- $sort = enrol_get_courses_sortingsql($sort);
- // Guest account does not have any courses
- if (isguestuser($userid) or empty($userid)) {
- return(array());
- }
- $basefields = array('id', 'category', 'sortorder',
- 'shortname', 'fullname', 'idnumber',
- 'startdate', 'visible',
- 'defaultgroupingid',
- 'groupmode', 'groupmodeforce');
- if (empty($fields)) {
- $fields = $basefields;
- } else if (is_string($fields)) {
- // turn the fields from a string to an array
- $fields = explode(',', $fields);
- $fields = array_map('trim', $fields);
- $fields = array_unique(array_merge($basefields, $fields));
- } else if (is_array($fields)) {
- $fields = array_unique(array_merge($basefields, $fields));
- } else {
- throw new coding_exception('Invalid $fields parameter in enrol_get_all_users_courses()');
- }
- if (in_array('*', $fields)) {
- $fields = array('*');
- }
- $orderby = "";
- $sort = trim($sort);
- if (!empty($sort)) {
- $rawsorts = explode(',', $sort);
- $sorts = array();
- foreach ($rawsorts as $rawsort) {
- $rawsort = trim($rawsort);
- if (strpos($rawsort, 'c.') === 0) {
- $rawsort = substr($rawsort, 2);
- }
- $sorts[] = trim($rawsort);
- }
- $sort = 'c.'.implode(',c.', $sorts);
- $orderby = "ORDER BY $sort";
- }
- $params = array('siteid'=>SITEID);
- if ($onlyactive) {
- $subwhere = "WHERE ue.status = :active AND e.status = :enabled AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)";
- $params['now1'] = round(time(), -2); // improves db caching
- $params['now2'] = $params['now1'];
- $params['active'] = ENROL_USER_ACTIVE;
- $params['enabled'] = ENROL_INSTANCE_ENABLED;
- } else {
- $subwhere = "";
- }
- $coursefields = 'c.' .join(',c.', $fields);
- $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
- $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
- $params['contextlevel'] = CONTEXT_COURSE;
- //note: we can not use DISTINCT + text fields due to Oracle and MS limitations, that is why we have the subselect there
- $sql = "SELECT $coursefields $ccselect
- FROM {course} c
- JOIN (SELECT DISTINCT e.courseid
- FROM {enrol} e
- JOIN {user_enrolments} ue ON (ue.enrolid = e.id AND ue.userid = :userid)
- $subwhere
- ) en ON (en.courseid = c.id)
- $ccjoin
- WHERE c.id <> :siteid
- $orderby";
- $params['userid'] = $userid;
- $courses = $DB->get_records_sql($sql, $params);
- return $courses;
- }
- /**
- * Called when user is about to be deleted.
- * @param object $user
- * @return void
- */
- function enrol_user_delete($user) {
- global $DB;
- $plugins = enrol_get_plugins(true);
- foreach ($plugins as $plugin) {
- $plugin->user_delete($user);
- }
- // force cleanup of all broken enrolments
- $DB->delete_records('user_enrolments', array('userid'=>$user->id));
- }
- /**
- * Called when course is about to be deleted.
- * If a user id is passed, only enrolments that the user has permission to un-enrol will be removed,
- * otherwise all enrolments in the course will be removed.
- *
- * @param stdClass $course
- * @param int|null $userid
- * @return void
- */
- function enrol_course_delete($course, $userid = null) {
- global $DB;
- $context = context_course::instance($course->id);
- $instances = enrol_get_instances($course->id, false);
- $plugins = enrol_get_plugins(true);
- if ($userid) {
- // If the user id is present, include only course enrolment instances which allow manual unenrolment and
- // the given user have a capability to perform unenrolment.
- $instances = array_filter($instances, function($instance) use ($userid, $plugins, $context) {
- $unenrolcap = "enrol/{$instance->enrol}:unenrol";
- return $plugins[$instance->enrol]->allow_unenrol($instance) &&
- has_capability($unenrolcap, $context, $userid);
- });
- }
- foreach ($instances as $instance) {
- if (isset($plugins[$instance->enrol])) {
- $plugins[$instance->enrol]->delete_instance($instance);
- }
- // low level delete in case plugin did not do it
- $DB->delete_records('role_assignments', array('itemid'=>$instance->id, 'component'=>'enrol_'.$instance->enrol));
- $DB->delete_records('user_enrolments', array('enrolid'=>$instance->id));
- $DB->delete_records('enrol', array('id'=>$instance->id));
- }
- }
- /**
- * Try to enrol user via default internal auth plugin.
- *
- * For now this is always using the manual enrol plugin...
- *
- * @param $courseid
- * @param $userid
- * @param $roleid
- * @param $timestart
- * @param $timeend
- * @return bool success
- */
- function enrol_try_internal_enrol($courseid, $userid, $roleid = null, $timestart = 0, $timeend = 0) {
- global $DB;
- //note: this is hardcoded to manual plugin for now
- if (!enrol_is_enabled('manual')) {
- return false;
- }
- if (!$enrol = enrol_get_plugin('manual')) {
- return false;
- }
- if (!$instances = $DB->get_records('enrol', array('enrol'=>'manual', 'courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder,id ASC')) {
- return false;
- }
- $instance = reset($instances);
- $enrol->enrol_user($instance, $userid, $roleid, $timestart, $timeend);
- return true;
- }
- /**
- * Is there a chance users might self enrol
- * @param int $courseid
- * @return bool
- */
- function enrol_selfenrol_available($courseid) {
- $result = false;
- $plugins = enrol_get_plugins(true);
- $enrolinstances = enrol_get_instances($courseid, true);
- foreach($enrolinstances as $instance) {
- if (!isset($plugins[$instance->enrol])) {
- continue;
- }
- if ($instance->enrol === 'guest') {
- continue;
- }
- if ($plugins[$instance->enrol]->show_enrolme_link($instance)) {
- $result = true;
- break;
- }
- }
- return $result;
- }
- /**
- * This function returns the end of current active user enrolment.
- *
- * It deals correctly with multiple overlapping user enrolments.
- *
- * @param int $courseid
- * @param int $userid
- * @return int|bool timestamp when active enrolment ends, false means no active enrolment now, 0 means never
- */
- function enrol_get_enrolment_end($courseid, $userid) {
- global $DB;
- $sql = "SELECT ue.*
- FROM {user_enrolments} ue
- JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
- JOIN {user} u ON u.id = ue.userid
- WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
- $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$courseid);
- if (!$enrolments = $DB->get_records_sql($sql, $params)) {
- return false;
- }
- $changes = array();
- foreach ($enrolments as $ue) {
- $start = (int)$ue->timestart;
- $end = (int)$ue->timeend;
- if ($end != 0 and $end < $start) {
- debugging('Invalid enrolment start or end in user_enrolment id:'.$ue->id);
- continue;
- }
- if (isset($changes[$start])) {
- $changes[$start] = $changes[$start] + 1;
- } else {
- $changes[$start] = 1;
- }
- if ($end === 0) {
- // no end
- } else if (isset($changes[$end])) {
- $changes[$end] = $changes[$end] - 1;
- } else {
- $changes[$end] = -1;
- }
- }
- // let's sort then enrolment starts&ends and go through them chronologically,
- // looking for current status and the next future end of enrolment
- ksort($changes);
- $now = time();
- $current = 0;
- $present = null;
- foreach ($changes as $time => $change) {
- if ($time > $now) {
- if ($present === null) {
- // we have just went past current time
- $present = $current;
- if ($present < 1) {
- // no enrolment active
- return false;
- }
- }
- if ($present !== null) {
- // we are already in the future - look for possible end
- if ($current + $change < 1) {
- return $time;
- }
- }
- }
- $current += $change;
- }
- if ($current > 0) {
- return 0;
- } else {
- return false;
- }
- }
- /**
- * Is current user accessing course via this enrolment method?
- *
- * This is intended for operations that are going to affect enrol instances.
- *
- * @param stdClass $instance enrol instance
- * @return bool
- */
- function enrol_accessing_via_instance(stdClass $instance) {
- global $DB, $USER;
- if (empty($instance->id)) {
- return false;
- }
- if (is_siteadmin()) {
- // Admins may go anywhere.
- return false;
- }
- return $DB->record_exists('user_enrolments', array('userid'=>$USER->id, 'enrolid'=>$instance->id));
- }
- /**
- * Returns true if user is enrolled (is participating) in course
- * this is intended for students and teachers.
- *
- * Since 2.2 the result for active enrolments and current user are cached.
- *
- * @param context $context
- * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
- * @param string $withcapability extra capability name
- * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
- * @return bool
- */
- function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
- global $USER, $DB;
- // First find the course context.
- $coursecontext = $context->get_course_context();
- // Make sure there is a real user specified.
- if ($user === null) {
- $userid = isset($USER->id) ? $USER->id : 0;
- } else {
- $userid = is_object($user) ? $user->id : $user;
- }
- if (empty($userid)) {
- // Not-logged-in!
- return false;
- } else if (isguestuser($userid)) {
- // Guest account can not be enrolled anywhere.
- return false;
- }
- // Note everybody participates on frontpage, so for other contexts...
- if ($coursecontext->instanceid != SITEID) {
- // Try cached info first - the enrolled flag is set only when active enrolment present.
- if ($USER->id == $userid) {
- $coursecontext->reload_if_dirty();
- if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
- if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
- if ($withcapability and !has_capability($withcapability, $context, $userid)) {
- return false;
- }
- return true;
- }
- }
- }
- if ($onlyactive) {
- // Look for active enrolments only.
- $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
- if ($until === false) {
- return false;
- }
- if ($USER->id == $userid) {
- if ($until == 0) {
- $until = ENROL_MAX_TIMESTAMP;
- …
Large files files are truncated, but you can click here to view the full file