2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * This file contains the course_enrolment_manager class which is used to interface
19 * with the functions that exist in enrollib.php in relation to a single course.
22 * @copyright 2010 Sam Hemelryk
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
29 * This class provides a targeted tied together means of interfacing the enrolment
30 * tasks together with a course.
32 * It is provided as a convenience more than anything else.
34 * @copyright 2010 Sam Hemelryk
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class course_enrolment_manager
{
45 * The course we are managing enrolments for
48 protected $course = null;
50 * Limits the focus of the manager to one enrolment plugin instance
53 protected $instancefilter = null;
55 * Limits the focus of the manager to users with specified role
58 protected $rolefilter = 0;
60 * Limits the focus of the manager to users who match search string
63 protected $searchfilter = '';
65 * Limits the focus of the manager to users in specified group
68 protected $groupfilter = 0;
70 * Limits the focus of the manager to users who match status active/inactive
73 protected $statusfilter = -1;
76 * The total number of users enrolled in the course
77 * Populated by course_enrolment_manager::get_total_users
80 protected $totalusers = null;
82 * An array of users currently enrolled in the course
83 * Populated by course_enrolment_manager::get_users
86 protected $users = array();
89 * An array of users who have roles within this course but who have not
90 * been enrolled in the course
93 protected $otherusers = array();
96 * The total number of users who hold a role within the course but who
100 protected $totalotherusers = null;
103 * The current moodle_page object
106 protected $moodlepage = null;
109 * These variables are used to cache the information this class uses
110 * please never use these directly instead use their get_ counterparts.
114 private $_instancessql = null;
115 private $_instances = null;
116 private $_inames = null;
117 private $_plugins = null;
118 private $_allplugins = null;
119 private $_roles = null;
120 private $_assignableroles = null;
121 private $_assignablerolesothers = null;
122 private $_groups = null;
126 * Constructs the course enrolment manager
128 * @param moodle_page $moodlepage
129 * @param stdClass $course
130 * @param string $instancefilter
131 * @param int $rolefilter If non-zero, filters to users with specified role
132 * @param string $searchfilter If non-blank, filters to users with search text
133 * @param int $groupfilter if non-zero, filter users with specified group
134 * @param int $statusfilter if not -1, filter users with active/inactive enrollment.
136 public function __construct(moodle_page
$moodlepage, $course, $instancefilter = null,
137 $rolefilter = 0, $searchfilter = '', $groupfilter = 0, $statusfilter = -1) {
138 $this->moodlepage
= $moodlepage;
139 $this->context
= context_course
::instance($course->id
);
140 $this->course
= $course;
141 $this->instancefilter
= $instancefilter;
142 $this->rolefilter
= $rolefilter;
143 $this->searchfilter
= $searchfilter;
144 $this->groupfilter
= $groupfilter;
145 $this->statusfilter
= $statusfilter;
149 * Returns the current moodle page
150 * @return moodle_page
152 public function get_moodlepage() {
153 return $this->moodlepage
;
157 * Returns the total number of enrolled users in the course.
159 * If a filter was specificed this will be the total number of users enrolled
160 * in this course by means of that instance.
162 * @global moodle_database $DB
165 public function get_total_users() {
167 if ($this->totalusers
=== null) {
168 list($instancessql, $params, $filter) = $this->get_instance_sql();
169 list($filtersql, $moreparams) = $this->get_filter_sql();
170 $params +
= $moreparams;
171 $sqltotal = "SELECT COUNT(DISTINCT u.id)
173 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
174 JOIN {enrol} e ON (e.id = ue.enrolid)
175 LEFT JOIN {groups_members} gm ON u.id = gm.userid AND gm.groupid IN (
178 WHERE g.courseid = e.courseid
181 $this->totalusers
= (int)$DB->count_records_sql($sqltotal, $params);
183 return $this->totalusers
;
187 * Returns the total number of enrolled users in the course.
189 * If a filter was specificed this will be the total number of users enrolled
190 * in this course by means of that instance.
192 * @global moodle_database $DB
195 public function get_total_other_users() {
197 if ($this->totalotherusers
=== null) {
198 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context
->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'ctx');
199 $params['courseid'] = $this->course
->id
;
200 $sql = "SELECT COUNT(DISTINCT u.id)
201 FROM {role_assignments} ra
202 JOIN {user} u ON u.id = ra.userid
203 JOIN {context} ctx ON ra.contextid = ctx.id
205 SELECT ue.id, ue.userid
206 FROM {user_enrolments} ue
207 LEFT JOIN {enrol} e ON e.id=ue.enrolid
208 WHERE e.courseid = :courseid
209 ) ue ON ue.userid=u.id
210 WHERE ctx.id $ctxcondition AND
212 $this->totalotherusers
= (int)$DB->count_records_sql($sql, $params);
214 return $this->totalotherusers
;
218 * Gets all of the users enrolled in this course.
220 * If a filter was specified this will be the users who were enrolled
221 * in this course by means of that instance. If role or search filters were
222 * specified then these will also be applied.
224 * @global moodle_database $DB
225 * @param string $sort
226 * @param string $direction ASC or DESC
227 * @param int $page First page should be 0
228 * @param int $perpage Defaults to 25
231 public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
233 if ($direction !== 'ASC') {
236 $key = md5("$sort-$direction-$page-$perpage");
237 if (!array_key_exists($key, $this->users
)) {
238 list($instancessql, $params, $filter) = $this->get_instance_sql();
239 list($filtersql, $moreparams) = $this->get_filter_sql();
240 $params +
= $moreparams;
241 $extrafields = get_extra_user_fields($this->get_context());
242 $extrafields[] = 'lastaccess';
243 $ufields = user_picture
::fields('u', $extrafields);
244 $sql = "SELECT DISTINCT $ufields, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
246 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
247 JOIN {enrol} e ON (e.id = ue.enrolid)
248 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)
249 LEFT JOIN {groups_members} gm ON u.id = gm.userid AND gm.groupid IN (
252 WHERE g.courseid = e.courseid
255 ORDER BY $sort $direction";
256 $this->users
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
258 return $this->users
[$key];
262 * Obtains WHERE clause to filter results by defined search and role filter
263 * (instance filter is handled separately in JOIN clause, see
266 * @return array Two-element array with SQL and params for WHERE clause
268 protected function get_filter_sql() {
272 $extrafields = get_extra_user_fields($this->get_context());
273 list($sql, $params) = users_search_sql($this->searchfilter
, 'u', true, $extrafields);
276 if ($this->rolefilter
) {
278 $contextids = $this->context
->get_parent_context_ids();
279 $contextids[] = $this->context
->id
;
280 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
);
281 $params +
= $contextparams;
283 // Role check condition.
284 $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
285 "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
286 $params['roleid'] = $this->rolefilter
;
290 if ($this->groupfilter
) {
291 if ($this->groupfilter
< 0) {
292 // Show users who are not in any group.
293 $sql .= " AND gm.groupid IS NULL";
295 $sql .= " AND gm.groupid = :groupid";
296 $params['groupid'] = $this->groupfilter
;
301 if ($this->statusfilter
=== ENROL_USER_ACTIVE
) {
302 $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
303 AND (ue.timeend = 0 OR ue.timeend > :now2)";
304 $now = round(time(), -2); // rounding helps caching in DB
305 $params +
= array('enabled' => ENROL_INSTANCE_ENABLED
,
306 'active' => ENROL_USER_ACTIVE
,
309 } else if ($this->statusfilter
=== ENROL_USER_SUSPENDED
) {
310 $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
311 OR (ue.timeend <> 0 AND ue.timeend < :now2))";
312 $now = round(time(), -2); // rounding helps caching in DB
313 $params +
= array('disabled' => ENROL_INSTANCE_DISABLED
,
314 'inactive' => ENROL_USER_SUSPENDED
,
319 return array($sql, $params);
323 * Gets and array of other users.
325 * Other users are users who have been assigned roles or inherited roles
326 * within this course but who have not been enrolled in the course
328 * @global moodle_database $DB
329 * @param string $sort
330 * @param string $direction
332 * @param int $perpage
335 public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
337 if ($direction !== 'ASC') {
340 $key = md5("$sort-$direction-$page-$perpage");
341 if (!array_key_exists($key, $this->otherusers
)) {
342 list($ctxcondition, $params) = $DB->get_in_or_equal($this->context
->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'ctx');
343 $params['courseid'] = $this->course
->id
;
344 $params['cid'] = $this->course
->id
;
345 $extrafields = get_extra_user_fields($this->get_context());
346 $ufields = user_picture
::fields('u', $extrafields);
347 $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, $ufields,
348 coalesce(u.lastaccess,0) AS lastaccess
349 FROM {role_assignments} ra
350 JOIN {user} u ON u.id = ra.userid
351 JOIN {context} ctx ON ra.contextid = ctx.id
353 SELECT ue.id, ue.userid
354 FROM {user_enrolments} ue
355 JOIN {enrol} e ON e.id = ue.enrolid
356 WHERE e.courseid = :courseid
357 ) ue ON ue.userid=u.id
358 WHERE ctx.id $ctxcondition AND
360 ORDER BY $sort $direction, ctx.depth DESC";
361 $this->otherusers
[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
363 return $this->otherusers
[$key];
367 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
369 * @param string $search the search term, if any.
370 * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
371 * @return array with three elements:
372 * string list of fields to SELECT,
373 * string contents of SQL WHERE clause,
374 * array query params. Note that the SQL snippets use named parameters.
376 protected function get_basic_search_conditions($search, $searchanywhere) {
379 // Add some additional sensible conditions
380 $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
381 $params = array('guestid' => $CFG->siteguest
);
382 if (!empty($search)) {
383 $conditions = get_extra_user_fields($this->get_context());
384 $conditions[] = 'u.firstname';
385 $conditions[] = 'u.lastname';
386 $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
387 if ($searchanywhere) {
388 $searchparam = '%' . $search . '%';
390 $searchparam = $search . '%';
393 foreach ($conditions as $key => $condition) {
394 $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
395 $params["con{$i}00"] = $searchparam;
398 $tests[] = '(' . implode(' OR ', $conditions) . ')';
400 $wherecondition = implode(' AND ', $tests);
402 $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
403 $extrafields[] = 'username';
404 $extrafields[] = 'lastaccess';
405 $ufields = user_picture
::fields('u', $extrafields);
407 return array($ufields, $params, $wherecondition);
411 * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
413 * @param string $search the search string, if any.
414 * @param string $fields the first bit of the SQL when returning some users.
415 * @param string $countfields fhe first bit of the SQL when counting the users.
416 * @param string $sql the bulk of the SQL statement.
417 * @param array $params query parameters.
418 * @param int $page which page number of the results to show.
419 * @param int $perpage number of users per page.
420 * @param int $addedenrollment number of users added to enrollment.
421 * @return array with two elememts:
422 * int total number of users matching the search.
423 * array of user objects returned by the query.
425 protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
428 list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
429 $order = ' ORDER BY ' . $sort;
431 $totalusers = $DB->count_records_sql($countfields . $sql, $params);
432 $availableusers = $DB->get_records_sql($fields . $sql . $order,
433 array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
435 return array('totalusers' => $totalusers, 'users' => $availableusers);
439 * Gets an array of the users that can be enrolled in this course.
441 * @global moodle_database $DB
442 * @param int $enrolid
443 * @param string $search
444 * @param bool $searchanywhere
445 * @param int $page Defaults to 0
446 * @param int $perpage Defaults to 25
447 * @param int $addedenrollment Defaults to 0
448 * @return array Array(totalusers => int, users => array)
450 public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
453 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
455 $fields = 'SELECT '.$ufields;
456 $countfields = 'SELECT COUNT(1)';
457 $sql = " FROM {user} u
458 LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
459 WHERE $wherecondition
461 $params['enrolid'] = $enrolid;
463 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
467 * Searches other users and returns paginated results
469 * @global moodle_database $DB
470 * @param string $search
471 * @param bool $searchanywhere
472 * @param int $page Starting at 0
473 * @param int $perpage
476 public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
479 list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
481 $fields = 'SELECT ' . $ufields;
482 $countfields = 'SELECT COUNT(u.id)';
483 $sql = " FROM {user} u
484 LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
485 WHERE $wherecondition
487 $params['contextid'] = $this->context
->id
;
489 return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
493 * Gets an array containing some SQL to user for when selecting, params for
494 * that SQL, and the filter that was used in constructing the sql.
496 * @global moodle_database $DB
499 protected function get_instance_sql() {
501 if ($this->_instancessql
=== null) {
502 $instances = $this->get_enrolment_instances();
503 $filter = $this->get_enrolment_filter();
504 if ($filter && array_key_exists($filter, $instances)) {
505 $sql = " = :ifilter";
506 $params = array('ifilter'=>$filter);
510 list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED
);
512 // no enabled instances, oops, we should probably say something
514 $params = array('never'=>-1);
517 $this->instancefilter
= $filter;
518 $this->_instancessql
= array($sql, $params, $filter);
520 return $this->_instancessql
;
524 * Returns all of the enrolment instances for this course.
526 * NOTE: since 2.4 it includes instances of disabled plugins too.
530 public function get_enrolment_instances() {
531 if ($this->_instances
=== null) {
532 $this->_instances
= enrol_get_instances($this->course
->id
, false);
534 return $this->_instances
;
538 * Returns the names for all of the enrolment instances for this course.
540 * NOTE: since 2.4 it includes instances of disabled plugins too.
544 public function get_enrolment_instance_names() {
545 if ($this->_inames
=== null) {
546 $instances = $this->get_enrolment_instances();
547 $plugins = $this->get_enrolment_plugins(false);
548 foreach ($instances as $key=>$instance) {
549 if (!isset($plugins[$instance->enrol
])) {
550 // weird, some broken stuff in plugin
551 unset($instances[$key]);
554 $this->_inames
[$key] = $plugins[$instance->enrol
]->get_instance_name($instance);
557 return $this->_inames
;
561 * Gets all of the enrolment plugins that are active for this course.
563 * @param bool $onlyenabled return only enabled enrol plugins
566 public function get_enrolment_plugins($onlyenabled = true) {
567 if ($this->_plugins
=== null) {
568 $this->_plugins
= enrol_get_plugins(true);
572 return $this->_plugins
;
575 if ($this->_allplugins
=== null) {
576 // Make sure we have the same objects in _allplugins and _plugins.
577 $this->_allplugins
= $this->_plugins
;
578 foreach (enrol_get_plugins(false) as $name=>$plugin) {
579 if (!isset($this->_allplugins
[$name])) {
580 $this->_allplugins
[$name] = $plugin;
585 return $this->_allplugins
;
589 * Gets all of the roles this course can contain.
593 public function get_all_roles() {
594 if ($this->_roles
=== null) {
595 $this->_roles
= role_fix_names(get_all_roles($this->context
), $this->context
);
597 return $this->_roles
;
601 * Gets all of the assignable roles for this course.
605 public function get_assignable_roles($otherusers = false) {
606 if ($this->_assignableroles
=== null) {
607 $this->_assignableroles
= get_assignable_roles($this->context
, ROLENAME_ALIAS
, false); // verifies unassign access control too
611 if (!is_array($this->_assignablerolesothers
)) {
612 $this->_assignablerolesothers
= array();
613 list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context
, 'moodle/course:view');
614 foreach ($this->_assignableroles
as $roleid=>$role) {
615 if (isset($courseviewroles[$roleid])) {
616 $this->_assignablerolesothers
[$roleid] = $role;
620 return $this->_assignablerolesothers
;
622 return $this->_assignableroles
;
627 * Gets all of the groups for this course.
631 public function get_all_groups() {
632 if ($this->_groups
=== null) {
633 $this->_groups
= groups_get_all_groups($this->course
->id
);
634 foreach ($this->_groups
as $gid=>$group) {
635 $this->_groups
[$gid]->name
= format_string($group->name
);
638 return $this->_groups
;
642 * Unenrols a user from the course given the users ue entry
644 * @global moodle_database $DB
645 * @param stdClass $ue
648 public function unenrol_user($ue) {
650 list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
651 if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context
)) {
652 $plugin->unenrol_user($instance, $ue->userid
);
659 * Given a user enrolment record this method returns the plugin and enrolment
660 * instance that relate to it.
662 * @param stdClass|int $userenrolment
663 * @return array array($instance, $plugin)
665 public function get_user_enrolment_components($userenrolment) {
667 if (is_numeric($userenrolment)) {
668 $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
670 $instances = $this->get_enrolment_instances();
671 $plugins = $this->get_enrolment_plugins(false);
672 if (!$userenrolment ||
!isset($instances[$userenrolment->enrolid
])) {
673 return array(false, false);
675 $instance = $instances[$userenrolment->enrolid
];
676 $plugin = $plugins[$instance->enrol
];
677 return array($instance, $plugin);
681 * Removes an assigned role from a user.
683 * @global moodle_database $DB
688 public function unassign_role_from_user($userid, $roleid) {
690 // Admins may unassign any role, others only those they could assign.
691 if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
692 if (defined('AJAX_SCRIPT')) {
693 throw new moodle_exception('invalidrole');
697 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST
);
698 $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context
->id
, 'userid'=>$user->id
, 'roleid'=>$roleid));
699 foreach ($ras as $ra) {
700 if ($ra->component
) {
701 if (strpos($ra->component
, 'enrol_') !== 0) {
704 if (!$plugin = enrol_get_plugin(substr($ra->component
, 6))) {
707 if ($plugin->roles_protected()) {
711 role_unassign($ra->roleid
, $ra->userid
, $ra->contextid
, $ra->component
, $ra->itemid
);
717 * Assigns a role to a user.
723 public function assign_role_to_user($roleid, $userid) {
724 require_capability('moodle/role:assign', $this->context
);
725 if (!array_key_exists($roleid, $this->get_assignable_roles())) {
726 if (defined('AJAX_SCRIPT')) {
727 throw new moodle_exception('invalidrole');
731 return role_assign($roleid, $userid, $this->context
->id
, '', NULL);
735 * Adds a user to a group
737 * @param stdClass $user
738 * @param int $groupid
741 public function add_user_to_group($user, $groupid) {
742 require_capability('moodle/course:managegroups', $this->context
);
743 $group = $this->get_group($groupid);
747 return groups_add_member($group->id
, $user->id
);
751 * Removes a user from a group
753 * @global moodle_database $DB
754 * @param StdClass $user
755 * @param int $groupid
758 public function remove_user_from_group($user, $groupid) {
760 require_capability('moodle/course:managegroups', $this->context
);
761 $group = $this->get_group($groupid);
762 if (!groups_remove_member_allowed($group, $user)) {
768 return groups_remove_member($group, $user);
772 * Gets the requested group
774 * @param int $groupid
775 * @return stdClass|int
777 public function get_group($groupid) {
778 $groups = $this->get_all_groups();
779 if (!array_key_exists($groupid, $groups)) {
782 return $groups[$groupid];
788 * @param stdClass $userenrolment
789 * @param stdClass $data
792 public function edit_enrolment($userenrolment, $data) {
793 //Only allow editing if the user has the appropriate capability
794 //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
795 list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
796 if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context
)) {
797 if (!isset($data->status
)) {
798 $data->status
= $userenrolment->status
;
800 $plugin->update_user_enrol($instance, $userenrolment->userid
, $data->status
, $data->timestart
, $data->timeend
);
807 * Returns the current enrolment filter that is being applied by this class
810 public function get_enrolment_filter() {
811 return $this->instancefilter
;
815 * Gets the roles assigned to this user that are applicable for this course.
820 public function get_user_roles($userid) {
822 $ras = get_user_roles($this->context
, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
823 $plugins = $this->get_enrolment_plugins(false);
824 foreach ($ras as $ra) {
825 if ($ra->contextid
!= $this->context
->id
) {
826 if (!array_key_exists($ra->roleid
, $roles)) {
827 $roles[$ra->roleid
] = null;
829 // higher ras, course always takes precedence
832 if (array_key_exists($ra->roleid
, $roles) && $roles[$ra->roleid
] === false) {
836 if ($ra->component
) {
838 if (strpos($ra->component
, 'enrol_') === 0) {
839 $plugin = substr($ra->component
, 6);
840 if (isset($plugins[$plugin])) {
841 $changeable = !$plugins[$plugin]->roles_protected();
846 $roles[$ra->roleid
] = $changeable;
852 * Gets the enrolments this user has in the course - including all suspended plugins and instances.
854 * @global moodle_database $DB
858 public function get_user_enrolments($userid) {
860 list($instancessql, $params, $filter) = $this->get_instance_sql();
861 $params['userid'] = $userid;
862 $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
863 $instances = $this->get_enrolment_instances();
864 $plugins = $this->get_enrolment_plugins(false);
865 $inames = $this->get_enrolment_instance_names();
866 foreach ($userenrolments as &$ue) {
867 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
868 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
869 $ue->enrolmentinstancename
= $inames[$ue->enrolmentinstance
->id
];
871 return $userenrolments;
875 * Gets the groups this user belongs to
880 public function get_user_groups($userid) {
881 return groups_get_all_groups($this->course
->id
, $userid, 0, 'g.id');
885 * Retursn an array of params that would go into the URL to return to this
890 public function get_url_params() {
892 'id' => $this->course
->id
894 if (!empty($this->instancefilter
)) {
895 $args['ifilter'] = $this->instancefilter
;
897 if (!empty($this->rolefilter
)) {
898 $args['role'] = $this->rolefilter
;
900 if ($this->searchfilter
!== '') {
901 $args['search'] = $this->searchfilter
;
903 if (!empty($this->groupfilter
)) {
904 $args['filtergroup'] = $this->groupfilter
;
906 if ($this->statusfilter
!== -1) {
907 $args['status'] = $this->statusfilter
;
913 * Returns the course this object is managing enrolments for
917 public function get_course() {
918 return $this->course
;
922 * Returns the course context
926 public function get_context() {
927 return $this->context
;
931 * Gets an array of other users in this course ready for display.
933 * Other users are users who have been assigned or inherited roles within this
934 * course but have not been enrolled.
936 * @param core_enrol_renderer $renderer
937 * @param moodle_url $pageurl
938 * @param string $sort
939 * @param string $direction ASC | DESC
940 * @param int $page Starting from 0
941 * @param int $perpage
944 public function get_other_users_for_display(core_enrol_renderer
$renderer, moodle_url
$pageurl, $sort, $direction, $page, $perpage) {
946 $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
947 $roles = $this->get_all_roles();
948 $plugins = $this->get_enrolment_plugins(false);
950 $context = $this->get_context();
952 $extrafields = get_extra_user_fields($context);
955 foreach ($userroles as $userrole) {
956 $contextid = $userrole->contextid
;
957 unset($userrole->contextid
); // This would collide with user avatar.
958 if (!array_key_exists($userrole->id
, $users)) {
959 $users[$userrole->id
] = $this->prepare_user_for_display($userrole, $extrafields, $now);
962 $a->role
= $roles[$userrole->roleid
]->localname
;
963 if ($contextid == $this->context
->id
) {
965 if ($userrole->component
) {
967 if (strpos($userrole->component
, 'enrol_') === 0) {
968 $plugin = substr($userrole->component
, 6);
969 if (isset($plugins[$plugin])) {
970 $changeable = !$plugins[$plugin]->roles_protected();
974 $roletext = get_string('rolefromthiscourse', 'enrol', $a);
977 switch ($userrole->contextlevel
) {
978 case CONTEXT_COURSE
:
980 $roletext = get_string('rolefrommetacourse', 'enrol', $a);
982 case CONTEXT_COURSECAT
:
983 $roletext = get_string('rolefromcategory', 'enrol', $a);
987 $roletext = get_string('rolefromsystem', 'enrol', $a);
991 if (!isset($users[$userrole->id
]['roles'])) {
992 $users[$userrole->id
]['roles'] = array();
994 $users[$userrole->id
]['roles'][$userrole->roleid
] = array(
996 'unchangeable' => !$changeable
1003 * Gets an array of users for display, this includes minimal user information
1004 * as well as minimal information on the users roles, groups, and enrolments.
1006 * @param core_enrol_renderer $renderer
1007 * @param moodle_url $pageurl
1009 * @param string $direction ASC or DESC
1011 * @param int $perpage
1014 public function get_users_for_display(course_enrolment_manager
$manager, $sort, $direction, $page, $perpage) {
1015 $pageurl = $manager->get_moodlepage()->url
;
1016 $users = $this->get_users($sort, $direction, $page, $perpage);
1019 $straddgroup = get_string('addgroup', 'group');
1020 $strunenrol = get_string('unenrol', 'enrol');
1021 $stredit = get_string('edit');
1023 $allroles = $this->get_all_roles();
1024 $assignable = $this->get_assignable_roles();
1025 $allgroups = $this->get_all_groups();
1026 $context = $this->get_context();
1027 $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1029 $url = new moodle_url($pageurl, $this->get_url_params());
1030 $extrafields = get_extra_user_fields($context);
1032 $enabledplugins = $this->get_enrolment_plugins(true);
1034 $userdetails = array();
1035 foreach ($users as $user) {
1036 $details = $this->prepare_user_for_display($user, $extrafields, $now);
1039 $details['roles'] = array();
1040 foreach ($this->get_user_roles($user->id
) as $rid=>$rassignable) {
1041 $unchangeable = !$rassignable;
1042 if (!is_siteadmin() and !isset($assignable[$rid])) {
1043 $unchangeable = true;
1045 $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname
, 'unchangeable'=>$unchangeable);
1049 $usergroups = $this->get_user_groups($user->id
);
1050 $details['groups'] = array();
1051 foreach($usergroups as $gid=>$unused) {
1052 $details['groups'][$gid] = $allgroups[$gid]->name
;
1056 $details['enrolments'] = array();
1057 foreach ($this->get_user_enrolments($user->id
) as $ue) {
1058 if (!isset($enabledplugins[$ue->enrolmentinstance
->enrol
])) {
1059 $details['enrolments'][$ue->id
] = array(
1060 'text' => $ue->enrolmentinstancename
,
1063 'actions' => array()
1066 } else if ($ue->timestart
and $ue->timeend
) {
1067 $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart
), 'end'=>userdate($ue->timeend
)));
1068 $periodoutside = ($ue->timestart
&& $ue->timeend
&& ($now < $ue->timestart ||
$now > $ue->timeend
));
1069 } else if ($ue->timestart
) {
1070 $period = get_string('periodstart', 'enrol', userdate($ue->timestart
));
1071 $periodoutside = ($ue->timestart
&& $now < $ue->timestart
);
1072 } else if ($ue->timeend
) {
1073 $period = get_string('periodend', 'enrol', userdate($ue->timeend
));
1074 $periodoutside = ($ue->timeend
&& $now > $ue->timeend
);
1076 // If there is no start or end show when user was enrolled.
1077 $period = get_string('periodnone', 'enrol', userdate($ue->timecreated
));
1078 $periodoutside = false;
1080 $details['enrolments'][$ue->id
] = array(
1081 'text' => $ue->enrolmentinstancename
,
1082 'period' => $period,
1083 'dimmed' => ($periodoutside or $ue->status
!= ENROL_USER_ACTIVE
or $ue->enrolmentinstance
->status
!= ENROL_INSTANCE_ENABLED
),
1084 'actions' => $ue->enrolmentplugin
->get_user_enrolment_actions($manager, $ue)
1087 $userdetails[$user->id
] = $details;
1089 return $userdetails;
1093 * Prepare a user record for display
1095 * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1096 * prepare user fields for display
1098 * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1100 * @param object $user The user record
1101 * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1102 * additional fields may be displayed
1103 * @param int $now The time used for lastaccess calculation
1104 * @return array The fields to be displayed including userid, courseid, picture, firstname, lastcourseaccess, lastaccess and any
1105 * additional fields from $extrafields
1107 private function prepare_user_for_display($user, $extrafields, $now) {
1109 'userid' => $user->id
,
1110 'courseid' => $this->get_course()->id
,
1111 'picture' => new user_picture($user),
1112 'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1113 'lastaccess' => get_string('never'),
1114 'lastcourseaccess' => get_string('never'),
1117 foreach ($extrafields as $field) {
1118 $details[$field] = $user->{$field};
1121 // Last time user has accessed the site.
1122 if (!empty($user->lastaccess
)) {
1123 $details['lastaccess'] = format_time($now - $user->lastaccess
);
1126 // Last time user has accessed the course.
1127 if (!empty($user->lastcourseaccess
)) {
1128 $details['lastcourseaccess'] = format_time($now - $user->lastcourseaccess
);
1133 public function get_manual_enrol_buttons() {
1134 $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1136 foreach ($plugins as $plugin) {
1137 $newbutton = $plugin->get_manual_enrol_button($this);
1138 if (is_array($newbutton)) {
1139 $buttons +
= $newbutton;
1140 } else if ($newbutton instanceof enrol_user_button
) {
1141 $buttons[] = $newbutton;
1147 public function has_instance($enrolpluginname) {
1148 // Make sure manual enrolments instance exists
1149 foreach ($this->get_enrolment_instances() as $instance) {
1150 if ($instance->enrol
== $enrolpluginname) {
1158 * Returns the enrolment plugin that the course manager was being filtered to.
1160 * If no filter was being applied then this function returns false.
1162 * @return enrol_plugin
1164 public function get_filtered_enrolment_plugin() {
1165 $instances = $this->get_enrolment_instances();
1166 $plugins = $this->get_enrolment_plugins(false);
1168 if (empty($this->instancefilter
) ||
!array_key_exists($this->instancefilter
, $instances)) {
1172 $instance = $instances[$this->instancefilter
];
1173 return $plugins[$instance->enrol
];
1177 * Returns and array of users + enrolment details.
1179 * Given an array of user id's this function returns and array of user enrolments for those users
1180 * as well as enough user information to display the users name and picture for each enrolment.
1182 * @global moodle_database $DB
1183 * @param array $userids
1186 public function get_users_enrolments(array $userids) {
1189 $instances = $this->get_enrolment_instances();
1190 $plugins = $this->get_enrolment_plugins(false);
1192 if (!empty($this->instancefilter
)) {
1193 $instancesql = ' = :instanceid';
1194 $instanceparams = array('instanceid' => $this->instancefilter
);
1196 list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED
, 'instanceid0000');
1199 $userfields = user_picture
::fields('u');
1200 list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED
, 'userid0000');
1202 list($sort, $sortparams) = users_order_by_sql('u');
1204 $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1205 FROM {user_enrolments} ue
1206 LEFT JOIN {user} u ON u.id = ue.userid
1207 WHERE ue.enrolid $instancesql AND
1211 $rs = $DB->get_recordset_sql($sql, $idparams +
$instanceparams +
$sortparams);
1213 foreach ($rs as $ue) {
1214 $user = user_picture
::unalias($ue);
1215 $ue->id
= $ue->ueid
;
1217 if (!array_key_exists($user->id
, $users)) {
1218 $user->enrolments
= array();
1219 $users[$user->id
] = $user;
1221 $ue->enrolmentinstance
= $instances[$ue->enrolid
];
1222 $ue->enrolmentplugin
= $plugins[$ue->enrolmentinstance
->enrol
];
1223 $users[$user->id
]->enrolments
[$ue->id
] = $ue;
1231 * A button that is used to enrol users in a course
1233 * @copyright 2010 Sam Hemelryk
1234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1236 class enrol_user_button
extends single_button
{
1239 * An array containing JS YUI modules required by this button
1242 protected $jsyuimodules = array();
1245 * An array containing JS initialisation calls required by this button
1248 protected $jsinitcalls = array();
1251 * An array strings required by JS for this button
1254 protected $jsstrings = array();
1257 * Initialises the new enrol_user_button
1259 * @staticvar int $count The number of enrol user buttons already created
1260 * @param moodle_url $url
1261 * @param string $label The text to display in the button
1262 * @param string $method Either post or get
1264 public function __construct(moodle_url
$url, $label, $method = 'post') {
1267 parent
::__construct($url, $label, $method);
1268 $this->class = 'singlebutton enrolusersbutton';
1269 $this->formid
= 'enrolusersbutton-'.$count;
1273 * Adds a YUI module call that will be added to the page when the button is used.
1275 * @param string|array $modules One or more modules to require
1276 * @param string $function The JS function to call
1277 * @param array $arguments An array of arguments to pass to the function
1278 * @param string $galleryversion Deprecated: The gallery version to use
1279 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1281 public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1282 if ($galleryversion != null) {
1283 debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER
);
1287 $js->modules
= (array)$modules;
1288 $js->function = $function;
1289 $js->arguments
= $arguments;
1290 $js->ondomready
= $ondomready;
1291 $this->jsyuimodules
[] = $js;
1295 * Adds a JS initialisation call to the page when the button is used.
1297 * @param string $function The function to call
1298 * @param array $extraarguments An array of arguments to pass to the function
1299 * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1300 * @param array $module A module definition
1302 public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1304 $js->function = $function;
1305 $js->extraarguments
= $extraarguments;
1306 $js->ondomready
= $ondomready;
1307 $js->module
= $module;
1308 $this->jsinitcalls
[] = $js;
1312 * Requires strings for JS that will be loaded when the button is used.
1314 * @param type $identifiers
1315 * @param string $component
1318 public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1319 $string = new stdClass
;
1320 $string->identifiers
= (array)$identifiers;
1321 $string->component
= $component;
1323 $this->jsstrings
[] = $string;
1327 * Initialises the JS that is required by this button
1329 * @param moodle_page $page
1331 public function initialise_js(moodle_page
$page) {
1332 foreach ($this->jsyuimodules
as $js) {
1333 $page->requires
->yui_module($js->modules
, $js->function, $js->arguments
, null, $js->ondomready
);
1335 foreach ($this->jsinitcalls
as $js) {
1336 $page->requires
->js_init_call($js->function, $js->extraarguments
, $js->ondomready
, $js->module
);
1338 foreach ($this->jsstrings
as $string) {
1339 $page->requires
->strings_for_js($string->identifiers
, $string->component
, $string->a
);
1345 * User enrolment action
1347 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1350 * @copyright 2011 Sam Hemelryk
1351 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1353 class user_enrolment_action
implements renderable
{
1356 * The icon to display for the action
1362 * The title for the action
1368 * The URL to the action
1374 * An array of HTML attributes
1377 protected $attributes = array();
1381 * @param pix_icon $icon
1382 * @param string $title
1383 * @param moodle_url $url
1384 * @param array $attributes
1386 public function __construct(pix_icon
$icon, $title, $url, array $attributes = null) {
1387 $this->icon
= $icon;
1388 $this->title
= $title;
1389 $this->url
= new moodle_url($url);
1390 if (!empty($attributes)) {
1391 $this->attributes
= $attributes;
1393 $this->attributes
['title'] = $title;
1397 * Returns the icon for this action
1400 public function get_icon() {
1405 * Returns the title for this action
1408 public function get_title() {
1409 return $this->title
;
1413 * Returns the URL for this action
1414 * @return moodle_url
1416 public function get_url() {
1421 * Returns the attributes to use for this action
1424 public function get_attributes() {
1425 return $this->attributes
;
1429 class enrol_ajax_exception
extends moodle_exception
{
1432 * @param string $errorcode The name of the string from error.php to print
1433 * @param string $module name of module
1434 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
1435 * @param object $a Extra words and phrases that might be required in the error string
1436 * @param string $debuginfo optional debugging information
1438 public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1439 parent
::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1444 * This class is used to manage a bulk operations for enrolment plugins.
1446 * @copyright 2011 Sam Hemelryk
1447 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1449 abstract class enrol_bulk_enrolment_operation
{
1452 * The course enrolment manager
1453 * @var course_enrolment_manager
1458 * The enrolment plugin to which this operation belongs
1465 * @param course_enrolment_manager $manager
1466 * @param stdClass $plugin
1468 public function __construct(course_enrolment_manager
$manager, enrol_plugin
$plugin = null) {
1469 $this->manager
= $manager;
1470 $this->plugin
= $plugin;
1474 * Returns a moodleform used for this operation, or false if no form is required and the action
1475 * should be immediatly processed.
1477 * @param moodle_url|string $defaultaction
1478 * @param mixed $defaultcustomdata
1479 * @return enrol_bulk_enrolment_change_form|moodleform|false
1481 public function get_form($defaultaction = null, $defaultcustomdata = null) {
1486 * Returns the title to use for this bulk operation
1490 abstract public function get_title();
1493 * Returns the identifier for this bulk operation.
1494 * This should be the same identifier used by the plugins function when returning
1495 * all of its bulk operations.
1499 abstract public function get_identifier();
1502 * Processes the bulk operation on the given users
1504 * @param course_enrolment_manager $manager
1505 * @param array $users
1506 * @param stdClass $properties
1508 abstract public function process(course_enrolment_manager
$manager, array $users, stdClass
$properties);